@smartico/public-api 0.0.379 → 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,127 @@
1
+ import { ECacheContext, OCache } from '../OCache';
2
+ import {
3
+ TAvatarDefinition,
4
+ TAvatarCustomized,
5
+ TAvatarPrompt,
6
+ TSetAvatarResult,
7
+ } from './WSAPITypes';
8
+ import {
9
+ CACHE_DATA_SEC,
10
+ onUpdateContextKey,
11
+ } from './WSAPIBase';
12
+ import { WSAPIMiniGames } from './WSAPIMiniGames';
13
+
14
+ /** @group Avatars */
15
+ export class WSAPIAvatars extends WSAPIMiniGames {
16
+ /**
17
+ * Returns the list of avatars available in the catalog for the current user.
18
+ * The response includes both free avatars and earned/purchased ones.
19
+ * Avatars with `hide_until_achieved = true` and `is_given = false` should be hidden from the user.
20
+ * The result is cached for 30 seconds.
21
+ *
22
+ * **Example**:
23
+ * ```
24
+ * _smartico.api.getAvatarsList().then((result) => {
25
+ * console.log(result);
26
+ * });
27
+ * ```
28
+ *
29
+ * **Visitor mode: not supported**
30
+ */
31
+ public async getAvatarsList(): Promise<TAvatarDefinition[]> {
32
+ return OCache.use(
33
+ onUpdateContextKey.AvatarsList,
34
+ ECacheContext.WSAPI,
35
+ () => this.api.avatarsGetListT(this.userExtId),
36
+ CACHE_DATA_SEC,
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Returns the list of AI-customized avatars for the current user.
42
+ * Each entry represents a previously generated AI customization for a specific base avatar.
43
+ * The result is cached for 30 seconds.
44
+ *
45
+ * **Example**:
46
+ * ```
47
+ * _smartico.api.getAvatarsCustomized().then((result) => {
48
+ * console.log(result);
49
+ * });
50
+ * ```
51
+ *
52
+ * **Visitor mode: not supported**
53
+ */
54
+ public async getAvatarsCustomized(): Promise<TAvatarCustomized[]> {
55
+ return OCache.use(
56
+ onUpdateContextKey.AvatarsCustomized,
57
+ ECacheContext.WSAPI,
58
+ () => this.api.avatarsGetCustomizedT(this.userExtId),
59
+ CACHE_DATA_SEC,
60
+ );
61
+ }
62
+
63
+ /**
64
+ * Returns the list of AI customization prompts (styles) available for avatar customization.
65
+ * Each prompt represents a visual style that can be applied to a base avatar.
66
+ * The result is cached for 30 seconds.
67
+ *
68
+ * **Example**:
69
+ * ```
70
+ * _smartico.api.getAvatarPrompts().then((result) => {
71
+ * console.log(result);
72
+ * });
73
+ * ```
74
+ *
75
+ * **Visitor mode: not supported**
76
+ */
77
+ public async getAvatarPrompts(): Promise<TAvatarPrompt[]> {
78
+ return OCache.use(
79
+ onUpdateContextKey.AvatarPrompts,
80
+ ECacheContext.WSAPI,
81
+ () => this.api.avatarsGetPromptsT(this.userExtId),
82
+ CACHE_DATA_SEC,
83
+ );
84
+ }
85
+
86
+ /**
87
+ * Sets the specified avatar as the active avatar for the current user.
88
+ * Pass `avatar_url` (the `TAvatarDefinition.url` path or a CDN URL for AI-customized avatars)
89
+ * and `avatar_real_id` from the avatar catalog.
90
+ * After a successful call, the avatar list cache is cleared so the next `getAvatarsList()` call reflects `is_in_use`.
91
+ *
92
+ * **Example**:
93
+ * ```
94
+ * _smartico.api.getAvatarsList().then((avatars) => {
95
+ * const avatar = avatars.find((a) => !a.hide_until_achieved || a.is_given);
96
+ * if (avatar) {
97
+ * _smartico.api.setAvatar({
98
+ * avatar_url: avatar.url,
99
+ * avatar_real_id: avatar.avatar_real_id,
100
+ * }).then((result) => {
101
+ * console.log(result);
102
+ * });
103
+ * }
104
+ * });
105
+ * ```
106
+ *
107
+ * **Visitor mode: not supported**
108
+ */
109
+ public async setAvatar(props: { avatar_url: string; avatar_real_id: number }): Promise<TSetAvatarResult> {
110
+ if (!props.avatar_url) {
111
+ throw new Error('avatar_url is required');
112
+ }
113
+ if (!props.avatar_real_id) {
114
+ throw new Error('avatar_real_id is required');
115
+ }
116
+
117
+ const r = await this.api.avatarSetAvatar(this.userExtId, props.avatar_url, props.avatar_real_id);
118
+
119
+ OCache.clear(ECacheContext.WSAPI, onUpdateContextKey.AvatarsList);
120
+ OCache.clear(ECacheContext.WSAPI, onUpdateContextKey.AvatarsCustomized);
121
+
122
+ return {
123
+ err_code: r.errCode ?? 0,
124
+ err_message: r.errMsg,
125
+ };
126
+ }
127
+ }
@@ -0,0 +1,93 @@
1
+ import { ECacheContext, OCache } from '../OCache';
2
+ import { SmarticoAPI } from '../SmarticoAPI';
3
+
4
+ /** @hidden */
5
+ export const CACHE_DATA_SEC = 30;
6
+
7
+ /** @hidden */
8
+ export const JACKPOT_TEMPLATE_CACHE_SEC = 30;
9
+ /** @hidden */
10
+ export const JACKPOT_POT_CACHE_SEC = 1;
11
+ /** @hidden */
12
+ export const JACKPOT_WINNERS_CACHE_SEC = 30;
13
+ /** @hidden */
14
+ export const JACKPOT_ELIGIBLE_GAMES_CACHE_SEC = 30;
15
+
16
+ /** @hidden */
17
+ export enum onUpdateContextKey {
18
+ Saw = 'saw',
19
+ Missions = 'missions',
20
+ TournamentList = 'tournamentList',
21
+ InboxMessages = 'inboxMessages',
22
+ Badges = 'badges',
23
+ Levels = 'levels',
24
+ StoreItems = 'storeItems',
25
+ StoreCategories = 'storeCategories',
26
+ AchCategories = 'achCategories',
27
+ LeaderBoards = 'leaderBoards',
28
+ LevelExtraCounters = 'levelExtraCounters',
29
+ Segments = 'segments',
30
+ StoreHistory = 'storeHistory',
31
+ Jackpots = 'jackpots',
32
+ Pots = 'Pots',
33
+ CustomSections = 'customSections',
34
+ Bonuses = 'bonuses',
35
+ Clans = 'clans',
36
+ SAWHistory = 'sawHistory',
37
+ JackpotWinners = 'jackpotWinners',
38
+ Raffles = 'raffles',
39
+ JackpotEligibleGames = 'jackpotEligibleGames',
40
+ CurrentLevel = 'currentLevel',
41
+ InboxUnreadCount = 'inboxUnreadCount',
42
+ ActivityLog = 'activityLog',
43
+ AvatarsList = 'avatarsList',
44
+ AvatarsCustomized = 'avatarsCustomized',
45
+ AvatarPrompts = 'avatarPrompts',
46
+ }
47
+
48
+ /**
49
+ * Abstract base of the SDK's public surface. Holds the shared state
50
+ * (`api`, `userExtId`, `onUpdateCallback` map) and the generic cache /
51
+ * subscription helper (`updateEntity`). Domain-specific methods live on
52
+ * subclasses; the terminator `WSAPI` class composes the whole chain.
53
+ *
54
+ * **Consumers should not instantiate this directly** — the SDK constructs
55
+ * the concrete `WSAPI` via `_smartico.api`.
56
+ *
57
+ * @hidden
58
+ */
59
+ export abstract class WSAPIBase {
60
+ /** @hidden */
61
+ protected onUpdateCallback: Map<onUpdateContextKey, (data: any) => void> = new Map();
62
+
63
+ /** @hidden */
64
+ protected userExtId: string = null;
65
+
66
+ /** @private */
67
+ constructor(protected api: SmarticoAPI, userExtId: string = null) {
68
+ this.userExtId = userExtId;
69
+ OCache.clearAll();
70
+ }
71
+
72
+ /** @private */
73
+ // AA: this method is used from the _smartico script to clear cache when the context is changed,
74
+ // e.g. when user is changed or language is changed
75
+ public clearCaches() {
76
+ OCache.clearAll();
77
+ }
78
+
79
+ /**
80
+ * Generic cache-update + subscription-notify helper. Used by domain
81
+ * classes' `update*` methods to refresh a context and fire any
82
+ * registered `onUpdate` callback.
83
+ * @hidden
84
+ */
85
+ protected async updateEntity(contextKey: onUpdateContextKey, payload: any) {
86
+ OCache.set(contextKey, payload, ECacheContext.WSAPI);
87
+
88
+ const onUpdate = this.onUpdateCallback.get(contextKey);
89
+ if (onUpdate) {
90
+ onUpdate(payload);
91
+ }
92
+ }
93
+ }
@@ -0,0 +1,54 @@
1
+ import { ECacheContext, OCache } from '../OCache';
2
+ import {
3
+ TBonus,
4
+ TClaimBonusResult,
5
+ } from './WSAPITypes';
6
+ import {
7
+ CACHE_DATA_SEC,
8
+ onUpdateContextKey,
9
+ } from './WSAPIBase';
10
+ import { WSAPIMissions } from './WSAPIMissions';
11
+
12
+ /** @group Bonuses */
13
+ export class WSAPIBonuses extends WSAPIMissions {
14
+ /**
15
+ * Returns all the bonuses for the current user
16
+ * The returned bonuses are cached for 30 seconds. But you can pass the onUpdate callback as a parameter.
17
+ * Note that each time you call getBonuses with a new onUpdate callback, the old one will be overwritten by the new one.
18
+ * The onUpdate callback will be called on bonus claimed and the updated bonuses will be passed to it.
19
+ *
20
+ * **Visitor mode: not supported**
21
+ */
22
+ public async getBonuses({ onUpdate }: { onUpdate?: (data: TBonus[]) => void } = {}): Promise<TBonus[]> {
23
+ if (onUpdate) {
24
+ this.onUpdateCallback.set(onUpdateContextKey.Bonuses, onUpdate);
25
+ }
26
+
27
+ return OCache.use(onUpdateContextKey.Bonuses, ECacheContext.WSAPI, () => this.api.bonusesGetItemsT(this.userExtId), CACHE_DATA_SEC);
28
+ }
29
+
30
+ /**
31
+ * Claim the bonus by bonus_id. Returns the err_code in case of success or error.
32
+ * Note that this method can be used only on integrations where originally failed bonus can be claimed again.
33
+ * For example, user won a bonus in the mini-game, but Operator rejected this bonus.
34
+ * This bonus will be available for the user to claim again.
35
+ *
36
+ * **Visitor mode: not supported**
37
+ */
38
+ public async claimBonus(bonus_id: number): Promise<TClaimBonusResult> {
39
+ const r = await this.api.bonusClaimItem(this.userExtId, bonus_id);
40
+
41
+ const o: TClaimBonusResult = {
42
+ err_code: r.errCode,
43
+ err_message: r.errMsg,
44
+ success: r.success,
45
+ };
46
+
47
+ return o;
48
+ }
49
+
50
+ protected async updateBonuses() {
51
+ const payload = await this.api.bonusesGetItemsT(this.userExtId);
52
+ this.updateEntity(onUpdateContextKey.Bonuses, payload);
53
+ }
54
+ }
@@ -0,0 +1,417 @@
1
+ import { ECacheContext, OCache } from '../OCache';
2
+ import {
3
+ TClans,
4
+ TClanInfo,
5
+ TClanJoinResult,
6
+ } from './WSAPITypes';
7
+ import {
8
+ CACHE_DATA_SEC,
9
+ onUpdateContextKey,
10
+ } from './WSAPIBase';
11
+ import { WSAPITournaments } from './WSAPITournaments';
12
+
13
+ /** @group Clans */
14
+ export class WSAPIClans extends WSAPITournaments {
15
+ /**
16
+ * Returns the active clans visible to the current user along with the
17
+ * user's own membership state (`user_clan_id`, `cooldown_until`,
18
+ * `join_date`). Use this to power a clan-picker / clan-browser screen.
19
+ *
20
+ * The returned `clans[]` is server-sorted by `rating_position` ASC
21
+ * (1 = highest-ranked). The server has already filtered out archived
22
+ * clans, clans the user fails segment conditions for, and (when any
23
+ * clan has a non-zero score) clans with a zero rating score.
24
+ *
25
+ * @remarks
26
+ * **Subscription model (`onUpdate`)**
27
+ * The callback receives the FULL refreshed `TClans` payload (never a
28
+ * diff/patch). Each subsequent call to `getClans({ onUpdate })`
29
+ * REPLACES the prior callback. Pass `onUpdate: undefined` (or omit
30
+ * it) to keep the prior callback in place; the callback is never
31
+ * auto-cleared.
32
+ *
33
+ * **Update triggers** — note that, unlike most other subscription
34
+ * methods in the SDK, this callback is **poll-driven only**. There
35
+ * is NO server push that refreshes the clans list. The callback
36
+ * fires when:
37
+ *
38
+ * 1. The 30-second cache TTL expires and a subsequent `getClans()`
39
+ * call (from the consumer) triggers a fresh fetch.
40
+ *
41
+ * Consequence: clan-membership changes (other users joining your
42
+ * clan, an operator-driven kick, a clan being archived) surface
43
+ * only on the next consumer-driven fetch. If your UI needs
44
+ * near-live state, poll `getClans()` on an interval; or re-call
45
+ * after a {@link joinClan} resolves to pick up the new
46
+ * `user_clan_id` immediately.
47
+ *
48
+ * **Reading state from the returned payload**
49
+ * Drive list rendering from `clans[]` (already sorted). Identify
50
+ * the user's own clan via `clan.clan_id === user_clan_id`
51
+ * (`null` for clanless users). Detect an active switch-cooldown
52
+ * with `cooldown_until !== null` — when set, the user cannot join
53
+ * any clan until the cooldown expires, even clans they could
54
+ * normally join. The cooldown is **user-level**, not per-clan.
55
+ *
56
+ * `cooldown_until` is an ISO 8601 UTC datetime string with no
57
+ * timezone suffix (`"YYYY-MM-DDTHH:MM:SS"`). Parse as UTC:
58
+ * `new Date(cooldown_until + 'Z')` or `moment.utc(cooldown_until)`.
59
+ * Display in the user's local time. The default cooldown period
60
+ * is configured per label by the operator (typically 7 days).
61
+ *
62
+ * `rating_position` is a global rank computed server-side across
63
+ * all active clans in the label (1 = highest-rated). Because some
64
+ * clans may be hidden by per-user segment visibility, positions
65
+ * the user sees may skip (e.g. 1, 3, 7) — don't assume the array
66
+ * spans a contiguous range.
67
+ *
68
+ * The `entry_fee_currency_type_id` enum on each clan uses values
69
+ * `0` = points, `1` = gems, `2` = diamonds, `3` = free. Compare
70
+ * `entry_fee_amount` against the user's matching balance (from
71
+ * {@link getUserProfile}) to drive Join button affordability.
72
+ *
73
+ * **Cache TTL**: the SDK caches the response for 30 seconds. Cache
74
+ * is fully cleared on login / logout.
75
+ *
76
+ * **Idempotency**: safe. Read-only. Repeated calls within the
77
+ * cache window return a deep-cloned cached payload without a
78
+ * network round-trip.
79
+ *
80
+ * **Side effects**: none — pure metadata read.
81
+ *
82
+ * **UI guidance**: see [UI Guide — `getClans`](../../docs/ui/clans/UIGuide_getClans.md).
83
+ *
84
+ * **Visitor mode**: not supported.
85
+ *
86
+ * @param params Optional. Omit to fetch without subscribing.
87
+ * @param params.onUpdate Callback invoked with the full refreshed
88
+ * `TClans` payload whenever the 30 s cache
89
+ * expires and a subsequent fetch lands.
90
+ * Each call to `getClans` overwrites the
91
+ * prior callback.
92
+ * @returns Promise resolving to `TClans`. Empty
93
+ * `clans` array if no clans are visible.
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * const result = await window._smartico.api.getClans({
98
+ * onUpdate: (refreshed) => {
99
+ * console.log('[smartico] clans payload refreshed (poll-driven; ~30 s cadence) — re-render the clan list from this payload:', refreshed);
100
+ * },
101
+ * });
102
+ *
103
+ * console.log('[smartico] user is', result.user_clan_id == null ? 'clanless' : 'in clan ' + result.user_clan_id);
104
+ *
105
+ * // Cooldown handling — affects ALL clans, not a specific one.
106
+ * if (result.cooldown_until) {
107
+ * const cooldownEndsUtc = new Date(result.cooldown_until + 'Z');
108
+ * console.log('[smartico] switch-cooldown active — disable all Join buttons until', cooldownEndsUtc.toLocaleString(),
109
+ * '(local). Render the cooldown end on the disabled button label.');
110
+ * }
111
+ *
112
+ * // Render clans — already sorted by rating_position ASC.
113
+ * for (const clan of result.clans) {
114
+ * const isMine = clan.clan_id === result.user_clan_id;
115
+ * const isFull = clan.member_count >= clan.capacity_limit;
116
+ *
117
+ * if (isMine) {
118
+ * console.log('[smartico] highlight clan', clan.clan_id, 'as "Your clan"; CTA label "Your clan", no-op');
119
+ * } else if (result.cooldown_until) {
120
+ * console.log('[smartico] clan', clan.clan_id, '— Join blocked by user cooldown; show disabled button with cooldown end date');
121
+ * } else if (isFull) {
122
+ * console.log('[smartico] clan', clan.clan_id, '— Clan full; show disabled "Clan is full" button');
123
+ * } else {
124
+ * const label = clan.entry_fee_amount === 0 || clan.entry_fee_currency_type_id === 3
125
+ * ? 'Join free'
126
+ * : `Join (${clan.entry_fee_amount} ${['Points','Gems','Diamonds'][clan.entry_fee_currency_type_id]})`;
127
+ * console.log('[smartico] clan', clan.clan_id, '— render enabled Join button labelled', label);
128
+ * }
129
+ * }
130
+ *
131
+ * // After a successful joinClan(), re-call getClans manually — no push refresh.
132
+ * // const r = await window._smartico.api.joinClan(targetClanId);
133
+ * // if (r.errCode === 0) await window._smartico.api.getClans();
134
+ * ```
135
+ */
136
+ public async getClans({ onUpdate }: { onUpdate?: (data: TClans) => void } = {}): Promise<TClans> {
137
+ if (onUpdate) {
138
+ this.onUpdateCallback.set(onUpdateContextKey.Clans, onUpdate);
139
+ }
140
+
141
+ return OCache.use(
142
+ onUpdateContextKey.Clans,
143
+ ECacheContext.WSAPI,
144
+ () => this.api.clansGetListT(this.userExtId),
145
+ CACHE_DATA_SEC,
146
+ );
147
+ }
148
+
149
+ /**
150
+ * Returns the full detail of a single clan — adds the ranked
151
+ * `members[]` roster and a fresh `cooldown_until` on top of the same
152
+ * fields exposed on a `TClan` list entry. Use this to power a clan
153
+ * detail screen / popup after the user picks an item from
154
+ * {@link getClans}.
155
+ *
156
+ * Each call is a fresh server round-trip — there is no client cache
157
+ * and no push event refreshes detail state. Re-call to refresh.
158
+ *
159
+ * @remarks
160
+ * **Preconditions**
161
+ * Pass a valid `clanId` (typically read from
162
+ * `TClans.clans[i].clan_id` returned by {@link getClans}). The
163
+ * method works standalone — `getClans()` is not required first —
164
+ * but is the only stable source of valid IDs.
165
+ *
166
+ * **Refresh model**
167
+ * - **No subscription.** One-shot promise.
168
+ * - **No client cache.** Every call sends a network request.
169
+ * - **No push event** refreshes the detail. Member-join, kick, or
170
+ * contribution-score changes require a fresh `getClanInfo` call.
171
+ *
172
+ * **Returned shape — beyond `TClan`**
173
+ * `TClanInfo` adds two things on top of the same identity / capacity
174
+ * / fee / rating fields you'd see on a `TClan` list entry:
175
+ * 1. A ranked `members[]` array — each entry carries `user_id`,
176
+ * `public_username`, `avatar_id` / `avatar_real_id`, the resolved
177
+ * `avatar_url`, the member's `position` (rank within this clan),
178
+ * `contribution_score`, the `is_me` flag identifying the current
179
+ * user's row, and the optional `clean_ext_user_id`. The server
180
+ * orders members by score DESC (i.e. `position` ASC); no
181
+ * client-side re-sort is required.
182
+ * 2. A fresh `cooldown_until` on the clan info itself. This is the
183
+ * SAME user-level cooldown as `TClans.cooldown_until` (the
184
+ * cooldown is global to the user, not per clan) — but `getClans`
185
+ * returns a value cached for up to 30 s while `getClanInfo`
186
+ * always returns the current value. If the list-cached cooldown
187
+ * has just expired, this detail call will reflect it first.
188
+ *
189
+ * **Username display**: in the default Smartico UI, member rows use
190
+ * `public_username`. Some surfaces (e.g. the tournament clan
191
+ * drill-down) prefer `clean_ext_user_id` as the primary display
192
+ * with `public_username` as fallback — pick the convention that
193
+ * matches your product's identity model.
194
+ *
195
+ * **Idempotency**: safe. Read-only.
196
+ *
197
+ * **Side effects**: none — pure metadata read.
198
+ *
199
+ * **UI guidance**: see [UI Guide — `getClanInfo`](../../docs/ui/clans/UIGuide_getClanInfo.md).
200
+ *
201
+ * **Visitor mode**: not supported.
202
+ *
203
+ * @param clanId The clan ID from `TClans.clans[i].clan_id`.
204
+ * @returns Promise resolving to `TClanInfo`. Rejects if the
205
+ * clan ID is invalid or the user lacks visibility
206
+ * for it.
207
+ *
208
+ * @example
209
+ * ```ts
210
+ * const result = await window._smartico.api.getClans();
211
+ * const clan = result.clans[0];
212
+ *
213
+ * console.log('[smartico] loading detail for clan', clan.clan_id);
214
+ * const detail = await window._smartico.api.getClanInfo(clan.clan_id);
215
+ *
216
+ * console.log('[smartico] render detail with', detail.members.length, 'members');
217
+ *
218
+ * // Find current user's row to power a sticky "me" footer.
219
+ * const meRow = detail.members.find(m => m.is_me);
220
+ * if (meRow) {
221
+ * console.log('[smartico] current user rank in this clan:', meRow.position,
222
+ * 'contribution:', meRow.contribution_score, '— render sticky my-member footer');
223
+ * }
224
+ *
225
+ * // Resolve Join CTA state using the detail's cooldown (always fresh).
226
+ * const isMyClan = detail.clan_id === result.user_clan_id;
227
+ * const inCooldown = detail.cooldown_until != null;
228
+ * const isFull = detail.member_count >= detail.capacity_limit;
229
+ * if (isMyClan) {
230
+ * console.log('[smartico] this is the user\'s clan — render disabled "Your clan" button');
231
+ * } else if (inCooldown) {
232
+ * const ends = new Date(detail.cooldown_until + 'Z');
233
+ * console.log('[smartico] user is in clan-switch cooldown until', ends.toLocaleString(),
234
+ * '— render disabled cooldown button');
235
+ * } else if (isFull) {
236
+ * console.log('[smartico] clan is full — render disabled "Clan is full" button');
237
+ * } else {
238
+ * console.log('[smartico] joinable — render enabled Join button');
239
+ * }
240
+ * ```
241
+ */
242
+ public async getClanInfo(clanId: number): Promise<TClanInfo> {
243
+ return this.api.clansGetInfoT(this.userExtId, clanId);
244
+ }
245
+
246
+ /**
247
+ * Joins (or switches into) a clan on behalf of the current user. For
248
+ * paid clans (`entry_fee_amount > 0`), the user's balance for the
249
+ * matching currency is debited synchronously before the response
250
+ * returns. If the user is already in a clan, this is treated as an
251
+ * atomic clan-switch (deactivate old membership + insert new + debit
252
+ * fee, all in one transaction — the user is never observably
253
+ * clanless).
254
+ *
255
+ * A successful response (`errCode === 0`) means: membership is
256
+ * persisted, the fee (if any) has been debited, the user's
257
+ * switch-cooldown has restarted, and a clan-joined CRM event has
258
+ * fired server-side.
259
+ *
260
+ * @remarks
261
+ * **Result shape note**: `TClanJoinResult` uses `errCode` / `errMsg`
262
+ * (camelCase) — different from most other SDK result types in this
263
+ * library which use `err_code` / `err_message` (snake_case). Branch
264
+ * on the camelCase keys when reading this method's result.
265
+ *
266
+ * **Preconditions**
267
+ * Read the candidate from {@link getClans} and gate the call on
268
+ * `clan.member_count < clan.capacity_limit`, `cooldown_until == null`
269
+ * (on the `TClans` payload — the cooldown is user-level, not
270
+ * per-clan), and the user's balance for `entry_fee_currency_type_id`
271
+ * being at least `entry_fee_amount` (free clans bypass this check).
272
+ * The SDK forwards the call unconditionally — calling without
273
+ * satisfying these will most likely return one of the error codes
274
+ * below.
275
+ *
276
+ * **Error codes** (in `errCode`, typed as {@link JoinClanErrorCode})
277
+ * - `0` (`JOIN_CLAN_OK`) — success; membership persisted, fee
278
+ * debited, cooldown restarted.
279
+ * - `1000` (`JOIN_CLAN_INVALID_PARAMETERS`) — request body missing
280
+ * `clan_id`. Should not occur via the SDK; treat as a programming
281
+ * error.
282
+ * - `1001` (`JOIN_CLAN_NOT_FOUND`) — clan doesn't exist for this
283
+ * label, OR the clan is archived / in draft state. The server
284
+ * merges "missing" and "archived" into this single code. Refresh
285
+ * `getClans()` and remove the entry from the UI.
286
+ * - `1002` (`JOIN_CLAN_FULL`) — capacity reached between the list
287
+ * fetch and the join click (`member_count >= capacity_limit` at
288
+ * the server's atomic check). Refresh the list — the button will
289
+ * become "Clan is full".
290
+ * - `1003` (`JOIN_CLAN_INSUFFICIENT_FUNDS`) — insufficient balance
291
+ * for the clan's entry fee. A single code covers all three
292
+ * currencies (points / gems / diamonds); read
293
+ * `clan.entry_fee_currency_type_id` to identify which currency
294
+ * the user is short on. Show an insufficient-balance UI naming
295
+ * the deficit.
296
+ * - `1004` (`JOIN_CLAN_SEGMENT_MISMATCH`) — user does not meet the
297
+ * clan's entry segment or numeric conditions. There is no
298
+ * client-side pre-guard for this — surface a gating message.
299
+ * - `1005` (`JOIN_CLAN_USER_IS_NOT_IN_CLAN`) — this method NEVER
300
+ * returns `1005`. The code is shared with the tournament
301
+ * registration error space and fires only on
302
+ * {@link registerInTournament} responses when a clan-based
303
+ * tournament requires the user to be in a clan first.
304
+ * - `1006` (`JOIN_CLAN_COOLDOWN_ACTIVE`) — user is inside the
305
+ * switch-cooldown window from a previous clan join (default
306
+ * 7 days, configurable per label). Surface the
307
+ * `TClans.cooldown_until` expiry in the disabled CTA.
308
+ * - `1007` (`JOIN_CLAN_ARCHIVED`) — defined on the public enum but
309
+ * the server does NOT emit this code in practice (archived clans
310
+ * are reported as `1001`). Handle it as a synonym for `1001`
311
+ * defensively, but do not rely on it.
312
+ * - `1011` (`JOIN_CLAN_JOINED_AFTER_TOURNAMENT_START`) — this
313
+ * method does NOT return `1011` directly. The code fires on
314
+ * {@link registerInTournament} responses when the user joined
315
+ * their current clan after the tournament started AND already
316
+ * has tournament scores.
317
+ * - other non-zero — generic server error. Surface `errMsg` if any.
318
+ *
319
+ * **Idempotency**: NOT safe — and notably dangerous. Calling
320
+ * `joinClan` with the user's CURRENT `clanId` does NOT short-circuit
321
+ * server-side; the call is treated as a clan-switch to the same
322
+ * clan. If the label's cooldown is non-zero (the default), the
323
+ * second call returns `1006`. If the cooldown is configured to
324
+ * zero, the second call will deduct the entry fee AGAIN, deactivate
325
+ * the membership, and re-insert it. The SDK does NOT enforce an
326
+ * in-flight lock. Consumers MUST guard the call site against
327
+ * double-clicks (set a local "joining" flag on click, clear it on
328
+ * response) AND short-circuit when the user is already in the
329
+ * target clan.
330
+ *
331
+ * **Refresh after success (and after failure)**
332
+ * The SDK does NOT automatically refresh the {@link getClans} cache
333
+ * after a join. Manually re-call `getClans()` on success to pick up
334
+ * the new `user_clan_id`, refreshed `member_count`, and the new
335
+ * `cooldown_until` value. Until you do, the cached `TClans` payload
336
+ * is stale.
337
+ *
338
+ * **Side effects** (consumer-observable on success)
339
+ * - Entry-fee currency balance decreases by `entry_fee_amount`
340
+ * (visible on the next {@link getUserProfile} refresh / via the
341
+ * user-properties update channel).
342
+ * - The user's clan membership row is created (or replaced, on a
343
+ * switch). `member_count` on the new clan increments by 1; on a
344
+ * switch, the old clan's `member_count` decrements by 1 in the
345
+ * same transaction.
346
+ * - The user's switch-cooldown restarts at the join time (the
347
+ * `TClans.cooldown_until` field on the next list fetch reflects
348
+ * the new expiry).
349
+ * - Server-side CRM analytics fire (clan-joined event, currency-
350
+ * deducted event for paid clans). These surface only as
351
+ * server-side traces; the SDK consumer observes them indirectly
352
+ * via balance / membership refresh.
353
+ *
354
+ * **UI guidance**: see [UI Guide — `joinClan`](../../docs/ui/clans/UIGuide_joinClan.md).
355
+ *
356
+ * **Visitor mode**: not supported. The server rejects the request
357
+ * for unauthenticated sessions.
358
+ *
359
+ * @param clanId The clan ID from `TClans.clans[i].clan_id` (or
360
+ * `TClanInfo.clan_id`).
361
+ * @returns `{ errCode, errMsg }`; success when `errCode === 0`.
362
+ * Note camelCase keys (see "Result shape note" above).
363
+ *
364
+ * @example
365
+ * ```ts
366
+ * const result = await window._smartico.api.getClans();
367
+ * const target = result.clans.find(c => c.clan_id === clanId);
368
+ *
369
+ * if (!target) {
370
+ * console.log('[smartico] clan not in current list — refresh getClans and retry');
371
+ * return;
372
+ * }
373
+ * if (target.clan_id === result.user_clan_id) {
374
+ * console.log('[smartico] user is already in this clan — short-circuit; do NOT call joinClan again, the server will treat it as a switch and may re-deduct the fee');
375
+ * return;
376
+ * }
377
+ * if (result.cooldown_until) {
378
+ * console.log('[smartico] user is in cooldown — disable Join until', new Date(result.cooldown_until + 'Z').toLocaleString());
379
+ * return;
380
+ * }
381
+ * if (target.member_count >= target.capacity_limit) {
382
+ * console.log('[smartico] clan is full — disable Join');
383
+ * return;
384
+ * }
385
+ *
386
+ * console.log('[smartico] join starting — set in-flight flag, show loading dots on Join button, keep modal open');
387
+ * const r = await window._smartico.api.joinClan(target.clan_id);
388
+ * console.log('[smartico] join response received — clear in-flight flag');
389
+ *
390
+ * if (r.errCode === 0) {
391
+ * console.log('[smartico] joined successfully — refresh getClans to pick up the new user_clan_id, member_count, and cooldown_until');
392
+ * await window._smartico.api.getClans();
393
+ * } else if (r.errCode === 1002) {
394
+ * console.error('[smartico] clan is full — refresh list, hide the Join CTA on the now-full clan');
395
+ * } else if (r.errCode === 1003) {
396
+ * const currencyLabel = ['points', 'gems', 'diamonds'][target.entry_fee_currency_type_id] ?? 'currency';
397
+ * console.error('[smartico] insufficient', currencyLabel, '— need', target.entry_fee_amount);
398
+ * } else if (r.errCode === 1004) {
399
+ * console.error('[smartico] user does not meet segment / entry conditions — show a gating message');
400
+ * } else if (r.errCode === 1006) {
401
+ * console.error('[smartico] cooldown active — surface the cooldown_until from getClans:', result.cooldown_until);
402
+ * } else if (r.errCode === 1001) {
403
+ * console.error('[smartico] clan not found or archived — refresh list and remove from UI');
404
+ * } else {
405
+ * console.error('[smartico] join failed — show a generic error toast with this message:', r.errMsg);
406
+ * }
407
+ * ```
408
+ */
409
+ public async joinClan(clanId: number): Promise<TClanJoinResult> {
410
+ return this.api.clanJoin(this.userExtId, clanId);
411
+ }
412
+
413
+ protected async updateClans() {
414
+ const payload = await this.api.clansGetListT(this.userExtId);
415
+ this.updateEntity(onUpdateContextKey.Clans, payload);
416
+ }
417
+ }