Hybris ModelService remove not removing - sap-commerce-cloud

I'm trying to remove all the Stock from query products in a cronjob:
List<ProductModel> products = flexibleSearchService.search(GET_SPECIAL_PRODUCTS_QUERY);
for (ProductModel product : products.getResult()) {
modelService.removeAll(product.getStockLevels());
}
If I debug here I can see that all the products have stock, however, after performing the removeAll method from model Service, the Stock is not removed.
How can I fix this?

Related

Mongoose needs 2 times excecution to update collection

Something strange is going on or something idiotic I did but I got the following problem.
I got aenter code here web app where I have an online menu for a restaurant.
The structure of the products is as follows.
Facility->Category->Item->Name
So all item models have saved the name of the category they belong to as a string.
But sometimes you want to change the name of the category. What I wanted to do was find all the items in this category and change the name of the assigned category to the new one. Everything looked great until I saw that it took two times to run the controller that changed the name of the category and on the items to fully save the new name to the items.
The category changed the name but the items updated to the new name on the second run. Weird right?
So, what is that you can see that I don't and I implemented the silliest way of bugfix in the history of bugfixes.
Here is the controller - route.
module.exports.updateCtg = async(req,res)=>{
const {id} = req.params;
for(i=0;i<2; i++){
category = await CategoryModel.findByIdAndUpdate(id,{...req.body.category});
await category.save();
items = await ItemModel.find({});
for(item of items){
if(item.facility === category.facility){
item.category = category.name;
await single.save();
}
}
}
res.render('dashboard/ctgview', {category._id});
}
The findByIdAndUpdate function returns the found document, i.e. the document before any updates are applied.
This means that on the first run through category is set to the original document. Since the following loop uses category.name, it is setting the category of each item to the unmodified name.
The second iteration find the modified document, and the nested loop uses the new value in category.name.
To get this in a single pass, use
item.category = req.category.name;
or if you aren't certain it will contain a new name, use
item.category = req.category.name || category.name;
Or perhaps instead of a loop, use updateMany
if (req.category.name) {
ItemModel.updateMany(
{"item.facility": category.facility},
{"item.category": req.category.name}
)
}

How to get the total quantity of products sold? Node

In the product table add one field like sellcounter and do following the operation.
After placing an order make one update query in product Table Like...
await productModel.updateAll({
id: product.id
}, {
sellcounter: product.sellcounter + 1
});
Above code is for loopback Node
The idea here is to increment the number of sales by one on a specific product.
To do so, you'll need to use the method findOne or findById to update the specific product.
The resulted code should look like this (assuming that you have the product object with its id):
const productToUpdate = await productModel.findById(product.id);
await productToUpdate.updateAttributes({ sellcounter: product.sellcounter + 1 });

insert and update multiple documents mongodb

I know there's a lot of threads about this subject - but i still didn't find anything that matches my situation.
There is a big database with companies and products schema's.
Each company uploads their products, (product has "company" field with the mongo id of the company)
My operation goes like this -
Company uploads array of products.
Each product has his own productId.
I need to insert all the products in to the DB but -
If i find product with the same productId - update it - if not - insert a new product.
Change some fields (change product "status" to "deleted") to all of the products that belongs to that company in the DB, that didn't match any of the product id's (from the array of products the user uploaded).
I'm searching for a better solution than the one i'm using, my process goes like this -
fetching all the company's products.
looping through all of the products - and updating a field (status = "deleted") building a mapping object for each product, so i can identify it and check if it exists in the uploaded array.
looping through the company's array (with async library), checking if product exists (in the mapping array), if exists - updating it, if not - create a new product.
It feels very sloppy and i'm sure there is a better way to do it.
the thing i tried to use is -
await Product.updateMany({ productStatus: { $ne: 'manual'} , company: {$eq: company._id}}, { $set: {status: 'deleted' }});
and then
Product.bulkWrite(
productsArray.map((row) =>
({
updateOne: {
filter: { productId: row.productId, company: row.company },
update: row,
upsert: true
}
})
)
)
It was super slow (my method was faster even thought it's more complicated)
If i find product with the same productId - update it - if not - insert a new product.
You can use upserts, which is a find-and-modify operation with upsert: true set. Pass the whole product document.
Change some fields (change product "status" to "deleted") to all of the products that belongs to that company in the DB, that didn't match any of the product id's (from the array of products the user uploaded).
You can use $nin to update the status on all products whose ids are not in the list of currently available products.

How do I find the history of transactions for an Asset in a blockchain implemented using hyperledger-composer?

I'm working on the latest rev of hyperledger-composer (V0.13) and have built a network with multiple roles, each of which can invoke selected transactions within the blockchain. I would now like to query the blockchain (?Historian?) for all transactions which have been executed against a specific Order (defined type of asset).
I've used two different appoaches to pulling Historian data, once through direct API access historian.getall() and the other through a defined query:
query getHistorianRecords {
description: "get all Historian records"
statement: SELECT org.hyperledger.composer.system.HistorianRecord
}
Both queries succeed in that they return all transactions within the system. per ex:
ValidatedResource {
'$modelManager': ModelManager { modelFiles: [Object] },
'$namespace': 'org.hyperledger.composer.system',
'$type': 'HistorianRecord',
'$identifier': '0c3274475fed3703692bb7344453ab0910686905451b41d5d08ff1b032732aa1',
'$validator': ResourceValidator { options: {} },
transactionId: '0c3274475fed3703692bb7344453ab0910686905451b41d5d08ff1b032732aa1',
transactionType: 'org.acme.Z2BTestNetwork.CreateOrder',
transactionInvoked:
Relationship {
'$modelManager': [Object],
'$namespace': 'org.acme.Z2BTestNetwork',
'$type': 'CreateOrder',
'$identifier': '0c3274475fed3703692bb7344453ab0910686905451b41d5d08ff1b032732aa1',
'$class': 'Relationship' },
eventsEmitted: [],
transactionTimestamp: 2017-09-22T19:32:48.182Z }
What I can't find, and need, is a way to query the history of transactions against a single Order. An Order is defined (partial listing) as follows:
asset Order identified by orderNumber {
o String orderNumber
o String[] items
o String status
...
o String approved
o String paid
--> Provider provider
--> Shipper shipper
--> Buyer buyer
--> Seller seller
--> FinanceCo financeCo
What I'm looking for is a mechanism that will allow me to query the blockchain to get every record pertaining to an Order with orderNumber = '009'. I can, and have, easily found the current state of Order # 009, but am now looking for the history of transactions against that order. How to I tell Historian, or another service in the hyperledger-composer system, to give me that information?
What you are trying to do makes total sense, however the Historian doesn't yet support it. This requirement is being tracked here:
https://github.com/hyperledger/composer/issues/991
The plan is to add metadata into the HistorianRecord to capture the IDs of the assets and participants that where impacted by the transaction along with the operation performed (delete, update, create, read?).
Once that is in place you will be able to query for HistorianRecords that reference a given asset/participant id.
My work around is to have the transaction emit the results as event and have a query to then fetch the transaction by id from HistorianRecords which will contains the results emitted as event before.
I've posted the detailed answer here:
https://github.com/hyperledger/composer/issues/2458#issuecomment-383377837
A good workaround would be write a script function to update asset , emit the results as an event . And filter it from the rest endpoint in transactions tab .
One workaround solution is to emit an Event for your transaction. Mention ASSET as a field of the event. Please experiment with the following code.
let historian = await businessNetworkConnection.getHistorian();
let historianRecords = await historian.getAll();
for(let i=0; i< historianRecords.length;i++)
{console.log(historianRecords[i].transactionId+ "-----> " + historianRecords[i].eventsEmitted[0].YOUR_ASSET_NAME);}

Mongoose express sort items order with populate function

How do I send through a sorted list of documents with mongoose when using the populate function?
The high level structure for my data is Project > Task > Todo item.
I'm currently attempting to find a list of tasks for a given project, then for each task that is found I'm populating the associated todo items. This is working as expected, however I'm now trying to sort the todo items by their "rank" (each todo has an integer representing its rank).
The below piece of code is working to a certain extent...the todo items are coming back in the correct order, but grouped by the parent Task.
How can I apply a top level sort that provides the true sorted list of todo items?
Task.find().where("project.id").equals(req.params.id).populate({path: "todos", options: {sort:{"rank": 1}}}).exec(function(err, projectTasks){
if (err) {
console.log(err);
} else {
res.render("tasks/show", {currentUser: req.user, tasks: projectTasks});
}
});
Thanks!

Resources