Some more code, cosmetics
This commit is contained in:
19
packages/bookshop/srv/admin-service.js
Normal file
19
packages/bookshop/srv/admin-service.js
Normal 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)
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -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}`
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user