add invoice action
This commit is contained in:
committed by
Daniel Hutzel
parent
49f6b8c060
commit
0690762207
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user