-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdiscount_shorttime.js
More file actions
182 lines (166 loc) · 5.34 KB
/
discount_shorttime.js
File metadata and controls
182 lines (166 loc) · 5.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import { readFileSync, writeFileSync } from "bun:fs";
import { postToDiscord } from "./post_to_discord.js";
import { config } from "./config.js";
import {
getRandomValueWithChance,
generateDiscountCode,
addMinutesToIsoTime,
expiresIn,
} from "./functions.js";
// Function to fetch all product IDs from Creem API
async function getAllCreemProductIds() {
try {
let allProductIds = [];
let currentPage = 1;
let hasMorePages = true;
while (hasMorePages) {
const response = await fetch(
`https://api.creem.io/v1/products/search?page_number=${currentPage}&page_size=50`,
{
method: "GET",
headers: {
"x-api-key": process.env.CREEM_API_KEY,
},
}
);
if (!response.ok) {
throw new Error(
`Failed to fetch products: ${response.status} ${response.statusText}`
);
}
const data = await response.json();
// Extract product IDs from the current page
const productIds = data.items.map((product) => product.id);
allProductIds.push(...productIds);
// Check if there are more pages
hasMorePages = data.pagination.next_page !== null;
currentPage = data.pagination.next_page || currentPage + 1;
}
console.log(`Fetched ${allProductIds.length} product IDs from Creem API`);
return allProductIds;
} catch (error) {
console.error("Error fetching Creem products:", error);
}
}
const discountSpecialPath = "./docs/api/discount_special.json";
let skipRequest = false;
try {
const discountSpecialData = JSON.parse(
readFileSync(discountSpecialPath, "utf-8")
);
const expiresAt = new Date(discountSpecialData.data.attributes.expires_at);
const now = new Date();
if (expiresAt > now) {
console.log("Special discount exists. Skipping...");
skipRequest = true;
}
} catch (error) {
console.error("Error reading discount_special.json:", error);
}
const data = {
data: {
type: "discounts",
attributes: {
name: "Limited time discount code!",
code: `LTD${generateDiscountCode(9)}`,
amount: getRandomValueWithChance(config.discountPercentages),
amount_type: "percent",
expires_at: addMinutesToIsoTime(
getRandomValueWithChance(config.discountDuration)
),
},
relationships: {
store: {
data: {
type: "stores",
id: config.storeId,
},
},
},
},
};
if (!skipRequest && Math.random() < config.chanceToRun) {
fetch("https://api.lemonsqueezy.com/v1/discounts", {
method: "POST",
headers: {
Accept: "application/vnd.api+json",
"Content-Type": "application/vnd.api+json",
Authorization: `Bearer ${process.env.LEMONSQUEEZY_API_KEY}`,
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then(async (json) => {
if (json.data?.id) {
writeFileSync(
"docs/api/discount_shorttime.json",
JSON.stringify(json, null, 2)
);
console.log("LemonSqueezy discount code created successfully");
// Fetch all product IDs from Creem API
const productIds = await getAllCreemProductIds();
// Create the same discount on Creem
const creemData = {
name: json.data.attributes.name,
code: json.data.attributes.code,
type: "percentage",
percentage: json.data.attributes.amount,
expiry_date: json.data.attributes.expires_at,
duration: "once",
applies_to_products: productIds,
};
fetch("https://api.creem.io/v1/discounts", {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-api-key": process.env.CREEM_API_KEY,
},
body: JSON.stringify(creemData),
})
.then((response) => {
return response.json();
})
.then((creemResult) => {
if (creemResult.id) {
console.log("Creem discount code created successfully");
} else {
console.error("Failed to create Creem discount:", creemResult);
if (creemResult.status === 403) {
console.error("403 Forbidden - Check:");
console.error(
"- CREEM_API_KEY is set:",
!!process.env.CREEM_API_KEY
);
console.error("- Product IDs count:", productIds.length);
console.error(
"- Try test endpoint: https://test-api.creem.io/v1/discounts"
);
}
}
})
.catch((error) => {
console.error("Error creating Creem discount:", error);
});
if (Math.random() < config.chanceToShare) {
postToDiscord(
config.channelId,
`🎁 daisyUI Store: short time discount
Use code \`${json.data.attributes.code}\` at checkout to get ${
json.data.attributes.amount
}% discount on all products
${expiresIn(json.data.attributes.expires_at)}
https://daisyui.com/store`
);
} else {
console.log("skipped posting to Discord");
}
} else {
console.error("Failed to create LemonSqueezy discount code:", json);
}
})
.catch((error) => {
console.error("Error:", error);
});
} else {
console.log("skipped");
}