-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.gs
288 lines (247 loc) · 9 KB
/
code.gs
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/**
* Serves the User.html file as the web app interface.
*/
function doGet(e) {
return HtmlService.createTemplateFromFile('User')
.evaluate()
.setTitle('Price Generator')
.addMetaTag('viewport', 'width=device-width, initial-scale=1');
}
/**
* Includes HTML files for the web app.
* @param {string} filename - The name of the HTML file to include.
* @return {string} - The content of the HTML file.
*/
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
/**
* Validates the admin password.
* @param {string} inputPassword - The password entered by the admin.
* @return {boolean} - Returns true if valid, false otherwise.
*/
function validateAdminPassword(inputPassword) {
const scriptProperties = PropertiesService.getScriptProperties();
const storedPassword = scriptProperties.getProperty('adminPassword') || 'admin'; // Default password is 'admin'
return inputPassword === storedPassword;
}
/**
* Sets a new admin password. (Use with caution)
* @param {string} newPassword - The new admin password.
*/
function setAdminPassword(newPassword) {
const scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperty('adminPassword', newPassword);
}
/**
* Retrieves all multipliers and their probabilities.
* @return {Object} - An object containing arrays of multipliers and probabilities.
*/
function getMultipliers() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Multipliers');
if (!sheet) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet('Multipliers');
// Set headers
sheet.appendRow(['Multiplier', 'Probability']);
return { multipliers: [], probabilities: [] };
}
const data = sheet.getDataRange().getValues();
// Assuming the first row is headers
const multipliers = [];
const probabilities = [];
for (let i = 1; i < data.length; i++) {
const multiplier = parseFloat(data[i][0]);
const probability = parseFloat(data[i][1]);
if (!isNaN(multiplier) && !isNaN(probability)) {
multipliers.push(multiplier);
probabilities.push(probability);
}
}
return { multipliers, probabilities };
}
/**
* Saves multipliers and their probabilities to the sheet.
* @param {Object} settings - An object containing arrays of multipliers and probabilities.
*/
function saveMultipliers(settings) {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Multipliers');
if (!sheet) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet('Multipliers');
// Set headers
sheet.appendRow(['Multiplier', 'Probability']);
}
// Clear existing data except headers
sheet.clearContents();
sheet.appendRow(['Multiplier', 'Probability']);
// Append new data
for (let i = 0; i < settings.multipliers.length; i++) {
sheet.appendRow([settings.multipliers[i], settings.probabilities[i]]);
}
}
/**
* Retrieves all sales options.
* @return {Array} - An array of sales options objects.
*/
function getSalesOptions() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SalesOptions');
if (!sheet) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet('SalesOptions');
// Set headers
sheet.appendRow(['Number', 'Name', 'Cost (成本)', 'Selling Price (售價)']);
return [];
}
const data = sheet.getDataRange().getValues();
// Assuming the first row is headers
const salesOptions = [];
for (let i = 1; i < data.length; i++) {
const number = parseInt(data[i][0], 10);
const name = data[i][1];
const cost = parseFloat(data[i][2]);
const sellingPrice = parseFloat(data[i][3]);
if (!isNaN(number) && name && !isNaN(cost) && !isNaN(sellingPrice)) {
salesOptions.push({ number, name, cost, sellingPrice });
}
}
return salesOptions;
}
/**
* Saves sales options to the sheet.
* @param {Object} settings - An object containing arrays of numbers, names, costs, and sellingPrices.
*/
function saveSalesOptions(settings) {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SalesOptions');
if (!sheet) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet('SalesOptions');
// Set headers
sheet.appendRow(['Number', 'Name', 'Cost (成本)', 'Selling Price (售價)']);
}
// Clear existing data except headers
sheet.clearContents();
sheet.appendRow(['Number', 'Name', 'Cost (成本)', 'Selling Price (售價)']);
// Append new data
for (let i = 0; i < settings.numbers.length; i++) {
sheet.appendRow([
settings.numbers[i],
settings.names[i],
settings.costs[i],
settings.sellingPrices[i]
]);
}
}
/**
* Retrieves the full setup including multipliers and sales options.
* @return {Object} - An object containing multipliers, probabilities, and sales options.
*/
function getFullSetup() {
const multipliersData = getMultipliers();
const salesOptions = getSalesOptions();
return { multipliers: multipliersData.multipliers, probabilities: multipliersData.probabilities, salesOptions };
}
/**
* Generates the final prices based on selected options and random multiplier selection.
* @param {Array} selectedOptions - An array of selected sales options with their quantities.
* @return {Object} - An object containing the total final price, total profit, and summary data.
*/
function generateFinalPrices(selectedOptions) {
const multipliersData = getMultipliers();
const totalMultipliers = multipliersData.multipliers.length;
if (totalMultipliers === 0) {
throw new Error('No multipliers defined. Please configure multipliers in the Admin Panel.');
}
// Determine selected multiplier based on probability
const random = Math.random() * 100;
let cumulative = 0;
let selectedMultiplier = multipliersData.multipliers[0];
for (let i = 0; i < totalMultipliers; i++) {
cumulative += multipliersData.probabilities[i];
if (random <= cumulative) {
selectedMultiplier = multipliersData.multipliers[i];
break;
}
}
// Calculate total final price and total profit
let totalFinalPrice = 0;
let totalProfit = 0;
selectedOptions.forEach(option => {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SalesOptions');
const data = sheet.getDataRange().getValues();
// Find the sales option by number
let salesOption = null;
for (let i = 1; i < data.length; i++) {
if (parseInt(data[i][0], 10) === option.optionNumber) {
salesOption = {
number: parseInt(data[i][0], 10),
name: data[i][1],
cost: parseFloat(data[i][2]),
sellingPrice: parseFloat(data[i][3])
};
break;
}
}
if (salesOption) {
const finalPrice = salesOption.sellingPrice * option.quantity * selectedMultiplier;
const profit = (salesOption.sellingPrice - salesOption.cost) * option.quantity * selectedMultiplier;
totalFinalPrice += finalPrice;
totalProfit += profit;
}
});
// Log the sale
logSale({ selectedOptions, selectedMultiplier, totalFinalPrice, totalProfit });
// Prepare summary
const summary = getSummary();
return { totalFinalPrice, totalProfit, summary, selectedMultiplier };
}
/**
* Logs the sale details to the SalesLog sheet.
* @param {Object} saleData - An object containing sale details.
*/
function logSale(saleData) {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SalesLog');
if (!sheet) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet('SalesLog');
sheet.appendRow(['Timestamp', 'Selected Options', 'Selected Multiplier', 'Total Final Price', 'Total Profit']);
}
// Prepare log entry
const timestamp = new Date();
const selectedOptionsStr = saleData.selectedOptions.map(opt =>
`#${opt.optionNumber} (${opt.quantity})`
).join(', ');
const logEntry = [
timestamp,
selectedOptionsStr,
saleData.selectedMultiplier,
saleData.totalFinalPrice,
saleData.totalProfit
];
// Append to SalesLog
sheet.appendRow(logEntry);
}
/**
* Retrieves a summary of total income, revenue, and profit.
* @return {Object} - An object containing total income, total revenue, and total profit.
*/
function getSummary() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SalesLog');
if (!sheet) {
SpreadsheetApp.getActiveSpreadsheet().insertSheet('SalesLog');
sheet.appendRow(['Timestamp', 'Selected Options', 'Selected Multiplier', 'Total Final Price', 'Total Profit']);
return { totalIncome: 0, totalRevenue: 0, totalProfit: 0 };
}
const data = sheet.getDataRange().getValues();
let totalIncome = 0;
let totalRevenue = 0;
let totalProfit = 0;
for (let i = 1; i < data.length; i++) { // Skip headers
const finalPrice = parseFloat(data[i][3]);
const profit = parseFloat(data[i][4]);
if (!isNaN(finalPrice)) {
totalIncome += finalPrice;
}
if (!isNaN(profit)) {
totalProfit += profit;
}
}
// Assuming Total Revenue = Total Income in this context
totalRevenue = totalIncome;
return { totalIncome, totalRevenue, totalProfit };
}