ai-lls-lib 2.0.0rc2__py3-none-any.whl

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.
@@ -0,0 +1,102 @@
1
+ """Payment data models with legacy shape compatibility."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Optional, Dict, Any
5
+ from enum import Enum
6
+
7
+
8
+ class PlanType(Enum):
9
+ """Plan types matching legacy frontend expectations."""
10
+ PREPAID = "prepaid"
11
+ POSTPAID = "postpaid"
12
+ INTRO = "intro"
13
+
14
+
15
+ class SubscriptionStatus(Enum):
16
+ """Subscription statuses."""
17
+ ACTIVE = "active"
18
+ PAUSED = "paused"
19
+ CANCELLED = "cancelled"
20
+ PAST_DUE = "past_due"
21
+
22
+
23
+ @dataclass
24
+ class Plan:
25
+ """
26
+ Plan model matching legacy frontend data structure.
27
+ Maps from Stripe Price/Product to legacy fields.
28
+ """
29
+ plan_reference: str # Stripe price ID or legacy reference
30
+ plan_type: str # prepaid, postpaid, intro
31
+ plan_name: str # STANDARD, POWER, ELITE, UNLIMITED
32
+ plan_subtitle: str
33
+ plan_amount: float # Price in USD
34
+ plan_credits: Optional[int] # Number of credits or None for unlimited
35
+ plan_credits_text: str # Display text like "5,000 credits"
36
+ percent_off: str # Discount percentage display text
37
+
38
+ # Additional fields for internal use
39
+ stripe_price_id: Optional[str] = None
40
+ stripe_product_id: Optional[str] = None
41
+
42
+ def to_dict(self) -> Dict[str, Any]:
43
+ """Convert to dictionary for JSON serialization."""
44
+ result = {
45
+ "plan_reference": self.plan_reference,
46
+ "plan_type": self.plan_type,
47
+ "plan_name": self.plan_name,
48
+ "plan_subtitle": self.plan_subtitle,
49
+ "plan_amount": self.plan_amount,
50
+ "plan_credits": self.plan_credits,
51
+ "plan_credits_text": self.plan_credits_text,
52
+ "percent_off": self.percent_off
53
+ }
54
+
55
+ # Add variable_amount flag for VARIABLE product
56
+ if self.plan_name == "VARIABLE":
57
+ result["variable_amount"] = True
58
+
59
+ return result
60
+
61
+ @classmethod
62
+ def from_stripe_price(cls, price: Dict[str, Any], product: Dict[str, Any]) -> "Plan":
63
+ """
64
+ Create Plan from Stripe Price and Product objects.
65
+ Maps Stripe metadata to legacy fields.
66
+ """
67
+ metadata = price.get("metadata", {})
68
+
69
+ # Determine plan type
70
+ if price.get("recurring"):
71
+ plan_type = "postpaid"
72
+ else:
73
+ plan_type = metadata.get("plan_type", "prepaid")
74
+
75
+ # Extract credits
76
+ credits_str = metadata.get("credits", "")
77
+ if credits_str.lower() == "unlimited":
78
+ plan_credits = None
79
+ plan_credits_text = "Unlimited"
80
+ elif credits_str:
81
+ try:
82
+ plan_credits = int(credits_str)
83
+ plan_credits_text = f"{plan_credits:,} credits"
84
+ except ValueError:
85
+ plan_credits = None
86
+ plan_credits_text = credits_str
87
+ else:
88
+ plan_credits = None
89
+ plan_credits_text = ""
90
+
91
+ return cls(
92
+ plan_reference=metadata.get("plan_reference", price["id"]),
93
+ plan_type=plan_type,
94
+ plan_name=metadata.get("tier", product.get("name", "")).upper(),
95
+ plan_subtitle=metadata.get("plan_subtitle", product.get("description", "")),
96
+ plan_amount=price["unit_amount"] / 100.0, # Convert cents to dollars
97
+ plan_credits=plan_credits,
98
+ plan_credits_text=metadata.get("plan_credits_text", plan_credits_text),
99
+ percent_off=metadata.get("percent_off", ""),
100
+ stripe_price_id=price["id"],
101
+ stripe_product_id=product["id"]
102
+ )
@@ -0,0 +1,486 @@
1
+ """Stripe API management with metadata conventions."""
2
+
3
+ import os
4
+ from typing import List, Optional, Dict, Any
5
+ import logging
6
+
7
+ try:
8
+ import stripe
9
+ except ImportError:
10
+ stripe = None # Handle gracefully for testing
11
+
12
+ from .models import Plan
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class StripeManager:
18
+ """
19
+ Manages Stripe resources with metadata conventions.
20
+ Uses metadata to discover and filter products/prices.
21
+ """
22
+
23
+ METADATA_SCHEMA = {
24
+ "product_type": "landline_scrubber",
25
+ "environment": None, # Set at runtime
26
+ "tier": None,
27
+ "credits": None,
28
+ "active": "true"
29
+ }
30
+
31
+ def __init__(self, api_key: Optional[str] = None, environment: Optional[str] = None):
32
+ """Initialize with Stripe API key and environment."""
33
+ if not stripe:
34
+ raise ImportError("stripe package not installed. Run: pip install stripe")
35
+
36
+ self.api_key = api_key or os.environ.get("STRIPE_SECRET_KEY")
37
+ if not self.api_key:
38
+ raise ValueError("Stripe API key not provided and STRIPE_SECRET_KEY not set")
39
+
40
+ stripe.api_key = self.api_key
41
+ self.environment = environment or os.environ.get("ENVIRONMENT", "staging")
42
+
43
+ def list_plans(self) -> List[Plan]:
44
+ """
45
+ Fetch active plans from Stripe using metadata.
46
+ Returns list of Plan objects sorted by price.
47
+ """
48
+ try:
49
+ # Fetch all active prices with expanded product data
50
+ prices = stripe.Price.list(
51
+ active=True,
52
+ expand=["data.product"],
53
+ limit=100
54
+ )
55
+
56
+ plans = []
57
+ for price in prices.data:
58
+ metadata = price.metadata or {}
59
+
60
+ # Filter by our metadata conventions
61
+ if (metadata.get("product_type") == "landline_scrubber" and
62
+ metadata.get("active") == "true"):
63
+
64
+ # Convert to Plan object
65
+ plan = Plan.from_stripe_price(price, price.product)
66
+ plans.append(plan)
67
+
68
+ # Sort by price amount
69
+ plans.sort(key=lambda p: p.plan_amount)
70
+
71
+ logger.info(f"Found {len(plans)} active plans for environment {self.environment}")
72
+ return plans
73
+
74
+ except stripe.error.StripeError as e:
75
+ logger.error(f"Stripe error listing plans: {e}")
76
+ # Let error propagate - no fallback to mock data
77
+ raise
78
+
79
+ def create_setup_intent(self, user_id: str) -> Dict[str, str]:
80
+ """
81
+ Create a SetupIntent for secure payment method collection.
82
+ Frontend will confirm this with Stripe Elements.
83
+ """
84
+ try:
85
+ # Get or create customer
86
+ customer = self._get_or_create_customer(user_id)
87
+
88
+ # Create SetupIntent
89
+ setup_intent = stripe.SetupIntent.create(
90
+ customer=customer.id,
91
+ metadata={
92
+ "user_id": user_id,
93
+ "environment": self.environment
94
+ }
95
+ )
96
+
97
+ return {
98
+ "client_secret": setup_intent.client_secret,
99
+ "setup_intent_id": setup_intent.id,
100
+ "customer_id": customer.id
101
+ }
102
+
103
+ except stripe.error.StripeError as e:
104
+ logger.error(f"Stripe error creating setup intent: {e}")
105
+ raise
106
+
107
+ def attach_payment_method(self, user_id: str, payment_method_id: str, billing_details: Dict[str, Any]) -> Dict[str, Any]:
108
+ """
109
+ Attach a payment method to customer (legacy path).
110
+ Returns whether this is the first card.
111
+ """
112
+ try:
113
+ # Get or create customer
114
+ customer = self._get_or_create_customer(user_id)
115
+
116
+ # Attach payment method to customer
117
+ payment_method = stripe.PaymentMethod.attach(
118
+ payment_method_id,
119
+ customer=customer.id
120
+ )
121
+
122
+ # Update billing details if provided
123
+ if billing_details:
124
+ stripe.PaymentMethod.modify(
125
+ payment_method_id,
126
+ billing_details=billing_details
127
+ )
128
+
129
+ # Check if this is the first payment method
130
+ payment_methods = stripe.PaymentMethod.list(
131
+ customer=customer.id,
132
+ type="card"
133
+ )
134
+
135
+ first_card = len(payment_methods.data) == 1
136
+
137
+ # Set as default if first card
138
+ if first_card:
139
+ stripe.Customer.modify(
140
+ customer.id,
141
+ invoice_settings={"default_payment_method": payment_method_id}
142
+ )
143
+
144
+ return {
145
+ "payment_method_id": payment_method_id,
146
+ "first_card": first_card,
147
+ "customer_id": customer.id
148
+ }
149
+
150
+ except stripe.error.StripeError as e:
151
+ logger.error(f"Stripe error attaching payment method: {e}")
152
+ raise
153
+
154
+ def verify_payment_method(self, user_id: str, payment_method_id: str) -> Dict[str, Any]:
155
+ """
156
+ Perform $1 verification charge on new payment method.
157
+ """
158
+ try:
159
+ customer = self._get_or_create_customer(user_id)
160
+
161
+ # Create $1 verification charge
162
+ payment_intent = stripe.PaymentIntent.create(
163
+ amount=100, # $1.00 in cents
164
+ currency="usd",
165
+ customer=customer.id,
166
+ payment_method=payment_method_id,
167
+ off_session=True,
168
+ confirm=True,
169
+ description="Card verification - $1 charge",
170
+ metadata={
171
+ "user_id": user_id,
172
+ "type": "verification",
173
+ "environment": self.environment
174
+ }
175
+ )
176
+
177
+ return {
178
+ "status": payment_intent.status,
179
+ "payment_intent_id": payment_intent.id
180
+ }
181
+
182
+ except stripe.error.StripeError as e:
183
+ logger.error(f"Stripe error verifying payment method: {e}")
184
+ raise
185
+
186
+ def charge_prepaid(self, user_id: str, reference_code: str, amount: Optional[float] = None) -> Dict[str, Any]:
187
+ """
188
+ Charge saved payment method for credit purchase.
189
+ Supports both fixed-price and metadata-based variable-amount plans.
190
+ """
191
+ try:
192
+ customer = self._get_or_create_customer(user_id)
193
+
194
+ # Look up price from Stripe
195
+ prices = stripe.Price.list(active=True, limit=100, expand=["data.product"])
196
+ price = None
197
+
198
+ for p in prices.data:
199
+ metadata = p.metadata or {}
200
+ # Match by price ID or plan_reference in metadata
201
+ if (p.id == reference_code or
202
+ metadata.get("plan_reference") == reference_code or
203
+ (metadata.get("tier") == reference_code and
204
+ metadata.get("environment") == self.environment)):
205
+ price = p
206
+ break
207
+
208
+ if not price:
209
+ raise ValueError(f"Invalid plan reference: {reference_code}")
210
+
211
+ price_metadata = price.metadata or {}
212
+
213
+ # Check if this is a variable amount plan
214
+ if price_metadata.get("variable_amount") == "true":
215
+ # Variable amount plan - validate amount
216
+ if not amount:
217
+ raise ValueError("Amount required for variable-amount plan")
218
+
219
+ # Get validation rules from metadata
220
+ min_amount = float(price_metadata.get("min_amount", "5"))
221
+ if amount < min_amount:
222
+ raise ValueError(f"Amount ${amount} is below minimum ${min_amount}")
223
+
224
+ # Check against default amounts if specified
225
+ default_amounts_str = price_metadata.get("default_amounts", "")
226
+ if default_amounts_str:
227
+ allowed_amounts = [float(x.strip()) for x in default_amounts_str.split(",")]
228
+ # Allow default amounts OR any amount >= minimum
229
+ if amount not in allowed_amounts and amount < max(allowed_amounts):
230
+ logger.info(f"Amount ${amount} not in defaults {allowed_amounts}, but allowed as >= ${min_amount}")
231
+
232
+ # Calculate credits based on credits_per_dollar
233
+ credits_per_dollar = float(price_metadata.get("credits_per_dollar", "285"))
234
+ credits_to_add = int(amount * credits_per_dollar)
235
+ charge_amount = int(amount * 100) # Convert to cents
236
+
237
+ else:
238
+ # Fixed price plan
239
+ charge_amount = price.unit_amount
240
+ credits_str = price_metadata.get("credits", "0")
241
+ if credits_str.lower() == "unlimited":
242
+ credits_to_add = 0 # Subscription handles this differently
243
+ else:
244
+ credits_to_add = int(credits_str)
245
+
246
+ # Get default payment method
247
+ default_pm = customer.invoice_settings.get("default_payment_method")
248
+ if not default_pm:
249
+ # Try to get first payment method
250
+ payment_methods = stripe.PaymentMethod.list(
251
+ customer=customer.id,
252
+ type="card",
253
+ limit=1
254
+ )
255
+ if not payment_methods.data:
256
+ raise ValueError("No payment method on file")
257
+ default_pm = payment_methods.data[0].id
258
+
259
+ # Create payment intent
260
+ payment_intent = stripe.PaymentIntent.create(
261
+ amount=charge_amount,
262
+ currency="usd",
263
+ customer=customer.id,
264
+ payment_method=default_pm,
265
+ off_session=True,
266
+ confirm=True,
267
+ description=f"Credit purchase - {credits_to_add} credits",
268
+ metadata={
269
+ "user_id": user_id,
270
+ "credits": credits_to_add,
271
+ "reference_code": reference_code,
272
+ "environment": self.environment
273
+ }
274
+ )
275
+
276
+ return {
277
+ "id": payment_intent.id,
278
+ "status": payment_intent.status,
279
+ "credits_added": credits_to_add,
280
+ "amount_charged": charge_amount / 100 # Convert back to dollars
281
+ }
282
+
283
+ except stripe.error.StripeError as e:
284
+ logger.error(f"Stripe error processing payment: {e}")
285
+ raise
286
+
287
+ def customer_has_payment_method(self, stripe_customer_id: str) -> bool:
288
+ """
289
+ Check if customer has any saved payment methods.
290
+ """
291
+ try:
292
+ payment_methods = stripe.PaymentMethod.list(
293
+ customer=stripe_customer_id,
294
+ type="card",
295
+ limit=1
296
+ )
297
+ return len(payment_methods.data) > 0
298
+ except stripe.error.StripeError as e:
299
+ logger.error(f"Stripe error checking payment methods: {e}")
300
+ return False
301
+
302
+ def list_payment_methods(self, stripe_customer_id: str) -> Dict[str, Any]:
303
+ """
304
+ List all payment methods for a customer.
305
+ """
306
+ try:
307
+ # Get customer to find default payment method
308
+ customer = stripe.Customer.retrieve(stripe_customer_id)
309
+ default_pm_id = customer.invoice_settings.get("default_payment_method")
310
+
311
+ # List all payment methods
312
+ payment_methods = stripe.PaymentMethod.list(
313
+ customer=stripe_customer_id,
314
+ type="card"
315
+ )
316
+
317
+ items = []
318
+ for pm in payment_methods.data:
319
+ items.append({
320
+ "id": pm.id,
321
+ "brand": pm.card.brand,
322
+ "last4": pm.card.last4,
323
+ "exp_month": pm.card.exp_month,
324
+ "exp_year": pm.card.exp_year,
325
+ "is_default": pm.id == default_pm_id
326
+ })
327
+
328
+ return {
329
+ "items": items,
330
+ "default_payment_method_id": default_pm_id
331
+ }
332
+
333
+ except stripe.error.StripeError as e:
334
+ logger.error(f"Stripe error listing payment methods: {e}")
335
+ return {"items": [], "default_payment_method_id": None}
336
+
337
+ def _get_or_create_customer(self, user_id: str, email: Optional[str] = None) -> Any:
338
+ """
339
+ Get existing Stripe customer or create new one.
340
+ First checks by user_id in metadata, then by email if provided.
341
+ """
342
+ try:
343
+ # First try to find by user_id in metadata
344
+ customers = stripe.Customer.search(
345
+ query=f'metadata["user_id"]:"{user_id}"',
346
+ limit=1
347
+ )
348
+
349
+ if customers.data:
350
+ return customers.data[0]
351
+
352
+ # If email provided, try to find by email
353
+ if email:
354
+ customers = stripe.Customer.list(email=email, limit=1)
355
+ if customers.data:
356
+ # Update metadata with user_id
357
+ customer = customers.data[0]
358
+ stripe.Customer.modify(
359
+ customer.id,
360
+ metadata={"user_id": user_id}
361
+ )
362
+ return customer
363
+
364
+ # Create new customer
365
+ return stripe.Customer.create(
366
+ email=email,
367
+ metadata={
368
+ "user_id": user_id,
369
+ "environment": self.environment
370
+ }
371
+ )
372
+
373
+ except stripe.error.StripeError as e:
374
+ logger.error(f"Stripe error getting/creating customer: {e}")
375
+ raise
376
+
377
+ def create_subscription(self, user_id: str, email: str, price_id: str) -> Dict[str, Any]:
378
+ """Create a subscription for unlimited access."""
379
+ try:
380
+ # Create or retrieve customer
381
+ customers = stripe.Customer.list(email=email, limit=1)
382
+ if customers.data:
383
+ customer = customers.data[0]
384
+ else:
385
+ customer = stripe.Customer.create(
386
+ email=email,
387
+ metadata={"user_id": user_id}
388
+ )
389
+
390
+ # Create subscription
391
+ subscription = stripe.Subscription.create(
392
+ customer=customer.id,
393
+ items=[{"price": price_id}],
394
+ metadata={
395
+ "user_id": user_id,
396
+ "environment": self.environment
397
+ }
398
+ )
399
+
400
+ return {
401
+ "subscription_id": subscription.id,
402
+ "status": subscription.status,
403
+ "customer_id": customer.id
404
+ }
405
+
406
+ except stripe.error.StripeError as e:
407
+ logger.error(f"Stripe error creating subscription: {e}")
408
+ raise
409
+
410
+ def pause_subscription(self, subscription_id: str) -> Dict[str, str]:
411
+ """Pause a subscription."""
412
+ try:
413
+ subscription = stripe.Subscription.modify(
414
+ subscription_id,
415
+ pause_collection={"behavior": "mark_uncollectible"}
416
+ )
417
+ return {"message": "Subscription paused", "status": "paused"}
418
+ except stripe.error.StripeError as e:
419
+ logger.error(f"Stripe error pausing subscription: {e}")
420
+ raise
421
+
422
+ def resume_subscription(self, subscription_id: str) -> Dict[str, str]:
423
+ """Resume a paused subscription."""
424
+ try:
425
+ subscription = stripe.Subscription.modify(
426
+ subscription_id,
427
+ pause_collection="" # Remove pause
428
+ )
429
+ return {"message": "Subscription resumed", "status": "active"}
430
+ except stripe.error.StripeError as e:
431
+ logger.error(f"Stripe error resuming subscription: {e}")
432
+ raise
433
+
434
+ def cancel_subscription(self, subscription_id: str) -> Dict[str, str]:
435
+ """Cancel a subscription."""
436
+ try:
437
+ subscription = stripe.Subscription.delete(subscription_id)
438
+ return {"message": "Subscription cancelled", "status": "cancelled"}
439
+ except stripe.error.StripeError as e:
440
+ logger.error(f"Stripe error cancelling subscription: {e}")
441
+ raise
442
+
443
+ def _get_mock_plans(self) -> List[Plan]:
444
+ """Return mock plans for development/testing."""
445
+ return [
446
+ Plan(
447
+ plan_reference="price_standard_mock",
448
+ plan_type="prepaid",
449
+ plan_name="STANDARD",
450
+ plan_subtitle="One-time purchase",
451
+ plan_amount=10.0,
452
+ plan_credits=5000,
453
+ plan_credits_text="5,000 credits",
454
+ percent_off=""
455
+ ),
456
+ Plan(
457
+ plan_reference="price_power_mock",
458
+ plan_type="prepaid",
459
+ plan_name="POWER",
460
+ plan_subtitle="Best value",
461
+ plan_amount=50.0,
462
+ plan_credits=28500,
463
+ plan_credits_text="28,500 credits",
464
+ percent_off="12.5% OFF"
465
+ ),
466
+ Plan(
467
+ plan_reference="price_elite_mock",
468
+ plan_type="prepaid",
469
+ plan_name="ELITE",
470
+ plan_subtitle="Maximum savings",
471
+ plan_amount=100.0,
472
+ plan_credits=66666,
473
+ plan_credits_text="66,666 credits",
474
+ percent_off="25% OFF"
475
+ ),
476
+ Plan(
477
+ plan_reference="price_unlimited_mock",
478
+ plan_type="postpaid",
479
+ plan_name="UNLIMITED",
480
+ plan_subtitle="Monthly subscription",
481
+ plan_amount=299.0,
482
+ plan_credits=None,
483
+ plan_credits_text="Unlimited",
484
+ percent_off=""
485
+ )
486
+ ]