@react-pakistan/util-functions 1.24.98 → 1.25.0

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.
Files changed (59) hide show
  1. package/api/stellar-solutions/bank/cache.d.ts +99 -0
  2. package/api/stellar-solutions/bank/cache.js +256 -0
  3. package/api/stellar-solutions/bank/index.d.ts +1 -1
  4. package/api/stellar-solutions/bank/index.js +15 -0
  5. package/api/stellar-solutions/branch/cache.d.ts +97 -0
  6. package/api/stellar-solutions/branch/cache.js +256 -0
  7. package/api/stellar-solutions/branch/index.d.ts +1 -1
  8. package/api/stellar-solutions/branch/index.js +15 -0
  9. package/api/stellar-solutions/company/cache.d.ts +106 -0
  10. package/api/stellar-solutions/company/cache.js +307 -0
  11. package/api/stellar-solutions/company/index.d.ts +1 -1
  12. package/api/stellar-solutions/company/index.js +15 -0
  13. package/api/stellar-solutions/constants.d.ts +21 -0
  14. package/api/stellar-solutions/constants.js +24 -0
  15. package/api/stellar-solutions/contact/cache.d.ts +108 -0
  16. package/api/stellar-solutions/contact/cache.js +307 -0
  17. package/api/stellar-solutions/contact/index.d.ts +1 -1
  18. package/api/stellar-solutions/contact/index.js +15 -0
  19. package/api/stellar-solutions/currency/cache.d.ts +99 -0
  20. package/api/stellar-solutions/currency/cache.js +256 -0
  21. package/api/stellar-solutions/currency/index.d.ts +1 -1
  22. package/api/stellar-solutions/currency/index.js +15 -0
  23. package/api/stellar-solutions/customer/cache.d.ts +108 -0
  24. package/api/stellar-solutions/customer/cache.js +307 -0
  25. package/api/stellar-solutions/customer/index.d.ts +1 -1
  26. package/api/stellar-solutions/customer/index.js +15 -0
  27. package/api/stellar-solutions/expense/cache.d.ts +106 -0
  28. package/api/stellar-solutions/expense/cache.js +307 -0
  29. package/api/stellar-solutions/expense/index.d.ts +1 -1
  30. package/api/stellar-solutions/expense/index.js +15 -0
  31. package/api/stellar-solutions/expense-category/cache.d.ts +94 -0
  32. package/api/stellar-solutions/expense-category/cache.js +280 -0
  33. package/api/stellar-solutions/expense-category/index.d.ts +1 -1
  34. package/api/stellar-solutions/expense-category/index.js +15 -0
  35. package/api/stellar-solutions/payment-mode/cache.d.ts +97 -0
  36. package/api/stellar-solutions/payment-mode/cache.js +256 -0
  37. package/api/stellar-solutions/payment-mode/index.d.ts +1 -1
  38. package/api/stellar-solutions/payment-mode/index.js +15 -0
  39. package/api/stellar-solutions/preference/cache.d.ts +85 -0
  40. package/api/stellar-solutions/preference/cache.js +229 -0
  41. package/api/stellar-solutions/preference/index.d.ts +1 -1
  42. package/api/stellar-solutions/preference/index.js +15 -0
  43. package/api/stellar-solutions/product/cache.d.ts +94 -0
  44. package/api/stellar-solutions/product/cache.js +280 -0
  45. package/api/stellar-solutions/product/index.d.ts +4 -6
  46. package/api/stellar-solutions/product/index.js +24 -8
  47. package/api/stellar-solutions/product-category/cache.d.ts +94 -0
  48. package/api/stellar-solutions/product-category/cache.js +280 -0
  49. package/api/stellar-solutions/product-category/index.d.ts +1 -1
  50. package/api/stellar-solutions/product-category/index.js +15 -0
  51. package/api/stellar-solutions/tax/cache.d.ts +97 -0
  52. package/api/stellar-solutions/tax/cache.js +256 -0
  53. package/api/stellar-solutions/tax/index.d.ts +1 -1
  54. package/api/stellar-solutions/tax/index.js +15 -0
  55. package/api/stellar-solutions/type.d.ts +15 -0
  56. package/api/stellar-solutions/type.js +17 -1
  57. package/index.d.ts +6 -5
  58. package/index.js +6 -6
  59. package/package.json +1 -1
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
50
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
51
+ if (ar || !(i in from)) {
52
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
53
+ ar[i] = from[i];
54
+ }
55
+ }
56
+ return to.concat(ar || Array.prototype.slice.call(from));
57
+ };
58
+ Object.defineProperty(exports, "__esModule", { value: true });
59
+ exports.isProductCategoriesCacheStale = exports.preloadProductCategories = exports.invalidateProductCategoriesCache = exports.getCachedProductCategoryById = exports.getCachedProductCategories = exports.getCachedProductCategoriesSync = void 0;
60
+ var constants_1 = require("../constants");
61
+ var type_1 = require("../type");
62
+ var api_methods_1 = require("../../../constants/api-methods");
63
+ var fetch_data_1 = require("../../../general/fetch-data");
64
+ var get_storage_value_1 = require("../../../local-storage/get-storage-value");
65
+ var set_storage_value_1 = require("../../../local-storage/set-storage-value");
66
+ /**
67
+ * Synchronous utility function to get product categories from cache only
68
+ * Returns cached data immediately if available and fresh, otherwise returns empty array
69
+ * Does not trigger any API calls
70
+ *
71
+ * @returns ProductCategoryBE[] - Array of cached product categories or empty array
72
+ *
73
+ * @example
74
+ * const categories = getCachedProductCategoriesSync();
75
+ * if (categories.length > 0) {
76
+ * console.log(categories[0].name);
77
+ * }
78
+ */
79
+ var getCachedProductCategoriesSync = function () {
80
+ try {
81
+ var cachedData = (0, get_storage_value_1.getStorageValue)(type_1.LS_KEYS.PRODUCT_CATEGORIES);
82
+ if (!cachedData) {
83
+ return { count: 0, items: [] };
84
+ }
85
+ var currentTime = new Date().getTime();
86
+ var cachedTime = new Date(cachedData.cachedAt).getTime();
87
+ var ageInMs = currentTime - cachedTime;
88
+ // If cached data is less than 1 week old, return it
89
+ if (ageInMs < constants_1.ONE_DAY_IN_MS) {
90
+ return {
91
+ count: cachedData.productCategories.length,
92
+ items: cachedData.productCategories,
93
+ };
94
+ }
95
+ return { count: 0, items: [] };
96
+ }
97
+ catch (error) {
98
+ console.error('Error getting cached product categories:', error);
99
+ return { count: 0, items: [] };
100
+ }
101
+ };
102
+ exports.getCachedProductCategoriesSync = getCachedProductCategoriesSync;
103
+ /**
104
+ * Utility function to get product categories from cache or fetch from API
105
+ *
106
+ * This function manages a localStorage cache of product categories with the following logic:
107
+ * - If categories exist in cache and are less than 1 week old, return cached version
108
+ * - If categories exist but are older than 1 week, fetch fresh data and update cache
109
+ * - If categories don't exist in cache, fetch from API and cache them
110
+ *
111
+ * @param searchQuery - Optional search query to filter categories
112
+ * @param filters - Optional filters object to apply additional filtering (bypasses cache)
113
+ * @param pageLimit - Number of categories to fetch (default: 100)
114
+ * @returns Promise<ProductCategoryBE[]> - Array of product categories
115
+ *
116
+ * @example
117
+ * const categories = await getCachedProductCategories();
118
+ * console.log(categories[0].name);
119
+ *
120
+ * // With search
121
+ * const filtered = await getCachedProductCategories('Electronics');
122
+ *
123
+ * // With filters
124
+ * const filteredCategories = await getCachedProductCategories(undefined, { enabled: true });
125
+ */
126
+ var getCachedProductCategories = function (searchQuery_1, filters_1) {
127
+ var args_1 = [];
128
+ for (var _i = 2; _i < arguments.length; _i++) {
129
+ args_1[_i - 2] = arguments[_i];
130
+ }
131
+ return __awaiter(void 0, __spreadArray([searchQuery_1, filters_1], args_1, true), void 0, function (searchQuery, filters, pageLimit) {
132
+ var response_1, cachedData, currentTime, cachedTime, ageInMs, response, updatedCache, error_1;
133
+ var _a;
134
+ if (pageLimit === void 0) { pageLimit = 100; }
135
+ return __generator(this, function (_b) {
136
+ switch (_b.label) {
137
+ case 0:
138
+ _b.trys.push([0, 4, , 5]);
139
+ if (!((searchQuery && searchQuery.trim()) ||
140
+ (filters && Object.keys(filters).length > 0))) return [3 /*break*/, 2];
141
+ return [4 /*yield*/, (0, fetch_data_1.fetchData)({
142
+ url: constants_1.API_ROUTES.PRODUCT_CATEGORIES,
143
+ body: JSON.stringify(__assign(__assign({ searchQuery: searchQuery }, filters), { pageLimit: pageLimit, currentPage: 1 })),
144
+ method: api_methods_1.API_METHODS.POST,
145
+ })];
146
+ case 1:
147
+ response_1 = _b.sent();
148
+ return [2 /*return*/, (response_1 === null || response_1 === void 0 ? void 0 : response_1.data) || { count: 0, items: [] }];
149
+ case 2:
150
+ cachedData = (0, get_storage_value_1.getStorageValue)(type_1.LS_KEYS.PRODUCT_CATEGORIES);
151
+ currentTime = new Date().getTime();
152
+ // Check if cached data exists and is still fresh
153
+ if (cachedData) {
154
+ cachedTime = new Date(cachedData.cachedAt).getTime();
155
+ ageInMs = currentTime - cachedTime;
156
+ // If cached data is less than 1 week old, return it
157
+ if (ageInMs < constants_1.ONE_DAY_IN_MS) {
158
+ return [2 /*return*/, {
159
+ count: cachedData.productCategories.length,
160
+ items: cachedData.productCategories,
161
+ }];
162
+ }
163
+ }
164
+ return [4 /*yield*/, (0, fetch_data_1.fetchData)({
165
+ url: constants_1.API_ROUTES.PRODUCT_CATEGORIES,
166
+ body: JSON.stringify({
167
+ pageLimit: pageLimit,
168
+ currentPage: 1,
169
+ }),
170
+ method: api_methods_1.API_METHODS.POST,
171
+ })];
172
+ case 3:
173
+ response = _b.sent();
174
+ if ((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.items) {
175
+ updatedCache = {
176
+ productCategories: response.data.items,
177
+ cachedAt: new Date().toISOString(),
178
+ };
179
+ (0, set_storage_value_1.setStorageValue)(type_1.LS_KEYS.PRODUCT_CATEGORIES, updatedCache);
180
+ return [2 /*return*/, response.data];
181
+ }
182
+ return [2 /*return*/, { count: 0, items: [] }];
183
+ case 4:
184
+ error_1 = _b.sent();
185
+ console.error('Error fetching product categories:', error_1);
186
+ return [2 /*return*/, { count: 0, items: [] }];
187
+ case 5: return [2 /*return*/];
188
+ }
189
+ });
190
+ });
191
+ };
192
+ exports.getCachedProductCategories = getCachedProductCategories;
193
+ /**
194
+ * Utility function to get a specific product category by ID from cache
195
+ * If not found in cache, returns null (does not trigger API call)
196
+ *
197
+ * @param categoryId - The ID of the category to retrieve
198
+ * @returns ProductCategoryBE | null - The category or null if not found
199
+ *
200
+ * @example
201
+ * const category = getCachedProductCategoryById('cat-123');
202
+ * if (category) {
203
+ * console.log(category.name);
204
+ * }
205
+ */
206
+ var getCachedProductCategoryById = function (categoryId) {
207
+ if (!categoryId) {
208
+ return null;
209
+ }
210
+ try {
211
+ var productCategories = (0, exports.getCachedProductCategoriesSync)().items;
212
+ return productCategories.find(function (cat) { return cat.id === categoryId; }) || null;
213
+ }
214
+ catch (error) {
215
+ console.error('Error getting cached product category by ID:', error);
216
+ return null;
217
+ }
218
+ };
219
+ exports.getCachedProductCategoryById = getCachedProductCategoryById;
220
+ /**
221
+ * Utility function to invalidate (remove) product categories from cache
222
+ * Useful when categories have been updated and you want to force a refresh
223
+ *
224
+ * @example
225
+ * invalidateProductCategoriesCache();
226
+ * const freshCategories = await getCachedProductCategories();
227
+ */
228
+ var invalidateProductCategoriesCache = function () {
229
+ try {
230
+ localStorage.removeItem(type_1.LS_KEYS.PRODUCT_CATEGORIES);
231
+ }
232
+ catch (error) {
233
+ console.error('Error invalidating product categories cache:', error);
234
+ }
235
+ };
236
+ exports.invalidateProductCategoriesCache = invalidateProductCategoriesCache;
237
+ /**
238
+ * Utility function to preload product categories into cache
239
+ * Useful to call on app initialization or login
240
+ *
241
+ * @returns Promise<ProductCategoryBE[]> - Array of preloaded categories
242
+ *
243
+ * @example
244
+ * // On app initialization
245
+ * await preloadProductCategories();
246
+ */
247
+ var preloadProductCategories = function () { return __awaiter(void 0, void 0, void 0, function () {
248
+ return __generator(this, function (_a) {
249
+ return [2 /*return*/, (0, exports.getCachedProductCategories)()];
250
+ });
251
+ }); };
252
+ exports.preloadProductCategories = preloadProductCategories;
253
+ /**
254
+ * Utility function to check if product categories cache is stale
255
+ * Returns true if cache is older than 1 week or doesn't exist
256
+ *
257
+ * @returns boolean - True if cache is stale or doesn't exist
258
+ *
259
+ * @example
260
+ * if (isProductCategoriesCacheStale()) {
261
+ * await getCachedProductCategories(); // This will fetch fresh data
262
+ * }
263
+ */
264
+ var isProductCategoriesCacheStale = function () {
265
+ try {
266
+ var cachedData = (0, get_storage_value_1.getStorageValue)(type_1.LS_KEYS.PRODUCT_CATEGORIES);
267
+ if (!cachedData) {
268
+ return true;
269
+ }
270
+ var currentTime = new Date().getTime();
271
+ var cachedTime = new Date(cachedData.cachedAt).getTime();
272
+ var ageInMs = currentTime - cachedTime;
273
+ return ageInMs >= constants_1.ONE_DAY_IN_MS;
274
+ }
275
+ catch (error) {
276
+ console.error('Error checking product categories cache staleness:', error);
277
+ return true;
278
+ }
279
+ };
280
+ exports.isProductCategoriesCacheStale = isProductCategoriesCacheStale;
@@ -1,3 +1,4 @@
1
+ export * from './cache';
1
2
  import { ProductCategoryBE } from '../type';
2
3
  type PrismaClient = any;
3
4
  export interface ListProductCategoryArgs {
@@ -48,4 +49,3 @@ export declare const updateProductCategory: ({ description, id, name, prisma, }:
48
49
  * @returns {Promise<ProductCategoryBE>} Deleted product category
49
50
  */
50
51
  export declare const deleteProductCategory: ({ id, prisma, }: DeleteProductCategoryArgs) => Promise<ProductCategoryBE>;
51
- export {};
@@ -10,6 +10,20 @@ var __assign = (this && this.__assign) || function () {
10
10
  };
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
25
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
26
+ };
13
27
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
28
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
29
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -57,6 +71,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
57
71
  };
58
72
  Object.defineProperty(exports, "__esModule", { value: true });
59
73
  exports.deleteProductCategory = exports.updateProductCategory = exports.unitProductCategoryById = exports.listProductCategory = void 0;
74
+ __exportStar(require("./cache"), exports);
60
75
  var multi_part_search_1 = require("../../../general/multi-part-search");
61
76
  /**
62
77
  * Retrieves a paginated list of product categories
@@ -0,0 +1,97 @@
1
+ import { TaxBE } from '../type';
2
+ /**
3
+ * Synchronous utility function to get taxes from cache only
4
+ * Returns cached data immediately if available and fresh, otherwise returns empty array
5
+ * Does not trigger any API calls
6
+ *
7
+ * @returns TaxBE[] - Array of cached taxes or empty array wrapper ({count, items})
8
+ *
9
+ * @example
10
+ * const taxes = getCachedTaxesSync();
11
+ * if (taxes.items.length > 0) {
12
+ * console.log(taxes.items[0].taxName);
13
+ * }
14
+ */
15
+ export declare const getCachedTaxesSync: () => {
16
+ count: number;
17
+ items: TaxBE[];
18
+ };
19
+ /**
20
+ * Utility function to get taxes from cache or fetch from API
21
+ *
22
+ * This function manages a localStorage cache of taxes with the following logic:
23
+ * - If taxes exist in cache and are less than 1 week old, return cached version
24
+ * - If taxes exist but are older than 1 week, fetch fresh data and update cache
25
+ * - If taxes don't exist in cache, fetch from API and cache them
26
+ *
27
+ * @returns Promise<{count:number, items: TaxBE[]}> - Paged taxes
28
+ *
29
+ * @example
30
+ * const taxes = await getCachedTaxes();
31
+ * console.log(taxes.items[0].taxName);
32
+ */
33
+ export declare const getCachedTaxes: () => Promise<{
34
+ count: number;
35
+ items: TaxBE[];
36
+ }>;
37
+ /**
38
+ * Utility function to get a specific tax by ID from cache
39
+ * If not found in cache, returns null (does not trigger API call)
40
+ *
41
+ * @param taxId - The ID of the tax to retrieve
42
+ * @returns TaxBE | null - The tax or null if not found
43
+ *
44
+ * @example
45
+ * const tax = getCachedTaxById('tax-123');
46
+ * if (tax) {
47
+ * console.log(tax.taxName);
48
+ * }
49
+ */
50
+ export declare const getCachedTaxById: (taxId: string) => TaxBE | null;
51
+ /**
52
+ * Utility function to get taxes by name from cache
53
+ * If not found in cache, returns empty array (does not trigger API call)
54
+ *
55
+ * @param taxName - The name of the tax to search for
56
+ * @returns TaxBE[] - Array of matching taxes or empty array
57
+ *
58
+ * @example
59
+ * const taxes = getCachedTaxesByName('VAT');
60
+ * console.log(taxes.length);
61
+ */
62
+ export declare const getCachedTaxesByName: (taxName: string) => TaxBE[];
63
+ /**
64
+ * Utility function to invalidate (remove) taxes from cache
65
+ * Useful when taxes have been updated and you want to force a refresh
66
+ *
67
+ * @example
68
+ * invalidateTaxesCache();
69
+ * const freshTaxes = await getCachedTaxes();
70
+ */
71
+ export declare const invalidateTaxesCache: () => void;
72
+ /**
73
+ * Utility function to preload taxes into cache
74
+ * Useful to call on app initialization or login
75
+ *
76
+ * @returns Promise<{count:number, items: TaxBE[]}> - Array of preloaded taxes
77
+ *
78
+ * @example
79
+ * // On app initialization
80
+ * await preloadTaxes();
81
+ */
82
+ export declare const preloadTaxes: () => Promise<{
83
+ count: number;
84
+ items: TaxBE[];
85
+ }>;
86
+ /**
87
+ * Utility function to check if taxes cache is stale
88
+ * Returns true if cache is older than 1 week or doesn't exist
89
+ *
90
+ * @returns boolean - True if cache is stale or doesn't exist
91
+ *
92
+ * @example
93
+ * if (isTaxesCacheStale()) {
94
+ * await getCachedTaxes(); // This will fetch fresh data
95
+ * }
96
+ */
97
+ export declare const isTaxesCacheStale: () => boolean;
@@ -0,0 +1,256 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.isTaxesCacheStale = exports.preloadTaxes = exports.invalidateTaxesCache = exports.getCachedTaxesByName = exports.getCachedTaxById = exports.getCachedTaxes = exports.getCachedTaxesSync = void 0;
40
+ var constants_1 = require("../constants");
41
+ var type_1 = require("../type");
42
+ var api_methods_1 = require("../../../constants/api-methods");
43
+ var fetch_data_1 = require("../../../general/fetch-data");
44
+ var get_storage_value_1 = require("../../../local-storage/get-storage-value");
45
+ var set_storage_value_1 = require("../../../local-storage/set-storage-value");
46
+ /**
47
+ * Synchronous utility function to get taxes from cache only
48
+ * Returns cached data immediately if available and fresh, otherwise returns empty array
49
+ * Does not trigger any API calls
50
+ *
51
+ * @returns TaxBE[] - Array of cached taxes or empty array wrapper ({count, items})
52
+ *
53
+ * @example
54
+ * const taxes = getCachedTaxesSync();
55
+ * if (taxes.items.length > 0) {
56
+ * console.log(taxes.items[0].taxName);
57
+ * }
58
+ */
59
+ var getCachedTaxesSync = function () {
60
+ try {
61
+ var cachedData = (0, get_storage_value_1.getStorageValue)(type_1.LS_KEYS.TAXES);
62
+ if (!cachedData) {
63
+ return { count: 0, items: [] };
64
+ }
65
+ var currentTime = new Date().getTime();
66
+ var cachedTime = new Date(cachedData.cachedAt).getTime();
67
+ var ageInMs = currentTime - cachedTime;
68
+ // If cached data is less than 1 week old, return it
69
+ if (ageInMs < constants_1.ONE_WEEK_IN_MS) {
70
+ return {
71
+ count: cachedData.taxes.length,
72
+ items: cachedData.taxes,
73
+ };
74
+ }
75
+ return { count: 0, items: [] };
76
+ }
77
+ catch (error) {
78
+ console.error('Error getting cached taxes:', error);
79
+ return { count: 0, items: [] };
80
+ }
81
+ };
82
+ exports.getCachedTaxesSync = getCachedTaxesSync;
83
+ /**
84
+ * Utility function to get taxes from cache or fetch from API
85
+ *
86
+ * This function manages a localStorage cache of taxes with the following logic:
87
+ * - If taxes exist in cache and are less than 1 week old, return cached version
88
+ * - If taxes exist but are older than 1 week, fetch fresh data and update cache
89
+ * - If taxes don't exist in cache, fetch from API and cache them
90
+ *
91
+ * @returns Promise<{count:number, items: TaxBE[]}> - Paged taxes
92
+ *
93
+ * @example
94
+ * const taxes = await getCachedTaxes();
95
+ * console.log(taxes.items[0].taxName);
96
+ */
97
+ var getCachedTaxes = function () { return __awaiter(void 0, void 0, void 0, function () {
98
+ var cachedData, currentTime, cachedTime, ageInMs, response, updatedCache, error_1;
99
+ var _a;
100
+ return __generator(this, function (_b) {
101
+ switch (_b.label) {
102
+ case 0:
103
+ _b.trys.push([0, 2, , 3]);
104
+ cachedData = (0, get_storage_value_1.getStorageValue)(type_1.LS_KEYS.TAXES);
105
+ currentTime = new Date().getTime();
106
+ // Check if cached data exists and is still fresh
107
+ if (cachedData) {
108
+ cachedTime = new Date(cachedData.cachedAt).getTime();
109
+ ageInMs = currentTime - cachedTime;
110
+ // If cached data is less than 1 week old, return it
111
+ if (ageInMs < constants_1.ONE_WEEK_IN_MS) {
112
+ return [2 /*return*/, {
113
+ count: cachedData.taxes.length,
114
+ items: cachedData.taxes,
115
+ }];
116
+ }
117
+ }
118
+ return [4 /*yield*/, (0, fetch_data_1.fetchData)({
119
+ url: constants_1.API_ROUTES.TAXES,
120
+ method: api_methods_1.API_METHODS.GET,
121
+ })];
122
+ case 1:
123
+ response = _b.sent();
124
+ if ((_a = response === null || response === void 0 ? void 0 : response.data) === null || _a === void 0 ? void 0 : _a.items) {
125
+ updatedCache = {
126
+ taxes: response.data.items,
127
+ cachedAt: new Date().toISOString(),
128
+ };
129
+ (0, set_storage_value_1.setStorageValue)(type_1.LS_KEYS.TAXES, updatedCache);
130
+ return [2 /*return*/, response.data];
131
+ }
132
+ return [2 /*return*/, { count: 0, items: [] }];
133
+ case 2:
134
+ error_1 = _b.sent();
135
+ console.error('Error fetching taxes:', error_1);
136
+ return [2 /*return*/, { count: 0, items: [] }];
137
+ case 3: return [2 /*return*/];
138
+ }
139
+ });
140
+ }); };
141
+ exports.getCachedTaxes = getCachedTaxes;
142
+ /**
143
+ * Utility function to get a specific tax by ID from cache
144
+ * If not found in cache, returns null (does not trigger API call)
145
+ *
146
+ * @param taxId - The ID of the tax to retrieve
147
+ * @returns TaxBE | null - The tax or null if not found
148
+ *
149
+ * @example
150
+ * const tax = getCachedTaxById('tax-123');
151
+ * if (tax) {
152
+ * console.log(tax.taxName);
153
+ * }
154
+ */
155
+ var getCachedTaxById = function (taxId) {
156
+ if (!taxId) {
157
+ return null;
158
+ }
159
+ try {
160
+ var taxes = (0, exports.getCachedTaxesSync)().items;
161
+ return taxes.find(function (tax) { return tax.id === taxId; }) || null;
162
+ }
163
+ catch (error) {
164
+ console.error('Error getting cached tax by ID:', error);
165
+ return null;
166
+ }
167
+ };
168
+ exports.getCachedTaxById = getCachedTaxById;
169
+ /**
170
+ * Utility function to get taxes by name from cache
171
+ * If not found in cache, returns empty array (does not trigger API call)
172
+ *
173
+ * @param taxName - The name of the tax to search for
174
+ * @returns TaxBE[] - Array of matching taxes or empty array
175
+ *
176
+ * @example
177
+ * const taxes = getCachedTaxesByName('VAT');
178
+ * console.log(taxes.length);
179
+ */
180
+ var getCachedTaxesByName = function (taxName) {
181
+ if (!taxName) {
182
+ return [];
183
+ }
184
+ try {
185
+ var taxes = (0, exports.getCachedTaxesSync)().items;
186
+ return taxes.filter(function (tax) {
187
+ return tax.taxName.toLowerCase().includes(taxName.toLowerCase());
188
+ });
189
+ }
190
+ catch (error) {
191
+ console.error('Error getting cached taxes by name:', error);
192
+ return [];
193
+ }
194
+ };
195
+ exports.getCachedTaxesByName = getCachedTaxesByName;
196
+ /**
197
+ * Utility function to invalidate (remove) taxes from cache
198
+ * Useful when taxes have been updated and you want to force a refresh
199
+ *
200
+ * @example
201
+ * invalidateTaxesCache();
202
+ * const freshTaxes = await getCachedTaxes();
203
+ */
204
+ var invalidateTaxesCache = function () {
205
+ try {
206
+ localStorage.removeItem(type_1.LS_KEYS.TAXES);
207
+ }
208
+ catch (error) {
209
+ console.error('Error invalidating taxes cache:', error);
210
+ }
211
+ };
212
+ exports.invalidateTaxesCache = invalidateTaxesCache;
213
+ /**
214
+ * Utility function to preload taxes into cache
215
+ * Useful to call on app initialization or login
216
+ *
217
+ * @returns Promise<{count:number, items: TaxBE[]}> - Array of preloaded taxes
218
+ *
219
+ * @example
220
+ * // On app initialization
221
+ * await preloadTaxes();
222
+ */
223
+ var preloadTaxes = function () { return __awaiter(void 0, void 0, void 0, function () {
224
+ return __generator(this, function (_a) {
225
+ return [2 /*return*/, (0, exports.getCachedTaxes)()];
226
+ });
227
+ }); };
228
+ exports.preloadTaxes = preloadTaxes;
229
+ /**
230
+ * Utility function to check if taxes cache is stale
231
+ * Returns true if cache is older than 1 week or doesn't exist
232
+ *
233
+ * @returns boolean - True if cache is stale or doesn't exist
234
+ *
235
+ * @example
236
+ * if (isTaxesCacheStale()) {
237
+ * await getCachedTaxes(); // This will fetch fresh data
238
+ * }
239
+ */
240
+ var isTaxesCacheStale = function () {
241
+ try {
242
+ var cachedData = (0, get_storage_value_1.getStorageValue)(type_1.LS_KEYS.TAXES);
243
+ if (!cachedData) {
244
+ return true;
245
+ }
246
+ var currentTime = new Date().getTime();
247
+ var cachedTime = new Date(cachedData.cachedAt).getTime();
248
+ var ageInMs = currentTime - cachedTime;
249
+ return ageInMs >= constants_1.ONE_WEEK_IN_MS;
250
+ }
251
+ catch (error) {
252
+ console.error('Error checking taxes cache staleness:', error);
253
+ return true;
254
+ }
255
+ };
256
+ exports.isTaxesCacheStale = isTaxesCacheStale;
@@ -1,3 +1,4 @@
1
+ export * from './cache';
1
2
  import { TaxBE } from '../type';
2
3
  type PrismaClient = any;
3
4
  export interface ListTaxArgs {
@@ -52,4 +53,3 @@ export declare const updateTax: ({ description, enabled, id, isDefault, preferen
52
53
  * @returns {Promise<TaxBE>} Deleted tax
53
54
  */
54
55
  export declare const deleteTax: ({ id, prisma, }: DeleteTaxArgs) => Promise<TaxBE>;
55
- export {};