Getting sum complete (without pagination) of particular columns in backpack for laravel - datatables

I followed the recommendations I found here
jQuery(document).ready(function($) {
jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
return this.flatten().reduce( function ( a, b ) {
if ( typeof a === 'string' ) {
a = a.replace(/[^\d.-]/g, '') * 1;
}
if ( typeof b === 'string' ) {
b = b.replace(/[^\d.-]/g, '') * 1;
}
return a + b;
}, 0 );
} );
$("#crudTable tfoot").css("display", "table-footer-group");
crud.table.on("draw.dt", function ( row, data, start, end, display ) {
total = crud.table.rows( function ( idx, data, node ) {
return data[11].includes('Cancelado') ? false : true;} ).data().pluck(10).sum();
total = "$" + total.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
$("#crudTable tfoot tr th").html(
" <br> "
);
$("#crudTable tfoot tr").children().eq(10).html(
"Total <br>"+ total
);
});
});
And I added some modifications to get the total of the column by skipping the items that have canceled status, but I have not been able to get the total of the records but without paging. With Datatable I get the records that are being drawn, but I can't find how to intercept the ajax query or modify it to get the full total on that column including filter modifications.
Currently if in the pagination I request "show all records" obviously I get the value I need. But the requirement is that this value is displayed even if the table is visually paginated.

one way to achieve that would be to overwrite the search() function of the ListOperation (it's the table ajax endpoint).
You would need do do the full query without the pagination part to get the full data, and then pass the calculation along with the paginated response for display.
Cheers

Related

getProduct()->getTag() return null, when it should return tags associated to the Product

In my project, we have products that has tag called serviceItem. Those item with that tag when ordered should be separated by the quantity into individuals order.
It issue is that getTags() returns null, and getTagIds gets "Call to a member function getTagIds() on null" when it gets to the next loop.
Is there a reason for why getTags() returns null?
private function transformOrderLines(OrderEntity $order): array
{
/**
* TODO: If we need to send advanced prices,
* the price value of the the lines array should be changed to caldulate the advanced price,
* with the built in quantity calculator
*/
$lines = [];
foreach ($order->getLineItems() as $orderLine) {
$hasDsmServiceItemTag = $orderLine->getProduct()->getTags();
$lines[] = [
'name' => $orderLine->getLabel(),
'sku' => substr($orderLine->getProduct()->getProductNumber(), 0, 19),
'price' => (string) ($orderLine->getProduct()->getPrice()->first()->getNet()
* $order->getCurrencyFactor()), //gets original price, calculates factor
'quantity' => (string) $orderLine->getQuantity()
];
}
$shipping = $this->transformShipping($order);
if ($shipping) {
$lines = array_merge($lines, $shipping);
}
return $lines;
}`
I also tried $orderLine->getProduct()->getTags()->getName() it also return "Call to a member function getTags() on null"
The problem is wherever the $order is fetched from the DB the orderLineItem.product.tag association is not included in the criteria.
For performance reasons shopware does not lazily load all association when you access them on entities, but you have to exactly define which associations should be included when you fetch the entities from the database.
For the full explanation take a look at the docs.

How can I build a query scope in Laravel that takes data if sum of relative table column is between requested range?

I have two tables loads and stops. The Stops table has a price column. Loads' price is equal to the sum of stops' price related to the load. I want to build a scope that builds a query to get all loads where it's the price is in the requested range.
My scope:
public function scopeBetweenPrice($query, $from, $to) {
if ($from !== null || $to !== null) {
return $query;
}
return $query;
}

Dynamic column search in multiple tables with gorm golang

My scenario is i have a grid with search option where user can select the column and can do the search, the grid data is coming from various tables. I have attached a sample screen of grid.
User Screen
So i'm trying to create a dynamic query for search but the problem is i can able to search only in main table (schema.Robot) not in Preload tables. whenever i trying to search data data from Preload tables let say from RobotModel table that time getting below error
pq: missing FROM-clause entry for table "robot_models"
Here is my go code
func (r *RobotsRepository) GetRobotsSummary(listParams viewmodel.ListParams, companyID uint) ([]*schema.Robot, int, error) {
mrobots := []*schema.Robot{}
var count int
var order string
if listParams.SortColumn == "" {
listParams.SortColumn = "id"
listParams.SortOrder = 1
} else {
listParams.SortColumn = util.Underscore(listParams.SortColumn)
}
if listParams.SortOrder == 0 {
order = "ASC"
} else {
order = "DESC"
}
var searchQuery string
if listParams.SearchText != "" {
switch listParams.SearchColumn {
case "Robot":
listParams.SearchColumn = "name"
case "Model":
listParams.SearchColumn = "robot_models.name"
}
searchQuery = listParams.SearchColumn +" LIKE '%"+ listParams.SearchText +"%' and Company_ID = " + fmt.Sprint(companyID)
}else{
searchQuery = "Company_ID = " + fmt.Sprint(companyID)
}
orderBy := fmt.Sprintf("%s %s", listParams.SortColumn, order)
err := r.Conn.
Preload("RobotModel", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Name")
}).
Preload("Task", func(db *gorm.DB) *gorm.DB {
return db.Where("Task_Status in ('In-Progress','Pending')").Select("ID, Task_Status")
}).
Preload("CreatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Preload("UpdatedUser", func(db *gorm.DB) *gorm.DB {
return db.Select("ID,Display_Name")
}).
Where(searchQuery).
Order(orderBy).
Offset(listParams.PageSize * (listParams.PageNo - 1)).
Limit(listParams.PageSize).
Find(&mrobots).Error
r.Conn.Model(&schema.Robot{}).Where(searchQuery).Count(&count)
return mrobots, count, err
}
In searchQuery variable i'm storing my dynamic query.
My question is how can i search data for preload table columns
Here is the sql query which i'm trying to achieve using gorm
SELECT robots.id,robots.name,robot_models.name as
model_name,count(tasks.task_status) as task_on_hand,
robots.updated_at,users.user_name as updated_by
FROM rfm.robots as robots
left join rfm.tasks as tasks on tasks.robot_id = robots.id and
tasks.task_status in ('In-Progress','Pending')
left join rfm.robot_models as robot_models on robot_models.id =
robots.robot_model_id
left join rfm.users as users on users.id = robots.updated_by
WHERE robot_models.name::varchar like '%RNR%' and robots.deleted_at is null
GROUP BY robots.id,robot_models.name,users.user_name
ORDER BY task_on_hand DESC LIMIT 2 OFFSET 0
and sorry for bad English!
Even though you are preloading, you are still required to explicitly use joins when filtering and ordering on columns on other tables. Preloading is used to eagerly load the data to map into your models, not to join tables.
Chain on something like this:
.Joins("LEFT JOIN rfm.robot_models AS robot_models ON robot_models.id = robots.robot_model_id")
I'm not positive if you can use the AS keyword using this technique, but if not, it should be easy enough to adjust your query accordingly.

In typescript, how to sort exactly like MSSQL's 'order by' clause for special characters like * , + - etc

I have a Angular5 based front-end which needs to show a list of persons. A similar list is shown at the back-end application. Both lists need to be sorted exactly the same. The back-end list is fetched via a query in MSSQL DB which uses an 'order by' clause like this :
select * from PERSON where GROUP=1 order by PERSON.LAST_NAME ASC, PERSON.INITIALS ASC, PERSON.PREFIX ASC, PERSON.FIRSTNAME ASC
On the frontend, my person model looks like :
export interface Person {
id?: number;
fullName?: string;
}
The fullName here is as per this format : [LastName, Initials Prefix FirstName] eg : Adams, Mr P John.
I am using this method to sort it :
public sortByName(aPersonArr: Person[]) {
aPersonArr.sort((p1, p2) => {
let name1 = p1.fullName;
let name2 = p2.fullName;
// If both names are blank, consider them equal, If one name is blank, place it at the last
if (!name1 && !name2) {
return 0;
} else if (name1 && !name2) {
return -1;
} else if (name2 && !name1) {
return 1;
}
name1 = name1.toLowerCase();
name2 = name2.toLowerCase();
if (name1 < name2) {
return -1;
}
if (name1 > name2) {
return 1;
}
return 0;
});
}
}
But the problem occurs when a person's fullName begins with a special character because SQL Query fetches the names in this order : (Showing only the lastNames here)
*Account
,Adams
.Alkin
+Account
-Adams
Whereas my typescript code sorts them like this : (Showing only the lastNames here)
*Account
+Account
,Adams
-Adams
.Alkin
The reason that I need to have this logic at frontend is that many a times my person list is dynamically prepared and needs to be sorted right away. Is there a way to know what exact logic is used by SQL query to compare strings, so that i can use the same in my sorting method.

second entity query is executed with errors

I have 2 linq queries. First query does nothing because of unique index and this is OK. But second also does nothing while it should add records . If I bypass first query second query works. Should I refresh entity ? How ?
foreach (var product in productList)
{
cc2nexo_SubiektProduct newproduct = new cc2nexo_SubiektProduct();
newproduct.Name = product.Name;
newproduct.VAT = product.VAT;
newproduct.Id = product.Id;
foreach (var stawkaVAT in myNexo_ExitoEntities.StawkiVat)
{
if (stawkaVAT.Stawka * 100 == tryconvert_dec(newproduct.VAT))
{
newproduct.VAT_Id = stawkaVAT.Id;
}
}
myNexo_ExitoEntities.cc2nexo_SubiektProduct.Add(newproduct);
SurroundWithTryCatchDB(() =>
{
myNexo_ExitoEntities.SaveChanges();
});
}
var orders = (from myorders in myNexo_ExitoEntities.temp_SubiektOrderList
select myorders).ToList();
foreach (var order in orders)
{
cc2nexo_SubiektOrderList neworder = new cc2nexo_SubiektOrderList();
neworder.Data_utworzenia_sprawy = tryconvert_date(order.Data_utworzenia_sprawy);
neworder.Data_modyfikacji_sprawy = tryconvert_date(order.Data_modyfikacji_sprawy);
neworder.Data_umowy = tryconvert_date(order.Data_umowy);
neworder.Id = order.Id;
myNexo_ExitoEntities.cc2nexo_SubiektOrderList.Add(neworder);
SurroundWithTryCatchDB(() =>
{
myNexo_ExitoEntities.SaveChanges();
});
Debug.WriteLine(neworder.LastName);
}
I am receiving an error
Cannot insert duplicate key row in object 'dbo.cc2nexo_SubiektProduct' with unique index 'K_ID'. The duplicate key value is (1).The statement has been terminated
The reason of problem was SurroundWithTryCatchDB procedure not listed in my question. Because first query caused exception due to unique index all next SaveChanges did not work. I have changed my first query to work with unique values and now everything is OK.