WFDASH-WEBAPP/pocketbase/pb_hooks/stock_counts.pb.js

103 lines
3.5 KiB
JavaScript

routerAdd(
"GET",
"/api/wfdash/stock-counts-capability",
(e) => {
const utils = require(`${__hooks}/stock_count_utils.js`);
utils.assertSchema(e.app);
return e.json(200, { version: 1 });
},
$apis.requireSuperuserAuth(),
);
routerAdd(
"POST",
"/api/wfdash/stock-count-command",
(e) => {
const utils = require(`${__hooks}/stock_count_utils.js`);
utils.assertSchema(e.app);
const body = e.requestInfo().body;
let result;
e.app.runInTransaction((app) => {
const data = body.data || {};
if (body.action === "invalidate") {
const count = app.findRecordById("stock_counts", data.id);
if (count.getString("owner") !== data.owner) throw new NotFoundError();
const prior = app.findRecordsByFilter(
"stock_quantity_plans",
"count = {:id} && (status = 'pending' || status = 'partial')",
"",
0,
0,
{ id: count.id },
);
prior.forEach((p) => {
p.set("status", "superseded");
app.save(p);
});
count.set(
"review_revision",
Number(count.get("review_revision") || 0) + 1,
);
app.save(count);
result = JSON.parse(JSON.stringify(count));
} else if (body.action === "plan") {
if (data.count) {
const count = app.findRecordById("stock_counts", data.count);
if (
count.getString("owner") !== data.owner ||
count.getString("status") !== "ready" ||
count.getInt("revision") !== data.count_revision ||
Number(count.get("review_revision") || 0) !== data.review_revision
)
throw new ApiError(409, "The count sheet changed. Read it again.");
}
if (!data.count && data.chat) {
const prior = app.findRecordsByFilter(
"stock_quantity_plans",
"owner = {:owner} && chat = {:chat} && count = '' && (status = 'pending' || status = 'partial')",
"",
0,
0,
{ owner: data.owner, chat: data.chat },
);
prior.forEach((p) => {
p.set("status", "superseded");
app.save(p);
});
}
const record = new Record(
app.findCollectionByNameOrId("stock_quantity_plans"),
);
Object.keys(data).forEach((k) => record.set(k, data[k]));
app.save(record);
result = JSON.parse(JSON.stringify(record));
} else if (body.action === "split") {
const count = app.findRecordById("stock_counts", data.id);
if (count.getString("owner") !== data.owner) throw new NotFoundError();
if (count.getString("status") !== "ready")
throw new ApiError(
409,
"This count is already being generated. Wait for it to finish.",
);
const plans = app.findRecordsByFilter(
"stock_quantity_plans",
"count = {:id}",
"",
1,
0,
{ id: count.id },
);
if (plans.length)
throw new ApiError(
409,
"A review already exists for this sheet. Create a new count instead.",
);
count.set("revision", count.getInt("revision") + 1);
count.set("status", "building");
app.save(count);
result = JSON.parse(JSON.stringify(count));
} else throw new BadRequestError("Unknown stock count command.");
});
return e.json(200, result);
},
$apis.requireSuperuserAuth(),
);