/*
 * 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 { generateNonprofitWorkflows } from '../generators/workflows/nonprofit.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const nonprofitProfile = {
    id: 'nonprofit',
    label: 'Nonprofit Cloud',
    ruleFile: 'nonprofit-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/npsp__General_Accounting_Unit__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/npsp__Allocation__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/npe03__Recurring_Donation__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/Program__c')));
    },
    workflows: generateNonprofitWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Nonprofit Cloud Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Nonprofit Cloud Standards',
            '',
            '> Role: Nonprofit Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Nonprofit Cloud includes legacy NPSP (Nonprofit Success Pack) and the new Nonprofit Cloud (Fundraising, Program Management, Outcome Management). All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Nonprofit Cloud data model and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Nonprofit Cloud Data Model (CRITICAL)',
            '',
            '### NPSP Legacy vs New Nonprofit Cloud',
            '- **NPSP (Nonprofit Success Pack):** managed package with `npsp__` and `npe03__` namespaces. Legacy but still widely deployed.',
            '- **New Nonprofit Cloud:** native Salesforce objects (`Program__c`, `ProgramEngagement__c`, `Benefit__c`, `Deliverable__c`) without managed package namespace.',
            '- **Coexistence strategy:** Both can run simultaneously. New implementations should target Nonprofit Cloud objects; existing NPSP orgs should plan a phased migration.',
            '- **Migration path:** NPSP Recurring Donations → Fundraising (native), NPSP Allocations → GAU Allocations (retained), NPSP Households → standard Account model.',
            '',
            '### Core Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| General Accounting Unit | `npsp__General_Accounting_Unit__c` | Fund/grant/campaign financial buckets for allocation tracking |',
            '| Allocation | `npsp__Allocation__c` | Links a Donation (Opportunity) to one or more GAUs with amount/percentage |',
            '| Recurring Donation | `npe03__Recurring_Donation__c` | Scheduled giving: donor, amount, frequency, installment schedule |',
            '| Donation | `Opportunity` | Standard Opportunity used as Donation with nonprofit Record Types |',
            '| Program | `Program__c` | Defines a nonprofit program with goals, eligibility, and duration |',
            '| Benefit | `Benefit__c` | A service or resource provided by a program to participants |',
            '| Program Engagement | `ProgramEngagement__c` | Links a Contact to a Program with status, start/end dates |',
            '| Deliverable | `Deliverable__c` | Trackable unit of service delivery within a Program Engagement |',
            '',
            '### Deprecated/Replaced Objects (NPSP → Nonprofit Cloud)',
            '- `npo02__Household__c` → Use standard Account with Household Record Type',
            '- `npsp__Level__c` → Use Engagement Levels or custom picklist on Contact',
            '- NPSP batch donation entry → Gift Entry Manager',
            '- NPSP Customizable Rollups → Nonprofit Cloud rollup framework or DLRS for complex cases',
            '',
            '## Fundraising',
            '',
            '### Donation Tracking',
            '- Use `Opportunity` with nonprofit Record Types (Donation, Grant, In-Kind Gift, Membership).',
            '- Key fields: `Amount`, `CloseDate`, `StageName`, `npsp__Primary_Contact__c` (or standard `ContactId`).',
            '- **Soft Credits:** Use `OpportunityContactRole` with role = "Soft Credit" for recognition without primary donor change.',
            '- **Matching Gifts:** Track via `npsp__Matching_Gift__c` lookup or a custom junction when matching corporate programs.',
            '',
            '### Recurring Donations',
            '- `npe03__Recurring_Donation__c` defines the schedule; child `Opportunity` records are installments.',
            '- Key fields: `npe03__Amount__c`, `npe03__Installment_Period__c` (Monthly, Quarterly, Yearly), `npe03__Date_Established__c`.',
            '- Enhanced Recurring Donations (ERD): enables pause, schedule changes, and installment mapping.',
            '- **Never create Opportunities manually for a Recurring Donation** — let the NPSP engine generate installments.',
            '',
            '### GAU Allocations',
            '- `npsp__Allocation__c` splits a donation across multiple `npsp__General_Accounting_Unit__c` records.',
            '- Allocation can be by amount (`npsp__Amount__c`) or percentage (`npsp__Percent__c`).',
            '- A default GAU can be set to capture unallocated portions automatically.',
            '- Rollup fields on GAU track total allocated across all donations.',
            '',
            '## Program Management',
            '',
            '### Program Definition',
            '- `Program__c` represents a discrete program with fields for description, status, start/end dates, and target population.',
            '- Link programs to funding sources via custom lookup or junction to Opportunity/Campaign.',
            '',
            '### Engagements',
            '- `ProgramEngagement__c` tracks a constituent participating in a program.',
            '- Key fields: `Contact__c`, `Program__c`, `Stage__c` (Applied, Active, Completed, Withdrawn), `StartDate__c`, `EndDate__c`.',
            '- Use Record-Triggered Flows to automate stage transitions and notifications.',
            '',
            '### Deliverables',
            '- `Deliverable__c` records individual service units (sessions, meals, hours) within an engagement.',
            '- Track quantity, date, provider, and completion status.',
            '- Roll up deliverable counts/hours to the Program Engagement for outcome reporting.',
            '',
            '### Outcome Management',
            '- Define measurable outcomes at the Program level (e.g., "employment rate at 6 months").',
            '- Track outcome data via custom fields on `ProgramEngagement__c` or a dedicated `Outcome__c` object.',
            '- Use CRM Analytics or Reports & Dashboards for outcome visualization.',
            '',
            '## Gift Entry',
            '',
            '### Gift Entry Manager',
            '- Native Salesforce feature replacing NPSP Batch Gift Entry.',
            '- Configure Gift Entry Templates in Setup → Nonprofit → Gift Entry.',
            '- Templates define which fields are visible, required, and defaulted during data entry.',
            '- Supports batch processing: import CSV or manual entry of multiple gifts in a single session.',
            '',
            '### Payment Integration',
            '- Integrate payment processors (Stripe, PayPal, Authorize.net) via Named Credentials and Apex callouts.',
            '- **Never store full credit card numbers in Salesforce** — use tokenized references only.',
            '- Map payment processor webhooks to Platform Events for real-time donation confirmation.',
            '- Use `npe01__Payment__c` (NPSP) or standard Payment object for tracking payment status.',
            '',
            '## Constituent Management',
            '',
            '### Households',
            '- Use standard Account with Household Record Type (not the deprecated `npo02__Household__c`).',
            '- Link household members via Account Contact Relationship or `npe4__Relationship__c`.',
            '- Set primary Contact for the household for greeting and communication defaults.',
            '',
            '### Relationships & Affiliations',
            '- `npe4__Relationship__c`: Contact-to-Contact relationships (spouse, sibling, employer/employee).',
            '- `npe5__Affiliation__c`: Contact-to-Organization affiliations (board member, volunteer, employee).',
            '- Both support reciprocal relationship types — define both directions.',
            '',
            '### Engagement Plans',
            '- `npsp__Engagement_Plan__c` templates define a series of tasks/activities for donor cultivation.',
            '- Assign plans to Contacts, Opportunities, or Campaigns to automate stewardship sequences.',
            '- Tasks created from plans inherit due dates relative to plan activation date.',
            '',
            '## Integration Patterns',
            '',
            '### Payment Processors',
            '- **Stripe:** Use Stripe Connect with Named Credential. Map `charge.succeeded` webhook to Platform Event.',
            '- **PayPal:** Use PayPal REST API via Named Credential. Map IPN notifications to inbound webhook handler.',
            '- Reconcile processor transactions against `Opportunity`/`Payment` records via scheduled batch Apex.',
            '',
            '### Wealth Screening',
            '- Integrate DonorSearch, WealthEngine, or iWave via REST API callouts.',
            '- Store screening results on Contact custom fields (e.g., `Wealth_Rating__c`, `Giving_Capacity__c`).',
            '- Schedule periodic re-screening via Batch Apex or Schedulable.',
            '',
            '### Marketing Platforms',
            '- Sync donor/constituent data to Mailchimp, Constant Contact, or Marketing Cloud.',
            '- Use middleware (MuleSoft, Zapier) or direct API integration via Named Credentials.',
            '- Map campaign membership and engagement metrics back to Salesforce Campaign Members.',
            '',
            '## Managed Package Safety (CRITICAL)',
            '- **`npsp__` namespace:** NPSP managed package objects and fields. Do NOT modify, rename, or delete.',
            '- **`npe__` / `npe01__` – `npe05__` namespaces:** NPSP extension packages (Payments, Relationships, Affiliations, Recurring Donations, Households).',
            '- **Do NOT add Apex triggers directly on NPSP managed objects** — use Record-Triggered Flows or custom extension objects.',
            '- **Do NOT override NPSP managed page layouts** — clone and assign to custom Record Types.',
            '- Before NPSP package upgrades: run `sf package version list` and review release notes for breaking changes.',
            '- Test package upgrades in a sandbox before promoting to production.',
            '',
            '## Security',
            '',
            '### Donor Data Privacy',
            '- Donor financial information (giving history, wealth screening) is sensitive — restrict via FLS and Permission Sets.',
            '- Use Sharing Rules or Criteria-Based Sharing for chapter/affiliate models where regional staff see only their constituents.',
            '- Enable **Data Classification** on fields containing PII (name, email, phone, address, giving history).',
            '',
            '### PCI Considerations',
            '- **Never store raw credit card numbers, CVV, or full bank account numbers in Salesforce.**',
            '- Use tokenized payment references from the processor (Stripe token, PayPal billing agreement ID).',
            '- If storing last-4 digits for display: use a text field with encryption at rest enabled.',
            '- Payment processing pages should use processor-hosted forms (Stripe Elements, PayPal buttons) — not custom LWC forms that handle raw card data.',
            '',
            '### Chapter/Affiliate Sharing Model',
            '- Use Territory Management or custom sharing rules for multi-chapter organizations.',
            '- Each chapter sees only their assigned Accounts/Contacts via OWD = Private + Sharing Rules by role or territory.',
            '- National office users get "View All" via Permission Set for cross-chapter reporting.',
            '- Audit sharing access quarterly — chapters merge, split, and change scope frequently.',
            '',
            '## Testing',
            '',
            '### Test Factories',
            '- Create a `NonprofitTestDataFactory` class with methods for:',
            '  - `createDonation(Contact donor, Decimal amount)` → Opportunity with Donation Record Type',
            '  - `createRecurringDonation(Contact donor, Decimal amount, String frequency)` → `npe03__Recurring_Donation__c`',
            '  - `createProgramEngagement(Contact participant, Program__c program)` → `ProgramEngagement__c`',
            '  - `createGAUAllocation(Opportunity donation, npsp__General_Accounting_Unit__c gau, Decimal amount)` → `npsp__Allocation__c`',
            '- Use `@TestSetup` for shared test data. Assign NPSP Permission Sets to test users.',
            '- NPSP triggers fire in test context — always query rollup fields after DML in the same transaction.',
            '- Mock payment processor callouts using `Test.setMock(HttpCalloutMock.class, ...)` pattern.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Nonprofit Cloud References',
            '- Nonprofit Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.nonprofit_cloud.meta/nonprofit_cloud/',
            '- NPSP Documentation: https://developer.salesforce.com/docs/atlas.en-us.npsp.meta/npsp/',
            '- Program Management Module: https://help.salesforce.com/s/articleView?id=sf.npc_program_management.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('nonprofit'),
            '',
            ...interactionPreferences('Nonprofit Cloud configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=nonprofit.js.map