@umituz/react-native-subscription 2.27.93 → 2.27.95

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umituz/react-native-subscription",
3
- "version": "2.27.93",
3
+ "version": "2.27.95",
4
4
  "description": "Complete subscription management with RevenueCat, paywall UI, and credits system for React Native apps",
5
5
  "main": "./src/index.ts",
6
6
  "types": "./src/index.ts",
@@ -28,10 +28,6 @@ export async function initializeCreditsTransaction(
28
28
  throw new Error("Firestore instance is not available");
29
29
  }
30
30
 
31
- if (!metadata.productId) {
32
- throw new Error("productId is required in metadata");
33
- }
34
-
35
31
  return runTransaction(db, async (transaction: Transaction) => {
36
32
  const creditsDoc = await transaction.get(creditsRef);
37
33
  const now = serverTimestamp();
@@ -44,7 +40,11 @@ export async function initializeCreditsTransaction(
44
40
  }
45
41
 
46
42
  if (existingData.processedPurchases.includes(purchaseId)) {
47
- return { credits: existingData.credits, alreadyProcessed: true };
43
+ return {
44
+ credits: existingData.credits,
45
+ alreadyProcessed: true,
46
+ finalData: existingData
47
+ };
48
48
  }
49
49
 
50
50
  const creditLimit = CreditLimitCalculator.calculate(metadata.productId, config);
@@ -69,15 +69,17 @@ export async function initializeCreditsTransaction(
69
69
  }, existingData);
70
70
 
71
71
  const isPremium = metadata.isPremium;
72
- const isExpired = metadata.expirationDate
73
- ? new Date(metadata.expirationDate).getTime() < Date.now()
74
- : false;
72
+
73
+ let isExpired = false;
74
+ if (metadata.expirationDate) {
75
+ isExpired = new Date(metadata.expirationDate).getTime() < Date.now();
76
+ }
75
77
 
76
78
  const status = resolveSubscriptionStatus({
77
79
  isPremium,
78
- willRenew: metadata.willRenew,
80
+ willRenew: metadata.willRenew ?? false,
79
81
  isExpired,
80
- periodType: metadata.periodType,
82
+ periodType: metadata.periodType ?? undefined,
81
83
  });
82
84
 
83
85
  const isStatusSync = purchaseId.startsWith("status_sync_");
@@ -136,6 +138,10 @@ export async function initializeCreditsTransaction(
136
138
  ...creditsData,
137
139
  };
138
140
 
139
- return { credits: newCredits, finalData };
141
+ return {
142
+ credits: newCredits,
143
+ alreadyProcessed: false,
144
+ finalData
145
+ };
140
146
  });
141
147
  }
@@ -16,37 +16,55 @@ export class DeductCreditsCommand implements IDeductCreditsCommand {
16
16
  private getCreditsRef: (db: Firestore, userId: string) => DocumentReference
17
17
  ) {}
18
18
 
19
- async execute(userId: string, cost: number = 1): Promise<DeductCreditsResult> {
19
+ async execute(userId: string, cost: number): Promise<DeductCreditsResult> {
20
20
  const db = getFirestore();
21
- if (!db) return { success: false, error: { message: "No DB", code: "ERR" } };
21
+ if (!db) {
22
+ return {
23
+ success: false,
24
+ remainingCredits: null,
25
+ error: { message: "No DB", code: "ERR" }
26
+ };
27
+ }
22
28
 
23
29
  try {
24
30
  const remaining = await runTransaction(db, async (tx: Transaction) => {
25
31
  const ref = this.getCreditsRef(db, userId);
26
32
  const docSnap = await tx.get(ref);
27
-
28
- if (!docSnap.exists()) throw new Error("NO_CREDITS");
29
-
33
+
34
+ if (!docSnap.exists()) {
35
+ throw new Error("NO_CREDITS");
36
+ }
37
+
30
38
  const current = docSnap.data().credits as number;
31
- if (current < cost) throw new Error("CREDITS_EXHAUSTED");
32
-
39
+ if (current < cost) {
40
+ throw new Error("CREDITS_EXHAUSTED");
41
+ }
42
+
33
43
  const updated = current - cost;
34
- tx.update(ref, {
35
- credits: updated,
36
- lastUpdatedAt: serverTimestamp()
44
+ tx.update(ref, {
45
+ credits: updated,
46
+ lastUpdatedAt: serverTimestamp()
37
47
  });
38
-
48
+
39
49
  return updated;
40
50
  });
41
51
 
42
52
  // Emit event via EventBus (Observer Pattern)
43
53
  subscriptionEventBus.emit(SUBSCRIPTION_EVENTS.CREDITS_UPDATED, userId);
44
54
 
45
- return { success: true, remainingCredits: remaining };
55
+ return {
56
+ success: true,
57
+ remainingCredits: remaining,
58
+ error: null
59
+ };
46
60
  } catch (e: unknown) {
47
61
  const message = e instanceof Error ? e.message : String(e);
48
62
  const code = message === "NO_CREDITS" || message === "CREDITS_EXHAUSTED" ? message : "DEDUCT_ERR";
49
- return { success: false, error: { message, code } };
63
+ return {
64
+ success: false,
65
+ remainingCredits: null,
66
+ error: { message, code }
67
+ };
50
68
  }
51
69
  }
52
70
  }
@@ -1,6 +1,6 @@
1
1
  import { Timestamp } from "firebase/firestore";
2
- import type {
3
- PurchaseType,
2
+ import type {
3
+ PurchaseType,
4
4
  PurchaseMetadata,
5
5
  UserCreditsDocumentRead,
6
6
  PurchaseSource
@@ -8,37 +8,31 @@ import type {
8
8
  import { detectPackageType } from "../../../utils/packageTypeDetector";
9
9
 
10
10
  export interface MetadataGeneratorConfig {
11
- productId?: string;
12
- source?: PurchaseSource;
13
- type?: PurchaseType;
11
+ productId: string;
12
+ source: PurchaseSource;
13
+ type: PurchaseType;
14
14
  creditLimit: number;
15
15
  platform: "ios" | "android";
16
- appVersion?: string;
16
+ appVersion: string;
17
17
  }
18
18
 
19
19
  export class PurchaseMetadataGenerator {
20
20
  static generate(
21
21
  config: MetadataGeneratorConfig,
22
- existingData: UserCreditsDocumentRead | null
22
+ existingData: UserCreditsDocumentRead
23
23
  ): { purchaseType: PurchaseType; purchaseHistory: PurchaseMetadata[] } {
24
24
  const { productId, source, type, creditLimit, platform, appVersion } = config;
25
-
26
- if (!productId || !source) {
27
- return {
28
- purchaseType: type ?? "initial",
29
- purchaseHistory: existingData?.purchaseHistory || []
30
- };
31
- }
32
25
 
33
26
  const packageType = detectPackageType(productId);
34
- let purchaseType: PurchaseType = type ?? "initial";
27
+ let purchaseType: PurchaseType = type;
35
28
 
36
- if (existingData?.packageType && packageType !== "unknown") {
37
- const oldLimit = existingData.creditLimit || 0;
38
- if (creditLimit > oldLimit) purchaseType = "upgrade";
39
- else if (creditLimit < oldLimit) purchaseType = "downgrade";
40
- // This check is a bit fragile if purchaseId is not passed here,
41
- // but we use the explicit 'type' if provided.
29
+ if (packageType !== "unknown") {
30
+ const oldLimit = existingData.creditLimit;
31
+ if (creditLimit > oldLimit) {
32
+ purchaseType = "upgrade";
33
+ } else if (creditLimit < oldLimit) {
34
+ purchaseType = "downgrade";
35
+ }
42
36
  }
43
37
 
44
38
  const newMetadata: PurchaseMetadata = {
@@ -49,10 +43,10 @@ export class PurchaseMetadataGenerator {
49
43
  type: purchaseType,
50
44
  platform,
51
45
  appVersion,
52
- timestamp: Timestamp.fromDate(new Date()) as any,
46
+ timestamp: Timestamp.fromDate(new Date()),
53
47
  };
54
48
 
55
- const purchaseHistory = [...(existingData?.purchaseHistory || []), newMetadata].slice(-10);
49
+ const purchaseHistory = [...existingData.purchaseHistory, newMetadata].slice(-10);
56
50
 
57
51
  return { purchaseType, purchaseHistory };
58
52
  }
@@ -6,22 +6,22 @@
6
6
  */
7
7
 
8
8
  import type { SubscriptionPackageType } from "../../../utils/packageTypeDetector";
9
- import type {
10
- SubscriptionStatusType,
11
- PeriodType,
12
- PackageType,
13
- Platform,
14
- PurchaseSource,
15
- PurchaseType
9
+ import type {
10
+ SubscriptionStatusType,
11
+ PeriodType,
12
+ PackageType,
13
+ Platform,
14
+ PurchaseSource,
15
+ PurchaseType
16
16
  } from "../../subscription/core/SubscriptionConstants";
17
17
 
18
- export type {
19
- SubscriptionStatusType,
20
- PeriodType,
21
- PackageType,
22
- Platform,
23
- PurchaseSource,
24
- PurchaseType
18
+ export type {
19
+ SubscriptionStatusType,
20
+ PeriodType,
21
+ PackageType,
22
+ Platform,
23
+ PurchaseSource,
24
+ PurchaseType
25
25
  };
26
26
 
27
27
  export type CreditType = "text" | "image";
@@ -36,30 +36,31 @@ export interface UserCredits {
36
36
  purchasedAt: Date | null;
37
37
  expirationDate: Date | null;
38
38
  lastUpdatedAt: Date | null;
39
+ lastPurchaseAt: Date | null;
39
40
 
40
41
  // RevenueCat subscription details
41
- willRenew: boolean;
42
- productId?: string;
43
- packageType?: PackageType;
44
- originalTransactionId?: string;
42
+ willRenew: boolean | null;
43
+ productId: string | null;
44
+ packageType: PackageType | null;
45
+ originalTransactionId: string | null;
45
46
 
46
47
  // Trial fields
47
- periodType?: PeriodType;
48
- isTrialing?: boolean;
49
- trialStartDate?: Date | null;
50
- trialEndDate?: Date | null;
51
- trialCredits?: number;
52
- convertedFromTrial?: boolean;
48
+ periodType: PeriodType | null;
49
+ isTrialing: boolean | null;
50
+ trialStartDate: Date | null;
51
+ trialEndDate: Date | null;
52
+ trialCredits: number | null;
53
+ convertedFromTrial: boolean | null;
53
54
 
54
55
  // Credits
55
56
  credits: number;
56
- creditLimit?: number;
57
+ creditLimit: number;
57
58
 
58
59
  // Metadata
59
- purchaseSource?: PurchaseSource;
60
- purchaseType?: PurchaseType;
61
- platform?: Platform;
62
- appVersion?: string;
60
+ purchaseSource: PurchaseSource | null;
61
+ purchaseType: PurchaseType | null;
62
+ platform: Platform;
63
+ appVersion: string | null;
63
64
  }
64
65
 
65
66
  export interface CreditAllocation {
@@ -75,28 +76,27 @@ export interface CreditsConfig {
75
76
  collectionName: string;
76
77
  creditLimit: number;
77
78
  /** When true, stores credits at users/{userId}/credits instead of {collectionName}/{userId} */
78
- useUserSubcollection?: boolean;
79
+ useUserSubcollection: boolean;
79
80
  /** Credit amounts per product ID for consumable credit packages */
80
- creditPackageAmounts?: Record<string, number>;
81
+ creditPackageAmounts: Record<string, number>;
81
82
  /** Credit allocations for different subscription types (weekly, monthly, yearly) */
82
- packageAllocations?: PackageAllocationMap;
83
+ packageAllocations: PackageAllocationMap;
83
84
  }
84
85
 
85
86
  export interface CreditsResult<T = UserCredits> {
86
87
  success: boolean;
87
- data?: T;
88
- error?: {
88
+ data: T | null;
89
+ error: {
89
90
  message: string;
90
91
  code: string;
91
- };
92
+ } | null;
92
93
  }
93
94
 
94
95
  export interface DeductCreditsResult {
95
96
  success: boolean;
96
- remainingCredits?: number;
97
- error?: {
97
+ remainingCredits: number | null;
98
+ error: {
98
99
  message: string;
99
100
  code: string;
100
- };
101
+ } | null;
101
102
  }
102
-
@@ -6,8 +6,8 @@ import type { UserCreditsDocumentRead } from "./UserCreditsDocument";
6
6
  /** Maps Firestore document to domain entity with expiration validation */
7
7
  export class CreditsMapper {
8
8
  static toEntity(doc: UserCreditsDocumentRead): UserCredits {
9
- const expirationDate = doc.expirationDate?.toDate?.() ?? null;
10
- const periodType = doc.periodType as PeriodType | undefined;
9
+ const expirationDate = doc.expirationDate ? doc.expirationDate.toDate() : null;
10
+ const periodType = doc.periodType;
11
11
 
12
12
  // Validate isPremium against expirationDate (real-time check)
13
13
  const { isPremium, status } = CreditsMapper.validateSubscription(doc, expirationDate, periodType);
@@ -18,12 +18,13 @@ export class CreditsMapper {
18
18
  status,
19
19
 
20
20
  // Dates
21
- purchasedAt: doc.purchasedAt?.toDate?.() ?? null,
21
+ purchasedAt: doc.purchasedAt.toDate(),
22
22
  expirationDate,
23
- lastUpdatedAt: doc.lastUpdatedAt?.toDate?.() ?? null,
23
+ lastUpdatedAt: doc.lastUpdatedAt.toDate(),
24
+ lastPurchaseAt: doc.lastPurchaseAt ? doc.lastPurchaseAt.toDate() : null,
24
25
 
25
26
  // RevenueCat details
26
- willRenew: doc.willRenew ?? false,
27
+ willRenew: doc.willRenew,
27
28
  productId: doc.productId,
28
29
  packageType: doc.packageType,
29
30
  originalTransactionId: doc.originalTransactionId,
@@ -31,8 +32,8 @@ export class CreditsMapper {
31
32
  // Trial fields
32
33
  periodType,
33
34
  isTrialing: doc.isTrialing,
34
- trialStartDate: doc.trialStartDate?.toDate?.() ?? null,
35
- trialEndDate: doc.trialEndDate?.toDate?.() ?? null,
35
+ trialStartDate: doc.trialStartDate ? doc.trialStartDate.toDate() : null,
36
+ trialEndDate: doc.trialEndDate ? doc.trialEndDate.toDate() : null,
36
37
  trialCredits: doc.trialCredits,
37
38
  convertedFromTrial: doc.convertedFromTrial,
38
39
 
@@ -52,9 +53,9 @@ export class CreditsMapper {
52
53
  private static validateSubscription(
53
54
  doc: UserCreditsDocumentRead,
54
55
  expirationDate: Date | null,
55
- periodType?: PeriodType
56
+ periodType: PeriodType | null
56
57
  ): { isPremium: boolean; status: SubscriptionStatusType } {
57
- const isPremium = doc.isPremium ?? false;
58
+ const isPremium = doc.isPremium;
58
59
  const willRenew = doc.willRenew ?? false;
59
60
  const isExpired = expirationDate ? expirationDate < new Date() : false;
60
61
 
@@ -62,7 +63,7 @@ export class CreditsMapper {
62
63
  isPremium,
63
64
  willRenew,
64
65
  isExpired,
65
- periodType,
66
+ periodType: periodType ?? undefined,
66
67
  });
67
68
 
68
69
  // Override isPremium if expired
@@ -3,7 +3,7 @@
3
3
  * Optimized to use Design Patterns: Command, Observer, and Strategy.
4
4
  */
5
5
 
6
- import { doc, getDoc, serverTimestamp, updateDoc, type Firestore } from "firebase/firestore";
6
+ import { doc, getDoc, type Firestore } from "firebase/firestore";
7
7
  import { BaseRepository, getFirestore } from "@umituz/react-native-firebase";
8
8
  import type { CreditsConfig, CreditsResult, DeductCreditsResult } from "../core/Credits";
9
9
  import type { UserCreditsDocumentRead, PurchaseSource } from "../core/UserCreditsDocument";
@@ -35,11 +35,11 @@ export class CreditsRepository extends BaseRepository {
35
35
 
36
36
  const snap = await getDoc(this.getRef(db, userId));
37
37
  if (!snap.exists()) {
38
- return { success: true, data: undefined };
38
+ return { success: true, data: null, error: null };
39
39
  }
40
40
 
41
41
  const entity = CreditsMapper.toEntity(snap.data() as UserCreditsDocumentRead);
42
- return { success: true, data: entity };
42
+ return { success: true, data: entity, error: null };
43
43
  }
44
44
 
45
45
  async initializeCredits(
@@ -75,7 +75,8 @@ export class CreditsRepository extends BaseRepository {
75
75
 
76
76
  return {
77
77
  success: true,
78
- data: result.finalData ? CreditsMapper.toEntity(result.finalData) : undefined,
78
+ data: result.finalData ? CreditsMapper.toEntity(result.finalData) : null,
79
+ error: null,
79
80
  };
80
81
  }
81
82
 
@@ -13,38 +13,38 @@ export interface FirebaseAuthLike {
13
13
  }
14
14
 
15
15
  export interface CreditPackageConfig {
16
- identifierPattern?: string;
17
- amounts?: Record<string, number>;
16
+ identifierPattern: string;
17
+ amounts: Record<string, number>;
18
18
  }
19
19
 
20
20
  export interface SubscriptionInitConfig {
21
- apiKey?: string;
22
- apiKeyIos?: string;
23
- apiKeyAndroid?: string;
21
+ apiKey: string;
22
+ apiKeyIos: string;
23
+ apiKeyAndroid: string;
24
24
  entitlementId: string;
25
25
  credits: CreditsConfig;
26
26
  getAnonymousUserId: () => Promise<string>;
27
27
  getFirebaseAuth: () => FirebaseAuthLike | null;
28
28
  showAuthModal: () => void;
29
- onCreditsUpdated?: (userId: string) => void;
30
- creditPackages?: CreditPackageConfig;
31
- timeoutMs?: number;
32
- authStateTimeoutMs?: number;
29
+ onCreditsUpdated: (userId: string) => void;
30
+ creditPackages: CreditPackageConfig;
31
+ timeoutMs: number;
32
+ authStateTimeoutMs: number;
33
33
  }
34
34
 
35
35
  export interface InitializeCreditsMetadata {
36
- productId?: string;
37
- source?: PurchaseSource;
38
- type?: PurchaseType;
39
- expirationDate?: string | null;
40
- willRenew?: boolean;
41
- originalTransactionId?: string;
42
- isPremium?: boolean;
43
- periodType?: PeriodType;
36
+ productId: string;
37
+ source: PurchaseSource;
38
+ type: PurchaseType;
39
+ expirationDate: string | null;
40
+ willRenew: boolean | null;
41
+ originalTransactionId: string | null;
42
+ isPremium: boolean;
43
+ periodType: PeriodType | null;
44
44
  }
45
45
 
46
46
  export interface InitializationResult {
47
- credits: number;
48
- alreadyProcessed?: boolean;
49
- finalData?: UserCreditsDocumentRead;
47
+ credits: number;
48
+ alreadyProcessed: boolean;
49
+ finalData: UserCreditsDocumentRead | null;
50
50
  }
@@ -5,10 +5,10 @@ import type { PeriodType } from "./SubscriptionStatus";
5
5
  * Used across the subscription package for storing RevenueCat data in Firestore
6
6
  */
7
7
  export interface RevenueCatData {
8
- expirationDate?: string | null;
9
- willRenew?: boolean;
10
- originalTransactionId?: string;
11
- isPremium?: boolean;
8
+ expirationDate: string | null;
9
+ willRenew: boolean | null;
10
+ originalTransactionId: string | null;
11
+ isPremium: boolean;
12
12
  /** RevenueCat period type: NORMAL, INTRO, or TRIAL */
13
- periodType?: PeriodType;
13
+ periodType: PeriodType | null;
14
14
  }