MongoDB Aggregation in nested collection data - php

In a collection I'm saving all the Store wise transactions and there is a key named "items" inside all the documents which contains all the items of a particular sale.
Now I've to perform aggregation onto it and send the data somewhere else.
Below I've given the collection data
[{
"_id": {
"$oid": "63ee26bcb64550cbb20de158"
},
"employee": "1",
"custId": "6357cb852c61064d53040ff2",
"store_code": "BAN-01",
"store_no": "7",
"shift": "Second",
"employee_role": "POS Store Manager",
"store_name": "175",
"customer_name": "Vivek Kumar",
"customer_email": "vivek.kumar98705#gmail.com",
"customer_phone": "9958137221",
"counter_code": "175-Counter-01",
"deposit_amount": "100",
"emp_code": "TCP004",
"items": "[{\"internalid\":2969,\"type\":\"InvtPart\",\"islotitem\":true,\"isserialitem\":false,\"isspecialorderitem\":false,\"itemName\":\"201450\",\"price\":\"252.50\",\"qty\":\"1\",\"itemamount\":\"265.13\",\"mrp\":\"252.50\",\"discount\":\"0.00\",\"tax\":\"12.63\",\"promotion\":\"NA\",\"item_display_name\":\"UOM: BETADINE GARGLE 100ML\",\"item_upc_code\":\"5285239186\",\"item_hsn_code\":\"30041090\",\"uom\":\"EA\",\"batchDetails\":{\"#PJ0672\":{\"batch_expiry\":\"4/4/2025\",\"qty\":1}}},{\"internalid\":2963,\"type\":\"InvtPart\",\"islotitem\":true,\"isserialitem\":false,\"isspecialorderitem\":false,\"itemName\":\"225124\",\"price\":\"7.00\",\"qty\":\"15\",\"itemamount\":\"110.25\",\"mrp\":\"7.00\",\"discount\":\"0.00\",\"tax\":\"5.25\",\"promotion\":\"NA\",\"item_display_name\":\"UOM: ZINCOVIT 15TAB\",\"item_upc_code\":\"8035476959\",\"item_hsn_code\":\"21069099\",\"uom\":\"SH(15)\",\"batchDetails\":{\"#ZVT21203\":{\"batch_expiry\":\"4/4/2025\",\"qty\":15}}},{\"internalid\":3067,\"type\":\"InvtPart\",\"islotitem\":true,\"isserialitem\":false,\"isspecialorderitem\":false,\"itemName\":\"315043\",\"price\":\"1.70\",\"qty\":\"45\",\"itemamount\":\"80.33\",\"mrp\":\"1.70\",\"discount\":\"0.00\",\"tax\":\"3.83\",\"promotion\":\"NA\",\"item_display_name\":\"UOM: FOLVITE 45TAB\",\"item_upc_code\":\"9312066071\",\"item_hsn_code\":\"30045039\",\"uom\":\"SH(45)\",\"batchDetails\":{\"#GH3735\":{\"batch_expiry\":\"4/4/2025\",\"qty\":45}}},{\"internalid\":3069,\"type\":\"InvtPart\",\"islotitem\":true,\"isserialitem\":false,\"isspecialorderitem\":false,\"itemName\":\"204009\",\"price\":\"75.44\",\"qty\":\"10\",\"itemamount\":\"792.12\",\"mrp\":\"75.44\",\"discount\":\"0.00\",\"tax\":\"37.72\",\"promotion\":\"NA\",\"item_display_name\":\"UOM: DUPHASTON 10TAB\",\"item_upc_code\":\"3444014334\",\"item_hsn_code\":\"30043919\",\"uom\":\"SH(10)\",\"batchDetails\":{\"#KAVA2050\":{\"batch_expiry\":\"4/4/2025\",\"qty\":10}}}]",
"total_amount": 1247.83,
"total_tax": 59.43,
"total_discount": 0,
"subTotal": 1188.4,
"payment_details": [
[
{
"paymentMethod": "cash",
"amount_paid": 1247.83,
"transaction_date": "2/16/2023 4:58:19 pm",
"payment_status": "Success",
"transaction_id": "test123"
}
]
],
"auth_id": "master_ad14cca679b44ef1d78a3e_master",
"created_by": "master_ad14cca679b44ef1d78a3e_master",
"updated_by": "master_ad14cca679b44ef1d78a3e_master",
"invoice_no": "WFINV#1",
"updated_at": {
"$date": {
"$numberLong": "1676551868017"
}
},
"created_at": {
"$date": {
"$numberLong": "1676551868017"
}
}
},
{
"_id": {
"$oid": "63ee2778b64550cbb20de17c"
},
"employee": "1",
"custId": "6357cb852c61064d53040ff2",
"store_code": "BAN-01",
"store_no": "7",
"shift": "Second",
"employee_role": "POS Store Manager",
"store_name": "175",
"customer_name": "Vivek Kumar",
"customer_email": "vivek.kumar98705#gmail.com",
"customer_phone": "9958137221",
"counter_code": "175-Counter-01",
"deposit_amount": "100",
"emp_code": "TCP004",
"items": "[{\"internalid\":\"undefined\",\"type\":\"undefined\",\"islotitem\":true,\"isserialitem\":false,\"isspecialorderitem\":false,\"itemName\":\"\",\"price\":\"2.30\",\"qty\":\"20\",\"itemamount\":\"48.30\",\"mrp\":\"2.30\",\"discount\":\"0.00\",\"tax\":\"2.3\",\"promotion\":\"NA\",\"item_display_name\":\"UOM: COMBIFLAM 20TAB\",\"item_upc_code\":\"UPC000004\",\"item_hsn_code\":\"30049063\",\"uom\":\"SH(20)\",\"batchDetails\":{\"#1022563\":{\"batch_expiry\":\"4/4/2025\",\"qty\":20}}},{\"internalid\":\"undefined\",\"type\":\"undefined\",\"islotitem\":true,\"isserialitem\":false,\"isspecialorderitem\":false,\"itemName\":\"\",\"price\":\"93.00\",\"qty\":\"1\",\"itemamount\":\"97.65\",\"mrp\":\"93.00\",\"discount\":\"0.00\",\"tax\":\"4.65\",\"promotion\":\"NA\",\"item_display_name\":\"UOM: FEBREX-PLUS DS SYP 60ML\",\"item_upc_code\":\"1036121752\",\"item_hsn_code\":\"30049093\",\"uom\":\"EA\",\"batchDetails\":{\"#22430041\":{\"batch_expiry\":\"4/4/2025\",\"qty\":1}}}]",
"total_amount": 145.95,
"total_tax": 6.95,
"total_discount": 0,
"subTotal": 139,
"payment_details": [
[
{
"paymentMethod": "cash",
"amount_paid": 145.95,
"transaction_date": "2/16/2023 4:54:25 pm",
"payment_status": "Success",
"transaction_id": "test123"
}
]
],
"auth_id": "master_ad14cca679b44ef1d78a3e_master",
"created_by": "master_ad14cca679b44ef1d78a3e_master",
"updated_by": "master_ad14cca679b44ef1d78a3e_master",
"invoice_no": "WFINV#4",
"updated_at": {
"$date": {
"$numberLong": "1676552056047"
}
},
"created_at": {
"$date": {
"$numberLong": "1676552056047"
}
}
}
]
I Tried the below aggregation but it didn't work.
$data = \DB::collection("online_orders")->raw(function($collection) use ($requestData) {
return $collection->aggregate([
[
'$match' => [
'created_at' => [
'$gte' => $requestData['from'],
'$lte' => $requestData['to']
]
],
'$group' => [
'_id' => [
'store_code' => '$store_code',
'sku' => '$items.itemName'
],
'items' => '$items',
'sold_qty' => [ '$sum' => '$items.qty' ]
]
]
]);
});
After Pipeline
Expected Result :
Result Keys relation to the collection keys just for reference**
sku -> itemName
sold_qty -> how many time that particular item has been sold store code wise
return_qty -> curerntly leave it as 0
total_amount -> total amount of particular item sold
uom -> uom
batchNo -> batchDetails key is batchNo
Quantity -> batchDetails -- qty
{
"order_type": "CS",
"data": [
{
"store_code": "175",
"cash_sale_details": [
{
"sku": "321405",
"sold_qty": "5",
"return_qty": "0",
"total_amount": "69.83",
"uom": "EA",
"batchDetails": [
{
"batchNo": "LOT121",
"Quantity": 5
}
]
},
{
"sku": "223327",
"sold_qty": "5",
"return_qty": "0",
"total_amount": "488.25",
"uom": "EA",
"batchDetails": [
{
"batchNo": "22430041",
"Quantity": 5
}
]
},
{
"sku": "222045",
"sold_qty": "5",
"return_qty": "0",
"total_amount": "842.89",
"uom": "EA",
"batchDetails": [
{
"batchNo": "B2329D164",
"Quantity": 5
}
]
},
{
"sku": "341106",
"sold_qty": "5",
"return_qty": "0",
"total_amount": "623.44",
"uom": "EA",
"batchDetails": [
{
"batchNo": "AS2211",
"Quantity": 5
}
]
}
]
}
]
}
Thanks

Related

PNR generating issue using amadeus flight create orders API

I want to create booking and generate PNR using amadeus flight booking API.
I have follow 3 step to create booking and generate PNR
Flight Offers Search API using bellow API
https://developers.amadeus.com/self-service/category/air/api-doc/flight-offers-search/api-reference
Flight Offers Price API using bellow API
https://developers.amadeus.com/self-service/category/air/api-doc/flight-offers-price/api-reference
Flight Create Orders API using bellow API
https://developers.amadeus.com/self-service/category/air/api-doc/flight-create-orders/api-reference
When i serach with city with one way thip and choose specific offer and puting passenger details
to create booking and generat PNR. then PNR will generate successfully
i am using bellow API to generate PNR
https://developers.amadeus.com/self-service/category/air/api-doc/flight-create-orders/api-reference
this is my request json
"data": {
"type": "flight-order",
"flightOffers": [
{
"type": "flight-offer",
"id": "5",
"source": "GDS",
"instantTicketingRequired": false,
"nonHomogeneous": false,
"paymentCardRequired": false,
"lastTicketingDate": "2021-07-23",
"itineraries": [
{
"segments": [
{
"departure": {
"iataCode": "JFK",
"terminal": "5",
"at": "2021-07-30T09:20:00"
},
"arrival": {
"iataCode": "FLL",
"terminal": "3",
"at": "2021-07-30T12:30:00"
},
"carrierCode": "B6",
"number": "201",
"aircraft": {
"code": "320"
},
"operating": {
"carrierCode": "B6"
},
"duration": "PT3H10M",
"id": "91",
"numberOfStops": 0,
"co2Emissions": [
{
"weight": 155,
"weightUnit": "KG",
"cabin": "ECONOMY"
}
]
},
{
"departure": {
"iataCode": "FLL",
"terminal": "3",
"at": "2021-07-30T16:25:00"
},
"arrival": {
"iataCode": "LAX",
"terminal": "5",
"at": "2021-07-30T18:49:00"
},
"carrierCode": "B6",
"number": "1301",
"aircraft": {
"code": "32S"
},
"operating": {
"carrierCode": "B6"
},
"duration": "PT5H24M",
"id": "92",
"numberOfStops": 0,
"co2Emissions": [
{
"weight": 253,
"weightUnit": "KG",
"cabin": "ECONOMY"
}
]
}
],
"duration": "PT12H29M"
}
],
"price": {
"currency": "USD",
"total": "276.20",
"base": "235.35",
"fees": [
{
"amount": "0.00",
"type": "SUPPLIER"
},
{
"amount": "0.00",
"type": "TICKETING"
},
{
"amount": "0.00",
"type": "FORM_OF_PAYMENT"
}
],
"grandTotal": "276.20",
"billingCurrency": "USD"
},
"pricingOptions": {
"fareType": [
"PUBLISHED"
],
"includedCheckedBagsOnly": false
},
"validatingAirlineCodes": [
"B6"
],
"travelerPricings": [
{
"travelerId": "1",
"fareOption": "STANDARD",
"travelerType": "ADULT",
"price": {
"currency": "USD",
"total": "276.20",
"base": "235.35",
"taxes": [
{
"amount": "8.60",
"code": "ZP"
},
{
"amount": "5.60",
"code": "AY"
},
{
"amount": "17.65",
"code": "US"
},
{
"amount": "9.00",
"code": "XF"
}
],
"refundableTaxes": "40.85"
},
"fareDetailsBySegment": [
{
"segmentId": "91",
"cabin": "ECONOMY",
"fareBasis": "OL7AUEL1",
"brandedFare": "DN",
"class": "L",
"includedCheckedBags": {
"quantity": 0
}
},
{
"segmentId": "92",
"cabin": "ECONOMY",
"fareBasis": "ZI3PUEL1",
"brandedFare": "DN",
"class": "L",
"includedCheckedBags": {
"quantity": 0
}
}
]
}
]
}
],
"travelers": [
{
"id": 1,
"dateOfBirth": "**********",
"name": {
"firstName": "**********",
"lastName": "**********"
},
"gender": "**********"
}
],
"contacts": [
{
"addresseeName": {
"firstName": "**********",
"lastName": "**********"
},
"purpose": "STANDARD",
"emailAddress": "**********",
"phones": [
{
"deviceType": "MOBILE",
"countryCallingCode": "**",
"number": "**********"
}
],
"address": {
"lines": [
"**********"
],
"postalCode": "**********",
"cityName": "**********",
"countryCode": "**********"
}
}
],
"remarks": {
"general": [
{
"subType": "GENERAL_MISCELLANEOUS",
"text": "ONLINE BOOKING FROM INCREIBLE VIAJES"
}
]
},
"ticketingAgreement": {
"option": "DELAY_TO_CANCEL",
"delay": "6D"
}
}
}
and this is my API response.
PNR generated successfully/
stdClass Object
(
[warnings] => Array
(
[0] => stdClass Object
(
[status] => 200
[code] => 0
[title] => ContactInfoSsrNotAddedToBookingWarning
[detail] => Unable to create some contact information SSR. Email and mobile phone number required.
)
)
[data] => stdClass Object
(
[type] => flight-order
[id] => eJzTd9f3cg228PcBAAskAls%3D
[associatedRecords] => Array
(
[0] => stdClass Object
(
[reference] => JES8OL
[creationDate] => 2021-07-23T10:28:00.000
[originSystemCode] => GDS
[flightOfferId] => 5
)
)
[flightOffers] => Array
(
[0] => stdClass Object
(
[type] => flight-offer
[id] => 5
[source] => GDS
[nonHomogeneous] =>
[lastTicketingDate] => 2021-07-23
[itineraries] => Array
But when i search with differnt city and follow the same step.
this is my request json
data": {
"type": "flight-order",
"flightOffers": [
{
"type": "flight-offer",
"id": "3",
"source": "GDS",
"instantTicketingRequired": false,
"nonHomogeneous": false,
"paymentCardRequired": false,
"lastTicketingDate": "2021-07-28",
"itineraries": [
{
"segments": [
{
"departure": {
"iataCode": "DEL",
"terminal": "3",
"at": "2021-08-05T05:35:00"
},
"arrival": {
"iataCode": "BLR",
"at": "2021-08-05T08:20:00"
},
"carrierCode": "AI",
"number": "803",
"aircraft": {
"code": "32B"
},
"operating": {
"carrierCode": "AI"
},
"duration": "PT2H45M",
"id": "17",
"numberOfStops": 0,
"co2Emissions": [
{
"weight": 145,
"weightUnit": "KG",
"cabin": "ECONOMY"
}
]
}
],
"duration": "PT2H45M"
},
{
"segments": [
{
"departure": {
"iataCode": "BLR",
"at": "2021-08-10T17:10:00"
},
"arrival": {
"iataCode": "DEL",
"terminal": "3",
"at": "2021-08-10T19:55:00"
},
"carrierCode": "AI",
"number": "501",
"aircraft": {
"code": "32B"
},
"operating": {
"carrierCode": "AI"
},
"duration": "PT2H45M",
"id": "42",
"numberOfStops": 0,
"co2Emissions": [
{
"weight": 145,
"weightUnit": "KG",
"cabin": "ECONOMY"
}
]
}
],
"duration": "PT2H45M"
}
],
"price": {
"currency": "USD",
"total": "88.59",
"base": "68.00",
"fees": [
{
"amount": "0.00",
"type": "SUPPLIER"
},
{
"amount": "0.00",
"type": "TICKETING"
},
{
"amount": "0.00",
"type": "FORM_OF_PAYMENT"
}
],
"grandTotal": "88.59",
"billingCurrency": "USD"
},
"pricingOptions": {
"fareType": [
"PUBLISHED"
],
"includedCheckedBagsOnly": true
},
"validatingAirlineCodes": [
"AI"
],
"travelerPricings": [
{
"travelerId": "1",
"fareOption": "STANDARD",
"travelerType": "ADULT",
"price": {
"currency": "USD",
"total": "88.59",
"base": "68.00",
"taxes": [
{
"amount": "6.34",
"code": "P2"
},
{
"amount": "3.78",
"code": "IN"
},
{
"amount": "3.63",
"code": "K3"
},
{
"amount": "2.28",
"code": "WO"
},
{
"amount": "4.56",
"code": "YR"
}
],
"refundableTaxes": "17.19"
},
"fareDetailsBySegment": [
{
"segmentId": "17",
"cabin": "ECONOMY",
"fareBasis": "SAP8",
"class": "S",
"includedCheckedBags": {
"weight": 25,
"weightUnit": "KG"
}
},
{
"segmentId": "42",
"cabin": "ECONOMY",
"fareBasis": "SAP8",
"class": "S",
"includedCheckedBags": {
"weight": 25,
"weightUnit": "KG"
}
}
]
}
]
}
],
"travelers": [
{
"id": 1,
"dateOfBirth": "**********",
"name": {
"firstName": "**********",
"lastName": "**********"
},
"gender": "**********"
}
],
"contacts": [
{
"addresseeName": {
"firstName": "**********",
"lastName": "**********"
},
"purpose": "STANDARD",
"emailAddress": "**********",
"phones": [
{
"deviceType": "**********",
"countryCallingCode": "**",
"number": "**********"
}
],
"address": {
"lines": [
"**********"
],
"postalCode": "**********",
"cityName": "**********",
"countryCode": "**********"
}
}
],
"remarks": {
"general": [
{
"subType": "GENERAL_MISCELLANEOUS",
"text": "ONLINE BOOKING FROM INCREIBLE VIAJES"
}
]
},
"ticketingAgreement": {
"option": "DELAY_TO_CANCEL",
"delay": "6D"
}
}
and this is my API response.
stdClass Object
(
[errors] => Array
(
[0] => stdClass Object
(
[status] => 400
[code] => 34651
[title] => SEGMENT SELL FAILURE
[detail] => Could not sell segment 2
[source] => stdClass Object
(
[pointer] => /data/flightOffers[0]/itineraries[1]/segments[0]
)
)
)
)
Can you please guide me what is the issue.I am using amadeus test API credential.Also guide me how to solve the issue
Thank You
You usually get this error when trying to book a seat that is not available anymore. You are using the test environment, it means everybody else using Amadeus for Developers in test can be trying to book the same seat.
Try with another flight and don't forget to perform the Flight Offers Price before booking.
PS: I see some personal data in the example above, you should edit your post to remove it.

creating json file from database

I need to create this json in the following format
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "5.00"
},
{
"productName": "Product 2",
"quantity": "2",
"price": "24.00"
},
{
"productName": "Product 3",
"quantity": "1",
"price": "6.50"
}
]
},
{
"orderId": "2",
"orderDate": "2/06/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "3.00"
},
{
"productName": "Product 2",
"quantity": "1",
"price": "11.50"
}
]
},
{
"orderId": "3",
"orderDate": "03/05/2021",
"products": [
{
"productName": "Product 1",
"quantity": "1",
"price": "3.00"
},
{
"productName": "Product 2",
"quantity": "1",
"price": "11.50"
}
]
}
]
}
This is my code that I use to retrive the information from the database
$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
$message[] = array(
"status" => true,
"message" => "",
"orders" => array(
array(
"orderId" => "$OrderID",
"orderDate" => "$OrderDate",
"products" => array(
array(
"productName" => "$ProductName",
"quantity" => "$ProductQty",
"price" => "$ProductPrice"
),
)
)
)
);
}
$json = $message;
header('content-type: application/json');
echo json_encode($json);
This is how the information from the database displays. I do not know how to show the information about the products correctly. Can anyone show me how to do it in the format that I require in php? Thanks in advance for any help.
[
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "620",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "240",
"quantity": "1",
"price": "5.00"
},
{
"productName": "270",
"quantity": "1",
"price": "10.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "30",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "280",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "610",
"quantity": "1",
"price": "5.00"
}
]
}
]
}
]
You are repeating the orders structure which you shouldn't. That's why you get the wrong structure. This is what you should do instead (your code, modified):
// specify your return response array only once
$message = array(
"status" => true,
"message" => "",
"orders" => array();
);
$stmt = $con->prepare("SELECT OrderID, OrderDate, ProductName, ProductQty, ProductPrice FROM Orders where CustomerID = ?");
$stmt->bind_param("s", $CustomerID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($OrderID, $OrderDate, $ProductName, $ProductQty, $ProductPrice);
while($stmt->fetch()) {
// and fill its "orders" member with your orders list
$message["orders"][] = array(
"orderId" => "$OrderID",
"orderDate" => "$OrderDate",
"products" => array(
array(
"productName" => "$ProductName",
"quantity" => "$ProductQty",
"price" => "$ProductPrice"
),
)
);
}
$json = $message;
header('content-type: application/json');
echo json_encode($json);
You can try like below
const data = [
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "620",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "240",
"quantity": "1",
"price": "5.00"
},
{
"productName": "270",
"quantity": "1",
"price": "10.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "30",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "280",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": true,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "610",
"quantity": "1",
"price": "5.00"
}
]
}
]
},
{
"status": false,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "800",
"quantity": "50",
"price": "5.00"
}
]
}
]
},
{
"status": false,
"message": "",
"orders": [
{
"orderId": "1",
"orderDate": "1/06/2021",
"products": [
{
"productName": "1800",
"quantity": "50",
"price": "5.00"
}
]
}
]
}
];
const resutl = data.reduce((acc, cur) => {
const key = cur.status ? "successItems" : "failureItems";
if (acc[key]) {
return {
...acc,
[key]: {
status: cur.status,
messgae: '',
orders: [
...acc[key].orders,
...cur.orders
]
}
}
} else {
return {
...acc,
[key]: {
status: cur.status,
messgae: '',
orders: [
...cur.orders
]
}
}
}
}, {});
console.log('resutl', resutl);
console.log('resutl', Object.values(resutl));

Calculate the total of amount by category in Laravel

I make this query :
$expenses = Expense::where('team_id', Auth::user()->currentTeam->id)
->with(['categories'])
->orderBy('entry_date', 'DESC')
->get();
ExpenseSumByCategoryResource :
return [
'id' => Hashids::encode($this->id),
'entry_date' => $this->entry_date,
'amount' => $this->amount,
'category' => $this->category->name
];
Response :
"expenses": [
{
"id": "GO3W1MkgWkngpnByQ6",
"entry_date": "2020-10-14",
"amount": "50.00",
"category": "Health"
},
{
"id": "7vK6bz0gnG7JBOYRLD",
"entry_date": "2020-10-14",
"amount": "30.00",
"category": "Uncategorize"
},
{
"id": "7vK6bz0gnG7JBOYRLD",
"entry_date": "2020-10-14",
"amount": "30.00",
"category": "Health"
},
{
"id": "7vK6bz0gnG7JBOYRLD",
"entry_date": "2020-10-14",
"amount": "30.00",
"category": "Food"
},
]
I would like to calculate, by category, the sum of "amount".
Ideally, I would like to have a result which is this :
"expenses": [
{
"category": "Health"
"total_amount": "80.00",
},
{
"category": "Uncategorized"
"total_amount": "30.00",
},
{
"category": "Food"
"total_amount": "30.00",
},
]
You may try adding a select() and groupBy() which makes sense for your query:
$expenses = Expense::select('category', DB::raw('SUM(amount) AS total_amount'))
->where('team_id', Auth::user()->currentTeam->id)
->groupBy('category')
->with(['categories'])
->orderBy('category')
->get();

Update Value on Multi-dimensional Array?

I would like to update destinos.origenes.base_price based on destinos.ciudad_id and destinos_origenes.ciudad_id, so far this is what I am been doing witouth success:
//
$updateResult2 = $coll_rutas->updateOne(
/* CONDITION */
[
"_id" => new \MongoDB\BSON\ObjectId($ruta_id),
"destinos.ciudad_id" => 1, // for morelia, mich
"destinos.origenes.ciudad_id" => 122 // for selma, ca
],
/* update */
[
'$set' => [
'destinos.$[].origenes.$[].base_price' => $destino_origen_amount
]
]
);
This is the mongo object:
{
"id": "5e27ee3e09558a0570003132",
"nombre": "THE RUTA"
"clave": "TR",
"descripcion": null,
"active": true,
"destinos": [
{
"ciudad_id": "1",
"nombre_destino": "Morelia, Mich",
"orden": "1",
"notas": null,
"origenes": [
{
"ciudad_id": "12",
"nombre_origen": "Tlaltenango, Zac",
"orden": "1",
"notas": null,
"base_price": "666.66"
},
{
"ciudad_id": "30",
"nombre_origen": "Camargo, Chih",
"orden": "2",
"notas": null,
"base_price": "666.66"
},
{
"ciudad_id": "122",
"nombre_origen": "Selma, Ca",
"orden": "3",
"notas": null,
"base_price": "666.66"
}
]
},
{
"ciudad_id": "2",
"nombre_destino": "Zamora, Mich",
"orden": "2",
"notas": null,
"origenes": [
{
"ciudad_id": "12",
"nombre_origen": "Tlaltenango, Zac",
"orden": "1",
"notas": null,
"base_price": "666.66"
},
{
"ciudad_id": "30",
"nombre_origen": "Camargo, Chih",
"orden": "2",
"notas": null,
"base_price": "666.66"
},
{
"ciudad_id": "122",
"nombre_origen": "Selma, Ca",
"orden": "3",
"notas": null,
"base_price": "666.66"
}
]
}
]
}
With arrayFilters works fine, I tested with your object example.
db.getCollection('temp').update({}, {
$set: {
"destinos.$[d].origenes.$[o].base_price":450
},
}, {
arrayFilters: [
{
"d.ciudad_id": "1",
},
{
"o.ciudad_id": "122"
}
]
})
And check this: https://www.php.net/manual/es/mongodb-driver-bulkwrite.update.php because arrayFilter is an element in the options.
[
"_id" => new \MongoDB\BSON\ObjectId($ruta_id)
],
[
'$set' => [
"destinos.$[d].origenes.$[o].base_price" => 450
]
],
[
"arrayFilters" =>
[
["d.ciudad_id" => "1"],["o.ciudad_id" => "122"]
]
]

json decode error on some requests but not others with Algolia php library

I'm seeing the following error:
My params are
array (size=4)
'facets' => string 'Instock.1' (length=9)
'facetFilters' => string 'inStock.1:1' (length=11)
'numericFilters' => string 'itemId!=511283' (length=14)
'getRankingInfo' => int 1
If I remove either getRankingInfo or numericFilters, it works for all requests.
According to the logs in Algolia it's returning results, but i don't get that far on my end for some requests.
One response that causes the error to appear is:
Request
{
"params": "facets=Instock.1&facetFilters=inStock.1%3A1&numericFilters=itemId%21%3D511283&getRankingInfo=1&query=WARBURTON+ORANGE+WRAPPER+800G"
}
Response
{
"hits": [
{
"itemId": 506241,
"name": "Warburton Blue Wrapper 800g",
"slug": "506241-warburton-blue-wrapper",
"brand": "Warburton",
"supplier_name": "Warburtons Bread",
"size": "800G",
"status": "L",
"vat_rate": "0.00",
"popularity": 18992,
"image": "/images/products/506241.jpg",
"thumbnail": "/images/products/506241_thumbnail.jpg",
"barcodes": [
"5010044000039"
],
"branches": [
1,
2,
4,
5,
6
],
"deepestCategory": "07013033337",
"inStock": {
"1": 1,
"2": 0,
"4": 1,
"5": 1,
"6": 1
},
"alternatives": [
],
"objectID": "506241",
"_highlightResult": {
"name": {
"value": "<em>Warburton</em> Blue <em>Wrapper</em> <em>800g</em>",
"matchLevel": "partial",
"matchedWords": [
"warburton",
"wrapper",
"800g"
]
},
"barcodes": [
{
"value": "5010044000039",
"matchLevel": "none",
"matchedWords": [
]
}
]
},
"_rankingInfo": {
"nbTypos": 0,
"firstMatchedWord": 0,
"proximityDistance": 10,
"userScore": 21542,
"geoDistance": 0,
"geoPrecision": 1,
"nbExactWords": 3,
"words": 3
}
},
{
"itemId": 511294,
"name": "Warburton Green Wrapper ",
"slug": "511294-warburton-green-wrapper",
"brand": "Warburton",
"supplier_name": "Warburtons Bread",
"size": "",
"status": "L",
"vat_rate": "0.00",
"popularity": 78098,
"image": "/images/products/511294.jpg",
"thumbnail": "/images/products/511294_thumbnail.jpg",
"barcodes": [
"5010044002347"
],
"branches": [
1,
2,
4,
5,
6
],
"deepestCategory": "07013033337",
"inStock": {
"1":
One that works fine is:
Request body
{
"params": "facets=Instock.1&facetFilters=inStock.1%3A1&numericFilters=itemId%21%3D558471&getRankingInfo=1&query=I+CAN%27T+BELIEVE+IT%27S+NOT+BUTTER+2KG"
}
Response
{
"hits": [
{
"itemId": 581691,
"name": "I Can't Believe Its Not Butter 500g",
"slug": "581691-i-cant-believe-its-not-butter",
"brand": "I Can't Believe",
"supplier_name": "U.lever Bestfoods (chilled)",
"size": "500G",
"status": "L",
"vat_rate": "0.00",
"popularity": 36597,
"image": "/images/products/581691.jpg",
"thumbnail": "/images/products/581691_thumbnail.jpg",
"barcodes": [
"000118039904",
"05000118039904",
"5000241007009"
],
"branches": [
1,
2,
3,
4,
5,
6
],
"deepestCategory": "07015269103",
"inStock": {
"1": 1,
"2": 1,
"3": 1,
"4": 1,
"5": 1,
"6": 1
},
"alternatives": [
],
"objectID": "581691",
"_highlightResult": {
"name": {
"value": "<em>I</em> <em>Can't</em> <em>Believe</em> <em>Its</em> <em>Not</em> <em>Butter</em> 500g",
"matchLevel": "partial",
"matchedWords": [
"i",
"can",
"t",
"believe",
"it",
"s",
"not",
"butter"
]
},
"barcodes": [
{
"value": "000118039904",
"matchLevel": "none",
"matchedWords": [
]
},
{
"value": "05000118039904",
"matchLevel": "none",
"matchedWords": [
]
},
{
"value": "5000241007009",
"matchLevel": "none",
"matchedWords": [
]
}
]
},
"_rankingInfo": {
"nbTypos": 0,
"firstMatchedWord": 0,
"proximityDistance": 22,
"userScore": 15914,
"geoDistance": 0,
"geoPrecision": 1,
"nbExactWords": 6,
"words": 8
}
},
{
"itemId": 247577,
"name": "I Can't Believe Its Not Butter 250g"
It seems the result set was causing an error with json_decode. When I limited the hitsPerPage to 10 all works fine. So the answer here is to paginate large sets, obvious really.
Thanks to all who read and commented.

Categories