CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/pages/api/v2/vouchers/create-vouchers.ts
Views: 687
1
import createVouchers from "@cocalc/server/vouchers/create-vouchers";
2
import getAccountId from "lib/account/get-account";
3
import userIsInGroup from "@cocalc/server/accounts/is-in-group";
4
import getParams from "lib/api/get-params";
5
6
export default async function handle(req, res) {
7
try {
8
const result = await doIt(req);
9
res.json({ ...result, success: true });
10
} catch (err) {
11
res.json({ error: `${err.message}` });
12
return;
13
}
14
}
15
16
async function doIt(req) {
17
const {
18
whenPay,
19
count,
20
active,
21
expire,
22
cancelBy,
23
title,
24
length,
25
charset,
26
prefix,
27
postfix,
28
} = getParams(req);
29
if (count == null) {
30
throw Error("must provide number of vouchers");
31
}
32
if (whenPay == "invoice") {
33
if (active == null) {
34
throw Error("must provide activation date");
35
}
36
if (expire == null) {
37
throw Error("must provide expiration date");
38
}
39
if (cancelBy == null) {
40
throw Error("must provide cancelBy date");
41
}
42
}
43
if (title == null) {
44
throw Error("must provide title");
45
}
46
if (length == null || length < 6 || length > 16) {
47
throw Error("must provide length that is at least 6 and less than 16");
48
}
49
if (prefix == null) {
50
throw Error("must provide prefix");
51
}
52
if (postfix == null) {
53
throw Error("must provide postfix");
54
}
55
if (charset == null) {
56
throw Error("must provide charset");
57
}
58
const account_id = await getAccountId(req);
59
if (account_id == null) {
60
throw Error("must be signed in to create vouchers");
61
}
62
if (whenPay == "invoice" && !(await userIsInGroup(account_id, "partner"))) {
63
throw Error("only partners can create vouchers");
64
}
65
66
return await createVouchers({
67
account_id,
68
whenPay,
69
count,
70
active: new Date(active),
71
expire: new Date(expire),
72
cancelBy: new Date(cancelBy),
73
title,
74
generate: { length, prefix, postfix, charset },
75
});
76
}
77
78