@jsb188/app 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/utils/logic.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { sortObjectByKeys, stringifyJSON } from './object.ts';
2
+
1
3
  /**
2
4
  * Types
3
5
  */
@@ -34,16 +36,28 @@ export function getDatabaseAction(
34
36
  if (Object.prototype.hasOwnProperty.call(data, key) && data[key] !== undefined) {
35
37
  // trim() on all string databse fields should be OK;
36
38
  // But if not, add an extra param.
37
- const value = typeof data[key] === 'string' ? data[key].trim() : data[key];
39
+ let value = typeof data[key] === 'string' ? data[key].trim() : data[key];
40
+ if (value instanceof Date) {
41
+ value = value.toISOString();
42
+ } else if (value && typeof value === 'object') {
43
+ value = stringifyJSON(sortObjectByKeys(value));
44
+ }
38
45
 
39
46
  const isNullValue = value !== null || allowNull;
40
47
  if (isNullValue) {
41
48
  documentData[key] = value;
42
49
  }
43
50
 
51
+ let currentValue = currentData[key];
52
+ if (currentValue instanceof Date) {
53
+ currentValue = currentValue.toISOString();
54
+ } else if (currentValue && typeof currentValue === 'object') {
55
+ currentValue = stringifyJSON(sortObjectByKeys(currentValue));
56
+ }
57
+
44
58
  if (
45
59
  // Doing loose != check instead of !== type check
46
- currentData[key] != value &&
60
+ currentValue != value &&
47
61
  isNullValue
48
62
  ) {
49
63
  hasChanges = true;
@@ -100,19 +114,56 @@ export function timeoutPromise<T>(
100
114
  ): Promise<T> {
101
115
  return new Promise<T>((resolve, reject) => {
102
116
  const timeout = setTimeout(() => {
103
- resolve(onTimeout());
117
+ resolve(onTimeout());
104
118
  }, timeoutMs);
105
119
 
106
120
  const p = mainPromise();
107
- if (typeof p?.then === 'function') {
121
+ if (typeof p?.then === 'function') {
108
122
  p.then((result: any) => {
109
123
  clearTimeout(timeout);
110
124
  resolve(result);
111
125
  })
112
- .catch((err: any) => {
113
- clearTimeout(timeout);
114
- reject(err);
115
- });
116
- }
126
+ .catch((err: any) => {
127
+ clearTimeout(timeout);
128
+ reject(err);
129
+ });
130
+ }
117
131
  });
118
132
  }
133
+
134
+ /**
135
+ * Make String based key from variables Object
136
+ * @param variables - any variables or arguments object
137
+ * @param doNotLowerCaseCacheKey - If true, the returned key will maintain original casing
138
+ * @return string key
139
+ */
140
+
141
+ export function makeVariablesKey(
142
+ variables: Record<string, any> | null | undefined,
143
+ doNotLowerCaseCacheKey?: boolean,
144
+ // gqlDefinitions?: any[],
145
+ ): string {
146
+ if (variables) {
147
+
148
+ // const gqlOperation = gqlDefinitions?.find((def: any) => def.kind === 'OperationDefinition');
149
+ const key = Object.keys(variables).sort().reduce((acc, key) => {
150
+ // I *could* loop and make sure the variables match those defined in the GQL operation,
151
+ // But instead of wasting compute, I rather make sure the variables are passed in identical manner from the app.
152
+ // if (gqlOperation) {
153
+ // console.log(key);
154
+ // ..
155
+ // }
156
+ const value = variables[key];
157
+ if (value || value === 0 || value === false) {
158
+ return `${acc}$${key}:${typeof value === 'object' ? stringifyJSON(value) : value}`;
159
+ }
160
+ return acc;
161
+ }, '');
162
+
163
+ if (!doNotLowerCaseCacheKey) {
164
+ return key.toLowerCase();
165
+ }
166
+ return key;
167
+ }
168
+ return 'none';
169
+ }
package/utils/number.ts CHANGED
@@ -1,3 +1,27 @@
1
+
2
+ /**
3
+ * Convert string value to BigInt safely
4
+ */
5
+
6
+ export function toBigInt(value: string | number | bigint): bigint | null {
7
+ try {
8
+ if (typeof value === 'bigint') {
9
+ return value;
10
+ } else if (typeof value === 'number') {
11
+ return BigInt(value);
12
+ } else if (typeof value === 'string') {
13
+ const trimmed = value.trim();
14
+ if (trimmed === '') {
15
+ return null;
16
+ }
17
+ return BigInt(trimmed);
18
+ }
19
+ return null;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
1
25
  /**
2
26
  * Check if number
3
27
  */
@@ -6,6 +30,8 @@ export function isNumber(input: unknown): input is number | string {
6
30
  switch (typeof input) {
7
31
  case 'number':
8
32
  return input - input === 0;
33
+ case 'bigint':
34
+ return true;
9
35
  case 'string':
10
36
  return input.trim() !== '' && !Number.isNaN(Number(input));
11
37
  }
@@ -125,15 +151,141 @@ export function calculateDiscount(normalPrice: number, discountedPrice: number)
125
151
  *
126
152
  * @param value - The number to format
127
153
  * @param trimDecimals - If true, trims the decimal places to the first non-zero digit
154
+ * @param doNotAllowNaN - If true, returns empty string "" if the value is NaN
128
155
  * @returns Formatted string representation of the number
129
156
  */
130
157
 
131
- export function formatDecimal(value_: string | number, trimDecimals: boolean = false): string {
132
- const value = String(value_);
133
- if (Number(value) % 1 === 0) {
134
- return Number(value).toString(); // Whole number
135
- } else if (trimDecimals) {
136
- return parseFloat(value.toString()).toString(); // Trims to first non-zero decimal
137
- }
138
- return String(value); // Keep existing decimal places
158
+ export function formatDecimal(
159
+ value_: string | number,
160
+ trimDecimals: boolean = false,
161
+ doNotAllowNaN: boolean = false,
162
+ ): string {
163
+ const value = String(value_);
164
+
165
+ let formattedStr;
166
+ if (Number(value) % 1 === 0) {
167
+ formattedStr = Number(value).toString(); // Whole number
168
+ } else if (trimDecimals) {
169
+ formattedStr = parseFloat(value.toString()).toString(); // Trims to first non-zero decimal
170
+ } else {
171
+ formattedStr = String(value); // Keep existing decimal places
172
+ }
173
+ return doNotAllowNaN && isNaN(Number(formattedStr)) ? '' : formattedStr;
174
+ }
175
+
176
+ /**
177
+ * Get quantity text by combining quantity and unit together
178
+ *
179
+ * @param quantity - The quantity value
180
+ * @param unit - The unit string
181
+ * @returns Combined quantity and unit string
182
+ */
183
+
184
+ export function getQuantityText(
185
+ quantity: string | number,
186
+ unit?: string,
187
+ ): string {
188
+ const value = formatDecimal(quantity, true, true);
189
+ return [
190
+ value + (value && unit && /^[0-9]/.test(unit) ? ', ' : ''),
191
+ unit,
192
+ ].filter(Boolean).join(' ');
193
+ }
194
+
195
+ /**
196
+ * Get currency symbol from settings
197
+ * Example 1: getCurrencySymbol('en-US', 'USD'); // "$"
198
+ * Example 2: getCurrencySymbol('fr-FR', 'EUR'); // "€"
199
+ * Example 3: getCurrencySymbol('ja-JP', 'JPY'); // "¥"
200
+ * Example 4: getCurrencySymbol('en-GB', 'GBP'); // "£"
201
+ *
202
+ * @param locale - The locale to use for formatting
203
+ * @param currency - The currency code (e.g., 'USD', 'EUR')
204
+ * @returns currency symbol as a string
205
+ */
206
+
207
+ export function getCurrencySymbol(locale: string, currency: string): string {
208
+ const parts = new Intl.NumberFormat(locale, {
209
+ style: 'currency',
210
+ currency,
211
+ minimumFractionDigits: 0,
212
+ maximumFractionDigits: 0,
213
+ }).formatToParts(1);
214
+
215
+ const symbolPart = parts.find((part) => part.type === 'currency');
216
+ return symbolPart?.value || '';
217
+ }
218
+
219
+ /**
220
+ * Format number to currency format
221
+ */
222
+
223
+ export function formatCurrency(
224
+ amount: string | number,
225
+ trailZeros: boolean = true,
226
+ locale: string = 'en-US',
227
+ currency: string = 'USD',
228
+ ): string {
229
+ const num = typeof amount === 'string' ? parseFloat(amount) : amount;
230
+ if (!num && num !== 0) {
231
+ return '';
232
+ }
233
+
234
+ if (isNaN(num)) {
235
+ return trailZeros ? '$0.00' : '$0';
236
+ }
237
+
238
+ const hasDecimals = num % 1 !== 0;
239
+ const symbol = getCurrencySymbol(locale, currency);
240
+
241
+ return symbol + num.toLocaleString(locale, {
242
+ minimumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
243
+ maximumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
244
+ });
245
+ }
246
+
247
+ /**
248
+ * Format number to have "," between every thousands
249
+ */
250
+
251
+ export function kFormat(
252
+ num: string | number,
253
+ locale: string = 'en-US',
254
+ ): string {
255
+ const number = typeof num === 'string' ? parseFloat(num) : num;
256
+ if (isNaN(number)) {
257
+ return String(num);
258
+ }
259
+
260
+ return number.toLocaleString(locale, {
261
+ minimumFractionDigits: 0,
262
+ maximumFractionDigits: 0,
263
+ });
264
+ }
265
+
266
+ /**
267
+ * Convert number based time to military time format (e.g., 1300 to 13:00)
268
+ */
269
+
270
+ export function convertToMilitaryTime(time?: number | string | null): string | null {
271
+ if (time) {
272
+ const timeString = String(time).padStart(4, '0');
273
+ return `${timeString.slice(0, 2)}:${timeString.slice(2)}`;
274
+ }
275
+ return null;
276
+ }
277
+
278
+ /**
279
+ * Calculate totals from LabelAndValueObj[]
280
+ */
281
+
282
+ export function calculateTotalAmount(values: any[], tax: number = 0): number {
283
+ return (values || []).reduce((acc, obj) => {
284
+ // NOTE: obj.value is the total, so obj.quantity can be ignored
285
+ const val = parseFloat(obj?.value);
286
+ if (!isNaN(val)) {
287
+ return acc + val;
288
+ }
289
+ return acc;
290
+ }, tax || 0);
139
291
  }