· 4 years ago · Jun 30, 2021, 05:12 PM
1const Airtable = require("airtable");
2
3const Client = require("shopify-buy");
4
5var moment = require("moment");
6
7var checkoutFinal = "";
8
9const client = Client.buildClient({
10 domain: process.env.SHOPIFY_DOMAIN,
11 storefrontAccessToken: process.env.STOREFRONT_API,
12});
13
14const createCheckout = (productId, quantitySelected, res) => {
15
16 client.checkout.create(res).then((checkout) => {
17
18 console.log(checkout.id);
19
20 const checkoutId = checkout.id;
21
22 const lineItemsToAdd = [
23 {
24 variantId: productId,
25 quantity: quantitySelected,
26 },
27 ];
28
29 client.checkout
30 .addLineItems(checkoutId, lineItemsToAdd)
31 .then((checkout) => {
32 checkoutFinal = checkout.webUrl
33 console.log(checkoutFinal)
34 });
35 });
36};
37
38Airtable.configure({
39 endpointUrl: "https://api.airtable.com",
40 //Your API Key from Airtable
41 apiKey: process.env.AIRTABLE_KEY,
42});
43
44const base = Airtable.base(process.env.AIRTABLE_DB);
45
46const handler = (req, res) => {
47 try {
48 if (req.method !== "POST") {
49 return res.redirect(302, "/404");
50 }
51
52 const data = req.body;
53
54 if (!data) {
55 return res.redirect(302, "/404"); // res.status(500).json({ error: "There isn't any data." })
56 }
57
58 const submissionDateTime = new Date();
59
60 const momentDate = moment(submissionDateTime);
61
62 base("Forms").create(
63 [
64 {
65 fields: {
66 "Data Prenotazione": momentDate.add(2, "h"),
67 Tour: data.tourname,
68 "Data di Partenza": data.tourdate,
69 Partecipanti: Number(data.quantity),
70 "Privacy Policy": data.privacypolicy ? true : false,
71 ToS: data.tos ? true : false,
72 "Viaggiatrice 1 (Leader)":
73 "Nome: " +
74 data.name.charAt(0).toUpperCase() +
75 data.name.slice(1) +
76 "\n" +
77 "Cognome: " +
78 data.lastname.charAt(0).toUpperCase() +
79 data.lastname.slice(1) +
80 "\n" +
81 "Data di Nascita: " +
82 data.dob +
83 "\n" +
84 "Luogo di Nascita: " +
85 data.city.charAt(0).toUpperCase() +
86 data.city.slice(1) +
87 "\n" +
88 "Codice Fiscale: " +
89 data.codfisc.toUpperCase() +
90 "\n" +
91 "Intolleranze: " +
92 (data.intolerancy === "on" ? "Si" : "No") +
93 "\n" +
94 "Vegetariana: " +
95 (data.vegan === "on" ? "Si" : "No") +
96 "\n" +
97 "Disabilità: " +
98 (data.disability === "on" ? "Si" : "No") +
99 "\n" +
100 "Note a riguardo: " +
101 (data.notes ? data.notes : "---")
102 },
103 },
104 ],
105 (err, records) => {
106 if (err) {
107 res.redirect(302, "/404");
108 } else {
109 const productId = data.productid; // Storing product id from hidden field
110 const quantitySelected = Number(data.quantity);
111 createCheckout(productId, quantitySelected);
112 res.redirect(302, checkoutFinal);
113 }
114 }
115 );
116 } catch (err) {
117 console.log(err);
118 res.redirect(302, "/404");
119 }
120};
121
122module.exports = handler;
123