drools - get index of item in collection - drools

I have a restaurant app and have a rule where a 20% discount needs to be offered for every 2nd ice-cream.
So,
If bill has 2 icecreams, 20% discount on the 2nd icecream
If bill has 3 icecreams, still 20% discount on the 2nd icecream
If bill has 4 icecreams, 20% discount on the 2nd and 4th icecreams
I have a collection called $bill.items which contains each individual item in the bill.
How can I write this rule in Drools given that there seems to be no way to access the index of an element in a collection.

Just collect them up and apply the discounts on the right-hand-side:
rule "Discount multiple ice creams"
when
$bill : Bill()
$iceCreams : ArrayList( size > 1 ) from $bill.items
then
for (int i = 0; i < $iceCreams.size(); i++) {
if (i % 2 == 0) {
// Apply a discount
}
}
end
Or if each bill item is available in working memory, the following can be used on the LHS to collect them:
$iceCreams : ArrayList( size > 1 )
from collect( BillItem(type == "Ice Cream") )
You may need to re-sort the list you have collected, based on each item's index within the bill.
Although, does the order of the items on a single bill really matter? The order in which items are entered on a bill is a rather unusual basis for a discount. As a customer buying 2 ice creams of differing price, I would ask for the cheapest item first because I will get a bigger discount on the second ice cream added to my bill. Hence why such discounts are usually applied to the N cheapest items. i.e. If 4 ice creams are purchased, then the 2 cheapest are discounted. Also, are ice creams different prices? If each ice cream is the same price, then all you really need to know is how many need to be discounted.

Related

How to change the total amount?

I’m building a shop app and i have many products, I want to put an offer that when the user put an order for 2 pieces of the same product he get the third one for free, so he put 3 in the cart but the total amount is for 2, the same if he ordered 3,6,9,.....
this var is for the total price, the counter is the quantity
double usedPrice = getCurrentProduct.isOnSale
? getCurrentProduct.salePrice
: double.parse(getCurrentProduct.price);
double totalPrice = usedPrice * int.parse(counter.toString());
After calculating totalPrice you can just update the quantity by
counter = counter + (counter / 2).floor() ;

Why wrong subtotal when I adding coupon code on magento2?

I did created a Coupon under "Cart Price Rule"
=========COUPON SETTINGS======================
Rule name: $20 Coupon
Websites :" Mai Website
Customer Groups : General
Uses per Coupon : 0
Uses per Customer: 1
Condetion
If ALL of these conditions are TRUE :
Subtotal equals or greater than 19.8
Actions
Apply : Fixed Amount Discount for Whole Cart
Discount Amount : 20
When I add my Coupon code on my Order
it showing
26.76 + 30 = 56.76 (subtotal+shipping)
56.76 - 20 = ?
Expected Result = 36.76
Actual Result = 35.36
Differance is = 1.4
Why this difference ? How to fix this?
This problem can be caused by Magento cache, you can clear cache and re-run indexer, and don't forget to clear browser cache.

How to query data from nested document in mongodb?

I'm struggling with this nested document too much. I tried to read the document and also follow other SO responses to see if it works for me, but I'm not getting the results that I'm looking for. I want to extract some information from a big nested document.
DATA
I've uploaded the data to mongo playground. https://mongoplayground.net/p/7nbLtXMlFMx
{"_id":{"$oid":"5f7f29259ac5883ec5eed1ec"},"name":"Walmart","page":{"name":"body","config":{},"children":[{"name":"company-title","config":{"title":"Walmart","rank":"1","franchiseTitle":"Fortune 500","franchisePermalink":"https://fortune.com/fortune500/2020/","parentPermalink":"https://fortune.com/company/walmart/"},"children":[]},{"name":"company-single-pagination","config":{"prevName":"","prevLink":"","prevRank":"","nextName":"Amazon.com","nextLink":"https://fortune.com/company/amazon-com/fortune500/","nextRank":2,"hideRanking":false,"rank":"1","franchiseTitle":"Fortune 500"},"children":[]},{"name":"company-hero","config":{"description":"After years of investment in its technology and stores, Walmart has indisputably emerged as a strong No. 2 to Amazon in U.S. e-commerce, with sales up 37% last year. But as the initial weeks of the novel coronavirus pandemic have shown, Walmart’s 4,600 U.S. stores have proved to be an effective weapon by allowing curbside pickup for online orders at a time shoppers want to limit time in stores—but still want their orders quickly. That sentiment is not likely to change anytime soon. Walmart Inc.’s Sam’s Club is finding renewed energy, too. Walmart is benefiting from focusing on select overseas markets, such as India and China, rather than competing everywhere."},"children":[{"name":"brightcove-video","config":{"accountId":"2111767321001","disableAds":false,"disableAutoplay":false,"disableContinuousPlay":false,"disableViewplay":false,"isLeadVideo":false,"loop":false,"playerId":"HDNR3TkSj","stickyPlayerOff":false,"silentlyAutoplay":true,"videoId":{"$numberLong":"6156999393001"},"section":""},"children":[]}]},{"name":"company-about-wrapper","config":{},"children":[{"name":"company-additional-media","config":{},"children":[]},{"name":"advertising-slot","config":{"align":"center","lazyload":true,"useDynamicChannel":true,"placementName":"InStream","slotId":"InStream0","targeting":{"placement_name":"InStream","index":1}},"children":[]},{"name":"company-information","config":{"title":"Company information","country":"U.S.","headquarters":"Bentonville, Ark.","industry":"General Merchandise","ceo":"C. Douglas McMillon","website":"https://www.stock.walmart.com","companyType":"Public","ticker":"WMT","revenues":"523964","profits":"14881","marketValue":"389244","employees":"2200000","updated":"9/21/20","footnote":"Market value as of Sept. 15, 2020."},"children":[]},{"name":"advertising-slot","config":{"align":"center","lazyload":true,"useDynamicChannel":true,"placementName":"InStream","slotId":"InStream1","targeting":{"placement_name":"InStream","index":2}},"children":[]},{"name":"company-information","config":{"title":"Company information","country":"U.S.","headquarters":"Bentonville, Ark.","industry":"General Merchandise","ceo":"C. Douglas McMillon","website":"https://www.stock.walmart.com","companyType":"Public","ticker":"WMT","revenues":"523964","profits":"14881","marketValue":"389244","employees":"2200000","updated":"9/21/20","footnote":"Market value as of Sept. 15, 2020."},"children":[]},{"name":"company-table-wrapper","config":{},"children":[{"name":"company-data-table","config":{"title":"Key Financials (Last Fiscal Year)","tableIndex":0,"table":{"franchiseId":2814606,"title":"Key Financials (Last Fiscal Year)","rows":[{"value":"Revenues ($M)","pctChange":"Revenue Percent Change"},{"value":"Profits ($M)","pctChange":"Profits Percent Change"},{"value":"Assets ($M)"},{"value":"Total Stockholder Equity ($M)"}],"showValue":"show_value","valueHeader":"$ millions","showPctChange":"show_pct_change","pctChangeHeader":"% change"},"updated":"","data":[{"key":"f500_revenues","value":"523964","fieldMeta":{"franchiseId":2814606,"title":"Revenues ($M)","altTitle":"Revenues ($M)","description":"Companies are ranked by total revenues for their respective fiscal years.","type":"Money","saveIn":"post_meta","importField":"f500_revenues","sortable":"sortable","order":"desc"}},{"key":"f500_profits","value":"14881","fieldMeta":{"franchiseId":2814606,"title":"Profits ($M)","altTitle":"Profits ($M)","description":"Net income after extraordinary charges for a company's respective fiscal year.","type":"Money","decimals":"1","saveIn":"post_meta","importField":"f500_profits","sortable":"sortable","order":"desc"}},{"key":"assets","value":"236495","fieldMeta":{"franchiseId":2814606,"title":"Assets ($M)","altTitle":"Assets ($M)","description":"Total assets on a company's fiscal year-end balance sheet.","type":"Money","saveIn":"post_meta","importField":"assets","sortable":"sortable","order":"desc"}},{"key":"totshequity","value":"74669","fieldMeta":{"franchiseId":2814606,"title":"Total Stockholder Equity ($M)","type":"Money","saveIn":"post_meta","importField":"totshequity"}}],"footnote":"","themeName":"half","change":[{"key":"revchange","value":"1.9","fieldMeta":{"franchiseId":2814606,"title":"Revenue Percent Change","altTitle":"Revenue Change","description":"Increase/decrease in revenues between the current and prior fiscal years.","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"revchange","sortable":"sortable","order":"desc"}},{"key":"prftchange","value":"123.1","fieldMeta":{"franchiseId":2814606,"title":"Profits Percent Change","altTitle":"Profit Change","description":"Increase/decrease in profits between the current and prior fiscal years.","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"prftchange","sortable":"sortable","order":"desc"}},{"key":null,"value":"","fieldMeta":false},{"key":null,"value":"","fieldMeta":false}],"changeHeader":"% change","valueHeader":"$ millions","showChange":true},"children":[]},{"name":"company-data-table","config":{"title":"Profit Ratios","tableIndex":1,"table":{"franchiseId":2814606,"title":"Profit Ratios","rows":[{"value":"Profit as % of Revenues"},{"value":"Profits as % of Assets"},{"value":"Profits as % of Stockholder Equity"}],"showValue":"show_value","pctChangeHeader":"% change"},"updated":"","data":[{"key":"prftpctsls","value":"2.8","fieldMeta":{"franchiseId":2814606,"title":"Profit as % of Revenues","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"prftpctsls"}},{"key":"prftpctasts","value":"6.3","fieldMeta":{"franchiseId":2814606,"title":"Profits as % of Assets","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"prftpctasts"}},{"key":"prftpctseqty","value":"19.9","fieldMeta":{"franchiseId":2814606,"title":"Profits as % of Stockholder Equity","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"prftpctseqty"}}],"footnote":"","themeName":"half","change":[{"key":null,"value":"","fieldMeta":false},{"key":null,"value":"","fieldMeta":false},{"key":null,"value":"","fieldMeta":false}],"changeHeader":"% change","valueHeader":"","showChange":false},"children":[]},{"name":"company-data-table","config":{"title":"Earnings Per Share (Last Fiscal Year)","tableIndex":2,"table":{"franchiseId":2814606,"title":"Earnings Per Share (Last Fiscal Year)","rows":[{"value":"Earnings Per Share ($)"},{"value":"EPS % Change (from 2018)"},{"value":"EPS % Change (5 year annual rate)"},{"value":"EPS % Change (10 year annual rate)"}],"showValue":"show_value","pctChangeHeader":"% change"},"updated":"","data":[{"key":"eps","value":"5.19","fieldMeta":{"franchiseId":2814606,"title":"Earnings Per Share ($)","altTitle":"EPS","type":"Number","decimals":"2","saveIn":"post_meta","importField":"eps"}},{"key":"epschange","value":"129.6","fieldMeta":{"franchiseId":2814606,"title":"EPS % Change (from 2018)","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"epschange"}},{"key":"eps5yr","value":"0.5","fieldMeta":{"franchiseId":2814606,"title":"EPS % Change (5 year annual rate)","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"eps5yr"}},{"key":"eps10yr","value":"3.4","fieldMeta":{"franchiseId":2814606,"title":"EPS % Change (10 year annual rate)","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"eps10yr"}}],"footnote":"","themeName":"half","change":[{"key":null,"value":"","fieldMeta":false},{"key":null,"value":"","fieldMeta":false},{"key":null,"value":"","fieldMeta":false},{"key":null,"value":"","fieldMeta":false}],"changeHeader":"% change","valueHeader":"","showChange":false},"children":[]},{"name":"company-data-table","config":{"title":"Total Return","tableIndex":3,"table":{"franchiseId":2814606,"title":"Total Return","rows":[{"value":"Total Return to Investors (2019)"},{"value":"Total Return to Investors (5 year, annualized)"},{"value":"Total Return to Investors (10 year, annualized)"}],"showValue":"show_value","pctChangeHeader":"% change"},"updated":"","data":[{"key":"totrti","value":"30.3","fieldMeta":{"franchiseId":2814606,"title":"Total Return to Investors (2019)","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"totrti"}},{"key":"totrti5yr","value":"9.4","fieldMeta":{"franchiseId":2814606,"title":"Total Return to Investors (5 year, annualized)","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"totrti5yr"}},{"key":"totrti10yr","value":"11","fieldMeta":{"franchiseId":2814606,"title":"Total Return to Investors (10 year, annualized)","type":"Percent","decimals":"1","saveIn":"post_meta","importField":"totrti10yr"}}],"footnote":"","themeName":"half","change":[{"key":null,"value":"","fieldMeta":false},{"key":null,"value":"","fieldMeta":false},{"key":null,"value":"","fieldMeta":false}],"changeHeader":"% change","valueHeader":"","showChange":false},"children":[]}]},{"name":"company-qlik","config":{"title":"Take a unique journey through the F500","eyebrowLabel":"fortune + qlik","description":"<p>We teamed up with Qlik, the Official Analytics Partner of the Fortune 500, to bring to life the shifting fortunes of iconic companies and sectors in an interactive data visualization.</p>\n","link":"https://qlik.fortune.com/"},"children":[{"name":"image","config":{"aspectRatio":0.6666666666666666,"attachmentId":2862622,"alt":"","caption":"","crops":[],"height":300,"imageSize":"qlik_2x3","lazyload":true,"lqipSrc":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif?quality=60&resize=60,40","postId":0,"retina":true,"showCaption":false,"sources":[{"default":true,"transforms":{"resize":[181,296]}}],"sourceTags":[],"src":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif","srcset":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif?resize=362,592 0w,https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif?resize=181,296 0w","url":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-2x3-1.gif","useBasicImg":false,"usingDataFallback":false,"width":200,"fallbackImageUrl":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","picture":false,"sizes":"100vw"},"children":[]},{"name":"image","config":{"aspectRatio":1.5,"attachmentId":2862623,"alt":"","caption":"","crops":[],"height":200,"imageSize":"qlik_3x2","lazyload":true,"lqipSrc":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif?quality=60&resize=60,90","postId":0,"retina":true,"showCaption":false,"sources":[{"default":true,"transforms":{"resize":[181,121]}}],"sourceTags":[],"src":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif","srcset":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif?resize=362,242 0w,https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif?resize=181,121 0w","url":"https://content.fortune.com/wp-content/uploads/2020/05/qlik-3x2-1.gif","useBasicImg":false,"usingDataFallback":false,"width":300,"fallbackImageUrl":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","picture":false,"sizes":"100vw"},"children":[]}]},{"name":"company-rank-history-wrapper","config":{},"children":[{"name":"company-interactives-wrapper","config":{},"children":[{"name":"interactive","config":{"heading":"Walmart Rank History","interactiveUrl":"https://interactives.fortune.com/f500-dataviz-2020/rank_chart_single_co/index.html?guid=2255","refinitivUrl":"https://interactives.fortune.com/f500-dataviz-2020/rank_chart_single_co/index.html?ric","themeName":"company"},"children":[]}]}]},{"name":"company-historical","config":{"franchiseId":2814606,"companyId":2818204},"children":[]},{"name":"sidebar","config":{"themeName":"right"},"children":[{"name":"company-data-store-cta","config":{"buttonText":"Purchase Now","text":"Leads, insights, and financial data for the FORTUNE 500, FORTUNE 1000, and Global 500 companies.","url":"/data-store/"},"children":[]},{"name":"advertising-slot","config":{"align":"center","lazyload":true,"useDynamicChannel":false,"placementName":"RightRailFlex","slotId":"RightRailFlex0","targeting":{"placement_name":"RightRailFlex","index":1}},"children":[]}]}]},{"name":"company-ranking-list","config":{"heading":"Lists ranking","title":"Walmart"},"children":[{"name":"company-ranking-list-item","config":{"title":"Change the World","permalink":"https://fortune.com/company/walmart/change-the-world/","excerpt":"As we face unprecedented collective challenges, cooperation has become a business superpower.","year":"2020","color":"#f3eee2","logo":"","rank":"9","itemId":2818204},"children":[{"name":"image","config":{"aspectRatio":false,"attachmentId":2885302,"alt":"","caption":"","crops":[],"height":1920,"imageSize":"franchise-logo","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":0,"retina":true,"showCaption":false,"sources":[{"default":true,"transforms":{"w":[115]},"descriptor":115}],"sourceTags":[],"src":"https://content.fortune.com/wp-content/uploads/2020/09/CTW20.change-the-world-Logo2-1.jpg","srcset":"https://content.fortune.com/wp-content/uploads/2020/09/CTW20.change-the-world-Logo2-1.jpg?w=230 230w,https://content.fortune.com/wp-content/uploads/2020/09/CTW20.change-the-world-Logo2-1.jpg?w=115 115w","url":"https://content.fortune.com/wp-content/uploads/2020/09/CTW20.change-the-world-Logo2-1.jpg","useBasicImg":false,"usingDataFallback":false,"width":2880,"fallbackImageUrl":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","picture":false,"sizes":"115px"},"children":[]}]},{"name":"company-ranking-list-item","config":{"title":"Global 500","permalink":"https://fortune.com/company/walmart/global500/","excerpt":"This year's Global 500 generated $33.3 trillion in revenues and $2.1 trillion in profits.","year":"2020","color":"#ffe500","logo":"","rank":"1","itemId":2818204},"children":[{"name":"image","config":{"aspectRatio":false,"attachmentId":2864400,"alt":"G500-Featured Image-Logo-2020","caption":"","crops":[],"height":1920,"imageSize":"franchise-logo","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":0,"retina":true,"showCaption":false,"sources":[{"default":true,"transforms":{"w":[115]},"descriptor":115}],"sourceTags":[],"src":"https://content.fortune.com/wp-content/uploads/2020/08/G500-Featured-Image-Logo-2020.jpg","srcset":"https://content.fortune.com/wp-content/uploads/2020/08/G500-Featured-Image-Logo-2020.jpg?w=230 230w,https://content.fortune.com/wp-content/uploads/2020/08/G500-Featured-Image-Logo-2020.jpg?w=115 115w","url":"https://content.fortune.com/wp-content/uploads/2020/08/G500-Featured-Image-Logo-2020.jpg","useBasicImg":false,"usingDataFallback":false,"width":2880,"fallbackImageUrl":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","picture":false,"sizes":"115px"},"children":[]}]},{"name":"company-ranking-list-item","config":{"title":"Fortune 500","permalink":"https://fortune.com/company/walmart/fortune500/","excerpt":"This year's Fortune 500 marks the 66th running of the list.","year":"2020","color":"#000000","logo":"","rank":"1","itemId":2818204},"children":[{"name":"image","config":{"aspectRatio":false,"attachmentId":2817676,"alt":"F500-2020-Logo","caption":"","crops":[],"height":1920,"imageSize":"franchise-logo","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":0,"retina":true,"showCaption":false,"sources":[{"default":true,"transforms":{"w":[115]},"descriptor":115}],"sourceTags":[],"src":"https://content.fortune.com/wp-content/uploads/2020/05/F500-2020-Logo.jpg","srcset":"https://content.fortune.com/wp-content/uploads/2020/05/F500-2020-Logo.jpg?w=230 230w,https://content.fortune.com/wp-content/uploads/2020/05/F500-2020-Logo.jpg?w=115 115w","url":"https://content.fortune.com/wp-content/uploads/2020/05/F500-2020-Logo.jpg","useBasicImg":false,"usingDataFallback":false,"width":2880,"fallbackImageUrl":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","picture":false,"sizes":"115px"},"children":[]}]},{"name":"company-ranking-list-item","config":{"title":"World’s Most Admired Companies","permalink":"https://fortune.com/worlds-most-admired-companies/2020/walmart/","excerpt":"For an astounding 13th straight year, Apple claims the top spot in Fortune’s annual ranking of corporate reputation, based on a survey of almost 3,800 executives, directors, and analysts.","year":"2020","color":"#000000","logo":"","rank":"18","itemId":2753766},"children":[{"name":"image","config":{"aspectRatio":false,"attachmentId":2757757,"alt":"","caption":"","crops":[],"height":356,"imageSize":"franchise-logo","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":0,"retina":true,"showCaption":false,"sources":[{"default":true,"transforms":{"w":[115]},"descriptor":115}],"sourceTags":[],"src":"https://content.fortune.com/wp-content/uploads/2019/01/wma_logo.jpg","srcset":"https://content.fortune.com/wp-content/uploads/2019/01/wma_logo.jpg?w=230 230w,https://content.fortune.com/wp-content/uploads/2019/01/wma_logo.jpg?w=115 115w","url":"https://content.fortune.com/wp-content/uploads/2019/01/wma_logo.jpg","useBasicImg":false,"usingDataFallback":false,"width":536,"fallbackImageUrl":"data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","picture":false,"sizes":"115px"},"children":[]}]}]},{"name":"company-latest-news-wrapper","config":{"title":"Latest news for Walmart"},"children":[{"name":"advertising-slot","config":{"align":"center","lazyload":true,"useDynamicChannel":true,"placementName":"InStream","slotId":"InStream2","targeting":{"placement_name":"InStream","index":3}},"children":[]},{"name":"company-latest-news","config":{},"children":[{"name":"content-item","config":{"themeName":"company_latest_news","timeago":"","isNativoTout":false,"eyebrowSectionLabel":"Conferences","eyebrowSectionLink":"https://fortune.com/section/conferences/","eyebrowTagLabel":"Most Powerful Women","eyebrowTagLink":"https://fortune.com/tag/most-powerful-women/","title":"How Sam’s Club helped small businesses through COVID","permalink":"https://fortune.com/2020/10/01/sams-club-ceo-kathryn-mclay-small-business-most-powerful-women/","id":2894934,"excerpt":"The pandemic has sped up tech innovation at the warehouse retailer.","publishDateIso8601":"2020-10-01T16:53:55-04:00","type":"post"},"children":[{"name":"image","config":{"aspectRatio":0.5625,"attachmentId":2891872,"alt":"","caption":"","crops":[],"height":0,"imageSize":"full","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":2894934,"retina":true,"showCaption":false,"sources":[],"sourceTags":[],"src":"","srcset":"","url":"","useBasicImg":false,"usingDataFallback":false,"width":0},"children":[]},{"name":"byline","config":{"link":"https://fortune.com/author/phil-wahba/","name":"Phil Wahba"},"children":[]}]},{"name":"content-item","config":{"themeName":"company_latest_news","timeago":"","isNativoTout":false,"eyebrowSectionLabel":"Retail","eyebrowSectionLink":"https://fortune.com/section/retail/","eyebrowTagLabel":"Walmart","eyebrowTagLink":"https://fortune.com/tag/walmart/","title":"Walmart unveils new store design inspired by Amazon and airports","permalink":"https://fortune.com/2020/09/30/walmart-new-store-design-app-online-pickup-amazon-airports/","id":2893828,"excerpt":"The discount chain wants people to use its Walmart app more and to be able to get in and out faster.","publishDateIso8601":"2020-09-30T11:41:27-04:00","type":"post"},"children":[{"name":"image","config":{"aspectRatio":0.5625,"attachmentId":2893884,"alt":"","caption":"","crops":[],"height":0,"imageSize":"full","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":2893828,"retina":true,"showCaption":false,"sources":[],"sourceTags":[],"src":"","srcset":"","url":"","useBasicImg":false,"usingDataFallback":false,"width":0},"children":[]},{"name":"byline","config":{"link":"https://fortune.com/author/phil-wahba/","name":"Phil Wahba"},"children":[]}]},{"name":"content-item","config":{"themeName":"company_latest_news","timeago":"","isNativoTout":false,"eyebrowSectionLabel":"Conferences","eyebrowSectionLink":"https://fortune.com/section/conferences/","eyebrowTagLabel":"MPW Summit","eyebrowTagLink":"https://fortune.com/tag/mpw-summit/","title":"3 ways Walmart and Home Depot execs think retail will change for good","permalink":"https://fortune.com/2020/09/29/retail-coronavirus-pandemic-home-depot-walmart-execs-covid-19/","id":2893036,"excerpt":"We won't go back to pre-pandemic behavior, top execs from Walmart and Home Depot predicted at Fortune's virtual Most Powerful Women's conference Tuesday. ","publishDateIso8601":"2020-09-29T18:12:00-04:00","type":"post"},"children":[{"name":"image","config":{"aspectRatio":0.5625,"attachmentId":2890633,"alt":"","caption":"","crops":[],"height":0,"imageSize":"full","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":2893036,"retina":true,"showCaption":false,"sources":[],"sourceTags":[],"src":"","srcset":"","url":"","useBasicImg":false,"usingDataFallback":false,"width":0},"children":[]},{"name":"byline","config":{"link":"https://fortune.com/author/anne-sraders/","name":"Anne Sraders"},"children":[]}]},{"name":"content-item","config":{"themeName":"company_latest_news","timeago":"","isNativoTout":false,"eyebrowSectionLabel":"Environment","eyebrowSectionLink":"https://fortune.com/section/environment/","eyebrowTagLabel":"Walmart","eyebrowTagLink":"https://fortune.com/tag/walmart/","title":"Walmart says it will eliminate emissions from global operations by 2040","permalink":"https://fortune.com/2020/09/21/walmart-emissions-global-reduction/","id":2888827,"excerpt":"The cuts, while substantial, will only cover its own operation's emissions—5% of the total. ","publishDateIso8601":"2020-09-21T06:52:56-04:00","type":"post"},"children":[{"name":"image","config":{"aspectRatio":0.5625,"attachmentId":2888833,"alt":"","caption":"","crops":[],"height":0,"imageSize":"full","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":2888827,"retina":true,"showCaption":false,"sources":[],"sourceTags":[],"src":"","srcset":"","url":"","useBasicImg":false,"usingDataFallback":false,"width":0},"children":[]},{"name":"byline","config":{"link":"https://fortune.com/author/stephen-stapczynski/","name":"Stephen Stapczynski"},"children":[]},{"name":"byline","config":{"link":"https://fortune.com/author/akshat-rathi/","name":"Akshat Rathi"},"children":[]},{"name":"byline","config":{"link":"https://fortune.com/author/bloomberg/","name":"Bloomberg"},"children":[]}]},{"name":"content-item","config":{"themeName":"company_latest_news","timeago":"","isNativoTout":false,"eyebrowSectionLabel":"Retail","eyebrowSectionLink":"https://fortune.com/section/retail/","eyebrowTagLabel":"Food Waste","eyebrowTagLink":"https://fortune.com/tag/food-waste/","title":"Exclusive: Startup Apeel is launching ‘plastic-free’ cucumbers at Walmart to cut back on waste","permalink":"https://fortune.com/2020/09/21/apeel-cucumbers-walmart-plastic-food-waste/","id":2888394,"excerpt":"Apeel’s English cucumbers are coated in a plant-based material that extends shelf life without the need for single-use plastic.","publishDateIso8601":"2020-09-21T06:00:31-04:00","type":"post"},"children":[{"name":"image","config":{"aspectRatio":0.5625,"attachmentId":2888387,"alt":"","caption":"","crops":[],"height":0,"imageSize":"full","lazyload":true,"lqipSrc":"data: image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7","postId":2888394,"retina":true,"showCaption":false,"sources":[],"sourceTags":[],"src":"","srcset":"","url":"","useBasicImg":false,"usingDataFallback":false,"width":0},"children":[]},{"name":"byline","config":{"link":"https://fortune.com/author/beth-kowitt/","name":"Beth Kowitt"},"children":[]}]}]},{"name":"company-latest-videos","config":{"tags":["Walmart"],"title":"Walmart"},"children":[]},{"name":"sidebar","config":{"themeName":"right"},"children":[{"name":"advertising-slot","config":{"align":"center","lazyload":true,"useDynamicChannel":false,"placementName":"RightRailFlex","slotId":"RightRailFlex1","targeting":{"placement_name":"RightRailFlex","index":2}},"children":[]}]}]}]}}
What I want to extract is the config from children of page where the name is company-information and description from name company-hero. I read the articles and documentation, and I can do what I want if the document is not as nested. But I'm completely lost on how to extract those info that I'm looking from. This is the first time working on Mongodb for me to this extent. I had done something very basic before.
I tried
db.collection.find(
{"page.children.3.children.2.name": {"$eq": "company-information"}},
{"page.children.3.children.2": 1}
)
but got empty result
Output
There are about 1000 rows(? Not sure if I can call it rows). The part that I'm interested in is pulling the page.children[3].children[2] where the name is company-information. So the result should be the following:
"config": {
"ceo": "C. Douglas McMillon",
"companyType": "Public",
"country": "U.S.",
"employees": "2200000",
"footnote": "Market value as of Sept. 15, 2020.",
"headquarters": "Bentonville, Ark.",
"industry": "General Merchandise",
"marketValue": "389244",
"profits": "14881",
"revenues": "523964",
"ticker": "WMT",
"title": "Company information",
"updated": "9/21/20",
"website": "https://www.stock.walmart.com"
}
You can do (almost!) anything with an aggregate query. In your case I suggest using $unwind to convert the lists to onjects, then $match on your target field(s), $project to trim down the output, $replaceRoot to simplify the structure and $limit for good measure as there's actually 2 records that match your criteria.
https://mongoplayground.net/p/UsKeqA0aWYK
db.collection.aggregate([
{
"$unwind": "$page.children"
},
{
"$unwind": "$page.children.children"
},
{
"$match": {
"page.children.children.name": "company-information"
}
},
{
"$project": {
"_id": 0,
"page.children.children.config": 1
}
},
{
"$replaceRoot": {
"newRoot": "$page.children.children"
}
},
{
"$limit": 1
}
])

How do accumulate functions actually work?

Let's say we have the next example :
There are certain products that belong to certain product groups, and we want the total price summed up in an logical fact as either the products in the product group change or as their price changes.
private class ProductGroup {
private String name;
}
public class Product {
private ProductGroup productGroup;
private int price;
}
This is the class that will be intended for the logical facts that will get inserted by the summation rule in Drools.
private class ProductGroupTotalPrice {
private ProductGroup productGroup;
private int totalPrice;
}
There is a rule that sums up the total price for a given ProductGroup.
rule "total price for product group"
when
$productGroup : ProductGroup()
$totalPrice : Number() from accumulate(
Product(productGroup == $productGroup, $price : price),
sum($price)
)
then
insertLogical(new ProductGroupTotalPrice($productGroup, $totalPrice));
end
So my question is what will the logic be when Products from a given ProductGroup are added/deleted from the working memory, they change the ProductGroup or their price is being changed?
- Lets say that the summation is done at the beggining of the application based on the current state and the logical fact is inserted into the working memory with the total price. Then the price for one Product is changed at one point so the totalPrice needs to be updated.
Here are three cases how the process would possibly be done :
Incrementally with doing a constant time calculation. Only take into account the change that has happened and subtract the old price from the total and add the new one for the one Product that was changed. (Excelent)
The whole summation is done again but the Product instances that meet the criteria(that are from the given ProductGroup) are already known, they are not searched for. (Good)
Besides the summation a loop through all the Product instances in the working memory is done to see which ones meet the criteria(that are from the given ProductGroup). (Bad)
Is the logic that is implemented one of these three cases or it is something else?
You can look at the documentation of the other form of accumulate, i.e., the one where you can define the steps for initialization, processings (note the plural!) and returning an arbitrary function. Some functions permit the reverse operation so that removing a fact that has been used for computing the function result can be handled: e.g., 'sum'. (But compare 'max'.)
So I think that your accumulate pattern will be updated efficiently.
However, I think that this does not mean that your logically inserted ProductGroupTotalPrice will be updated. (Try it, I may be wrong.)
I would use a simple rule
rule "total price for product group"
when
$productGroup: ProductGroup()
Number( $totalPrice: intValue ) from accumulate(
Product(productGroup == $productGroup, $price : price),
sum($price)
)
$pgtp: ProductGroupTotalPrice( productGroup == $productGroup,
totalPrice != $totalPrice )
then
modify( $pgtp ){ setTotalPrice( $totalPrice ) }
end
and an addition rule to insert an initial ProductGroupTotalPrice for the product group with totalPrice 0.

magento2 - How to get a product's stock status enabled/disabled?

I'm trying to get whether the product's stock status is instock/outofstock (Integers representing each state are fine. i don't necessarily need the "in stock"/"out of stock" strings per se).
I've tried various things to no avail.
1)
$inStock = $obj->get('Magento\CatalogInventory\Api\Data\StockItemInterface')->getisInStock()'
// Magento\CatalogInventory\Api\Data\StockItemInterface :: getisInStock returns true no matter what, even for 0qty products
// summary: not useful. How do you get the real one?
2)
$inStock = $obj->get('\Magento\CatalogInventory\Api\StockStateInterface')->verifyStock($_product->getId());
// test results for "verifyStock":
// a 0 qty product is in stock
// a 0 qty product is out of stock
// summary: fail. find correct method, with tests.
3)
$stockItemRepository = $obj->get('Magento\CatalogInventory\Model\Stock\StockItemRepository');
stockItem = $stockItemRepository->get($_product->getId());
$inStock = $stockItem->getIsInStock();
// Uncaught Magento\Framework\Exception\NoSuchEntityException: Stock Item with id "214"
// summmary: is stockitem not 1to1 with proudctid?
The weird thing is, getting stock quantities works just fine.
$availability = (String)$obj->get('\Magento\CatalogInventory\Api\StockStateInterface')->getStockQty($_product->getId(), $_product->getStore()->getWebsiteId());
So why isn't getIsInStock working?
This was one way I did it.
$stockItemResource = $obj->create('Magento\CatalogInventory\Model\ResourceModel\Stock\Item');
// grab ALL stock items (i.e. object that contains stock information)
$stockItemSelect = $stockItemResource->getConnection()->select()->from($stockItemResource->getMainTable());
$stockItems = $stockItemResource->getConnection()->fetchAll($stockItemSelect);
$inStock = null;
foreach($stockItems as $k => $item) {
if ($item['product_id'] == $_productId) {
$inStock = $item['is_in_stock'];
break; // not breaking properly. 'qz' still prints
}
}
Notes on efficiency:
I'm sure there are another ways to target the single item specifically, instead of getting all. Either through a method, or by adjusting the query passed in somehow.
But this method is probably more efficient for large n, avoiding the n+1 query problem.
You do still end up iterating through a lot, but perhaps theta(n) of iterating through a cached PHP variable is probably lower than n+1 querying the database. Haven't tested, just a hypothesis.
The returned structure is an array of arrays, where the sub-array (which also happens to be a stock item) has the product ID and the stock status value. And because the product ID and the stock status value is on the same level of nesting, we have no choice but to iterate through each sub-array to check the product_id, choose that sub-array, and grab the stock value. In short, we can't just utilize the hashmap, since the keys of the sub-array are not product IDs.
Ultimately, the efficiency of this depends on your use case. Rarely will you grab all stock items, unless doing mass exports. So the ultimate goal is to really just stay within the configured time limit is allowed for a request to persist.