/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { generateRevenueWorkflows } from '../generators/workflows/revenue.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const revenueProfile = {
    id: 'revenue',
    label: 'Revenue Cloud',
    ruleFile: 'revenue-standards.mdc',
    extensions: ['salesforce.salesforcedx-vscode'],
    capabilities: ['deploy', 'code-analysis', 'prompt-registry', 'declare-points'],
    cursorScope: 'description',
    detect(cwd) {
        return (existsSync(join(cwd, 'force-app/main/default/objects/blng__Invoice__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/SBQQ__Quote__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/BillingSchedule')));
    },
    workflows: generateRevenueWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Revenue Cloud (Billing, Subscriptions, Payments) Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Revenue Cloud Standards',
            '',
            '> Role: Revenue Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Revenue Cloud encompasses Salesforce Billing (blng__), Subscription Management, and Payment Processing. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Revenue Cloud billing, payment, and subscription architecture decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Revenue Cloud Data Model (CRITICAL)',
            '',
            '### Subscription Lifecycle',
            '- **Order → Billing Schedule → Invoice → Payment → Revenue Recognition**',
            '- CPQ Quote (SBQQ__Quote__c) activates into an Order.',
            '- Order activation triggers billing schedule creation.',
            '- Billing schedules generate invoices on the configured cadence.',
            '- Invoices drive payment collection and revenue recognition.',
            '',
            '### Core Revenue Cloud Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Invoice | `blng__Invoice__c` | Customer invoice with line items, tax, and payment status |',
            '| Invoice Line | `blng__InvoiceLine__c` | Individual billable line item on an invoice |',
            '| Payment | `blng__Payment__c` | Payment record linked to an invoice or account |',
            '| Credit Note | `blng__CreditNote__c` | Credit issued for overpayment, cancellation, or billing error |',
            '| Debit Note | `blng__DebitNote__c` | Debit issued for undercharges, overages, or adjustments |',
            '| Billing Schedule | `BillingSchedule` | Recurring billing cadence definition |',
            '| Billing Schedule Group | `BillingScheduleGroup` | Groups related billing schedules per customer/contract |',
            '| Payment Method | `PaymentMethod` | Customer payment instrument (card, ACH, wallet) |',
            '| Payment Gateway | `PaymentGateway` | Gateway adapter configuration (Stripe, PayPal, Adyen) |',
            '',
            '### CPQ to Billing Handoff',
            '- **SBQQ__Quote__c → Order → blng__ objects.** The CPQ-to-Billing connector activates billing on order activation.',
            '- Amendments in CPQ trigger mid-term billing changes (proration, credit notes).',
            '- Renewals in CPQ generate new billing schedules for the renewal term.',
            '- Never create billing records manually when CPQ is the source — let the connector handle the handoff.',
            '',
            '## Billing (CRITICAL)',
            '',
            '### Invoice Generation',
            '- Billing engine evaluates billing schedules where `NextBillingDate <= TODAY`.',
            '- Invoices are created in "Draft" status, then posted after review/approval.',
            '- Use batch Apex or scheduled jobs for bulk invoice generation — never generate invoices synchronously in triggers.',
            '- Invoice numbering: configure auto-number or custom sequence in Billing Settings.',
            '',
            '### Billing Schedules',
            '- Define billing frequency: Monthly, Quarterly, Annually, or custom intervals.',
            '- Set the billing day of month at the `BillingScheduleGroup` level.',
            '- `blng__NextBillingDate__c` drives when the next invoice is generated.',
            '- Align billing schedules with contract terms — mismatch causes revenue leakage.',
            '',
            '### Proration',
            '- **Daily proration:** charges calculated based on exact days used in the billing period.',
            '- **Monthly proration:** charges calculated based on full months.',
            '- **No proration:** full period charge regardless of start/end date.',
            '- Mid-term upgrades: prorate remaining period at old rate + prorated charge at new rate.',
            '- Mid-term downgrades: issue credit note for the difference.',
            '- Cancellations: issue credit note for unused portion.',
            '',
            '### Credit and Debit Notes',
            '- Credit notes (`blng__CreditNote__c`): overpayments, service credits, billing errors, cancellations.',
            '- Debit notes (`blng__DebitNote__c`): undercharges, usage overages, late fees, price adjustments.',
            '- Always link credit/debit notes to the source invoice via `blng__RelatedInvoice__c`.',
            '- Credit/debit notes above configurable threshold require approval flow — never auto-post large adjustments.',
            '',
            '## Payment Processing (CRITICAL)',
            '',
            '### Payment Gateway Integration',
            '- Implement `commercepayments.GatewayAdapter` interface for custom gateway adapters.',
            '- Required methods: `processAuthorization()`, `processCapture()`, `processRefund()`, `processSale()`.',
            '- Store gateway credentials in Named Credentials + External Credentials — **NEVER in Apex code or Custom Settings.**',
            '- Use separate gateway configurations per environment (sandbox vs production).',
            '',
            '### Payment Methods',
            '- Supported types: Credit/Debit Card, ACH/Direct Debit, Wire Transfer, Digital Wallets.',
            '- **Store only gateway token references** — never raw card numbers (PAN).',
            '- Mask card display in UI: show only last 4 digits (`****1234`).',
            '- Set a default payment method per customer for automatic billing.',
            '',
            '### Payment Retry Logic',
            '- Configure retry policy: max attempts (recommended: 3), escalating intervals (1, 3, 7 days).',
            '- **Soft declines** (insufficient funds, timeout): retry per policy.',
            '- **Hard declines** (stolen card, invalid account): do NOT retry — suspend payment method immediately.',
            '- After max retries exhausted: mark payment "Failed" and trigger dunning process.',
            '',
            '### PCI DSS Compliance',
            '- **Never store raw card numbers in any Salesforce field.**',
            '- Use gateway-side tokenization — Salesforce stores only the token reference.',
            '- Restrict `PaymentMethod` record access via Permission Set — billing admins only.',
            '- Enable Field History Tracking on payment method status changes for audit trail.',
            '- Payment data isolation: separate permission sets for payment read vs payment write.',
            '',
            '## Revenue Recognition',
            '',
            '### ASC 606 Compliance',
            '- **Step 1:** Identify the contract (Order or Contract record).',
            '- **Step 2:** Identify performance obligations (order products / billing schedule lines).',
            '- **Step 3:** Determine transaction price (total contract value).',
            '- **Step 4:** Allocate transaction price to performance obligations (standalone selling price method).',
            '- **Step 5:** Recognize revenue when (or as) performance obligations are satisfied.',
            '',
            '### Recognition Schedules',
            '- Point-in-time recognition: revenue recognized on delivery/completion.',
            '- Over-time recognition: revenue recognized ratably over the service period.',
            '- Milestone-based recognition: revenue recognized on milestone achievement.',
            '- Configure recognition schedules to align with billing schedules where possible.',
            '',
            '## Collections & Dunning',
            '',
            '### Dunning Process',
            '- Define escalation stages based on days past due:',
            '  - 0-7 days: automated email reminder.',
            '  - 8-14 days: second email + SMS.',
            '  - 15-30 days: phone outreach task to collections team.',
            '  - 31-60 days: service suspension warning.',
            '  - 61+ days: account suspension + write-off evaluation.',
            '- Implement via Record-Triggered Flows on `blng__Invoice__c` status changes.',
            '',
            '### Aging Buckets',
            '- Report on receivables by aging: Current, 31-60, 61-90, 90+ days.',
            '- Use formula fields or scheduled Apex to calculate days past due.',
            '',
            '### Write-Offs',
            '- Require multi-level approval (Finance Manager + Controller minimum).',
            '- Create a `blng__CreditNote__c` with type = "Write-Off".',
            '- Log as journal entry for ERP sync.',
            '',
            '## Taxation',
            '',
            '### Tax Engine Integration',
            '- Support Avalara, Vertex, or native Salesforce tax engine.',
            '- Tax calculation runs during invoice generation — before posting.',
            '- Store tax amounts at the invoice line level (`blng__TaxAmount__c`).',
            '',
            '### Tax Exempt Handling',
            '- Flag tax-exempt accounts with exemption certificate reference.',
            '- Validate exemption certificates are not expired before applying exemption.',
            '- Different jurisdictions may have different exemption rules — configure per billing address.',
            '',
            '### Multi-Jurisdiction',
            '- Tax calculated based on ship-to address (destination-based) or origin address depending on jurisdiction.',
            '- Configure nexus rules in the tax engine — not in Salesforce custom code.',
            '- International transactions: VAT, GST, and withholding tax handled by the tax engine.',
            '',
            '## Integration Patterns',
            '',
            '### ERP Sync (Journal Entries)',
            '- Sync posted invoices, payments, credit notes, and revenue recognition entries to ERP.',
            '- Use Platform Events or Change Data Capture for real-time sync.',
            '- Batch sync for reconciliation: scheduled Apex job runs nightly.',
            '- Map Salesforce billing objects to ERP GL accounts via Custom Metadata Type.',
            '',
            '### Payment Processors',
            '- Stripe, PayPal, Adyen: implement via `commercepayments.GatewayAdapter`.',
            '- Use webhooks (Platform Events) for asynchronous payment status updates from the gateway.',
            '- Reconcile gateway settlements with Salesforce payment records daily.',
            '',
            '### Tax Engines',
            '- Avalara AvaTax: callout during invoice generation for real-time tax calculation.',
            '- Vertex: similar pattern — callout with line item details, receive tax amounts.',
            '- Cache tax results to avoid redundant callouts on invoice re-calculation.',
            '',
            '## Managed Package Safety (blng__ namespace)',
            '- **Do NOT add Apex triggers directly on blng__ managed objects.**',
            '  Use Record-Triggered Flows or custom extension objects.',
            '- **Do NOT delete or rename blng__ managed fields.** Extend with project-prefixed custom fields only.',
            '- **Do NOT override blng__ managed page layouts.** Clone and assign to your Record Type.',
            '- Before each package upgrade, review release notes for breaking changes.',
            '- Test upgrades in a sandbox with full regression before promoting to production.',
            '',
            '## Security',
            '',
            '### Financial Data Access Control',
            '- Restrict invoice, payment, and credit note access via Permission Set Groups.',
            '- Separate read-only (reporting) from read-write (billing operations) access.',
            '- OWD for billing objects: Private — share via Sharing Rules based on territory or role.',
            '',
            '### Payment Data Isolation',
            '- `PaymentMethod` records: restricted to billing admin Permission Set only.',
            '- Gateway tokens: stored in encrypted fields where available.',
            '- Audit all payment method CRUD operations via Shield Event Monitoring or Field History.',
            '',
            '## Testing Revenue Cloud',
            '- **Use TestDataFactory** for invoices, payments, billing schedules, and credit notes.',
            '- **Never use real payment credentials in tests** — use test tokens provided by the gateway (e.g., Stripe test tokens).',
            '- Mock gateway callouts with `Test.setMock(HttpCalloutMock.class, ...)` — never make real gateway calls in tests.',
            '- Test proration logic with multiple mid-term change scenarios.',
            '- Verify dunning flows fire at correct thresholds using `Test.startTest()` / `Test.stopTest()`.',
            '- Assign billing Permission Sets to test users in `@TestSetup`.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Revenue Cloud References',
            '- Revenue Cloud (Billing) Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.blng.meta/blng/',
            '- Subscription Management: https://developer.salesforce.com/docs/atlas.en-us.subscription_management.meta/subscription_management/',
            '- Payment Platform: https://help.salesforce.com/s/articleView?id=sf.payments_overview.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('revenue'),
            '',
            ...interactionPreferences('Revenue Cloud billing and payment'),
        ].join('\n');
    },
};
//# sourceMappingURL=revenue.js.map