/*
 * 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 { workflow } from '../workflow-generator.js';
export function generateRevenueWorkflows(version) {
    return {
        'billing-setup.md': workflow(version, 'Billing Setup', `
## 1. Gather Requirements

Ask:
- **Billing model:** Is billing usage-based, subscription-based, one-time, or hybrid?
- **Billing frequency:** Monthly, quarterly, annually, or custom billing schedules?
- **Proration:** How are mid-term changes handled? Daily proration, monthly proration, or no proration?
- **Credit/debit notes:** Under what conditions are credit notes or debit notes issued?
- **Invoice delivery:** Email, portal, or ERP integration for invoice distribution?
- **Revenue recognition:** Does billing need to align with ASC 606 performance obligations?

Check \`force-app/main/default/objects/blng__\` and \`force-app/main/default/objects/BillingSchedule\` for existing configurations before adding new fields.

## 2. Configure Billing Schedules

### Billing Schedule Groups
- \`BillingScheduleGroup\` organizes related billing schedules for a single customer or contract.
- Group schedules by contract term, product family, or billing frequency.
- Set the billing day of month (e.g., 1st, 15th, last day) at the group level.

### Billing Schedule Configuration
1. Navigate to Setup → Billing → Billing Schedules.
2. Define schedule templates for each billing frequency:
   - **Monthly:** invoice generated on the same day each month.
   - **Quarterly:** invoice generated every 3 months from the start date.
   - **Annual:** single invoice at the start of each contract year.
3. Set \`blng__BillingSchedule__c\` fields:
   - \`blng__StartDate__c\` — billing period start
   - \`blng__EndDate__c\` — billing period end
   - \`blng__Frequency__c\` — billing cadence
   - \`blng__NextBillingDate__c\` — next invoice generation date

## 3. Invoice Generation

### Invoice Lifecycle
1. Billing engine evaluates billing schedules where \`NextBillingDate <= TODAY\`.
2. Creates \`blng__Invoice__c\` with status = "Draft".
3. Generates \`blng__InvoiceLine__c\` records for each billable line item.
4. Applies tax calculations (if tax engine is configured).
5. Invoice moves to "Posted" after review/approval.

### Invoice Configuration
- Set the invoice numbering scheme in Billing Settings (auto-number or custom sequence).
- Configure invoice templates for PDF generation.
- Define approval thresholds: invoices above a certain amount require manual approval before posting.

### Batch Invoice Generation
\`\`\`bash
# Run the billing batch job for a specific billing schedule group
sf apex run --target-org <alias> --file scripts/run-billing-batch.apex
\`\`\`

## 4. Credit and Debit Notes

### Credit Notes (\`blng__CreditNote__c\`)
- Issue credit notes for: overpayments, service credits, billing errors, cancellations.
- Link credit notes to the original \`blng__Invoice__c\` via \`blng__RelatedInvoice__c\`.
- Credit notes reduce the customer balance and can be applied to future invoices.

### Debit Notes (\`blng__DebitNote__c\`)
- Issue debit notes for: undercharges, usage overages, late fees, price adjustments.
- Link debit notes to the original invoice or billing schedule.
- Debit notes increase the customer balance and generate additional receivables.

### Automation Rules
- Use Record-Triggered Flows to auto-generate credit notes on order cancellation.
- Never auto-post credit/debit notes above threshold — require approval flow.

## 5. Proration Rules

### Mid-Term Changes
- **Upgrade:** prorate remaining period at old rate, bill prorated amount at new rate.
- **Downgrade:** issue credit note for the difference in the remaining period.
- **Cancellation:** issue credit note for unused portion of the billing period.

### Proration Configuration
1. Set proration method in Billing Settings: Daily, Monthly, or None.
2. Configure \`blng__ProrationPolicy__c\` per product or product family.
3. Mid-term changes trigger amendment billing via the CPQ → Billing handoff.

## 6. Deploy Billing Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/blng__Invoice__c \\
  --source-dir force-app/main/default/objects/blng__InvoiceLine__c \\
  --source-dir force-app/main/default/objects/blng__CreditNote__c \\
  --source-dir force-app/main/default/objects/blng__DebitNote__c \\
  --source-dir force-app/main/default/objects/BillingSchedule \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Billing schedules generate invoices on the configured date
- Credit/debit notes link correctly to source invoices
- Proration calculates correctly for mid-term changes
`),
        'payment-processing-setup.md': workflow(version, 'Payment Processing Setup', `
## 1. Gather Requirements

Ask:
- **Payment methods:** Which payment methods are supported? (Credit card, ACH/direct debit, wire transfer, digital wallets)
- **Payment gateway:** Which gateway provider? (Stripe, PayPal, Adyen, Authorize.Net, other)
- **Retry logic:** How many retry attempts for failed payments? What interval between retries?
- **Dunning process:** What is the escalation path for failed payments? (Email → SMS → phone → suspension)
- **PCI compliance:** Is the org handling raw card data or using tokenized gateway references?
- **Multi-currency:** Are payments processed in multiple currencies?

Check \`force-app/main/default/objects/PaymentGateway\` and \`force-app/main/default/objects/PaymentMethod\` for existing configurations.

## 2. Payment Gateway Setup

### Gateway Configuration
1. Navigate to Setup → Payments → Payment Gateway.
2. Create a \`PaymentGateway\` record:
   - **Gateway Provider:** select the registered provider adapter class.
   - **Merchant Account ID:** reference the merchant account (store in Named Credential, NEVER hardcode).
   - **Environment:** Sandbox or Production (use separate gateways per environment).
3. Register the gateway adapter Apex class implementing \`commercepayments.GatewayAdapter\`:
   - \`processCapture()\` — capture authorized payments
   - \`processAuthorization()\` — authorize payment methods
   - \`processRefund()\` — process refunds back to the payment method
   - \`processSale()\` — combined auth + capture

### Named Credentials for Gateway Secrets
\`\`\`
NEVER store API keys, merchant secrets, or tokens in Apex code or Custom Settings.
Use Named Credentials + External Credentials for all gateway authentication.
\`\`\`

1. Create an External Credential (Setup → Named Credentials → External Credentials).
2. Create a Named Credential pointing to the gateway endpoint.
3. Reference the Named Credential in the gateway adapter: \`new HttpRequest().setEndpoint('callout:PaymentGateway_NC/...')\`.

## 3. Payment Methods

### Supported Payment Method Types
- **Credit/Debit Card:** tokenized via gateway (store token reference only, never raw PAN).
- **ACH / Direct Debit:** bank account + routing number (tokenized).
- **Wire Transfer:** manual reconciliation via bank statement import.
- **Digital Wallets:** Apple Pay, Google Pay via gateway tokenization.

### Payment Method Configuration
1. Create \`PaymentMethod\` records linked to the customer Account.
2. Set \`PaymentMethodType\` (Card, BankAccount, DigitalWallet).
3. Store only the gateway token reference in \`GatewayToken__c\` — never raw credentials.
4. Set a default payment method per customer for automatic billing.

### PCI DSS Compliance
- **Never store raw card numbers (PAN) in any Salesforce field.**
- Use gateway-side tokenization — Salesforce stores only the token reference.
- Mask card display: show only last 4 digits in UI (e.g., \`****1234\`).
- Restrict access to \`PaymentMethod\` records via Permission Set — only billing admins.
- Audit trail: enable Field History Tracking on payment method status changes.

## 4. Payment Retry Logic

### Retry Configuration
1. Define retry policy in Custom Metadata Type \`blng__PaymentRetryPolicy__mdt\`:
   - **Max Attempts:** 3 (recommended default)
   - **Retry Interval:** 1 day, 3 days, 7 days (escalating)
   - **Retry on codes:** Soft declines only (insufficient funds, temporary hold) — never retry hard declines (stolen card, invalid account).
2. The billing engine automatically retries failed payments based on the policy.
3. After max retries exhausted: mark payment as "Failed" and trigger dunning process.

### Soft vs Hard Decline Handling
| Decline Type | Example Codes | Action |
|-------------|---------------|--------|
| Soft decline | Insufficient funds, Timeout | Retry per policy |
| Hard decline | Invalid card, Fraud, Stolen | Do NOT retry — suspend payment method |

## 5. Dunning Process

### Dunning Configuration
1. Define dunning stages based on days past due:
   - **0-7 days:** Automated email reminder with payment link.
   - **8-14 days:** Second email + SMS notification.
   - **15-30 days:** Phone outreach task assigned to collections team.
   - **31-60 days:** Service suspension warning.
   - **61+ days:** Account suspension + write-off evaluation.

2. Implement dunning via Record-Triggered Flows on \`blng__Invoice__c\`:
   - When \`Status = "Past Due"\` and \`DaysPastDue__c\` crosses each threshold.
   - Create Tasks, send Email Alerts, update Account status.

3. Aging Buckets: configure reports grouping invoices by:
   - Current (0-30 days)
   - 31-60 days
   - 61-90 days
   - 90+ days

### Write-Off Process
- Write-offs require approval (minimum: Finance Manager + Controller).
- Create a \`blng__CreditNote__c\` marked as "Write-Off" type.
- Log the write-off as a journal entry for ERP sync.

## 6. Deploy Payment Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/PaymentGateway \\
  --source-dir force-app/main/default/objects/PaymentMethod \\
  --source-dir force-app/main/default/classes/PaymentGatewayAdapter* \\
  --source-dir force-app/main/default/namedCredentials \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Payment gateway connects successfully (test transaction in sandbox)
- Payment methods are tokenized — no raw card data stored
- Retry logic triggers on soft declines only
- Dunning emails fire at configured intervals
- Named Credentials authenticate without hardcoded secrets
`),
    };
}
//# sourceMappingURL=revenue.js.map