diff --git a/media-store/srv/browse-tracks-service.cds b/media-store/srv/browse-tracks-service.cds index 88801e25..a13dc6e6 100644 --- a/media-store/srv/browse-tracks-service.cds +++ b/media-store/srv/browse-tracks-service.cds @@ -14,4 +14,12 @@ service BrowseTracks { entity Genres as projection on my.Genres { * , tracks : redirected to Tracks }; + + @readonly + entity Albums as projection on my.Albums { + * , tracks : redirected to Tracks + }; + + @readonly + entity Artists as projection on my.Artists; } diff --git a/media-store/srv/invoices-service.cds b/media-store/srv/invoices-service.cds index fa3e4d8f..ecbfed00 100644 --- a/media-store/srv/invoices-service.cds +++ b/media-store/srv/invoices-service.cds @@ -3,9 +3,12 @@ using {sap.capire.media.store as my} from '../db/schema'; @(requires : 'authenticated-user') service InvoicesService { @readonly - entity Invoices as projection on my.Invoices actions { - action invoice(); - } + entity Invoices as projection on my.Invoices; + + action invoice(tracks : array of { + track_ID : Integer; + unitPrice : Decimal(10, 2); + }); @readonly entity InvoiceItems as projection on my.InvoiceItems; diff --git a/media-store/srv/invoices-service.js b/media-store/srv/invoices-service.js index 8b2beaca..0e491e4a 100644 --- a/media-store/srv/invoices-service.js +++ b/media-store/srv/invoices-service.js @@ -2,6 +2,7 @@ const cds = require("@sap/cds"); module.exports = async function () { const db = await cds.connect.to("db"); // connect to database service + const { Invoices, InvoiceItems } = db.entities; this.before("*", (req) => { console.log( @@ -14,7 +15,36 @@ module.exports = async function () { ); }); - this.on("READ", "Invoices", async (req) => { - return await db.run(req.query.where({ customer_ID: req.user.attr.ID })); + this.on("invoice", async (req) => { + const { tracks } = req.data; + const customerId = req.user.attr.ID; + const total = tracks.reduce((acc, { unitPrice }) => acc + unitPrice, 0); + + const { ID: lastInvoiceItemId } = await db.run( + SELECT.one(InvoiceItems).columns("ID").orderBy({ ID: "desc" }) + ); + const { ID: lastInvoiceId } = await db.run( + SELECT.one(Invoices).columns("ID").orderBy({ ID: "desc" }) + ); + + const transaction = await db.tx(req); + await transaction.run( + INSERT.into(Invoices) + .columns("ID", "customer_ID", "total") + .values(lastInvoiceId + 1, customerId, total) + ); + await transaction.run( + INSERT.into(InvoiceItems) + .columns("ID", "invoice_ID", "track_ID", "unitPrice") + .rows( + tracks.map(({ track_ID, unitPrice }, index) => [ + lastInvoiceItemId + (index + 1), + lastInvoiceId + 1, + track_ID, + unitPrice, + ]) + ) + ); + await transaction.commit(); }); };