czapp-shared 1.0.37 → 1.0.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -51,6 +51,70 @@ declare const isTheSameDay: (date1: MySQLDate, date2: MySQLDate) => boolean;
51
51
  declare const getFormattedDate: (date: Date) => DateString;
52
52
  declare const isExpired: (date: MySQLDate) => boolean;
53
53
 
54
+ /**
55
+ * XP and experience levels.
56
+ *
57
+ * XP vs reward points - two separate running totals on the user, both updated by /test/complete:
58
+ *
59
+ * Reward points (IUserData.rewardPoints)
60
+ * - Measure PERFORMANCE: points per word known, plus bonuses for high scores in a session.
61
+ * - Shown to the user (home screen Reward Points card) and ranked on the leaderboard.
62
+ *
63
+ * XP (IUserData.xp)
64
+ * - Measure ENGAGEMENT and PROGRESS: doing reviews and tests at all, mastering (retiring) words, keeping a
65
+ * daily streak. A weak session still earns XP; scores barely matter.
66
+ * - Internal only: NEVER shown to the user, who would confuse it with reward points. Its sole purpose is to
67
+ * decide the user's experience level (the level name and alpha artwork on the home screen).
68
+ *
69
+ * Never derive one from the other, and don't show XP numbers in the app - show the level and progress towards the
70
+ * next one instead.
71
+ *
72
+ * A user's level is derived from their XP and their best streak - it is never stored, so client and server can't
73
+ * disagree, and because neither value ever decreases, a level once reached is never lost.
74
+ */
75
+ declare const XP_FLASHCARD_REVIEW = 10;
76
+ declare const XP_TEST = 15;
77
+ declare const XP_PER_TEST_KNOWN_ANSWER = 1;
78
+ declare const XP_PER_WORD_RETIRED = 5;
79
+ declare const XP_DAILY_STREAK_BONUS_CAP = 30;
80
+ interface ILevel {
81
+ level: number;
82
+ xpThreshold: number;
83
+ minBestStreak: number;
84
+ }
85
+ declare const LEVELS: readonly ILevel[];
86
+ declare const maxLevel: number;
87
+ /**
88
+ * @name getLevel
89
+ * @description The highest level whose XP threshold and best-streak requirement are both met. Levels must be
90
+ * reached in order, so a missing streak for level 5 holds the user at level 4 however much XP they have.
91
+ */
92
+ declare const getLevel: (xp: number, bestStreak: number) => number;
93
+ interface ILevelProgress {
94
+ level: number;
95
+ nextLevel?: number;
96
+ xpToNextLevel: number;
97
+ xpProgress: number;
98
+ streakDaysToNextLevel: number;
99
+ }
100
+ declare const getLevelProgress: (xp: number, bestStreak: number) => ILevelProgress;
101
+ /**
102
+ * @name getFlashcardReviewXp
103
+ * @param retiredCount - words promoted to RETIRED (mastered) by this review
104
+ * @param newStreakDayLength - the streak length if this review is the first of a new streak day, otherwise 0
105
+ */
106
+ declare const getFlashcardReviewXp: (retiredCount: number, newStreakDayLength: number) => number;
107
+ declare const getTestXp: (knownCount: number) => number;
108
+ declare const getBestStreak: (user: {
109
+ highStreakLength: number;
110
+ currentStreakLength: number;
111
+ }) => number;
112
+ declare const getUserLevelProgress: (user: {
113
+ xp: number;
114
+ highStreakLength: number;
115
+ currentStreakLength: number;
116
+ }) => ILevelProgress;
117
+
54
118
  interface ISession {
55
119
  sessionToken: string | undefined;
56
120
  deviceId: string | undefined;
@@ -118,6 +182,18 @@ interface IProgressHistoryDay {
118
182
  learningCount: number;
119
183
  retiredCount: number;
120
184
  }
185
+ /**
186
+ * One row of the reward points leaderboard. position is the user's 1-based rank across all users, ordered by
187
+ * rewardPoints, then highStreakLength, then sign-up order. name is the first name plus surname initial, never the
188
+ * full name.
189
+ */
190
+ interface ILeaderboardEntry {
191
+ position: number;
192
+ name: string;
193
+ rewardPoints: number;
194
+ highStreakLength: number;
195
+ isCurrentUser: boolean;
196
+ }
121
197
  type MySQLDate = `${number}-${number}-${number} ${number}:${number}:${number}`;
122
198
  type DateString = `${number}-${string}-${string}`;
123
199
  declare enum ReminderFrequency {
@@ -269,6 +345,7 @@ interface IUserData {
269
345
  uiLanguage: Language;
270
346
  completedOnboarding: boolean;
271
347
  learningSet: number;
348
+ xp: number;
272
349
  }
273
350
 
274
351
  declare enum HttpStatusCode {
@@ -291,6 +368,7 @@ declare enum ApiPath {
291
368
  DATA_HEATMAP = "/data/heatmap/:weekCount/:endDate",
292
369
  HEALTH = "/health",
293
370
  LAST_WORDS_ADDED = "/lastWordsAdded",
371
+ LEADERBOARD = "/leaderboard",
294
372
  LEXEMES = "/lexemes",
295
373
  LEXEMES_ALL = "/lexemes/all",
296
374
  LEXEMES_COUNT = "/lexemes/count/:language",
@@ -462,6 +540,7 @@ interface TestCompleteResponseData {
462
540
  user: IUserData;
463
541
  testResultIds: number[];
464
542
  rewardPointsDelta: number;
543
+ xpDelta: number;
465
544
  vocabCheckActivity: IVocabCheckActivity[];
466
545
  }
467
546
  interface HeatMapResponseData {
@@ -476,4 +555,4 @@ type DeeplTranslation = {
476
555
  }>;
477
556
  };
478
557
 
479
- export { ApiMethod, ApiPath, AppError, type AutologinRequestBody, ClientPlatform, type ControllerResponse, type DateString, type DeeplTranslation, type DeleteLexemePairRequestParams, Familiarity, type HeatMapParams, type HeatMapResponseData, HttpStatusCode, type IActivityCount, type ICount, type ILexeme, type ILexemeIdPair, type ILexemeLearningInfo, type ILexemePair, type ILexemePairTexts, type IProgressHistoryDay, type ISession, type ITestResult, type IUserData, type IVocabCheckActivity, type InsertOrUpdateRequestBody, type InsertOrUpdateResponseData, LEARNING_STAGES_IN_GROUP, Language, LearningStage, LearningStageGroup, Lexeme, LexemePair, type LexemePairRequestBody, type LexemePairWithLang, type MySQLDate, Progress, type RecycleLexemePairParams, type RegisterPushTokenRequestBody, ReminderFrequency, type ResetTestUserParams, type Result, Scenario, type SelectAllTranslationsParams, type SelectLexemeCountParams, type SelectLexemePairParams, type SelectLexemePairsByTextParams, type SelectLexemesParams, type SelectProgressHistoryParams, type SelectTestLexemesParams, type SelectVocabCheckActivityParams, type SignInRequestBody, type SignInResponseData, type Streaks, type TestCompleteRequestBody, type TestCompleteResponseData, type TestInitRequestBody, type TestInitResponseData, type TranslationRequestBody, type TranslationResponseData, type UpdateLexemePairFamiliarityParams, type UpdateOnboardingStatusRequestBody, type UpdateUserRequestBody, VocabCheckType, convertJSDateStringToMySQLDate, dateDifferenceInDays, deriveStreakFromVocabCheckActivity, getFormattedDate, getMysqlDateIgnoreTZ, isClientDateTooFarFromServerDate, isExpired, isFinalTest, isLearningStageGroup, isStringContainingInteger, isThePreviousDay, isTheSameDay, isValidJsDateString, isValidMysqlDateString, parameterReplace };
558
+ export { ApiMethod, ApiPath, AppError, type AutologinRequestBody, ClientPlatform, type ControllerResponse, type DateString, type DeeplTranslation, type DeleteLexemePairRequestParams, Familiarity, type HeatMapParams, type HeatMapResponseData, HttpStatusCode, type IActivityCount, type ICount, type ILeaderboardEntry, type ILevel, type ILevelProgress, type ILexeme, type ILexemeIdPair, type ILexemeLearningInfo, type ILexemePair, type ILexemePairTexts, type IProgressHistoryDay, type ISession, type ITestResult, type IUserData, type IVocabCheckActivity, type InsertOrUpdateRequestBody, type InsertOrUpdateResponseData, LEARNING_STAGES_IN_GROUP, LEVELS, Language, LearningStage, LearningStageGroup, Lexeme, LexemePair, type LexemePairRequestBody, type LexemePairWithLang, type MySQLDate, Progress, type RecycleLexemePairParams, type RegisterPushTokenRequestBody, ReminderFrequency, type ResetTestUserParams, type Result, Scenario, type SelectAllTranslationsParams, type SelectLexemeCountParams, type SelectLexemePairParams, type SelectLexemePairsByTextParams, type SelectLexemesParams, type SelectProgressHistoryParams, type SelectTestLexemesParams, type SelectVocabCheckActivityParams, type SignInRequestBody, type SignInResponseData, type Streaks, type TestCompleteRequestBody, type TestCompleteResponseData, type TestInitRequestBody, type TestInitResponseData, type TranslationRequestBody, type TranslationResponseData, type UpdateLexemePairFamiliarityParams, type UpdateOnboardingStatusRequestBody, type UpdateUserRequestBody, VocabCheckType, XP_DAILY_STREAK_BONUS_CAP, XP_FLASHCARD_REVIEW, XP_PER_TEST_KNOWN_ANSWER, XP_PER_WORD_RETIRED, XP_TEST, convertJSDateStringToMySQLDate, dateDifferenceInDays, deriveStreakFromVocabCheckActivity, getBestStreak, getFlashcardReviewXp, getFormattedDate, getLevel, getLevelProgress, getMysqlDateIgnoreTZ, getTestXp, getUserLevelProgress, isClientDateTooFarFromServerDate, isExpired, isFinalTest, isLearningStageGroup, isStringContainingInteger, isThePreviousDay, isTheSameDay, isValidJsDateString, isValidMysqlDateString, maxLevel, parameterReplace };
package/dist/index.d.ts CHANGED
@@ -51,6 +51,70 @@ declare const isTheSameDay: (date1: MySQLDate, date2: MySQLDate) => boolean;
51
51
  declare const getFormattedDate: (date: Date) => DateString;
52
52
  declare const isExpired: (date: MySQLDate) => boolean;
53
53
 
54
+ /**
55
+ * XP and experience levels.
56
+ *
57
+ * XP vs reward points - two separate running totals on the user, both updated by /test/complete:
58
+ *
59
+ * Reward points (IUserData.rewardPoints)
60
+ * - Measure PERFORMANCE: points per word known, plus bonuses for high scores in a session.
61
+ * - Shown to the user (home screen Reward Points card) and ranked on the leaderboard.
62
+ *
63
+ * XP (IUserData.xp)
64
+ * - Measure ENGAGEMENT and PROGRESS: doing reviews and tests at all, mastering (retiring) words, keeping a
65
+ * daily streak. A weak session still earns XP; scores barely matter.
66
+ * - Internal only: NEVER shown to the user, who would confuse it with reward points. Its sole purpose is to
67
+ * decide the user's experience level (the level name and alpha artwork on the home screen).
68
+ *
69
+ * Never derive one from the other, and don't show XP numbers in the app - show the level and progress towards the
70
+ * next one instead.
71
+ *
72
+ * A user's level is derived from their XP and their best streak - it is never stored, so client and server can't
73
+ * disagree, and because neither value ever decreases, a level once reached is never lost.
74
+ */
75
+ declare const XP_FLASHCARD_REVIEW = 10;
76
+ declare const XP_TEST = 15;
77
+ declare const XP_PER_TEST_KNOWN_ANSWER = 1;
78
+ declare const XP_PER_WORD_RETIRED = 5;
79
+ declare const XP_DAILY_STREAK_BONUS_CAP = 30;
80
+ interface ILevel {
81
+ level: number;
82
+ xpThreshold: number;
83
+ minBestStreak: number;
84
+ }
85
+ declare const LEVELS: readonly ILevel[];
86
+ declare const maxLevel: number;
87
+ /**
88
+ * @name getLevel
89
+ * @description The highest level whose XP threshold and best-streak requirement are both met. Levels must be
90
+ * reached in order, so a missing streak for level 5 holds the user at level 4 however much XP they have.
91
+ */
92
+ declare const getLevel: (xp: number, bestStreak: number) => number;
93
+ interface ILevelProgress {
94
+ level: number;
95
+ nextLevel?: number;
96
+ xpToNextLevel: number;
97
+ xpProgress: number;
98
+ streakDaysToNextLevel: number;
99
+ }
100
+ declare const getLevelProgress: (xp: number, bestStreak: number) => ILevelProgress;
101
+ /**
102
+ * @name getFlashcardReviewXp
103
+ * @param retiredCount - words promoted to RETIRED (mastered) by this review
104
+ * @param newStreakDayLength - the streak length if this review is the first of a new streak day, otherwise 0
105
+ */
106
+ declare const getFlashcardReviewXp: (retiredCount: number, newStreakDayLength: number) => number;
107
+ declare const getTestXp: (knownCount: number) => number;
108
+ declare const getBestStreak: (user: {
109
+ highStreakLength: number;
110
+ currentStreakLength: number;
111
+ }) => number;
112
+ declare const getUserLevelProgress: (user: {
113
+ xp: number;
114
+ highStreakLength: number;
115
+ currentStreakLength: number;
116
+ }) => ILevelProgress;
117
+
54
118
  interface ISession {
55
119
  sessionToken: string | undefined;
56
120
  deviceId: string | undefined;
@@ -118,6 +182,18 @@ interface IProgressHistoryDay {
118
182
  learningCount: number;
119
183
  retiredCount: number;
120
184
  }
185
+ /**
186
+ * One row of the reward points leaderboard. position is the user's 1-based rank across all users, ordered by
187
+ * rewardPoints, then highStreakLength, then sign-up order. name is the first name plus surname initial, never the
188
+ * full name.
189
+ */
190
+ interface ILeaderboardEntry {
191
+ position: number;
192
+ name: string;
193
+ rewardPoints: number;
194
+ highStreakLength: number;
195
+ isCurrentUser: boolean;
196
+ }
121
197
  type MySQLDate = `${number}-${number}-${number} ${number}:${number}:${number}`;
122
198
  type DateString = `${number}-${string}-${string}`;
123
199
  declare enum ReminderFrequency {
@@ -269,6 +345,7 @@ interface IUserData {
269
345
  uiLanguage: Language;
270
346
  completedOnboarding: boolean;
271
347
  learningSet: number;
348
+ xp: number;
272
349
  }
273
350
 
274
351
  declare enum HttpStatusCode {
@@ -291,6 +368,7 @@ declare enum ApiPath {
291
368
  DATA_HEATMAP = "/data/heatmap/:weekCount/:endDate",
292
369
  HEALTH = "/health",
293
370
  LAST_WORDS_ADDED = "/lastWordsAdded",
371
+ LEADERBOARD = "/leaderboard",
294
372
  LEXEMES = "/lexemes",
295
373
  LEXEMES_ALL = "/lexemes/all",
296
374
  LEXEMES_COUNT = "/lexemes/count/:language",
@@ -462,6 +540,7 @@ interface TestCompleteResponseData {
462
540
  user: IUserData;
463
541
  testResultIds: number[];
464
542
  rewardPointsDelta: number;
543
+ xpDelta: number;
465
544
  vocabCheckActivity: IVocabCheckActivity[];
466
545
  }
467
546
  interface HeatMapResponseData {
@@ -476,4 +555,4 @@ type DeeplTranslation = {
476
555
  }>;
477
556
  };
478
557
 
479
- export { ApiMethod, ApiPath, AppError, type AutologinRequestBody, ClientPlatform, type ControllerResponse, type DateString, type DeeplTranslation, type DeleteLexemePairRequestParams, Familiarity, type HeatMapParams, type HeatMapResponseData, HttpStatusCode, type IActivityCount, type ICount, type ILexeme, type ILexemeIdPair, type ILexemeLearningInfo, type ILexemePair, type ILexemePairTexts, type IProgressHistoryDay, type ISession, type ITestResult, type IUserData, type IVocabCheckActivity, type InsertOrUpdateRequestBody, type InsertOrUpdateResponseData, LEARNING_STAGES_IN_GROUP, Language, LearningStage, LearningStageGroup, Lexeme, LexemePair, type LexemePairRequestBody, type LexemePairWithLang, type MySQLDate, Progress, type RecycleLexemePairParams, type RegisterPushTokenRequestBody, ReminderFrequency, type ResetTestUserParams, type Result, Scenario, type SelectAllTranslationsParams, type SelectLexemeCountParams, type SelectLexemePairParams, type SelectLexemePairsByTextParams, type SelectLexemesParams, type SelectProgressHistoryParams, type SelectTestLexemesParams, type SelectVocabCheckActivityParams, type SignInRequestBody, type SignInResponseData, type Streaks, type TestCompleteRequestBody, type TestCompleteResponseData, type TestInitRequestBody, type TestInitResponseData, type TranslationRequestBody, type TranslationResponseData, type UpdateLexemePairFamiliarityParams, type UpdateOnboardingStatusRequestBody, type UpdateUserRequestBody, VocabCheckType, convertJSDateStringToMySQLDate, dateDifferenceInDays, deriveStreakFromVocabCheckActivity, getFormattedDate, getMysqlDateIgnoreTZ, isClientDateTooFarFromServerDate, isExpired, isFinalTest, isLearningStageGroup, isStringContainingInteger, isThePreviousDay, isTheSameDay, isValidJsDateString, isValidMysqlDateString, parameterReplace };
558
+ export { ApiMethod, ApiPath, AppError, type AutologinRequestBody, ClientPlatform, type ControllerResponse, type DateString, type DeeplTranslation, type DeleteLexemePairRequestParams, Familiarity, type HeatMapParams, type HeatMapResponseData, HttpStatusCode, type IActivityCount, type ICount, type ILeaderboardEntry, type ILevel, type ILevelProgress, type ILexeme, type ILexemeIdPair, type ILexemeLearningInfo, type ILexemePair, type ILexemePairTexts, type IProgressHistoryDay, type ISession, type ITestResult, type IUserData, type IVocabCheckActivity, type InsertOrUpdateRequestBody, type InsertOrUpdateResponseData, LEARNING_STAGES_IN_GROUP, LEVELS, Language, LearningStage, LearningStageGroup, Lexeme, LexemePair, type LexemePairRequestBody, type LexemePairWithLang, type MySQLDate, Progress, type RecycleLexemePairParams, type RegisterPushTokenRequestBody, ReminderFrequency, type ResetTestUserParams, type Result, Scenario, type SelectAllTranslationsParams, type SelectLexemeCountParams, type SelectLexemePairParams, type SelectLexemePairsByTextParams, type SelectLexemesParams, type SelectProgressHistoryParams, type SelectTestLexemesParams, type SelectVocabCheckActivityParams, type SignInRequestBody, type SignInResponseData, type Streaks, type TestCompleteRequestBody, type TestCompleteResponseData, type TestInitRequestBody, type TestInitResponseData, type TranslationRequestBody, type TranslationResponseData, type UpdateLexemePairFamiliarityParams, type UpdateOnboardingStatusRequestBody, type UpdateUserRequestBody, VocabCheckType, XP_DAILY_STREAK_BONUS_CAP, XP_FLASHCARD_REVIEW, XP_PER_TEST_KNOWN_ANSWER, XP_PER_WORD_RETIRED, XP_TEST, convertJSDateStringToMySQLDate, dateDifferenceInDays, deriveStreakFromVocabCheckActivity, getBestStreak, getFlashcardReviewXp, getFormattedDate, getLevel, getLevelProgress, getMysqlDateIgnoreTZ, getTestXp, getUserLevelProgress, isClientDateTooFarFromServerDate, isExpired, isFinalTest, isLearningStageGroup, isStringContainingInteger, isThePreviousDay, isTheSameDay, isValidJsDateString, isValidMysqlDateString, maxLevel, parameterReplace };
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ __export(index_exports, {
26
26
  Familiarity: () => Familiarity,
27
27
  HttpStatusCode: () => HttpStatusCode,
28
28
  LEARNING_STAGES_IN_GROUP: () => LEARNING_STAGES_IN_GROUP,
29
+ LEVELS: () => LEVELS,
29
30
  Language: () => Language,
30
31
  LearningStage: () => LearningStage,
31
32
  LearningStageGroup: () => LearningStageGroup,
@@ -35,11 +36,22 @@ __export(index_exports, {
35
36
  ReminderFrequency: () => ReminderFrequency,
36
37
  Scenario: () => Scenario,
37
38
  VocabCheckType: () => VocabCheckType,
39
+ XP_DAILY_STREAK_BONUS_CAP: () => XP_DAILY_STREAK_BONUS_CAP,
40
+ XP_FLASHCARD_REVIEW: () => XP_FLASHCARD_REVIEW,
41
+ XP_PER_TEST_KNOWN_ANSWER: () => XP_PER_TEST_KNOWN_ANSWER,
42
+ XP_PER_WORD_RETIRED: () => XP_PER_WORD_RETIRED,
43
+ XP_TEST: () => XP_TEST,
38
44
  convertJSDateStringToMySQLDate: () => convertJSDateStringToMySQLDate,
39
45
  dateDifferenceInDays: () => dateDifferenceInDays,
40
46
  deriveStreakFromVocabCheckActivity: () => deriveStreakFromVocabCheckActivity,
47
+ getBestStreak: () => getBestStreak,
48
+ getFlashcardReviewXp: () => getFlashcardReviewXp,
41
49
  getFormattedDate: () => getFormattedDate,
50
+ getLevel: () => getLevel,
51
+ getLevelProgress: () => getLevelProgress,
42
52
  getMysqlDateIgnoreTZ: () => getMysqlDateIgnoreTZ,
53
+ getTestXp: () => getTestXp,
54
+ getUserLevelProgress: () => getUserLevelProgress,
43
55
  isClientDateTooFarFromServerDate: () => isClientDateTooFarFromServerDate,
44
56
  isExpired: () => isExpired,
45
57
  isFinalTest: () => isFinalTest,
@@ -49,6 +61,7 @@ __export(index_exports, {
49
61
  isTheSameDay: () => isTheSameDay,
50
62
  isValidJsDateString: () => isValidJsDateString,
51
63
  isValidMysqlDateString: () => isValidMysqlDateString,
64
+ maxLevel: () => maxLevel,
52
65
  parameterReplace: () => parameterReplace
53
66
  });
54
67
  module.exports = __toCommonJS(index_exports);
@@ -116,6 +129,63 @@ var isExpired = (date) => {
116
129
  return dateObj.getTime() < now.getTime();
117
130
  };
118
131
 
132
+ // src/concrete/level.ts
133
+ var XP_FLASHCARD_REVIEW = 10;
134
+ var XP_TEST = 15;
135
+ var XP_PER_TEST_KNOWN_ANSWER = 1;
136
+ var XP_PER_WORD_RETIRED = 5;
137
+ var XP_DAILY_STREAK_BONUS_CAP = 30;
138
+ var LEVELS = [
139
+ { level: 1, xpThreshold: 0, minBestStreak: 0 },
140
+ { level: 2, xpThreshold: 60, minBestStreak: 0 },
141
+ { level: 3, xpThreshold: 200, minBestStreak: 0 },
142
+ { level: 4, xpThreshold: 450, minBestStreak: 0 },
143
+ { level: 5, xpThreshold: 900, minBestStreak: 7 },
144
+ { level: 6, xpThreshold: 1600, minBestStreak: 14 },
145
+ { level: 7, xpThreshold: 2700, minBestStreak: 21 },
146
+ { level: 8, xpThreshold: 4300, minBestStreak: 30 },
147
+ { level: 9, xpThreshold: 6500, minBestStreak: 45 },
148
+ { level: 10, xpThreshold: 1e4, minBestStreak: 60 }
149
+ ];
150
+ var maxLevel = LEVELS[LEVELS.length - 1].level;
151
+ var meetsRequirements = (level, xp, bestStreak) => xp >= level.xpThreshold && bestStreak >= level.minBestStreak;
152
+ var getLevel = (xp, bestStreak) => {
153
+ let reached = LEVELS[0].level;
154
+ for (const level of LEVELS) {
155
+ if (!meetsRequirements(level, xp, bestStreak)) {
156
+ break;
157
+ }
158
+ reached = level.level;
159
+ }
160
+ return reached;
161
+ };
162
+ var getLevelProgress = (xp, bestStreak) => {
163
+ const level = getLevel(xp, bestStreak);
164
+ const current = LEVELS[level - 1];
165
+ const next = LEVELS[level];
166
+ if (!next) {
167
+ return { level, xpToNextLevel: 0, xpProgress: 1, streakDaysToNextLevel: 0 };
168
+ }
169
+ const span = next.xpThreshold - current.xpThreshold;
170
+ return {
171
+ level,
172
+ nextLevel: next.level,
173
+ xpToNextLevel: Math.max(0, next.xpThreshold - xp),
174
+ xpProgress: Math.min(1, Math.max(0, (xp - current.xpThreshold) / span)),
175
+ streakDaysToNextLevel: Math.max(0, next.minBestStreak - bestStreak)
176
+ };
177
+ };
178
+ var getFlashcardReviewXp = (retiredCount, newStreakDayLength) => XP_FLASHCARD_REVIEW + retiredCount * XP_PER_WORD_RETIRED + Math.min(Math.max(0, newStreakDayLength), XP_DAILY_STREAK_BONUS_CAP);
179
+ var getTestXp = (knownCount) => XP_TEST + knownCount * XP_PER_TEST_KNOWN_ANSWER;
180
+ var getBestStreak = (user) => {
181
+ var _a, _b;
182
+ return Math.max((_a = user.highStreakLength) != null ? _a : 0, (_b = user.currentStreakLength) != null ? _b : 0);
183
+ };
184
+ var getUserLevelProgress = (user) => {
185
+ var _a;
186
+ return getLevelProgress((_a = user.xp) != null ? _a : 0, getBestStreak(user));
187
+ };
188
+
119
189
  // src/design/types.ts
120
190
  var Language = /* @__PURE__ */ ((Language2) => {
121
191
  Language2["CZECH"] = "CZECH";
@@ -311,6 +381,7 @@ var ApiPath = /* @__PURE__ */ ((ApiPath2) => {
311
381
  ApiPath2["DATA_HEATMAP"] = "/data/heatmap/:weekCount/:endDate";
312
382
  ApiPath2["HEALTH"] = "/health";
313
383
  ApiPath2["LAST_WORDS_ADDED"] = "/lastWordsAdded";
384
+ ApiPath2["LEADERBOARD"] = "/leaderboard";
314
385
  ApiPath2["LEXEMES"] = "/lexemes";
315
386
  ApiPath2["LEXEMES_ALL"] = "/lexemes/all";
316
387
  ApiPath2["LEXEMES_COUNT"] = "/lexemes/count/:language";
@@ -353,6 +424,7 @@ var ClientPlatform = /* @__PURE__ */ ((ClientPlatform2) => {
353
424
  Familiarity,
354
425
  HttpStatusCode,
355
426
  LEARNING_STAGES_IN_GROUP,
427
+ LEVELS,
356
428
  Language,
357
429
  LearningStage,
358
430
  LearningStageGroup,
@@ -362,11 +434,22 @@ var ClientPlatform = /* @__PURE__ */ ((ClientPlatform2) => {
362
434
  ReminderFrequency,
363
435
  Scenario,
364
436
  VocabCheckType,
437
+ XP_DAILY_STREAK_BONUS_CAP,
438
+ XP_FLASHCARD_REVIEW,
439
+ XP_PER_TEST_KNOWN_ANSWER,
440
+ XP_PER_WORD_RETIRED,
441
+ XP_TEST,
365
442
  convertJSDateStringToMySQLDate,
366
443
  dateDifferenceInDays,
367
444
  deriveStreakFromVocabCheckActivity,
445
+ getBestStreak,
446
+ getFlashcardReviewXp,
368
447
  getFormattedDate,
448
+ getLevel,
449
+ getLevelProgress,
369
450
  getMysqlDateIgnoreTZ,
451
+ getTestXp,
452
+ getUserLevelProgress,
370
453
  isClientDateTooFarFromServerDate,
371
454
  isExpired,
372
455
  isFinalTest,
@@ -376,5 +459,6 @@ var ClientPlatform = /* @__PURE__ */ ((ClientPlatform2) => {
376
459
  isTheSameDay,
377
460
  isValidJsDateString,
378
461
  isValidMysqlDateString,
462
+ maxLevel,
379
463
  parameterReplace
380
464
  });
package/dist/index.mjs CHANGED
@@ -61,6 +61,63 @@ var isExpired = (date) => {
61
61
  return dateObj.getTime() < now.getTime();
62
62
  };
63
63
 
64
+ // src/concrete/level.ts
65
+ var XP_FLASHCARD_REVIEW = 10;
66
+ var XP_TEST = 15;
67
+ var XP_PER_TEST_KNOWN_ANSWER = 1;
68
+ var XP_PER_WORD_RETIRED = 5;
69
+ var XP_DAILY_STREAK_BONUS_CAP = 30;
70
+ var LEVELS = [
71
+ { level: 1, xpThreshold: 0, minBestStreak: 0 },
72
+ { level: 2, xpThreshold: 60, minBestStreak: 0 },
73
+ { level: 3, xpThreshold: 200, minBestStreak: 0 },
74
+ { level: 4, xpThreshold: 450, minBestStreak: 0 },
75
+ { level: 5, xpThreshold: 900, minBestStreak: 7 },
76
+ { level: 6, xpThreshold: 1600, minBestStreak: 14 },
77
+ { level: 7, xpThreshold: 2700, minBestStreak: 21 },
78
+ { level: 8, xpThreshold: 4300, minBestStreak: 30 },
79
+ { level: 9, xpThreshold: 6500, minBestStreak: 45 },
80
+ { level: 10, xpThreshold: 1e4, minBestStreak: 60 }
81
+ ];
82
+ var maxLevel = LEVELS[LEVELS.length - 1].level;
83
+ var meetsRequirements = (level, xp, bestStreak) => xp >= level.xpThreshold && bestStreak >= level.minBestStreak;
84
+ var getLevel = (xp, bestStreak) => {
85
+ let reached = LEVELS[0].level;
86
+ for (const level of LEVELS) {
87
+ if (!meetsRequirements(level, xp, bestStreak)) {
88
+ break;
89
+ }
90
+ reached = level.level;
91
+ }
92
+ return reached;
93
+ };
94
+ var getLevelProgress = (xp, bestStreak) => {
95
+ const level = getLevel(xp, bestStreak);
96
+ const current = LEVELS[level - 1];
97
+ const next = LEVELS[level];
98
+ if (!next) {
99
+ return { level, xpToNextLevel: 0, xpProgress: 1, streakDaysToNextLevel: 0 };
100
+ }
101
+ const span = next.xpThreshold - current.xpThreshold;
102
+ return {
103
+ level,
104
+ nextLevel: next.level,
105
+ xpToNextLevel: Math.max(0, next.xpThreshold - xp),
106
+ xpProgress: Math.min(1, Math.max(0, (xp - current.xpThreshold) / span)),
107
+ streakDaysToNextLevel: Math.max(0, next.minBestStreak - bestStreak)
108
+ };
109
+ };
110
+ var getFlashcardReviewXp = (retiredCount, newStreakDayLength) => XP_FLASHCARD_REVIEW + retiredCount * XP_PER_WORD_RETIRED + Math.min(Math.max(0, newStreakDayLength), XP_DAILY_STREAK_BONUS_CAP);
111
+ var getTestXp = (knownCount) => XP_TEST + knownCount * XP_PER_TEST_KNOWN_ANSWER;
112
+ var getBestStreak = (user) => {
113
+ var _a, _b;
114
+ return Math.max((_a = user.highStreakLength) != null ? _a : 0, (_b = user.currentStreakLength) != null ? _b : 0);
115
+ };
116
+ var getUserLevelProgress = (user) => {
117
+ var _a;
118
+ return getLevelProgress((_a = user.xp) != null ? _a : 0, getBestStreak(user));
119
+ };
120
+
64
121
  // src/design/types.ts
65
122
  var Language = /* @__PURE__ */ ((Language2) => {
66
123
  Language2["CZECH"] = "CZECH";
@@ -256,6 +313,7 @@ var ApiPath = /* @__PURE__ */ ((ApiPath2) => {
256
313
  ApiPath2["DATA_HEATMAP"] = "/data/heatmap/:weekCount/:endDate";
257
314
  ApiPath2["HEALTH"] = "/health";
258
315
  ApiPath2["LAST_WORDS_ADDED"] = "/lastWordsAdded";
316
+ ApiPath2["LEADERBOARD"] = "/leaderboard";
259
317
  ApiPath2["LEXEMES"] = "/lexemes";
260
318
  ApiPath2["LEXEMES_ALL"] = "/lexemes/all";
261
319
  ApiPath2["LEXEMES_COUNT"] = "/lexemes/count/:language";
@@ -297,6 +355,7 @@ export {
297
355
  Familiarity,
298
356
  HttpStatusCode,
299
357
  LEARNING_STAGES_IN_GROUP,
358
+ LEVELS,
300
359
  Language,
301
360
  LearningStage,
302
361
  LearningStageGroup,
@@ -306,11 +365,22 @@ export {
306
365
  ReminderFrequency,
307
366
  Scenario,
308
367
  VocabCheckType,
368
+ XP_DAILY_STREAK_BONUS_CAP,
369
+ XP_FLASHCARD_REVIEW,
370
+ XP_PER_TEST_KNOWN_ANSWER,
371
+ XP_PER_WORD_RETIRED,
372
+ XP_TEST,
309
373
  convertJSDateStringToMySQLDate,
310
374
  dateDifferenceInDays,
311
375
  deriveStreakFromVocabCheckActivity,
376
+ getBestStreak,
377
+ getFlashcardReviewXp,
312
378
  getFormattedDate,
379
+ getLevel,
380
+ getLevelProgress,
313
381
  getMysqlDateIgnoreTZ,
382
+ getTestXp,
383
+ getUserLevelProgress,
314
384
  isClientDateTooFarFromServerDate,
315
385
  isExpired,
316
386
  isFinalTest,
@@ -320,5 +390,6 @@ export {
320
390
  isTheSameDay,
321
391
  isValidJsDateString,
322
392
  isValidMysqlDateString,
393
+ maxLevel,
323
394
  parameterReplace
324
395
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "czapp-shared",
3
- "version": "1.0.37",
3
+ "version": "1.0.39",
4
4
  "description": "This is a shared library for Czapp projects. It contains common code that is used across multiple projects.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -0,0 +1,119 @@
1
+ /**
2
+ * XP and experience levels.
3
+ *
4
+ * XP vs reward points - two separate running totals on the user, both updated by /test/complete:
5
+ *
6
+ * Reward points (IUserData.rewardPoints)
7
+ * - Measure PERFORMANCE: points per word known, plus bonuses for high scores in a session.
8
+ * - Shown to the user (home screen Reward Points card) and ranked on the leaderboard.
9
+ *
10
+ * XP (IUserData.xp)
11
+ * - Measure ENGAGEMENT and PROGRESS: doing reviews and tests at all, mastering (retiring) words, keeping a
12
+ * daily streak. A weak session still earns XP; scores barely matter.
13
+ * - Internal only: NEVER shown to the user, who would confuse it with reward points. Its sole purpose is to
14
+ * decide the user's experience level (the level name and alpha artwork on the home screen).
15
+ *
16
+ * Never derive one from the other, and don't show XP numbers in the app - show the level and progress towards the
17
+ * next one instead.
18
+ *
19
+ * A user's level is derived from their XP and their best streak - it is never stored, so client and server can't
20
+ * disagree, and because neither value ever decreases, a level once reached is never lost.
21
+ */
22
+
23
+ export const XP_FLASHCARD_REVIEW = 10;
24
+ export const XP_TEST = 15;
25
+ export const XP_PER_TEST_KNOWN_ANSWER = 1;
26
+ export const XP_PER_WORD_RETIRED = 5;
27
+ // The first review of each streak day earns XP equal to the streak length, capped here.
28
+ export const XP_DAILY_STREAK_BONUS_CAP = 30;
29
+
30
+ export interface ILevel {
31
+ // 1-based
32
+ level: number;
33
+ xpThreshold: number;
34
+ // Best streak (days) also needed to reach this level, so it can't be reached by grinding in one burst.
35
+ minBestStreak: number;
36
+ }
37
+
38
+ export const LEVELS: readonly ILevel[] = [
39
+ { level: 1, xpThreshold: 0, minBestStreak: 0 },
40
+ { level: 2, xpThreshold: 60, minBestStreak: 0 },
41
+ { level: 3, xpThreshold: 200, minBestStreak: 0 },
42
+ { level: 4, xpThreshold: 450, minBestStreak: 0 },
43
+ { level: 5, xpThreshold: 900, minBestStreak: 7 },
44
+ { level: 6, xpThreshold: 1600, minBestStreak: 14 },
45
+ { level: 7, xpThreshold: 2700, minBestStreak: 21 },
46
+ { level: 8, xpThreshold: 4300, minBestStreak: 30 },
47
+ { level: 9, xpThreshold: 6500, minBestStreak: 45 },
48
+ { level: 10, xpThreshold: 10000, minBestStreak: 60 },
49
+ ];
50
+
51
+ export const maxLevel = LEVELS[LEVELS.length - 1].level;
52
+
53
+ const meetsRequirements = (level: ILevel, xp: number, bestStreak: number): boolean =>
54
+ xp >= level.xpThreshold && bestStreak >= level.minBestStreak;
55
+
56
+ /**
57
+ * @name getLevel
58
+ * @description The highest level whose XP threshold and best-streak requirement are both met. Levels must be
59
+ * reached in order, so a missing streak for level 5 holds the user at level 4 however much XP they have.
60
+ */
61
+ export const getLevel = (xp: number, bestStreak: number): number => {
62
+ let reached = LEVELS[0].level;
63
+ for (const level of LEVELS) {
64
+ if (!meetsRequirements(level, xp, bestStreak)) {
65
+ break;
66
+ }
67
+ reached = level.level;
68
+ }
69
+ return reached;
70
+ };
71
+
72
+ export interface ILevelProgress {
73
+ level: number;
74
+ // undefined at the top level
75
+ nextLevel?: number;
76
+ // XP still needed for the next level (0 when only the streak is missing)
77
+ xpToNextLevel: number;
78
+ // 0..1 through the XP between this level's threshold and the next one's
79
+ xpProgress: number;
80
+ // Best streak still needed for the next level (0 when it's already met)
81
+ streakDaysToNextLevel: number;
82
+ }
83
+
84
+ export const getLevelProgress = (xp: number, bestStreak: number): ILevelProgress => {
85
+ const level = getLevel(xp, bestStreak);
86
+ const current = LEVELS[level - 1];
87
+ const next = LEVELS[level];
88
+ if (!next) {
89
+ return { level, xpToNextLevel: 0, xpProgress: 1, streakDaysToNextLevel: 0 };
90
+ }
91
+ const span = next.xpThreshold - current.xpThreshold;
92
+ return {
93
+ level,
94
+ nextLevel: next.level,
95
+ xpToNextLevel: Math.max(0, next.xpThreshold - xp),
96
+ xpProgress: Math.min(1, Math.max(0, (xp - current.xpThreshold) / span)),
97
+ streakDaysToNextLevel: Math.max(0, next.minBestStreak - bestStreak),
98
+ };
99
+ };
100
+
101
+ /**
102
+ * @name getFlashcardReviewXp
103
+ * @param retiredCount - words promoted to RETIRED (mastered) by this review
104
+ * @param newStreakDayLength - the streak length if this review is the first of a new streak day, otherwise 0
105
+ */
106
+ export const getFlashcardReviewXp = (retiredCount: number, newStreakDayLength: number): number =>
107
+ XP_FLASHCARD_REVIEW
108
+ + retiredCount * XP_PER_WORD_RETIRED
109
+ + Math.min(Math.max(0, newStreakDayLength), XP_DAILY_STREAK_BONUS_CAP);
110
+
111
+ export const getTestXp = (knownCount: number): number =>
112
+ XP_TEST + knownCount * XP_PER_TEST_KNOWN_ANSWER;
113
+
114
+ // highStreakLength can lag a still-running current streak (the leaderboard has the same caveat), so take the larger.
115
+ export const getBestStreak = (user: { highStreakLength: number, currentStreakLength: number }): number =>
116
+ Math.max(user.highStreakLength ?? 0, user.currentStreakLength ?? 0);
117
+
118
+ export const getUserLevelProgress = (user: { xp: number, highStreakLength: number, currentStreakLength: number }): ILevelProgress =>
119
+ getLevelProgress(user.xp ?? 0, getBestStreak(user));
package/src/design/api.ts CHANGED
@@ -35,6 +35,7 @@ export enum ApiPath {
35
35
  DATA_HEATMAP = '/data/heatmap/:weekCount/:endDate',
36
36
  HEALTH = '/health',
37
37
  LAST_WORDS_ADDED = '/lastWordsAdded',
38
+ LEADERBOARD = '/leaderboard',
38
39
  LEXEMES = '/lexemes',
39
40
  LEXEMES_ALL = '/lexemes/all',
40
41
  LEXEMES_COUNT = '/lexemes/count/:language',
@@ -217,7 +218,10 @@ export interface TestInitResponseData {
217
218
  export interface TestCompleteResponseData {
218
219
  user: IUserData;
219
220
  testResultIds: number[];
221
+ // Reward points earned by this completion - shown to the user on the results page.
220
222
  rewardPointsDelta: number;
223
+ // XP earned by this completion - internal, never shown; only used to detect a level-up. See concrete/level.ts.
224
+ xpDelta: number;
221
225
  vocabCheckActivity: IVocabCheckActivity[];
222
226
  }
223
227
  export interface HeatMapResponseData {
@@ -84,6 +84,19 @@ export interface IProgressHistoryDay {
84
84
  retiredCount: number;
85
85
  }
86
86
 
87
+ /**
88
+ * One row of the reward points leaderboard. position is the user's 1-based rank across all users, ordered by
89
+ * rewardPoints, then highStreakLength, then sign-up order. name is the first name plus surname initial, never the
90
+ * full name.
91
+ */
92
+ export interface ILeaderboardEntry {
93
+ position: number;
94
+ name: string;
95
+ rewardPoints: number;
96
+ highStreakLength: number;
97
+ isCurrentUser: boolean;
98
+ }
99
+
87
100
  export type MySQLDate = `${number}-${number}-${number} ${number}:${number}:${number}`;
88
101
 
89
102
  export type DateString = `${number}-${string}-${string}`;
@@ -12,10 +12,14 @@ export interface IUserData {
12
12
  learningLanguage: Language,
13
13
  name: string,
14
14
  phone: string,
15
+ // Shown to the user and ranked on the leaderboard - performance-based. Not the same as xp (see below).
15
16
  rewardPoints: number,
16
17
  signUpDate: MySQLDate,
17
18
  testsCompletedCount: number,
18
19
  uiLanguage: Language,
19
20
  completedOnboarding: boolean,
20
- learningSet: number
21
+ learningSet: number,
22
+ // Experience points: internal, never shown to the user - they only decide the experience level. Not the same as
23
+ // rewardPoints (shown, performance-based, leaderboard). See concrete/level.ts.
24
+ xp: number
21
25
  }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './concrete/date';
2
+ export * from './concrete/level';
2
3
  export * from './concrete/lexeme';
3
4
  export * from './concrete/string';
4
5
  export * from './concrete/vocabCheck';
@@ -0,0 +1,89 @@
1
+ import { expect } from 'chai';
2
+ import {
3
+ getBestStreak,
4
+ getFlashcardReviewXp,
5
+ getLevel,
6
+ getLevelProgress,
7
+ getTestXp,
8
+ LEVELS,
9
+ maxLevel,
10
+ } from '../src/concrete/level';
11
+
12
+ describe('levels', () => {
13
+ it('are numbered 1..n with rising thresholds and non-falling streak gates', () => {
14
+ LEVELS.forEach((level, i) => {
15
+ expect(level.level).to.equal(i + 1);
16
+ if (i > 0) {
17
+ expect(level.xpThreshold).to.be.above(LEVELS[i - 1].xpThreshold);
18
+ expect(level.minBestStreak).to.be.at.least(LEVELS[i - 1].minBestStreak);
19
+ }
20
+ });
21
+ expect(LEVELS[0].xpThreshold).to.equal(0);
22
+ });
23
+ });
24
+
25
+ describe('getLevel', () => {
26
+ it('starts everyone at level 1', () => {
27
+ expect(getLevel(0, 0)).to.equal(1);
28
+ });
29
+ it('changes exactly at the XP threshold', () => {
30
+ expect(getLevel(59, 0)).to.equal(1);
31
+ expect(getLevel(60, 0)).to.equal(2);
32
+ expect(getLevel(449, 0)).to.equal(3);
33
+ expect(getLevel(450, 0)).to.equal(4);
34
+ });
35
+ it('holds the user at the last level whose streak gate is met', () => {
36
+ expect(getLevel(5000, 6)).to.equal(4);
37
+ expect(getLevel(5000, 7)).to.equal(5);
38
+ expect(getLevel(5000, 30)).to.equal(8);
39
+ });
40
+ it('caps at the top level', () => {
41
+ expect(getLevel(1_000_000, 1000)).to.equal(maxLevel);
42
+ });
43
+ it('never goes down as XP and best streak grow', () => {
44
+ let previous = 1;
45
+ for (let xp = 0; xp <= 12000; xp += 50) {
46
+ const level = getLevel(xp, Math.floor(xp / 150));
47
+ expect(level).to.be.at.least(previous);
48
+ previous = level;
49
+ }
50
+ });
51
+ });
52
+
53
+ describe('getLevelProgress', () => {
54
+ it('reports XP still needed and progress through the level', () => {
55
+ expect(getLevelProgress(130, 0)).to.deep.equal({
56
+ level: 2, nextLevel: 3, xpToNextLevel: 70, xpProgress: 0.5, streakDaysToNextLevel: 0,
57
+ });
58
+ });
59
+ it('reports a missing streak once the XP is there', () => {
60
+ const progress = getLevelProgress(1000, 3);
61
+ expect(progress.level).to.equal(4);
62
+ expect(progress.xpToNextLevel).to.equal(0);
63
+ expect(progress.xpProgress).to.equal(1);
64
+ expect(progress.streakDaysToNextLevel).to.equal(4);
65
+ });
66
+ it('has no next level at the top', () => {
67
+ const progress = getLevelProgress(20000, 100);
68
+ expect(progress.level).to.equal(maxLevel);
69
+ expect(progress.nextLevel).to.equal(undefined);
70
+ expect(progress.xpProgress).to.equal(1);
71
+ });
72
+ });
73
+
74
+ describe('XP awards', () => {
75
+ it('flashcard review: base, mastered words and a capped streak-day bonus', () => {
76
+ expect(getFlashcardReviewXp(0, 0)).to.equal(10);
77
+ expect(getFlashcardReviewXp(2, 0)).to.equal(20);
78
+ expect(getFlashcardReviewXp(0, 5)).to.equal(15);
79
+ expect(getFlashcardReviewXp(0, 90)).to.equal(40);
80
+ });
81
+ it('test: base plus one per known answer', () => {
82
+ expect(getTestXp(0)).to.equal(15);
83
+ expect(getTestXp(12)).to.equal(27);
84
+ });
85
+ it('best streak takes the larger of high and current', () => {
86
+ expect(getBestStreak({ highStreakLength: 3, currentStreakLength: 5 })).to.equal(5);
87
+ expect(getBestStreak({ highStreakLength: 9, currentStreakLength: 2 })).to.equal(9);
88
+ });
89
+ });