@smartico/public-api 0.0.378 → 0.0.380

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 (99) hide show
  1. package/.nvmrc +1 -1
  2. package/README.md +31 -2
  3. package/dist/Store/BuyStoreItemErrorCode.d.ts +9 -1
  4. package/dist/Tournaments/TournamentRegistrationError.d.ts +3 -1
  5. package/dist/WSAPI/WSAPI.d.ts +13 -1235
  6. package/dist/WSAPI/WSAPIAvatars.d.ts +78 -0
  7. package/dist/WSAPI/WSAPIBase.d.ts +71 -0
  8. package/dist/WSAPI/WSAPIBonuses.d.ts +26 -0
  9. package/dist/WSAPI/WSAPIClans.d.ts +388 -0
  10. package/dist/WSAPI/WSAPIGamePick.d.ts +308 -0
  11. package/dist/WSAPI/WSAPIGeneral.d.ts +30 -0
  12. package/dist/WSAPI/WSAPIInbox.d.ts +126 -0
  13. package/dist/WSAPI/WSAPIJackpots.d.ts +109 -0
  14. package/dist/WSAPI/WSAPILeaderBoard.d.ts +25 -0
  15. package/dist/WSAPI/WSAPIMiniGames.d.ts +94 -0
  16. package/dist/WSAPI/WSAPIMissions.d.ts +517 -0
  17. package/dist/WSAPI/WSAPIRaffles.d.ts +119 -0
  18. package/dist/WSAPI/WSAPIStore.d.ts +656 -0
  19. package/dist/WSAPI/WSAPITournaments.d.ts +501 -0
  20. package/dist/WSAPI/WSAPITypes.d.ts +145 -85
  21. package/dist/WSAPI/WSAPIUser.d.ts +383 -0
  22. package/dist/index.js +3818 -1528
  23. package/dist/index.js.map +1 -1
  24. package/dist/index.modern.mjs +3180 -981
  25. package/dist/index.modern.mjs.map +1 -1
  26. package/docs/api/README.md +56 -2
  27. package/docs/api/classes/WSAPIAvatars.md +116 -0
  28. package/docs/api/classes/WSAPIBonuses.md +50 -0
  29. package/docs/api/classes/WSAPIClans.md +66 -0
  30. package/docs/api/classes/WSAPIGamePick.md +181 -0
  31. package/docs/api/classes/WSAPIGeneral.md +63 -0
  32. package/docs/api/classes/WSAPIInbox.md +277 -0
  33. package/docs/api/classes/WSAPIJackpots.md +185 -0
  34. package/docs/api/classes/WSAPILeaderBoard.md +39 -0
  35. package/docs/api/classes/WSAPIMiniGames.md +175 -0
  36. package/docs/api/classes/WSAPIMissions.md +611 -0
  37. package/docs/api/classes/WSAPIRaffles.md +195 -0
  38. package/docs/api/classes/WSAPIStore.md +744 -0
  39. package/docs/api/classes/WSAPITournaments.md +104 -0
  40. package/docs/api/classes/WSAPIUser.md +200 -0
  41. package/docs/api/enumerations/AchievementClaimPeriodTypeId.md +13 -0
  42. package/docs/api/enumerations/BuyStoreItemErrorCode.md +32 -0
  43. package/docs/api/interfaces/ClanPrizePublicMeta.md +41 -0
  44. package/docs/api/interfaces/ClanPrizeStructureEntry.md +7 -1
  45. package/docs/api/interfaces/ClanPublicMeta.md +4 -0
  46. package/docs/api/interfaces/SAWTemplateUI.md +10 -0
  47. package/docs/api/interfaces/TAchCategory.md +19 -4
  48. package/docs/api/interfaces/TBuyStoreItemResult.md +26 -8
  49. package/docs/api/interfaces/TMissionClaimRewardResult.md +14 -3
  50. package/docs/api/interfaces/TMissionOptInResult.md +10 -3
  51. package/docs/api/interfaces/TMissionOrBadge.md +6 -2
  52. package/docs/api/interfaces/TStoreItem.md +21 -1
  53. package/docs/api/interfaces/TTournamentDetailed.md +8 -0
  54. package/docs/api/interfaces/UserAchievement.md +1 -1
  55. package/docs/ui/clans/UIGuide_getClanInfo.md +153 -0
  56. package/docs/ui/clans/UIGuide_getClans.md +172 -0
  57. package/docs/ui/clans/UIGuide_joinClan.md +196 -0
  58. package/docs/ui/missions/UIGuide_getAchCategories.md +17 -0
  59. package/docs/ui/missions/UIGuide_getBadges.md +237 -0
  60. package/docs/ui/missions/UIGuide_getMissions.md +268 -0
  61. package/docs/ui/missions/UIGuide_requestMissionClaimReward.md +21 -0
  62. package/docs/ui/missions/UIGuide_requestMissionOptIn.md +16 -0
  63. package/docs/ui/store/UIGuide_buyStoreItem.md +133 -0
  64. package/docs/ui/store/UIGuide_getStoreCategories.md +19 -0
  65. package/docs/ui/store/UIGuide_getStoreItems.md +264 -0
  66. package/docs/ui/store/UIGuide_getStorePurchasedItems.md +122 -0
  67. package/docs/ui/tournaments/UIGuide_getClanTournamentPlayers.md +140 -0
  68. package/docs/ui/tournaments/UIGuide_getTournamentInstanceInfo.md +265 -0
  69. package/docs/ui/tournaments/UIGuide_getTournamentsList.md +236 -0
  70. package/docs/ui/tournaments/UIGuide_registerInTournament.md +156 -0
  71. package/docs/ui/user/UIGuide_getLevels.md +162 -0
  72. package/docs/ui/user/UIGuide_getUserProfile.md +213 -0
  73. package/package.json +3 -3
  74. package/scripts/postdoc-cleanup.js +195 -0
  75. package/src/Missions/MissionsUtils.ts +5 -2
  76. package/src/Store/BuyStoreItemErrorCode.ts +8 -0
  77. package/src/Store/StoreItem.ts +1 -0
  78. package/src/Store/StoreItemPurchased.ts +1 -0
  79. package/src/Store/StoreItemType.ts +1 -1
  80. package/src/Tournaments/TournamentRegistrationError.ts +4 -0
  81. package/src/WSAPI/WSAPI.ts +27 -2007
  82. package/src/WSAPI/WSAPIAvatars.ts +127 -0
  83. package/src/WSAPI/WSAPIBase.ts +93 -0
  84. package/src/WSAPI/WSAPIBonuses.ts +54 -0
  85. package/src/WSAPI/WSAPIClans.ts +417 -0
  86. package/src/WSAPI/WSAPIGamePick.ts +382 -0
  87. package/src/WSAPI/WSAPIGeneral.ts +57 -0
  88. package/src/WSAPI/WSAPIInbox.ts +222 -0
  89. package/src/WSAPI/WSAPIJackpots.ts +212 -0
  90. package/src/WSAPI/WSAPILeaderBoard.ts +40 -0
  91. package/src/WSAPI/WSAPIMiniGames.ts +181 -0
  92. package/src/WSAPI/WSAPIMissions.ts +572 -0
  93. package/src/WSAPI/WSAPIRaffles.ts +175 -0
  94. package/src/WSAPI/WSAPIStore.ts +732 -0
  95. package/src/WSAPI/WSAPITournaments.ts +541 -0
  96. package/src/WSAPI/WSAPITypes.ts +145 -87
  97. package/src/WSAPI/WSAPIUser.ts +456 -0
  98. package/tsconfig.json +17 -1
  99. package/docs/api/classes/WSAPI.md +0 -1927
@@ -0,0 +1,732 @@
1
+ import { ECacheContext, OCache } from '../OCache';
2
+ import {
3
+ TBuyStoreItemResult,
4
+ TStoreCategory,
5
+ TStoreItem,
6
+ } from './WSAPITypes';
7
+ import {
8
+ CACHE_DATA_SEC,
9
+ onUpdateContextKey,
10
+ } from './WSAPIBase';
11
+ import { WSAPIBonuses } from './WSAPIBonuses';
12
+
13
+ /** @group Store */
14
+ export class WSAPIStore extends WSAPIBonuses {
15
+ private storeHistoryOnUpdateParams: { limit: number; offset: number } = { limit: 20, offset: 0 };
16
+
17
+ private storeHistoryCacheKey(limit: number, offset: number): string {
18
+ return `${onUpdateContextKey.StoreHistory}:${limit}:${offset}`;
19
+ }
20
+
21
+ /**
22
+ * Returns the catalog of buyable store items visible to the current user,
23
+ * scoped server-side to what the user is qualified to see. Optionally
24
+ * subscribes to live updates via `onUpdate`: the callback is invoked with
25
+ * the full refreshed catalog after every purchase the user makes from this
26
+ * device.
27
+ *
28
+ * The returned list is the canonical source of truth for store state
29
+ * (`can_buy`, `pool`, `discounted_price`, `active_till_date`, etc.).
30
+ * Consumers should NEVER mutate it optimistically — always re-fetch (or
31
+ * wait for the `onUpdate` callback) to observe the new state.
32
+ *
33
+ * @remarks
34
+ * **Preconditions**
35
+ * The catalog is per-user. Visitor mode is supported with caveats (see
36
+ * "Visitor mode" below). For the authenticated path, the user's balances
37
+ * (`ach_points_balance`, `ach_gems_balance`, `ach_diamonds_balance` from
38
+ * {@link getUserProfile}) must be tracked client-side to drive the
39
+ * affordability state of the Buy button — the SDK does not pre-compute
40
+ * affordability into `can_buy`.
41
+ *
42
+ * **Subscription model (`onUpdate`)**
43
+ * The callback receives the FULL refreshed catalog (never a diff/patch).
44
+ * Each subsequent call to `getStoreItems({ onUpdate })` REPLACES the prior
45
+ * callback — only one active subscriber at a time. Pass
46
+ * `onUpdate: undefined` (or omit it) to keep the prior callback in place;
47
+ * the callback is never auto-cleared.
48
+ *
49
+ * **Update triggers**
50
+ *
51
+ * Fires after: any `buyStoreItem(...)` call resolves on this connection
52
+ * (success OR failure). This is the ONLY trigger. The refreshed array
53
+ * reflects pool decrement on the just-bought item, per-period purchase
54
+ * cap re-evaluation on `can_buy`, and any `purchased_today` /
55
+ * `purchased_this_week` / `purchased_this_month` flips visible via
56
+ * {@link getStorePurchasedItems}.
57
+ *
58
+ * Does NOT fire for:
59
+ * - Operator-side BO catalog edits (price, ribbons, pool seed, segment
60
+ * conditions, new/removed items) — surface only on the next cache miss.
61
+ * - Concurrent purchases by OTHER users — the current user's view of
62
+ * `pool` may be stale until they themselves refresh.
63
+ * - User balance changes from gameplay — the catalog is independent of
64
+ * balance; the consumer drives Buy-button affordability from a
65
+ * separately-tracked balance source.
66
+ * - Items going past their `active_till_date` while the page is open —
67
+ * the item simply disappears on the next refresh.
68
+ *
69
+ * **Server-side filtering** (what's already excluded before the SDK sees it)
70
+ * - Items outside the `[active_from_date, active_till_date]` window —
71
+ * past the till-date, items are ALWAYS filtered out server-side.
72
+ * - Items the user fails visibility-segment / visibility-condition
73
+ * checks for.
74
+ * - Items configured to hide-when-empty whose pool has reached 0
75
+ * (per-item operator flag). Items without that flag are still returned
76
+ * with `pool === 0` so a "Sold out" state can be rendered.
77
+ * - Items where the per-period bought-count cap is reached (and the
78
+ * operator chose to hide rather than just disable).
79
+ *
80
+ * **Reading state from the returned item**
81
+ * The catalog row carries everything a Buy button needs except the user's
82
+ * balance: `can_buy` already reflects segment / visibility / per-period
83
+ * cap checks, but the SDK does NOT pre-compute balance affordability —
84
+ * compare `discounted_price ?? price` against the user's balance for
85
+ * `purchase_type` (`ach_points_balance` / `ach_gems_balance` /
86
+ * `ach_diamonds_balance` from {@link getUserProfile}). `purchase_type` is
87
+ * per-item (`'points'` / `'gems'` / `'diamonds'`); operators can mix
88
+ * currencies within a single catalog. For sold-out display, `pool === 0`
89
+ * means the operator chose to keep the item visible — render an "Out of
90
+ * stock" overlay. When `discounted_price` is set, render `price` with a
91
+ * strikethrough and `discounted_price` as the active price; the
92
+ * accompanying `discount_price_ribbon` is either a percentage preset
93
+ * (`'10'`, `'15'`, `'20'`, `'25'`, `'50'`) or the literal `'custom'`
94
+ * (in which case `custom_ribbon_image` is the artwork at 250×300 px).
95
+ * A live countdown for time-limited items is rendered only when the
96
+ * operator has enabled the per-item `show_timer` flag.
97
+ *
98
+ * **Cross-references**
99
+ * `category_ids` joins to `TStoreCategory.id` from
100
+ * {@link getStoreCategories} (many-to-many — an item can belong to
101
+ * multiple categories). Items with `only_in_custom_section: true` are
102
+ * returned in the catalog but intended for their custom-section view
103
+ * only — filter them client-side for the main store view. The
104
+ * history-only fields (`purchase_ts`, `purchase_points_amount`, the
105
+ * `purchased_*` booleans) are populated only by
106
+ * {@link getStorePurchasedItems}, not by this method.
107
+ *
108
+ * **Idempotency**: yes. `getStoreItems` is a pure read. Calling it
109
+ * repeatedly within the 30-second cache window resolves from the cache
110
+ * without a network round-trip.
111
+ *
112
+ * **Side effects** (of a successful purchase that triggers `onUpdate`)
113
+ * Documented here because the consumer's `onUpdate` handler will observe
114
+ * the resulting state changes on the next refreshed array:
115
+ * - Points / gems / diamonds balance deducted per `purchase_type`. The
116
+ * new balance becomes visible on the user's gamification profile via
117
+ * the SDK's user-properties update channel (`ach_points_balance` /
118
+ * `ach_gems_balance` / `ach_diamonds_balance`).
119
+ * - `pool` decremented for limited-stock items.
120
+ * - `type = 'bonus'` → a CRM bonus is granted; surfaces via
121
+ * {@link getBonuses}.
122
+ * - `type = 'raffleticket'` → raffle tickets granted; surfaces via
123
+ * `getRaffles`.
124
+ * - `type = 'changelevel'` → user's level adjusted; surfaces via
125
+ * {@link getCurrentLevel}.
126
+ * - `type = 'minigamespin'` → SAW spin attempts granted; visible via the
127
+ * mini-game APIs.
128
+ * - `type = 'prizedrop'` → one prize-drop attempt granted.
129
+ * - `type = 'tangible'` → no automatic gameplay effect; the purchase is
130
+ * recorded for the operator's manual fulfillment (e.g. physical merch).
131
+ *
132
+ * **UI guidance**: see [UI Guide — `getStoreItems`](../../docs/ui/store/UIGuide_getStoreItems.md).
133
+ *
134
+ * @param params Optional. Omit to fetch without subscribing.
135
+ * @param params.onUpdate Callback invoked with the full refreshed
136
+ * catalog after every {@link buyStoreItem}
137
+ * round-trip on this connection. Each call to
138
+ * `getStoreItems` overwrites the prior
139
+ * callback. Never fires in visitor mode.
140
+ * @returns Promise resolving to the catalog of store
141
+ * items visible to the user. Empty array if
142
+ * the user has no items (or if the visitor
143
+ * proxy user has none configured).
144
+ *
145
+ * @example
146
+ * ```ts
147
+ * // 1. Initial fetch + subscribe to live updates
148
+ * const items = await window._smartico.api.getStoreItems({
149
+ * onUpdate: (refreshed) => {
150
+ * console.log('[smartico] store catalog refreshed after a purchase — re-render the entire store UI from this array, do not merge with prior state:', refreshed);
151
+ *
152
+ * // 2. onUpdate fires only after the current user's own purchase
153
+ * // round-trip. Pool counts and can_buy flags are now current
154
+ * // for this user.
155
+ * const soldOut = refreshed.filter(i => i.pool === 0);
156
+ * if (soldOut.length > 0) {
157
+ * console.log('[smartico] these items are now sold out — render an "Out of stock" overlay on each:', soldOut.map(i => i.id));
158
+ * }
159
+ * },
160
+ * });
161
+ *
162
+ * // 3. Live affordability per item. Compare each item's price against
163
+ * // the user's balance for its purchase_type (read from
164
+ * // getUserProfile(), kept live by the SDK's user-properties channel).
165
+ * const profile = window._smartico.api.getUserProfile();
166
+ * const balances = {
167
+ * points: profile?.ach_points_balance ?? 0,
168
+ * gems: profile?.ach_gems_balance ?? 0,
169
+ * diamonds: profile?.ach_diamonds_balance ?? 0,
170
+ * };
171
+ *
172
+ * // 4. Filter out items that are custom-section-only for the main view.
173
+ * const mainViewItems = items.filter(i => !i.only_in_custom_section);
174
+ *
175
+ * // 5. Bucket each item's button state for rendering.
176
+ * for (const i of mainViewItems) {
177
+ * const activePrice = i.discounted_price ?? i.price;
178
+ * const canAfford = balances[i.purchase_type] >= activePrice;
179
+ * if (i.pool === 0) {
180
+ * console.log('[smartico] item', i.id, 'is sold out — render disabled Buy with "Out of stock" overlay');
181
+ * } else if (i.can_buy === false) {
182
+ * console.log('[smartico] item', i.id, 'is not eligible — render disabled Buy and surface cant_buy_message on the popup:', i.cant_buy_message);
183
+ * } else if (!canAfford) {
184
+ * console.log('[smartico] item', i.id, 'is unaffordable — render disabled Buy and show "short by" line on popup; deficit =', activePrice - balances[i.purchase_type], i.purchase_type);
185
+ * } else {
186
+ * console.log('[smartico] item', i.id, 'is buyable — render enabled Buy at price', activePrice, i.purchase_type);
187
+ * }
188
+ * }
189
+ *
190
+ * // 6. Visitor-mode equivalent: onUpdate is accepted but never fires.
191
+ * // Re-poll if you need fresh data; buyStoreItem is not supported.
192
+ * // const visitorItems = await window._smartico.vapi('EN').getStoreItems();
193
+ * // console.log('[smartico] visitor catalog is the brand proxy user\'s — per-user fields are not meaningful');
194
+ * ```
195
+ */
196
+ public async getStoreItems({ onUpdate }: { onUpdate?: (data: TStoreItem[]) => void } = {}): Promise<TStoreItem[]> {
197
+ if (onUpdate) {
198
+ this.onUpdateCallback.set(onUpdateContextKey.StoreItems, onUpdate);
199
+ }
200
+ return OCache.use(
201
+ onUpdateContextKey.StoreItems,
202
+ ECacheContext.WSAPI,
203
+ () => this.api.storeGetItemsT(this.userExtId),
204
+ CACHE_DATA_SEC,
205
+ );
206
+ }
207
+
208
+ /**
209
+ * Purchase a specific store item on behalf of the current user. Spends
210
+ * the user's points / gems / diamonds (depending on the item's
211
+ * `purchase_type`) and triggers reward delivery (bonus issuance, mini-game
212
+ * spin grant, level change, prize-drop, raffle ticket, or tangible item).
213
+ *
214
+ * A successful response (`err_code === 0`) means the funds have already
215
+ * been debited and the reward has been queued / granted server-side. The
216
+ * user's balance change arrives over a separate push channel, not in this
217
+ * response — see "Refresh after success" below.
218
+ *
219
+ * @remarks
220
+ * **Preconditions**
221
+ * Read the candidate item from `getStoreItems()` first and gate the call
222
+ * on these fields:
223
+ * - `can_buy === true` — server-derived; combines segment / visibility
224
+ * conditions and any operator-set restrictions.
225
+ * - `pool == null || pool > 0` — `null` means unlimited stock; a positive
226
+ * number means N units remain.
227
+ * - User's balance for the item's `purchase_type`
228
+ * (`'points'` / `'gems'` / `'diamonds'`) is `>= price` (or
229
+ * `>= discounted_price` if set). Balances are not on `TStoreItem` —
230
+ * read them from the user properties returned by `getUserState()`.
231
+ * - If `active_till_date` is set, it is in the future.
232
+ *
233
+ * Calling without satisfying these will most likely return a non-zero
234
+ * `err_code` (one of the codes below). The SDK does not pre-validate
235
+ * — it forwards the request to the server unconditionally.
236
+ *
237
+ * **Error codes** (in `err_code`)
238
+ * - `0` — success; funds debited and reward delivered.
239
+ * - `1` — generic server error / control-group rejection. Treat as a
240
+ * transient failure; show a "try again later" message.
241
+ * - `106` — label mismatch detected before the purchase transaction
242
+ * (e.g. cross-label item id). From a consumer perspective: the item is
243
+ * not purchasable by this user.
244
+ * - `11000` (`SHOP_NO_BALANCE`) — insufficient **points** balance.
245
+ * Show an insufficient-balance message that names how many points are
246
+ * missing (`price - current_points_balance`). The Buy button on the
247
+ * item should already be disabled when this is the case; this code
248
+ * normally fires only on a stale local balance.
249
+ * - `11001` (`SHOP_WRONG_LABEL`) — user-vs-item label mismatch detected
250
+ * inside the purchase transaction. Distinct from `106`; both mean
251
+ * "not purchasable by this user" from the consumer's perspective.
252
+ * Surface as a generic "item not available" message.
253
+ * - `11002` (`SHOP_FAILED_TO_BUY_BONUS`) — the bonus configured on the
254
+ * store item couldn't be issued (bad / disabled bonus config on the
255
+ * operator side). Funds are NOT debited. Surface a generic error and
256
+ * advise the user to contact support if it persists.
257
+ * - `11003` (`SHOP_FAILED_TO_BUY_SHOP_ITEM_CONDITION`) — the item's
258
+ * **visibility** segment condition is not satisfied. Shouldn't be
259
+ * reachable through a correctly-rendered UI (the item shouldn't be
260
+ * shown in the first place); usually indicates a stale local store
261
+ * list. Re-fetch via `getStoreItems()`.
262
+ * - `11004` (`SHOP_FAILED_TO_BUY_SHOP_ITEM_CONDITION_PURSHASE`) — the
263
+ * item's **purchase** segment condition is not satisfied (the item is
264
+ * visible but the user is not in the buyable segment). Surface a
265
+ * localized "try again later" / "you're not eligible" message; do not
266
+ * retry automatically.
267
+ * - `11005` (`SHOP_FAILED_TO_BUY_MATCHING_BONUS`) — matching-bonus
268
+ * coupon issuance failed (variant of `11002` for matching-deposit
269
+ * bonuses). Funds are NOT debited. Surface a generic error.
270
+ * - `11006` (`SHOP_FAILED_MAX_BOUGHT_ITEMS_REACHED`) — per-user purchase
271
+ * cap reached (e.g. "max 1 per day"). Surface the item's
272
+ * `limit_message` if set, otherwise `err_message`. Do not retry.
273
+ * - `11007` — bonus was issued but a follow-up redemption step failed
274
+ * server-side. Funds **are** debited and the purchase event is recorded;
275
+ * the consumer's UI should refresh the store list (auto-refresh will
276
+ * fire) and surface a soft warning rather than a hard error.
277
+ * - `11009` (`SHOP_FAILED_POOL_EMPTY`) — stock pool is empty / sold out.
278
+ * Show a "sold out" message; auto-refresh will mark the item as such
279
+ * in subsequent `getStoreItems()` updates.
280
+ * - `11011` (`SHOP_NO_BALANCE_GEMS`) — insufficient **gems** balance.
281
+ * Same handling as `11000` but for the gems currency.
282
+ * - `11012` (`SHOP_NO_BALANCE_DIAMONDS`) — insufficient **diamonds**
283
+ * balance. Same handling as `11000` but for the diamonds currency.
284
+ * - `11014` (`SHOP_FAILED_PURCHASE_LIMITATION`) — outside the configured
285
+ * purchase window (purchase weekday / time-of-day / window). Surface
286
+ * the item's `purchase_limit_message` if set, otherwise `err_message`.
287
+ * - `9999` — uncaught server exception. Treat as a transient failure;
288
+ * surface a generic error and allow retry.
289
+ * - other non-zero — generic server error. Surface `err_message` if any.
290
+ *
291
+ * **Idempotency**: NOT idempotent. The server performs no de-duplication —
292
+ * a second successful call deducts funds again and grants the reward
293
+ * again (subject to per-user purchase caps). The SDK itself does **not**
294
+ * enforce a single in-flight call. The consumer MUST guard the call site
295
+ * against double-clicks (set a local "buying" flag on click, clear it on
296
+ * response).
297
+ *
298
+ * **Refresh after success (and after failure)**
299
+ * The SDK automatically re-fetches the store item list and the
300
+ * purchased-items history on every response (success or error). Any
301
+ * `onUpdate` callback registered via `getStoreItems({ onUpdate })` (or
302
+ * the purchased-items equivalent) fires shortly after with the updated
303
+ * arrays — reflecting the new `pool`, `can_buy`, and any `purchased_*`
304
+ * flags. The user's balance (points / gems / diamonds) is exposed on the
305
+ * user-properties channel and updates independently; if the UI displays
306
+ * the balance, subscribe to user-property updates separately (it does
307
+ * NOT flow through `getStoreItems`).
308
+ *
309
+ * **Side effects** (consumer-observable on success)
310
+ * - User's points / gems / diamonds balance decreases by `price`
311
+ * (or `discounted_price` if set).
312
+ * - Item's `pool` decrements by 1 (when `pool != null`).
313
+ * - Per-user purchase counters update — `purchased_today`,
314
+ * `purchased_this_week`, `purchased_this_month` on the next
315
+ * `getStoreItems()` refresh.
316
+ * - The reward is delivered: bonus issuance, mini-game spin grant,
317
+ * level change, prize drop, raffle ticket, or tangible-item record.
318
+ * Each reward type pushes its own follow-up update (e.g. a new
319
+ * bonus appears in `getBonuses()`, the spin shows up in
320
+ * `getMiniGames()`). Subscribe to each relevant channel separately.
321
+ * - A purchase row is appended to the user's purchase history,
322
+ * surfaced via the purchased-items list.
323
+ *
324
+ * **UI guidance**: see [UI Guide — `buyStoreItem`](../../docs/ui/store/UIGuide_buyStoreItem.md).
325
+ *
326
+ * @param item_id The store item `id` (from `getStoreItems()`).
327
+ * @returns `{ err_code, err_message }`; success when `err_code === 0`.
328
+ *
329
+ * @example
330
+ * ```ts
331
+ * const items = await window._smartico.api.getStoreItems({
332
+ * onUpdate: (next) => console.log('[smartico] store items updated — re-render store grid with this fresh array', next),
333
+ * });
334
+ * const item = items.find(i => i.id === itemId);
335
+ *
336
+ * if (!item) {
337
+ * console.log('[smartico] item not in current store list — keep UI as-is, possibly refresh getStoreItems');
338
+ * return;
339
+ * }
340
+ *
341
+ * // Local pre-checks: keep these aligned with the Buy-button decision matrix above.
342
+ * const effectivePrice = item.discounted_price ?? item.price;
343
+ * const inStock = item.pool == null || item.pool > 0;
344
+ * const inWindow = !item.active_till_date || Date.now() < item.active_till_date;
345
+ * if (!item.can_buy || !inStock || !inWindow) {
346
+ * console.log('[smartico] buy not applicable — show disabled state with operator copy if any:', item.cant_buy_message);
347
+ * return;
348
+ * }
349
+ *
350
+ * console.log('[smartico] buy starting — set in-flight flag, show loading dots on Buy button, keep detail modal open');
351
+ * const r = await window._smartico.api.buyStoreItem(item.id);
352
+ * console.log('[smartico] buy response received — clear in-flight flag');
353
+ *
354
+ * if (r.err_code === 0) {
355
+ * console.log('[smartico] purchase successful — close the detail modal, show a success toast; getStoreItems onUpdate above will fire with the refreshed list (do NOT manually re-fetch)');
356
+ * } else if (r.err_code === 11000 || r.err_code === 11011 || r.err_code === 11012) {
357
+ * console.error('[smartico] insufficient balance for this purchase_type — show insufficient-balance UI and how many units are missing:', item.purchase_type, effectivePrice);
358
+ * } else if (r.err_code === 11009) {
359
+ * console.error('[smartico] item sold out — show a dedicated "Sold out" message; the auto-refresh will mark the card as such shortly');
360
+ * } else if (r.err_code === 11006) {
361
+ * console.error('[smartico] per-user purchase cap reached — surface the operator-defined limit message:', item.limit_message || r.err_message);
362
+ * } else if (r.err_code === 11014) {
363
+ * console.error('[smartico] outside purchase window — surface the operator-defined purchase-limit message:', item.purchase_limit_message || r.err_message);
364
+ * } else if (r.err_code === 11004 || r.err_code === 11003) {
365
+ * console.error('[smartico] user not eligible / stale visibility — show a localized "try again later" message and let auto-refresh reconcile');
366
+ * } else {
367
+ * console.error('[smartico] buy failed — show a generic error toast/modal with this message:', r.err_message);
368
+ * }
369
+ * ```
370
+ */
371
+ public async buyStoreItem(item_id: number): Promise<TBuyStoreItemResult> {
372
+ const r = await this.api.buyStoreItem(this.userExtId, item_id);
373
+
374
+ const o: TBuyStoreItemResult = {
375
+ err_code: r.errCode,
376
+ err_message: r.errMsg,
377
+ };
378
+
379
+ return o;
380
+ }
381
+
382
+ /**
383
+ * Returns the list of active store categories configured for the current label.
384
+ * Categories are operator-defined groupings used to organize store items into tabs,
385
+ * sections, or filter chips in the gamification store UI.
386
+ *
387
+ * @remarks
388
+ * **What categories are**
389
+ * - Operator-defined groupings, configured per-label by the brand operator.
390
+ * Only active categories are returned; inactive / archived / deleted ones are
391
+ * filtered out server-side.
392
+ * - Each `TStoreCategory` exposes `{ id, name, order }`. `name` is the display label;
393
+ * `order` is the relative position (lower = appears first).
394
+ * - The same set of categories is returned to every user of the label — there is no
395
+ * per-segment / per-currency / per-device filtering on the category list. Item-level
396
+ * segment visibility happens on {@link getStoreItems}, not here.
397
+ *
398
+ * **Localization / translation**
399
+ * - `name` is **pre-translated server-side** to the authenticated user's stored language.
400
+ * In visitor mode, the language passed to `_smartico.vapi(lang)` drives the translation.
401
+ * Consumers never need to translate `name` themselves.
402
+ * - Fallback if no translation exists for the user's language: the operator-set default
403
+ * (typically the brand's English) value is returned. The field is never null for an
404
+ * active category.
405
+ *
406
+ * **Sort order**
407
+ * The server does NOT pre-sort. Sort client-side before rendering:
408
+ * `categories.sort((a, b) => a.order - b.order)`.
409
+ *
410
+ * **How store items join to categories**
411
+ * Each `TStoreItem` exposes `category_ids: number[]` (zero-or-more, many-to-many).
412
+ * A single store item can belong to multiple categories, or to none. To render a
413
+ * "category → items" view:
414
+ * `items.filter(i => i.category_ids.includes(cat.id))`.
415
+ *
416
+ * **Uncategorized items**
417
+ * Items with `category_ids: []` are NOT represented by a synthetic "Other" entry
418
+ * in the response. The convention used by the reference store UI is to synthesize
419
+ * a client-side bucket (e.g. labelled "General") for items that have no category, OR
420
+ * for items whose `category_ids` reference a category that is no longer returned by
421
+ * this method (e.g. archived since the item was tagged). If you choose to render
422
+ * such a synthetic bucket, place it first (the reference UI uses an `order: -1`
423
+ * convention so it precedes all operator-defined categories).
424
+ *
425
+ * **Empty categories**
426
+ * A category may be returned even if zero items currently reference it (since this
427
+ * method does not join against items). The reference store UI hides such empty
428
+ * categories from its tab strip — replicate that filter if you don't want to render
429
+ * tabs that lead to empty content panels.
430
+ *
431
+ * **Refresh cadence / cache**
432
+ * - The SDK caches the response for 30 seconds. Subsequent calls within that window
433
+ * return the cached array without a network round-trip.
434
+ * - The cache is NOT invalidated by store-item push events or purchases — operator-driven
435
+ * category changes propagate at the next 30 s cache miss.
436
+ * - Cache is fully cleared on login / logout.
437
+ * - In **visitor mode**, additional server-side caching applies on top of the SDK cache;
438
+ * worst-case staleness for an edited/added category is on the order of a few minutes
439
+ * for anonymous viewers.
440
+ *
441
+ * **Idempotency**: safe. Read-only metadata fetch. Cache de-duplicates concurrent calls.
442
+ *
443
+ * **Side effects**: none — pure metadata read.
444
+ *
445
+ * **UI guidance**: see [UI Guide — `getStoreCategories`](../../docs/ui/store/UIGuide_getStoreCategories.md).
446
+ *
447
+ * @returns Array of `{ id, name, order }`. Empty array if no active categories are
448
+ * configured for the label. `name` is pre-translated. Order is NOT applied — caller
449
+ * must sort.
450
+ *
451
+ * @example
452
+ * ```ts
453
+ * const [categories, items] = await Promise.all([
454
+ * window._smartico.api.getStoreCategories(),
455
+ * window._smartico.api.getStoreItems(),
456
+ * ]);
457
+ *
458
+ * if (categories.length === 0) {
459
+ * console.log('[smartico] no store categories configured — render items as a flat grid without tabs:', items.length);
460
+ * } else {
461
+ * // Sort categories; build per-category item buckets; hide empty categories
462
+ * const sorted = [...categories].sort((a, b) => a.order - b.order);
463
+ * const tabs = sorted
464
+ * .map(cat => ({ cat, items: items.filter(i => i.category_ids?.includes(cat.id)) }))
465
+ * .filter(t => t.items.length > 0);
466
+ *
467
+ * // Optional: synthesize an "Other" bucket for items with no (or unknown) category
468
+ * const knownIds = new Set(categories.map(c => c.id));
469
+ * const orphans = items.filter(i => !i.category_ids?.length || !i.category_ids.some(id => knownIds.has(id)));
470
+ * if (orphans.length > 0) {
471
+ * console.log('[smartico] uncategorized store items — render a client-synthesized "Other" tab at the front of the tab strip:', orphans.length);
472
+ * }
473
+ *
474
+ * console.log('[smartico] render store tabs in this order with these counts:', tabs.map(t => `${t.cat.name} (${t.items.length})`));
475
+ * }
476
+ *
477
+ * // Visitor mode — same shape, language driven by vapi(lang) argument
478
+ * const visitorCats = await window._smartico.vapi('DE').getStoreCategories();
479
+ * console.log('[smartico] visitor-mode store categories (names translated to DE):', visitorCats);
480
+ * ```
481
+ */
482
+ public async getStoreCategories(): Promise<TStoreCategory[]> {
483
+ return OCache.use(
484
+ onUpdateContextKey.StoreCategories,
485
+ ECacheContext.WSAPI,
486
+ () => this.api.storeGetCategoriesT(this.userExtId),
487
+ CACHE_DATA_SEC,
488
+ );
489
+ }
490
+
491
+ /**
492
+ * Fetches the authenticated user's **store purchase history** — a paginated,
493
+ * newest-first list of past store purchases (one row per redemption).
494
+ *
495
+ * Designed for a "My Purchases" / "Order History" screen. Each entry carries
496
+ * the same descriptive fields as the catalog card plus three history-only
497
+ * fields: `purchase_ts` (when the purchase happened), `purchase_points_amount`
498
+ * (the amount actually paid at that time — a price snapshot, not the
499
+ * current `price`), and `purchase_type` (`'points' | 'gems' | 'diamonds'`).
500
+ *
501
+ * @remarks
502
+ * **Preconditions**
503
+ * - User must be authenticated. Visitor mode is not supported (the SDK only
504
+ * exposes this method on the authenticated `_smartico.api`, not on
505
+ * `_smartico.vapi`).
506
+ * - No prerequisite calls — calling without first fetching
507
+ * {@link getStoreItems} or {@link getStoreCategories} is fine.
508
+ *
509
+ * **Pagination semantics**
510
+ * - **Offset-based**, newest-first. The server orders rows by purchase
511
+ * timestamp **descending** and the SDK does NOT re-sort — items arrive
512
+ * ready to render in display order.
513
+ * - `limit` — page size. **The SDK default is 20.** There is no server-side
514
+ * hard cap, but 20 matches what the default Smartico UI uses end-to-end; the
515
+ * protocol and storage layers were sized for this page size. Treat `20`
516
+ * as the conventional/recommended value; passing a much larger limit will
517
+ * return more rows but is not the supported integration pattern.
518
+ * Avoid `limit <= 0` — the server peeks `limit + 1` rows internally, so
519
+ * `limit = 0` returns 1 row with a misleading "has more" signal, and
520
+ * negative values produce undefined results.
521
+ * - `offset` — number of items to skip from the start. The SDK default is
522
+ * `0` (first page). For load-more pagination, pass
523
+ * `offset = (previously-loaded items).length` on each subsequent call.
524
+ * - **No `hasMore` on the returned array.** `TStoreItem[]` is a flat list;
525
+ * the underlying protocol response carries `hasMore` but it is not
526
+ * surfaced through this method. Two ways for consumers to know they
527
+ * reached the end:
528
+ * 1. The returned array is shorter than `limit` (definitive end), or
529
+ * 2. A subsequent call at `offset = previous.length` returns `[]`.
530
+ * Either is reliable.
531
+ * - No date-range / category / status filter parameters — pagination is the
532
+ * only server-side slicing. Apply any further filtering client-side.
533
+ *
534
+ * **No per-item fulfillment status**
535
+ * - History entries do NOT carry a `delivered` / `pending` / `cancelled` /
536
+ * `refunded` field. The list contains rows for committed purchase
537
+ * attempts; the server query does not filter by transaction-status, so in
538
+ * practice the rows that appear are completed purchases (failed
539
+ * transactions roll back and don't write a row). Treat every item as a
540
+ * completed transaction unless a future SDK release adds an explicit
541
+ * status field.
542
+ *
543
+ * **Bonus-type entries**
544
+ * - When the user redeemed a bonus item, the entry's `type` field surfaces
545
+ * as `'bonus'`. **Known limitation:** the SDK transform currently maps
546
+ * both `Bonus` and `Tangible` server-side item types to the same string
547
+ * `'bonus'` — so the `type` field on history rows cannot distinguish a
548
+ * bonus redemption from a tangible-prize redemption. The actual bonus
549
+ * payload (wallet credit, free spins, etc.) is dispatched by the server
550
+ * asynchronously and is NOT embedded in the history entry — consumers
551
+ * that need bonus details should subscribe to bonus push events
552
+ * separately rather than reading them from this list.
553
+ * - History rows render identically across types — there is no deep-link to
554
+ * the bonus wallet or re-claim affordance on the row itself.
555
+ *
556
+ * **Per-row data**
557
+ * Each row uses the `TStoreItem` shape but populates four history-only
558
+ * fields not present on `getStoreItems` output. `purchase_ts` is the
559
+ * Unix-ms timestamp of the purchase — format with
560
+ * `new Date(purchase_ts).toLocaleString()` in the user's local timezone;
561
+ * no relative labels ("Today" / "Yesterday") are produced by the SDK.
562
+ * `purchase_points_amount` is the amount actually paid at the time of
563
+ * purchase — a snapshot of the historical price, which may differ from
564
+ * the item's current `price`. `purchase_type` is the currency actually
565
+ * charged (`'points' | 'gems' | 'diamonds'`); render the matching
566
+ * balance icon next to the amount. The convenience booleans
567
+ * `purchased_today` / `purchased_this_week` / `purchased_this_month` are
568
+ * computed client-side from the consumer's local clock — useful for
569
+ * grouping rows under "Today" / "This Week" headers.
570
+ *
571
+ * **Catalog fields on a history row**
572
+ * The promotional fields (`ribbon`, `discounted_price`,
573
+ * `discount_price_ribbon`, `custom_ribbon_image`, `active_till_date`)
574
+ * reflect the CURRENT catalog state of the item, NOT its state at
575
+ * purchase time — the default Smartico UI hides them on history rows to
576
+ * avoid implying that the historical purchase carried the current
577
+ * promotional banner. Descriptive marketing fields (`description`,
578
+ * `hint_text`, `related_games`) are typically suppressed on a compact
579
+ * history row. The current-purchasability fields `can_buy` and `pool`
580
+ * reflect now, not then — useful only if you render a "Buy Again"
581
+ * affordance on the row. One implementation gotcha: unlike
582
+ * `getStoreItems`, this method's transform does NOT auto-parse JSON
583
+ * strings in `custom_data` — call `JSON.parse()` yourself if you store
584
+ * JSON there.
585
+ *
586
+ * **Cache & refresh**
587
+ * - The SDK caches each `(limit, offset)` page separately for 30 seconds.
588
+ * Repeated calls within that window resolve from cache without a
589
+ * network round-trip.
590
+ * - The cache is invalidated and `onUpdate` (when registered) is invoked
591
+ * automatically after a successful {@link buyStoreItem} call — the SDK
592
+ * re-fetches the same page parameters that were registered together with
593
+ * the current `onUpdate` callback and pushes the fresh array.
594
+ * - Multi-tab caveat: if the user has the same brand open in multiple
595
+ * tabs, **all open tabs** receive the `onUpdate` event on a purchase,
596
+ * not only the tab that initiated the buy. The event is scoped to the
597
+ * current authenticated user — a different user's purchase never fires
598
+ * this callback.
599
+ * - Only ONE `onUpdate` callback can be registered at a time. Each call to
600
+ * `getStorePurchasedItems({ onUpdate })` overwrites the previous handler.
601
+ *
602
+ * **Idempotency**: safe. Pure read.
603
+ *
604
+ * **Side effects**: none — read-only.
605
+ *
606
+ * **UI guidance**: see [UI Guide — `getStorePurchasedItems`](../../docs/ui/store/UIGuide_getStorePurchasedItems.md).
607
+ *
608
+ * @param params - Optional pagination + callback bag.
609
+ * @param params.limit - Page size. Defaults to `20`. Use `20` as the
610
+ * conventional value (matches the default Smartico UI end-to-end). Avoid
611
+ * non-positive values.
612
+ * @param params.offset - Number of rows to skip from the newest end.
613
+ * Defaults to `0`. For load-more pagination pass the current array
614
+ * length.
615
+ * @param params.onUpdate - Optional callback invoked after a successful
616
+ * {@link buyStoreItem} elsewhere in the session. Receives the refreshed
617
+ * page for the same `(limit, offset)` used on the call that registered
618
+ * this callback. Only ONE callback can be registered; each new call
619
+ * overwrites the previous one. Pass a stable handler or
620
+ * re-register intentionally on screen entry.
621
+ *
622
+ * @returns Promise resolving to an array of `TStoreItem` history entries
623
+ * in newest-first order. Empty array if the user has no purchases (or
624
+ * the requested `offset` is beyond the end). Each entry carries
625
+ * `purchase_ts`, `purchase_points_amount`, `purchase_type`, and the
626
+ * `purchased_today/this_week/this_month` convenience flags in addition
627
+ * to the standard item fields.
628
+ *
629
+ * @example
630
+ * ```ts
631
+ * // Initial load + subscribe to refresh-on-purchase.
632
+ * const handleHistoryUpdate = (items: TStoreItem[]) => {
633
+ * console.log(
634
+ * '[smartico] purchase history refreshed — re-render the history list with these',
635
+ * items.length,
636
+ * 'items (newest first):',
637
+ * items,
638
+ * );
639
+ * };
640
+ *
641
+ * try {
642
+ * const firstPage = await _smartico.api.getStorePurchasedItems({
643
+ * limit: 20,
644
+ * offset: 0,
645
+ * onUpdate: handleHistoryUpdate,
646
+ * });
647
+ *
648
+ * if (firstPage.length === 0) {
649
+ * console.log('[smartico] no purchase history — render the empty state ("No purchases yet")');
650
+ * } else {
651
+ * console.log(
652
+ * '[smartico] render',
653
+ * firstPage.length,
654
+ * 'history rows (newest first). Show "Load more" button if length === 20:',
655
+ * firstPage,
656
+ * );
657
+ *
658
+ * // Inspect the first entry's history-only fields.
659
+ * const first = firstPage[0];
660
+ * console.log(
661
+ * '[smartico] most-recent purchase: name=', first.name,
662
+ * 'paid', first.purchase_points_amount, first.purchase_type,
663
+ * 'at', new Date(first.purchase_ts ?? 0).toLocaleString(),
664
+ * '— format with toLocaleString (user-local time) on the row.',
665
+ * );
666
+ * }
667
+ *
668
+ * // Load-more pattern: fetch page 2 once the user scrolls / clicks "Load more".
669
+ * if (firstPage.length === 20) {
670
+ * const nextPage = await _smartico.api.getStorePurchasedItems({
671
+ * limit: 20,
672
+ * offset: firstPage.length,
673
+ * });
674
+ * const isLastPage = nextPage.length < 20;
675
+ * console.log(
676
+ * '[smartico] appended page 2 —',
677
+ * nextPage.length,
678
+ * 'rows.',
679
+ * isLastPage ? 'Hide "Load more" — end reached.' : 'Keep "Load more" visible.',
680
+ * );
681
+ * }
682
+ * } catch (e) {
683
+ * console.error(
684
+ * '[smartico] failed to load purchase history — show a generic error placeholder or retry with backoff:',
685
+ * e,
686
+ * );
687
+ * }
688
+ * ```
689
+ */
690
+ public async getStorePurchasedItems({
691
+ limit,
692
+ offset,
693
+ onUpdate,
694
+ }: { limit?: number; offset?: number; onUpdate?: (data: TStoreItem[]) => void } = {}): Promise<TStoreItem[]> {
695
+ const requestLimit = limit === undefined ? 20 : limit;
696
+ const requestOffset = offset === undefined ? 0 : offset;
697
+ const cacheKey = this.storeHistoryCacheKey(requestLimit, requestOffset);
698
+
699
+ if (onUpdate) {
700
+ this.onUpdateCallback.set(onUpdateContextKey.StoreHistory, onUpdate);
701
+ this.storeHistoryOnUpdateParams = { limit: requestLimit, offset: requestOffset };
702
+ }
703
+
704
+ return OCache.use(
705
+ cacheKey,
706
+ ECacheContext.WSAPI,
707
+ () => this.api.storeGetPurchasedItemsT(this.userExtId, requestLimit, requestOffset),
708
+ CACHE_DATA_SEC,
709
+ );
710
+ }
711
+
712
+ protected async updateStorePurchasedItems() {
713
+ const payload = await this.api.storeGetPurchasedItemsT(
714
+ this.userExtId,
715
+ this.storeHistoryOnUpdateParams.limit,
716
+ this.storeHistoryOnUpdateParams.offset,
717
+ );
718
+ const cacheKey = this.storeHistoryCacheKey(this.storeHistoryOnUpdateParams.limit, this.storeHistoryOnUpdateParams.offset);
719
+
720
+ OCache.set(cacheKey, payload, ECacheContext.WSAPI);
721
+
722
+ const onUpdate = this.onUpdateCallback.get(onUpdateContextKey.StoreHistory);
723
+ if (onUpdate) {
724
+ onUpdate(payload);
725
+ }
726
+ }
727
+
728
+ protected async updateStoreItems() {
729
+ const payload = await this.api.storeGetItemsT(this.userExtId);
730
+ this.updateEntity(onUpdateContextKey.StoreItems, payload);
731
+ }
732
+ }