Epic: Automated Non-Paying Account Management Goal: To implement a fully automated system that identifies non-paying user accounts, sends payment reminders, schedules accounts for deletion after failed recovery attempts, and executes the deletion, all leveraging Stripe integration and without needing manual intervention via an admin interface. User Story 1: Identify Overdue AccountsTitle: Automate Identification of Overdue Subscriptions via Stripe • User Story: As a SaaS Provider, I want the system to automatically detect when a user's subscription payment has failed or is marked as overdue within Stripe, so that we can accurately trigger the dunning (payment recovery) process. • Acceptance Criteria: ◦ The system successfully receives and processes relevant Stripe webhooks (e.g., invoice.payment_failed, customer.subscription.updated indicating past_due or unpaid status). ◦ Alternatively, a scheduled task (e.g., runs daily) correctly queries the Stripe API to find subscriptions with past_due or unpaid statuses. ◦ The system accurately maps the Stripe Customer ID or Subscription ID to the corresponding user account in our internal database. ◦ An internal status field on the user account record is updated to reflect the overdue status (e.g., payment_status: overdue_initial). ◦ The system correctly identifies the first payment failure within a specific billing cycle to initiate the process. • Technical Considerations: ◦ Requires a reliable mechanism for handling Stripe webhooks or a robust scheduler for API polling (e.g., cron, AWS Lambda scheduled event, background job queue). ◦ Secure mapping between Stripe identifiers and internal user IDs is essential. ◦ Database schema modification is needed for the internal payment_status field. ◦ Implement comprehensive error handling and logging for Stripe API interactions and webhook processing. • Notes: Stripe's subscription statuses should be treated as the definitive source. Factor in any grace periods configured directly within Stripe's subscription settings. User Story 2: Send Automated Payment RemindersTitle: Automate Sending of Sequenced Payment Reminder Emails • User Story: As a SaaS Provider, I want the system to automatically send a configured sequence of reminder emails to users whose accounts are overdue, so that they are clearly notified and guided to update their payment information before service disruption or account deletion. • Acceptance Criteria: ◦ Upon an account status changing to overdue_initial, the first reminder email is dispatched automatically. ◦ If the account remains overdue after a configurable period (e.g., X days), the internal status is updated (e.g., payment_status: overdue_followup_1), and a second reminder email is sent. ◦ If the account still remains overdue after another configurable period (e.g., Y days) following the second reminder, the status updates (e.g., payment_status: overdue_final_warning), and a final reminder email is sent. ◦ Reminder emails clearly state the payment issue, convey appropriate urgency, and include a direct, functional link for the user to update payment details (e.g., link generated via Stripe Billing Portal API or to a specific page in the application). ◦ The system logs the timestamp and type of each reminder sent to the user account. ◦ The reminder sequence for a specific overdue invoice halts immediately if payment is successfully confirmed (via Stripe webhooks like invoice.paid or customer.subscription.updated to active), and the internal payment_status is reset to a healthy state (e.g., active). • Technical Considerations: ◦ Integration with a transactional email service (e.g., SendGrid, Mailgun, AWS SES) is required. ◦ Need configurable email templates tailored for each reminder stage. ◦ Requires scheduled jobs or state management logic to monitor the time elapsed since the last reminder and verify the current Stripe subscription status before sending subsequent reminders. ◦ Leveraging the Stripe Billing Portal (stripe.billing_portal.sessions.create) is recommended for a seamless payment update experience. ◦ System configuration is needed for the intervals X and Y days (e.g., X=3, Y=7). • Notes: Evaluate using Stripe's built-in Dunning features, which might handle parts of this automatically. If custom logic is built, ensure it complements or replaces Stripe's features clearly. Email content should be compliant with relevant communication regulations. User Story 3: Schedule Account for DeletionTitle: Automate Scheduling of Account Deletion After Final Reminder Fails • User Story: As a SaaS Provider, I want the system to automatically schedule an account for deletion when payment hasn't been received after the final reminder period has lapsed, so that the account is formally marked for removal following a defined final grace period. • Acceptance Criteria: ◦ If an account remains overdue for a configurable period (e.g., Z days) after the final reminder (overdue_final_warning) was sent, the system updates the internal status to deletion_scheduled. ◦ A specific scheduled_deletion_timestamp (e.g., current time + W days, configurable) is recorded for the user account. ◦ A final notification email is automatically sent, explicitly informing the user that their account is scheduled for deletion on the specified date/time and that this is the absolute last opportunity to make a payment to prevent it. ◦ The scheduling event and the planned deletion timestamp are logged internally. ◦ If a successful payment is confirmed via Stripe before the scheduled_deletion_timestamp is reached, the deletion_scheduled status and timestamp are removed, the account status is reset (e.g., to active), the deletion is cancelled, and the Stripe subscription potentially reactivated if it was set to cancel. • Technical Considerations: ◦ Database schema requires a scheduled_deletion_timestamp field (nullable timestamp). ◦ Logic is needed (likely within the scheduled task monitoring overdue accounts) to transition accounts from the final warning state to the scheduled deletion state based on the Z day interval. ◦ Configuration required for intervals Z and W days (e.g., Z=7, W=14). ◦ A final check of the Stripe subscription status is crucial before marking for deletion. ◦ Consider configuring Stripe Dunning to automatically cancel the subscription after the final retry attempt, or implement an explicit API call (stripe.subscriptions.cancel) at this stage to prevent further billing attempts. Ensure the cancellation timing (immediate vs. end of period) aligns with policy. • Notes: This step establishes a clear, final deadline for the user. The cancellation of the Stripe subscription should ideally happen here or be confirmed as handled by Stripe's Dunning settings. User Story 4: Execute Automated Account DeletionTitle: Automate Execution of Scheduled Account Deletion • User Story: As a SaaS Provider, I want the system to automatically execute the deletion of user accounts that have passed their scheduled_deletion_timestamp without any intervening successful payment, so that we permanently remove non-paying user data and reclaim associated resources according to policy. • Acceptance Criteria: ◦ A scheduled job runs regularly (e.g., daily or hourly) to find accounts with the deletion_scheduled status where the scheduled_deletion_timestamp is in the past. ◦ Before proceeding with deletion, the system performs one last verification of the Stripe subscription status to prevent accidental deletion if a payment was made very recently but not yet processed internally. ◦ If payment was received last-minute, the deletion process is aborted, the account status is reset, and the event is logged (handling this edge case). ◦ If payment was not received, the system initiates and completes the defined account deletion procedure. ◦ The deletion procedure removes or anonymizes user records and associated data as per the company's data retention and privacy policies (e.g., GDPR/CCPA compliance). ◦ The system confirms the corresponding Stripe subscription is in a canceled state. If not, it attempts cancellation via API (stripe.subscriptions.cancel). ◦ A record of the successful deletion (including timestamp and user identifier) is logged internally for auditing purposes. • Technical Considerations: ◦ Requires a thoroughly tested, robust script or service function for performing account deletion. ◦ The exact definition of "deletion" (hard delete vs. soft delete/anonymization) must be clearly defined and implemented based on legal and business requirements. ◦ The deletion process must be idempotent (safe to run multiple times on the same target without adverse effects or errors after the first successful run). ◦ Include safety checks in the deletion job to prevent catastrophic failures, such as accidentally targeting a large number of active accounts (e.g., limit the number of deletions per run or add checks against unexpected conditions). • Notes: This is the point of no return for user data. Strict adherence to data privacy regulations and internal retention policies is paramount. Comprehensive logging is essential.