/*
 * 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 generateNonprofitWorkflows(version) {
    return {
        'fundraising-setup.md': workflow(version, 'Fundraising Setup', `
## 1. Gather Requirements

Ask:
- **Donation types:** One-time gifts, recurring donations, pledges, in-kind gifts, grants, memberships — which apply?
- **Recurring frequency:** Monthly, quarterly, yearly? Enhanced Recurring Donations enabled?
- **GAU structure:** How many General Accounting Units (funds/campaigns/grants)? Default GAU for unallocated?
- **Gift Entry:** Will staff use Gift Entry Manager for batch data entry? CSV imports?
- **Payment processor:** Stripe, PayPal, Authorize.net, or other? Online giving page needed?
- **Soft credits:** Are soft credits needed for household members, matching gift companies, or honoree/memorial gifts?

Check \`force-app/main/default/objects/\` for existing NPSP or Nonprofit Cloud customizations before adding new fields.

## 2. Configure the Donation Pipeline

### Opportunity as Donation
1. Create or verify nonprofit Record Types on Opportunity: \`Donation\`, \`Grant\`, \`In-Kind Gift\`, \`Membership\`.
2. Map Stages to the donation lifecycle: Pledged → Partially Paid → Closed Won / Closed Lost.
3. Set \`npsp__Primary_Contact__c\` or standard \`ContactId\` to link donations to individual donors.
4. For organizational gifts: use the Account lookup (standard Opportunity field).

### Soft Credits
1. Add \`OpportunityContactRole\` records with role = "Soft Credit" for household members or influencers.
2. NPSP rolls up soft credits to Contact fields (\`npsp__Soft_Credit_Total__c\`).
3. Define which roles qualify for soft credit rollups in NPSP Settings → Donations → Soft Credit Roles.

### Matching Gifts
1. Track matching via \`npsp__Matching_Gift__c\` lookup on Opportunity or a dedicated junction object.
2. Configure matching gift companies on the Account object with \`npsp__Matching_Gift_Company__c = true\`.
3. Automate matching gift status updates via Record-Triggered Flow.

## 3. Set Up Recurring Donations

### Enhanced Recurring Donations (ERD)
1. Enable ERD in NPSP Settings → Recurring Donations → Enable Enhanced Recurring Donations.
2. Key fields on \`npe03__Recurring_Donation__c\`:
   - \`npe03__Amount__c\` — installment amount
   - \`npe03__Installment_Period__c\` — Monthly, Quarterly, 1st and 15th, Yearly
   - \`npe03__Date_Established__c\` — start date
   - \`npsp__Status__c\` — Active, Lapsed, Closed
   - \`npsp__Day_of_Month__c\` — specific day for installment creation
3. ERD creates child Opportunity records automatically — do NOT create them manually.
4. Pause/resume: use \`npsp__Status__c\` transitions via Flow or API.

### Installment Mapping
- NPSP creates future installments based on the schedule. Configure the look-ahead window in NPSP Settings.
- Close installment Opportunities when payment is confirmed (move to Closed Won).
- Lapsed detection: schedule a Batch Apex job to flag RDs where installments are overdue by N days.

## 4. Configure GAU Allocations

### General Accounting Units
1. Create \`npsp__General_Accounting_Unit__c\` records for each fund, campaign, or grant.
2. Set \`npsp__Active__c = true\` for active GAUs; inactive GAUs are hidden from allocation picklists.
3. Configure a default GAU in NPSP Settings → Allocations → Default Allocation to capture unallocated amounts.

### Allocation Records
1. \`npsp__Allocation__c\` links an Opportunity to one or more GAUs.
2. Allocate by amount (\`npsp__Amount__c\`) or percentage (\`npsp__Percent__c\`).
3. Total allocations must not exceed the Opportunity amount — validate via trigger or Flow.
4. Rollup fields on GAU (\`npsp__Total_Allocations__c\`) track giving by fund.

## 5. Configure Gift Entry

### Gift Entry Manager
1. Navigate to Setup → Nonprofit → Gift Entry.
2. Create a Gift Entry Template:
   - Select fields to display (Donor, Amount, Date, GAU, Payment Method).
   - Set required fields and default values.
   - Configure batch settings (batch size, duplicate matching rules).
3. Assign the template to Gift Entry users via Permission Set.
4. For CSV imports: map CSV columns to template fields in the import wizard.

### Payment Integration
1. Set up Named Credential for the payment processor (Stripe, PayPal).
2. Create an Apex callout class to process payments or validate tokens.
3. Map webhook events (charge.succeeded, payment.failed) to Platform Events.
4. Create a Platform Event Trigger or Flow to update Opportunity/Payment status on webhook receipt.

## 6. Deploy Fundraising Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/Opportunity \\
  --source-dir force-app/main/default/objects/npsp__General_Accounting_Unit__c \\
  --source-dir force-app/main/default/objects/npsp__Allocation__c \\
  --source-dir force-app/main/default/objects/npe03__Recurring_Donation__c \\
  --source-dir force-app/main/default/flows \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Donation Record Types appear on Opportunity with correct page layouts
- Recurring Donation creates child installment Opportunities on schedule
- GAU Allocations roll up correctly to the GAU record
- Gift Entry template is accessible and processes test donations
`),
        'program-management-setup.md': workflow(version, 'Program Management Setup', `
## 1. Gather Requirements

Ask:
- **Programs:** What programs does the organization run? (e.g., job training, food assistance, housing, mentorship)
- **Engagement model:** How do constituents enter a program? (application, referral, self-enrollment, case worker assignment)
- **Deliverables:** What units of service are tracked? (sessions, meals, hours, materials distributed)
- **Outcomes:** What outcomes are measured? (employment rate, housing stability, graduation, health improvement)
- **Reporting:** What program metrics are reported to funders or the board?
- **Multi-program:** Can a constituent participate in multiple programs simultaneously?

Check \`force-app/main/default/objects/Program__c\` and \`ProgramEngagement__c\` for existing configurations.

## 2. Define Programs

### Program Object Configuration
1. Create \`Program__c\` records for each program the organization delivers.
2. Key fields:
   - \`Name\` — program title
   - \`Status__c\` — Active, Planned, Completed, Suspended
   - \`StartDate__c\` / \`EndDate__c\` — program operational dates
   - \`Description__c\` — program goals and eligibility criteria
   - \`TargetPopulation__c\` — who the program serves (picklist or text)
   - \`FundingSource__c\` — lookup to Campaign or custom Funding object
3. Add custom fields for capacity tracking: \`MaxParticipants__c\`, \`CurrentEnrollment__c\` (rollup from engagements).

### Benefits
1. Define \`Benefit__c\` records under each Program for services offered.
2. Key fields: \`Program__c\` (lookup), \`Name\`, \`Description__c\`, \`Type__c\` (Training, Material, Service, Financial).
3. Benefits represent what participants CAN receive; Deliverables track what they DID receive.

## 3. Configure Engagement Tracking

### Program Engagement
1. \`ProgramEngagement__c\` links a Contact (participant) to a \`Program__c\`.
2. Key fields:
   - \`Contact__c\` — the participant
   - \`Program__c\` — the program
   - \`Stage__c\` — Applied, Waitlisted, Active, Completed, Withdrawn, Referred Out
   - \`StartDate__c\` / \`EndDate__c\` — participation dates
   - \`Role__c\` — Participant, Volunteer, Mentor, Case Worker (if multiple roles tracked)
3. Use Record-Triggered Flows to automate:
   - On Stage = "Active": create initial Deliverable records from the Program's Benefit template.
   - On Stage = "Completed": trigger outcome assessment tasks.
   - On Stage = "Withdrawn": log reason and notify case worker.

### Capacity Management
- Use a rollup (Flow or DLRS) to count Active engagements per Program → \`CurrentEnrollment__c\`.
- Validate on Before Save: reject new "Active" engagements when \`CurrentEnrollment__c >= MaxParticipants__c\`.
- Waitlist: set Stage = "Waitlisted" and create a Task for case worker follow-up when capacity opens.

## 4. Track Deliverables

### Deliverable Configuration
1. \`Deliverable__c\` records track individual service units within an engagement.
2. Key fields:
   - \`ProgramEngagement__c\` — parent engagement
   - \`Benefit__c\` — which benefit this delivers
   - \`DeliveryDate__c\` — when the service was provided
   - \`Quantity__c\` — number of units (hours, sessions, items)
   - \`Status__c\` — Scheduled, Delivered, Missed, Cancelled
   - \`Provider__c\` — lookup to User or Contact (staff/volunteer who delivered)
3. Roll up deliverable totals to Program Engagement:
   - \`TotalDelivered__c\` — sum of Quantity where Status = Delivered
   - \`TotalScheduled__c\` — sum of Quantity where Status = Scheduled
   - \`AttendanceRate__c\` — formula: Delivered / (Delivered + Missed)

### Bulk Delivery Entry
- For programs with many participants per session (e.g., group classes):
  Use a custom LWC or Flow screen to mark attendance for all active engagements in a program on a given date.
- Create Deliverable records in bulk — one per participant per session.

## 5. Measure Outcomes

### Outcome Framework
1. Define outcome indicators at the Program level:
   - Create \`ProgramOutcome__c\` or custom fields on \`Program__c\` for target metrics.
   - Examples: "75% employment at 6 months", "90% housing retention at 12 months".
2. Track individual outcomes on \`ProgramEngagement__c\`:
   - \`OutcomeStatus__c\` — Positive, Negative, Pending, Not Measured
   - \`OutcomeDate__c\` — when the outcome was assessed
   - \`OutcomeNotes__c\` — qualitative notes
3. For longitudinal tracking: create follow-up \`Task\` records at 3, 6, and 12 months post-completion.

### Outcome Reporting
- Use Reports & Dashboards grouped by Program, Stage, and Outcome Status.
- Funder reports: filter by Program + date range, show deliverable totals and outcome rates.
- Board reports: aggregate across programs, show trends over quarters.
- For advanced analytics: connect to CRM Analytics with Program, Engagement, and Deliverable datasets.

## 6. Deploy Program Management Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/Program__c \\
  --source-dir force-app/main/default/objects/Benefit__c \\
  --source-dir force-app/main/default/objects/ProgramEngagement__c \\
  --source-dir force-app/main/default/objects/Deliverable__c \\
  --source-dir force-app/main/default/flows \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Programs display with correct fields and page layouts
- Program Engagements link Contacts to Programs with stage tracking
- Deliverables roll up correctly to the engagement record
- Capacity validation prevents over-enrollment
- Outcome fields capture assessment data post-completion
`),
    };
}
//# sourceMappingURL=nonprofit.js.map