Some more code, cosmetics

This commit is contained in:
Christian Georgi
2020-02-10 22:07:13 +01:00
parent 7b5b2210ae
commit 4ad21a47d6
2 changed files with 26 additions and 7 deletions

View File

@@ -0,0 +1,19 @@
const cds = require('@sap/cds')
/** Service implementation for AdminService */
module.exports = cds.service.impl(srv => {
const { OrderItems } = srv.entities ('sap.capire.bookshop')
// on-the-fly calculate the total Order price based on the OrderItems' netAmounts
srv.after (['READ','EDIT'], 'Orders', async (orders, req) => {
const ordersByID = Array.isArray(orders)
? orders.reduce ((all,o) => { (all[o.ID] = o).total=0; return all },{})
: { [orders.ID]: orders }
return cds.transaction(req) .run (
SELECT.from(OrderItems) .columns ('parent_ID', 'netAmount')
.where ({ parent_ID: {in: Object.keys(ordersByID)} })
) .then (items =>
items.forEach (item => ordersByID [item.parent_ID] .total += item.netAmount)
)
})
})

View File

@@ -14,15 +14,15 @@ function _addDiscount2 (each,discount) {
}
/** Reduce stock of ordered books if available stock suffices */
async function _reduceStock (req) {
const { Items: OrderItems } = req.data
// req.on('failed', () => { console.debug ('>>> failed for order', req.data.ID) })
const { Items: orderItems } = req.data
return cds.transaction(req) .run (()=> OrderItems.map (order =>
UPDATE (Books) .set ('stock -=', order.amount)
.where ('ID =', order.book_ID) .and ('stock >=', order.amount)
)) .then (all => all.forEach ((affectedRows,i) => {
return cds.transaction(req) .run (()=> orderItems.map (order =>
UPDATE (Books)
.set ('stock -=', order.amount)
.where ('ID =', order.book_ID) .and ('stock >=', order.amount)
)).then (all => all.forEach ((affectedRows,i) => {
if (affectedRows === 0) req.error (409,
`${OrderItems[i].amount} exceeds stock for book #${OrderItems[i].book_ID}`
`${orderItems[i].amount} exceeds stock for book #${orderItems[i].book_ID}`
)
}))
}