Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/components/store/add-to-cart.tsx
1450 views
1
/*
2
* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import {
7
delete_local_storage,
8
get_local_storage,
9
} from "@cocalc/frontend/misc/local-storage";
10
import apiPost from "lib/api/post";
11
import { LS_KEY_LICENSE_PROJECT } from "./util";
12
import { ALL_FIELDS } from "./quota-query-params";
13
14
// these are the hidden type fields of the forms
15
// regular and boost end up as "quota" types
16
// where the description.boost flag is true or false
17
export type LicenseTypeInForms = "regular" | "boost" | "vm" | "disk";
18
19
interface Props {
20
form: any;
21
router: any;
22
setCartError: (msg: string) => void;
23
}
24
25
// this is used by the "addBox" and the thin "InfoBar" to add/modify the selected license configuration to the cart
26
// If something goes wrong it throws an error *and* also calls setCartError.
27
export async function addToCart({ form, setCartError, router }: Props) {
28
// we make a copy, because otherwise this actually modifies the fields (user sees brief red errors)
29
const description = {
30
...form.getFieldsValue(true),
31
};
32
let product;
33
if (description.numVouchers != null) {
34
product = "cash-voucher";
35
} else {
36
product = "site-license";
37
}
38
39
if (product == "site-license") {
40
// exclude extra fields that are for UI only. See https://github.com/sagemathinc/cocalc/issues/6258
41
for (const field in description) {
42
if (!ALL_FIELDS.has(field)) {
43
delete description[field];
44
}
45
}
46
description.type = "quota";
47
description.boost = false;
48
} else {
49
description.type = "cash-voucher";
50
}
51
52
try {
53
setCartError("");
54
if (router.query.id != null) {
55
await apiPost("/shopping/cart/edit", {
56
id: router.query.id,
57
description,
58
});
59
} else {
60
// we get the project_id from local storage and save it to the new/edited license
61
const project_id = get_local_storage(LS_KEY_LICENSE_PROJECT);
62
delete_local_storage(LS_KEY_LICENSE_PROJECT);
63
64
await apiPost("/shopping/cart/add", {
65
product,
66
description,
67
project_id,
68
});
69
}
70
router.push("/store/cart");
71
} catch (err) {
72
setCartError(err.message);
73
throw err;
74
}
75
}
76
77