================================================================================ DRAWBID - FUNDRAISING MODULE COMPLETE END-TO-END REPLICATION PACK ================================================================================ Generated : 2026-11-08 Source app : DrawBid Wallet Platform (drawbid.com) Module : Fundraising (FUNDRAISER campaign type + SME_INNOVATION shared engine) Purpose : everything needed to rebuild this module in another application - schema, backend contracts, full frontend source, business rules, flows, known defects and a replication checklist. This document embeds the ACTUAL SOURCE of every file listed, read directly from the source repository. Narrative sections explain intent, contracts and traps. CONTENTS PART 0 How to use this pack PART 1 Background and business context PART 2 Architecture and data planes PART 3 Data model - PostgreSQL DDL PART 4 Data model - entity schemas PART 5 Money flow and ledger semantics PART 6 Backend functions - contracts PART 7 Backend functions - source PART 8 Query gateway operations (supabaseQuery) PART 9 Frontend pages - source PART 10 Frontend components - source PART 11 Services, validation and helpers - source PART 12 Access control, idempotency and safety PART 13 Business rules, fees and formulas PART 14 End-to-end flows, step by step PART 15 Known defects and traps in the source module PART 16 Replication checklist for the new app PART 17 Dependencies, secrets and platform assumptions APPENDIX File inventory ================================================================================ PART 0 - HOW TO USE THIS PACK ================================================================================ Read in this order: 1. PART 1-2 to understand what the module does and how it is split across Supabase (data) and the application runtime (auth + functions). 2. PART 3 to stand up the database. The DDL blocks are copy-paste ready and are the foundation of everything else. 3. PART 5 to understand money movement BEFORE touching any function. Every mutation in this module ends in a wallet ledger entry, and getting that wrong is how balances drift. 4. PART 6-8 for the backend contracts, then PART 7 copies the implementations. 5. PART 9-11 for the UI. React + Tailwind + shadcn/ui. 6. PART 16 as the ordered build plan, and PART 15 to avoid the defects that exist in the source module. Two decisions must be made before you start (details in PART 16): - whether contributions live in Supabase only, or in both Supabase and the application entity store (the source app does both - see PART 15); - whether the 5 percent platform commission is hardcoded or configurable. ================================================================================ PART 1 - BACKGROUND AND BUSINESS CONTEXT ================================================================================ 1.1 What DrawBid is A multi-tenant platform where organisations run four campaign types: DRAW raffle / promotional draw with ticket entries AUCTION item auction with escrow settlement FUNDRAISER cause-based fundraising with a goal and beneficiaries SME_INNOVATION funding rounds for small business projects Participants hold a platform wallet with two balances: real cash (balance) and promotional credit (promo_balance). A wallet may also carry a reserved_balance for funds committed to a pending settlement. Only (balance - reserved_balance) is spendable. 1.2 What the fundraising module does It lets an organisation publish a cause campaign with a funding goal, a story, impact milestones, suggested contribution tiers and a beneficiary. Participants contribute from their wallet. Contributions accumulate against the goal. When the campaign closes, an administrator disburses the collected funds to the beneficiary wallet less a platform commission. After disbursement the beneficiary files fund usage reports, an administrator approves them, and approved reports become publicly visible on the campaign page as transparency. Three contribution mechanisms: 1. Direct donation participant pays from wallet (contributeFundraiser) 2. Matching donation a sponsor matches contributions up to a cap (processMatchingDonations) 3. Contribution tiers fixed packages, optionally bundled with a voucher or perk (campaign_contribution_tiers + voucher functions) Sponsors can also attach to a fundraiser as campaign sponsorships (cash, in-kind or matching), which is why the detail page renders sponsor cards. 1.3 Why it is built this way Fundraising shares its campaign shell, wallet, currency, notification, audit and gamification subsystems with the draw and auction products, so it reuses the Campaign record rather than owning a table. When replicating standalone you can (a) keep the shared campaign shell and add the fundraiser columns, or (b) extract a dedicated fundraisers table. Option (a) is lower risk: every flow below assumes a campaign record with type, status, currency, end_date and organisation_id. 1.4 Regulatory context Fundraising campaigns are NON_REGULATED on this platform: no gaming permit is required, unlike DRAW and gaming products. A platform-mode switch hides all gaming-board copy and badges when a deployment is not regulated. Take it along if you ship into a regulated market; otherwise drop it. ================================================================================ PART 2 - ARCHITECTURE AND DATA PLANES ================================================================================ 2.1 Two data planes PLANE A - Supabase (PostgreSQL). Single source of truth for queryable data: campaigns, contributions, vouchers, fund usage reports. PLANE B - Application backend. Authentication, session, and the serverless function runtime that performs privileged work. The rule enforced in the codebase: the entity store is NOT a second database for operational data. Reads go to Supabase; writes go through a gateway or a domain function that owns the transaction. 2.2 Frontend read and write paths Reads a. invoke(supabaseQuery, { operation, filters, pagination }) - server-side filtering, real pagination, RLS safe. b. the Supabase JS client directly for simple public reads. Writes a. invoke(supabaseWrite, payload) - audited generic write gateway. b. a domain function (contributeFundraiser, disburseFundraiserFunds, redeemVoucher, ...) when the write must be atomic with money movement, idempotency or notifications. This is the norm for anything touching a balance. 2.3 Server-side conventions - Each function is a Deno.serve handler at base44/functions/NAME/entry.ts - const base44 = createClientFromRequest(req); const user = await base44.auth.me(); - Privileged work uses base44.asServiceRole (bypasses row-level rules). - Money never writes a balance column directly: it goes through the wallet ledger function so a ledger row and the balance move together, with an idempotency key. - Cross-function calls use base44.asServiceRole.functions.invoke(name, payload). - Every mutating function emits an audit row and a notification. - Every function returns a correlation_id that is also written into the audit trail, so a support ticket can be traced end to end. 2.4 Component map Browser FundraiserBrowse / ProductFundraisers list and filter published fundraisers FundraiserDetail the campaign page, all sections SponsorFundraiserBrowse sponsor-side discovery AdminFundUsageReview admin approves usage reports components/fundraiser/* 14 presentational and dialog pieces components/campaign/FundraisersTab tab in the unified detail page Functions contributeFundraiser debit wallet, write contribution, bump total disburseFundraiserFunds admin payout to beneficiary minus commission processMatchingDonations sponsor match engine approveFundUsageReport transparency approval workflow notifyNewContribution notification fan-out recommendFundraisersForSponsors sponsor matching createVoucher / bulkCreateVouchers / issueVoucherToPurchaser / redeemVoucher / enforceVoucherUsageLimits processCampaignEndings closes campaigns, drives payout paths Data: campaigns, contributions, fundraiser_vouchers, fund_usage_reports, campaign_contribution_tiers, campaign_fund_reservations ================================================================================ PART 3 - DATA MODEL: POSTGRESQL DDL ================================================================================ 3.1 Campaign columns the module depends on (add if missing): ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS funding_goal_amount numeric(18,2); ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS current_raised_amount numeric(18,2) NOT NULL DEFAULT 0; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS funding_mode text NOT NULL DEFAULT 'FLEXIBLE'; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS funds_disbursed boolean NOT NULL DEFAULT false; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS disbursement_date timestamptz; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS recurrence_parent_id uuid; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS recurrence_frequency text NOT NULL DEFAULT 'NONE'; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS draw_mode text NOT NULL DEFAULT 'SINGLE'; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS description text; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS terms_text text; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS video_url text; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS public_results_enabled boolean NOT NULL DEFAULT true; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS entry_code_used boolean NOT NULL DEFAULT false; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS sme_business_plan_summary text; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS sme_target_market text; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS sme_industry text; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS fundraiser_category text; ALTER TABLE campaigns ADD COLUMN IF NOT EXISTS beneficiary_details jsonb NOT NULL DEFAULT '{}'::jsonb; 3.2 Core fundraiser tables -- contributions --------------------------------------------- CREATE TABLE IF NOT EXISTS contributions ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), campaign_id uuid NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, participant_id uuid REFERENCES participants(id), organisation_id uuid REFERENCES organisations(id), amount numeric(18,2) NOT NULL, currency text NOT NULL DEFAULT 'PGK', contribution_type text NOT NULL DEFAULT 'DIRECT', wallet_tx_id uuid, message text, anonymous boolean NOT NULL DEFAULT false, created_at timestamptz NOT NULL DEFAULT now() ); -- fundraiser_vouchers --------------------------------------- CREATE TABLE IF NOT EXISTS fundraiser_vouchers ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), campaign_id uuid NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, issued_to_participant_id uuid REFERENCES participants(id), voucher_code text UNIQUE NOT NULL, discount_amount numeric(18,2), value numeric(18,2), is_used boolean NOT NULL DEFAULT false, is_expired boolean NOT NULL DEFAULT false, used_at timestamptz, expires_at timestamptz, created_at timestamptz NOT NULL DEFAULT now() ); -- fund_usage_reports ---------------------------------------- CREATE TABLE IF NOT EXISTS fund_usage_reports ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), fundraiser_campaign_id uuid NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, organisation_id uuid REFERENCES organisations(id), submitted_by uuid REFERENCES participants(id), title text NOT NULL, period_label text, funds_used_amount numeric(18,2), status text NOT NULL DEFAULT 'SUBMITTED' CHECK (status IN ('SUBMITTED','UNDER_REVIEW','APPROVED','REJECTED')), notes text, created_at timestamptz NOT NULL DEFAULT now() ); -- campaign_contribution_tiers ------------------------------- -- campaign_contribution_tiers: definition not found -- campaign_fund_reservations -------------------------------- CREATE TABLE IF NOT EXISTS campaign_fund_reservations ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), campaign_id uuid NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, wallet_account_id uuid NOT NULL REFERENCES wallet_accounts(id), organisation_id uuid REFERENCES organisations(id), amount numeric(18,2) NOT NULL, currency text NOT NULL DEFAULT 'PGK', status text NOT NULL DEFAULT 'ACTIVE' CHECK (status IN ('ACTIVE','RELEASED','CLAIMED')), released_at timestamptz, created_at timestamptz NOT NULL DEFAULT now() ); -- project_reports ------------------------------------------- CREATE TABLE IF NOT EXISTS project_reports ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), campaign_id uuid NOT NULL REFERENCES campaigns(id) ON DELETE CASCADE, organisation_id uuid REFERENCES organisations(id), submitted_by_participant_id uuid REFERENCES participants(id), report_type text NOT NULL DEFAULT 'PROGRESS_UPDATE', title text NOT NULL, period_label text, summary text, status text NOT NULL DEFAULT 'SUBMITTED' CHECK (status IN ('SUBMITTED','UNDER_REVIEW','APPROVED','REJECTED','REQUIRES_REVISION')), visibility text NOT NULL DEFAULT 'PUBLIC' CHECK (visibility IN ('PUBLIC','ADMIN_ONLY')), is_project_complete boolean NOT NULL DEFAULT false, funds_used_amount numeric(18,2), annual_revenue numeric(18,2), annual_expenses numeric(18,2), annual_profit numeric(18,2), employee_count integer, reviewer_notes text, reviewed_by text, reviewed_at timestamptz, created_at timestamptz NOT NULL DEFAULT now() ); 3.3 campaigns table (abridged structural context) -- campaigns: definition not found 3.4 Schema notes - Money is numeric(18,2) everywhere. Never float. - currency is denormalised onto every money row; org default PGK. Validate against the org default at write time. - contributions carries both participant_id and organisation_id so a row can be scoped either way. Anonymous contributions KEEP participant_id and only hide the name at render time - nulling it breaks refunds. - contributions.contribution_type distinguishes DIRECT from matched rows and tier purchases; it defaults to DIRECT. - wallet_tx_id is nullable and links a contribution back to the exact ledger entry for reconciliation. - fundraiser_vouchers carries both discount_amount and value because a voucher may be a discount or a stored-value perk. - fund_usage_reports.status is the transparency state machine: SUBMITTED -> UNDER_REVIEW -> APPROVED / REJECTED. - campaign_contribution_tiers is the queryable form of the JSON tier array that older campaigns still carry inline. - campaign_fund_reservations status enum (ACTIVE, RELEASED, CLAIMED) mirrors the ledger transaction types of the same names. ================================================================================ PART 4 - DATA MODEL: ENTITY SCHEMAS ================================================================================ Application-layer entity definitions used by the backend functions. If you move fully to Supabase, treat them as the field contract to mirror in tables and types. -------------------------------------------------------------------------------- FILE: base44/entities/Contribution.jsonc LINES: 58 NOTE: Contributor record rendered on the campaign page. -------------------------------------------------------------------------------- { "name": "Contribution", "type": "object", "properties": { "campaign_id": { "type": "string", "description": "Fundraiser campaign reference" }, "organisation_id": { "type": "string", "description": "Organisation reference" }, "participant_id": { "type": "string", "description": "Contributor participant" }, "amount": { "type": "number", "description": "Contribution amount" }, "supporter_name": { "type": "string", "description": "Name of the supporter (for display)" }, "is_anonymous": { "type": "boolean", "default": false, "description": "Hide contributor name publicly" }, "message": { "type": "string", "description": "Optional message from contributor" }, "reward_tier_id": { "type": "string", "description": "Optional reward tier selected" }, "wallet_transaction_id": { "type": "string", "description": "Related wallet transaction" }, "status": { "type": "string", "enum": [ "COMPLETED", "REFUNDED" ], "default": "COMPLETED", "description": "Contribution status" } }, "required": [ "campaign_id", "organisation_id", "participant_id", "amount" ] } -------------------------------------------------------------------------------- FILE: base44/entities/FundUsageReport.jsonc LINES: 119 NOTE: Beneficiary transparency report. -------------------------------------------------------------------------------- { "name": "FundUsageReport", "type": "object", "properties": { "fundraiser_campaign_id": { "type": "string", "description": "Fundraiser campaign reference" }, "organisation_id": { "type": "string", "description": "Organisation reference" }, "beneficiary_participant_id": { "type": "string", "description": "Beneficiary participant ID" }, "report_title": { "type": "string", "description": "Report title" }, "description_of_use": { "type": "string", "description": "Detailed description of fund usage" }, "amount_used": { "type": "number", "description": "Amount covered in this report" }, "supporting_documents_urls": { "type": "array", "items": { "type": "string" }, "description": "Receipts, photos, invoices" }, "date_reported": { "type": "string", "format": "date-time", "description": "Report submission date" }, "status": { "type": "string", "enum": [ "PENDING_REVIEW", "APPROVED", "REJECTED", "REQUIRES_REVISION" ], "default": "PENDING_REVIEW", "description": "Report status" }, "reviewer_id": { "type": "string", "description": "Admin who reviewed" }, "reviewed_at": { "type": "string", "format": "date-time", "description": "Review timestamp" }, "reviewer_notes": { "type": "string", "description": "Admin review notes" }, "visibility": { "type": "string", "enum": [ "PUBLIC", "SPONSORS_ONLY", "PRIVATE" ], "default": "PUBLIC", "description": "Who can view this report" } }, "required": [ "fundraiser_campaign_id", "organisation_id", "beneficiary_participant_id", "report_title", "amount_used" ], "rls": { "read": { "$or": [ { "created_by_id": "{{user.id}}" }, { "user_condition": { "role": "admin" } } ] }, "create": { "$or": [ { "created_by_id": "{{user.id}}" }, { "user_condition": { "role": "admin" } } ] }, "update": { "user_condition": { "role": "admin" } }, "delete": { "user_condition": { "role": "admin" } } } } -------------------------------------------------------------------------------- FILE: base44/entities/FundraiserVoucher.jsonc LINES: 90 NOTE: Perk voucher issued to a contributor. -------------------------------------------------------------------------------- { "name": "FundraiserVoucher", "type": "object", "properties": { "campaign_id": { "type": "string", "description": "Fundraiser campaign reference" }, "organisation_id": { "type": "string", "description": "Organisation reference" }, "sponsor_id": { "type": "string", "description": "Sponsor who provided the voucher" }, "product_name": { "type": "string", "description": "Name of the product/service (e.g., 'Dish Kaikai + Drinks')" }, "description": { "type": "string", "description": "Detailed description of the offering" }, "value": { "type": "number", "description": "Monetary value of the voucher" }, "unique_code": { "type": "string", "description": "Unique redeemable code" }, "status": { "type": "string", "enum": [ "AVAILABLE", "ISSUED", "REDEEMED", "EXPIRED" ], "default": "AVAILABLE", "description": "Voucher status" }, "issued_to_participant_id": { "type": "string", "description": "Participant who received/purchased the voucher" }, "issued_at": { "type": "string", "format": "date-time", "description": "When voucher was issued to participant" }, "redeemed_at": { "type": "string", "format": "date-time", "description": "When voucher was redeemed" }, "redeemed_by": { "type": "string", "description": "Admin/organizer who marked as redeemed" }, "expires_at": { "type": "string", "format": "date-time", "description": "Expiration date" }, "redemption_instructions": { "type": "string", "description": "How to redeem the voucher" }, "quantity_available": { "type": "number", "default": 1, "description": "How many of this voucher type are available" }, "quantity_issued": { "type": "number", "default": 0, "description": "How many have been issued" } }, "required": [ "campaign_id", "organisation_id", "sponsor_id", "product_name", "value", "unique_code" ] } -------------------------------------------------------------------------------- FILE: base44/entities/CampaignSponsorship.jsonc LINES: 140 NOTE: Sponsor attachment including MATCHING_DONATION. -------------------------------------------------------------------------------- { "name": "CampaignSponsorship", "type": "object", "properties": { "campaign_id": { "type": "string", "description": "Campaign reference" }, "sponsor_id": { "type": "string", "description": "Sponsor reference" }, "organisation_id": { "type": "string", "description": "Organisation reference" }, "campaign_type": { "type": "string", "enum": [ "DRAW", "FUNDRAISER", "SME_INNOVATION", "AUCTION" ], "description": "Type of campaign being sponsored" }, "sponsorship_type": { "type": "string", "enum": [ "DIRECT_CONTRIBUTION", "PRIZE_DONATION", "PROMOTIONAL_SUPPORT", "MATCHING_DONATION" ], "description": "Type of sponsorship" }, "amount": { "type": "number", "description": "Monetary contribution amount" }, "prize_details": { "type": "object", "description": "Details of donated prize", "properties": { "name": { "type": "string" }, "description": { "type": "string" }, "estimated_value": { "type": "number" }, "image_url": { "type": "string" } } }, "matching_ratio": { "type": "number", "description": "For matching donations (e.g., 1.0 = 1:1 match)" }, "matching_cap": { "type": "number", "description": "Maximum amount to match" }, "visibility": { "type": "string", "enum": [ "PUBLIC", "ANONYMOUS" ], "default": "PUBLIC", "description": "Sponsor visibility preference" }, "status": { "type": "string", "enum": [ "PENDING", "ACTIVE", "COMPLETED", "CANCELLED" ], "default": "PENDING", "description": "Sponsorship status" }, "commitment_date": { "type": "string", "format": "date-time", "description": "Date sponsorship was committed" }, "fulfilled_date": { "type": "string", "format": "date-time", "description": "Date sponsorship was fulfilled" }, "impact_metrics": { "type": "object", "description": "Sponsorship impact tracking", "properties": { "campaign_views": { "type": "number", "default": 0 }, "campaign_conversions": { "type": "number", "default": 0 }, "total_raised_attributed": { "type": "number", "default": 0 }, "participant_count": { "type": "number", "default": 0 } } }, "recognition_level": { "type": "string", "enum": [ "BRONZE", "SILVER", "GOLD", "PLATINUM" ], "description": "Sponsor recognition based on contribution" }, "notes": { "type": "string", "description": "Additional notes" } }, "required": [ "campaign_id", "sponsor_id", "organisation_id", "sponsorship_type" ] } 4.5 Campaign fields used by the fundraiser product (extracted) "type": "object",, "funding_goal_amount": { "type": "number", "description": "Target amount to raise (for FUNDRAISER type)" },, "current_raised_amount": { "type": "number", "default": 0, "description": "Current amount raised (for FUNDRAISER type)" },, "funding_mode": { "type": "string", "enum": [ "ALL_OR_NOTHING", "FLEXIBLE" ], "default": "FLEXIBLE", "description": "Funding disbursement mode (for FUNDRAISER type)" },, "beneficiary_details": { "type": "object", "description": "Beneficiary information (for FUNDRAISER type)", "properties": { "name": { "type": "string" }, "contact_email": { "type": "string" }, "contact_phone": { "type": "string" }, "story": { "type": "string" }, "participant_id": { "type": "string" } } },, "funds_disbursed": { "type": "boolean", "default": false, "description": "Whether funds have been disbursed to beneficiary" },, "disbursement_date": { "type": "string", "format": "date-time", "description": "Date funds were disbursed" },, "contribution_options_json": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "amount": { "type": "number" }, "description": { "type": "string" }, "includes_voucher": { "type": "boolean" }, "voucher_product": { "type": "string" } } }, "description": "Predefined contribution packages" },, "fundraiser_category": { "type": "string", "enum": [ "MEDICAL", "EDUCATION", "DISASTER", "BUSINESS_IDEA", "COMMUNITY", "OTHER" ], "description": "Fundraiser category (for FUNDRAISER type)" }, The complete Campaign entity schema follows for reference. -------------------------------------------------------------------------------- FILE: base44/entities/Campaign.jsonc LINES: 608 NOTE: Full shared campaign entity. -------------------------------------------------------------------------------- { "name": "Campaign", "type": "object", "properties": { "organisation_id": { "type": "string", "description": "Organisation reference", "index": true }, "type": { "type": "string", "enum": [ "DRAW", "AUCTION", "FUNDRAISER", "SME_INNOVATION" ], "description": "Campaign type", "index": true }, "product_subtype": { "type": "string", "enum": [ "STANDARD_DRAW", "INSTANT_WIN", "LIVE_DRAW_EVENT", "DAILY_NUMBER_PICK", null ], "description": "Specific product subtype for DRAW campaigns" }, "regulatory_category": { "type": "string", "enum": [ "REGULATED", "NON_REGULATED" ], "description": "Whether campaign requires PNG Gaming Board approval", "index": true }, "entry_code": { "type": "string", "description": "Short alphanumeric code for SMS/WhatsApp entry (e.g. DBD-X8K7). Used by phone participants to enter via TICKET .", "index": true }, "is_sealed_bid_tender": { "type": "boolean", "default": false, "description": "Whether this AUCTION is a sealed bid tender (bids hidden until close)" }, "tender_evaluation_criteria": { "type": "string", "description": "Evaluation criteria for sealed bid tenders" }, "tender_bank_account": { "type": "object", "description": "Bank account for tender notifications", "properties": { "bank_name": { "type": "string" }, "account_number": { "type": "string" }, "account_name": { "type": "string" }, "email": { "type": "string" } } }, "tender_contract_template_url": { "type": "string", "description": "URL to contract template for auto-generation" }, "title": { "type": "string", "description": "Campaign title" }, "subtitle": { "type": "string", "description": "Campaign subtitle" }, "description": { "type": "string", "description": "Full description with rich text HTML" }, "banner_image_url": { "type": "string", "description": "Banner image" }, "video_url": { "type": "string", "description": "Campaign video URL (YouTube, Vimeo, or direct link)" }, "images_json": { "type": "array", "items": { "type": "object", "properties": { "url": { "type": "string" }, "section": { "type": "string" }, "caption": { "type": "string" } } }, "description": "Additional campaign images with sections" }, "status": { "type": "string", "enum": [ "DRAFT", "PUBLISHED", "ONGOING", "CLOSED", "DRAW_COMPLETED", "ARCHIVED" ], "default": "DRAFT", "description": "Campaign status", "index": true }, "visibility": { "type": "string", "enum": [ "PUBLIC", "PRIVATE" ], "default": "PUBLIC", "description": "Public or Private campaign" }, "invited_participant_ids": { "type": "array", "items": { "type": "string" }, "description": "List of participant IDs invited to private campaigns" }, "start_date": { "type": "string", "format": "date-time", "description": "Start date" }, "end_date": { "type": "string", "format": "date-time", "description": "End date", "index": true }, "draw_date": { "type": "string", "format": "date-time", "description": "Scheduled draw date", "index": true }, "currency": { "type": "string", "description": "Currency" }, "entry_price": { "type": "number", "description": "Ticket price for draws" }, "ticket_capacity": { "type": "number", "description": "Maximum tickets" }, "max_entries_per_user": { "type": "number", "description": "Max tickets per user" }, "terms_text": { "type": "string", "description": "Terms and conditions" }, "public_results_enabled": { "type": "boolean", "default": true, "description": "Show results publicly" }, "draw_trigger_mode": { "type": "string", "enum": [ "MANUAL", "AUTO" ], "default": "MANUAL", "description": "Draw trigger mode" }, "payout_mode": { "type": "string", "enum": [ "FIXED", "PERCENT_OF_SALES", "HYBRID" ], "default": "PERCENT_OF_SALES", "description": "Payout calculation mode" }, "payout_winners_percentage": { "type": "number", "default": 0.7, "description": "Winner percentage (e.g. 0.70 = 70%)" }, "payout_admin_percentage": { "type": "number", "default": 0.3, "description": "Admin percentage (e.g. 0.30 = 30%)" }, "min_prize_pool_amount": { "type": "number", "description": "Minimum guaranteed prize pool" }, "total_sales_amount": { "type": "number", "default": 0, "description": "Total sales (calculated)" }, "total_entries_count": { "type": "number", "default": 0, "description": "Total entries sold" }, "redraw_policy_json": { "type": "object", "description": "Redraw policy configuration" }, "eligibility_rules_json": { "type": "object", "description": "Eligibility rules" }, "draw_mode": { "type": "string", "enum": [ "SINGLE", "RECURRING" ], "default": "SINGLE", "description": "Draw mode" }, "recurrence_frequency": { "type": "string", "enum": [ "NONE", "WEEKLY", "MONTHLY", "CUSTOM", "DAILY" ], "default": "NONE", "description": "Recurrence frequency" }, "recurrence_parent_id": { "type": "string", "description": "Parent campaign for recurring draws" }, "ai_generated": { "type": "boolean", "default": false, "description": "Whether campaign was AI-generated" }, "awaiting_approval": { "type": "boolean", "default": false, "description": "Whether AI-generated campaign awaits admin approval" }, "ai_prompt": { "type": "string", "description": "Original AI prompt used to generate campaign" }, "regulatory_permit_number": { "type": "string", "description": "Regulatory permit number if required" }, "regulatory_status": { "type": "string", "enum": [ "NONE", "PENDING_APPROVAL", "APPROVED", "REJECTED", "SUSPENDED" ], "default": "NONE", "description": "Regulatory approval status" }, "regulatory_approval_date": { "type": "string", "format": "date", "description": "Regulatory approval date" }, "regulatory_permit_valid_from": { "type": "string", "format": "date", "description": "Permit validity start" }, "regulatory_permit_valid_to": { "type": "string", "format": "date", "description": "Permit validity end" }, "regulatory_notes": { "type": "string", "description": "Regulatory notes" }, "instant_win_config": { "type": "object", "description": "Config for INSTANT_WIN campaigns", "properties": { "total_cards": { "type": "number" }, "winning_percentage": { "type": "number" }, "cards_generated": { "type": "boolean", "default": false } } }, "live_draw_config": { "type": "object", "description": "Config for LIVE_DRAW_EVENT campaigns", "properties": { "stream_provider": { "type": "string", "enum": [ "YOUTUBE", "TWITCH", "CUSTOM" ] }, "stream_url": { "type": "string" }, "schedule_timezone": { "type": "string" } } }, "number_pick_config": { "type": "object", "description": "Config for DAILY_NUMBER_PICK campaigns", "properties": { "number_range_min": { "type": "number" }, "number_range_max": { "type": "number" }, "numbers_to_pick": { "type": "number" }, "draw_time_utc": { "type": "string" }, "prize_tiers_json": { "type": "array" } } }, "fundraiser_category": { "type": "string", "enum": [ "MEDICAL", "EDUCATION", "DISASTER", "BUSINESS_IDEA", "COMMUNITY", "OTHER" ], "description": "Fundraiser category (for FUNDRAISER type)" }, "funding_goal_amount": { "type": "number", "description": "Target amount to raise (for FUNDRAISER type)" }, "current_raised_amount": { "type": "number", "default": 0, "description": "Current amount raised (for FUNDRAISER type)" }, "funding_mode": { "type": "string", "enum": [ "ALL_OR_NOTHING", "FLEXIBLE" ], "default": "FLEXIBLE", "description": "Funding disbursement mode (for FUNDRAISER type)" }, "beneficiary_details": { "type": "object", "description": "Beneficiary information (for FUNDRAISER type)", "properties": { "name": { "type": "string" }, "contact_email": { "type": "string" }, "contact_phone": { "type": "string" }, "story": { "type": "string" }, "participant_id": { "type": "string" } } }, "funds_disbursed": { "type": "boolean", "default": false, "description": "Whether funds have been disbursed to beneficiary" }, "disbursement_date": { "type": "string", "format": "date-time", "description": "Date funds were disbursed" }, "contribution_options_json": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "amount": { "type": "number" }, "description": { "type": "string" }, "includes_voucher": { "type": "boolean" }, "voucher_product": { "type": "string" } } }, "description": "Predefined contribution packages" }, "contact_info_json": { "type": "object", "description": "Contact information for direct communication", "properties": { "whatsapp": { "type": "string" }, "phone": { "type": "string" }, "email": { "type": "string" } } }, "event_details_json": { "type": "object", "description": "Event logistics for fundraisers", "properties": { "date": { "type": "string" }, "time": { "type": "string" }, "location": { "type": "string" }, "venue_details": { "type": "string" } } }, "sme_business_plan_summary": { "type": "string", "description": "Executive summary of business plan (for SME_INNOVATION type)" }, "sme_target_market": { "type": "string", "description": "Target market description (for SME_INNOVATION type)" }, "sme_team_json": { "type": "array", "items": { "type": "object", "properties": { "name": { "type": "string" }, "role": { "type": "string" }, "bio": { "type": "string" }, "image_url": { "type": "string" } } }, "description": "Team members (for SME_INNOVATION type)" }, "sme_milestones_json": { "type": "array", "items": { "type": "object", "properties": { "title": { "type": "string" }, "description": { "type": "string" }, "target_date": { "type": "string" }, "funding_required": { "type": "number" }, "status": { "type": "string", "enum": [ "PENDING", "IN_PROGRESS", "COMPLETED" ] }, "completion_date": { "type": "string" } } }, "description": "Business milestones (for SME_INNOVATION type)" }, "sme_perks_json": { "type": "array", "items": { "type": "object", "properties": { "tier_name": { "type": "string" }, "min_contribution": { "type": "number" }, "description": { "type": "string" }, "rewards": { "type": "array", "items": { "type": "string" } } } }, "description": "Contributor perks tiers (for SME_INNOVATION type)" }, "sme_industry": { "type": "string", "enum": [ "TECHNOLOGY", "AGRICULTURE", "MANUFACTURING", "SERVICES", "RETAIL", "HEALTHCARE", "EDUCATION", "OTHER" ], "description": "Industry sector (for SME_INNOVATION type)" }, "subscription_enabled": { "type": "boolean", "default": false, "description": "Whether participants can subscribe to auto-enter this campaign" }, "subscription_min_tickets": { "type": "number", "default": 1, "description": "Minimum tickets per subscription entry" }, "subscription_max_tickets": { "type": "number", "default": 10, "description": "Maximum tickets per subscription entry" } }, "required": [ "organisation_id", "type", "title", "regulatory_category" ] } ================================================================================ PART 5 - MONEY FLOW AND LEDGER SEMANTICS ================================================================================ 5.1 The one invariant A wallet balance only changes inside the wallet ledger function, and every call carries an idempotency_key. Everything else is bookkeeping around it. invoke(createWalletTransaction, { wallet_account_id, participant_id, organisation_id, transaction_type, direction, amount, description, related_campaign_id, idempotency_key, metadata }) returns { success, transaction_id, new_balance } or { success: false, duplicate: true } when the key was already used. 5.2 Contribution (money in) actor participant, authenticated direction DEBIT from the participant wallet type CAMPAIGN_FUNDS_RESERVED amount contribution amount in the wallet currency key contrib---- effect wallet.balance down, ledger row, contribution row, campaigns.current_raised_amount up. Naming caveat: the type says RESERVED but this path debits immediately. reserved_balance belongs to other products (auction escrow, draw holds). Treat the type as "campaign money", or rename it CAMPAIGN_CONTRIBUTION in your rebuild for clarity. 5.3 Disbursement (money out) actor administrator only direction CREDIT to the beneficiary wallet type CAMPAIGN_FUNDS_CLAIMED gross campaigns.current_raised_amount fee gross * 0.05 (platform commission, hardcoded) net gross - fee (this is credited) key disburse- guards funds_disbursed false, gross > 0, beneficiary wallet exists effect beneficiary balance up by net, TransactionFee row for the commission, funds_disbursed true, disbursement_date stamped, notification, AuditLog with gross / fee / net / correlation id. SME_INNOVATION credits the ORGANISATION wallet. FUNDRAISER credits the participant in campaigns.beneficiary_details.participant_id. 5.4 Matching donations For each ACTIVE CampaignSponsorship with sponsorship_type MATCHING_DONATION: matched_so_far = sum of contributions tagged metadata.matched_by_sponsorship_id = sponsorship.id remaining_cap = matching_cap - matched_so_far match_amount = min(contribution.amount * matching_ratio, remaining_cap) If match_amount > 0 a mirrored Contribution is created with supporter_name " (Matching Donation)", no wallet movement (the sponsor is billed through the sponsorship), and current_raised_amount rises by match_amount. The original contributor is notified that their gift was matched. 5.5 Worked example Goal 10000 PGK. A participant gives 100. A sponsor with ratio 2.0 and a cap of 1000 is active. participant wallet -100.00 ledger CAMPAIGN_FUNDS_RESERVED / DEBIT contributions row +100.00 DIRECT matched row +200.00 no wallet movement current_raised_amount 0 -> 300 Closes at 11300. Admin disburses: gross 11300.00, fee 565.00, net 10735.00. beneficiary wallet +10735.00 ledger CAMPAIGN_FUNDS_CLAIMED / CREDIT TransactionFee 565.00 PLATFORM_FEE ================================================================================ PART 6 - BACKEND FUNCTIONS: CONTRACTS ================================================================================ Implement these signatures first, then port the bodies from PART 7. 6.1 contributeFundraiser auth required (participant) input { campaignId | campaign_id, amount, contributionType?, notes? } output { success, contribution_id, amount, currency, new_balance, campaign_id, correlation_id } errors 401 unauthenticated 400 campaignId and amount required 404 Campaign not found / Participant not found / Wallet not found 400 Campaign does not accept contributions 400 Fundraiser is not accepting contributions 403 You are currently self-excluded. 400 Insufficient balance { available, required } 409 Duplicate contribution detected 500 unexpected 6.2 disburseFundraiserFunds auth admin only input { campaignId } output { success, campaign_id, beneficiary_id, gross_amount, platform_fee, net_disbursed, currency, new_balance, correlation_id } errors 403 Admin access required 400 campaignId required 404 Campaign / beneficiary / wallet not found 400 Campaign does not support fund disbursement 409 Funds already disbursed { disbursement_date } 400 No funds to disburse 400 Failed to credit beneficiary wallet 6.3 processMatchingDonations auth service / internal input { campaign_id, contribution_id } output { success, matched, matches[], total_matched } match { sponsorship_id, sponsor_name, match_amount, contribution_id } 6.4 approveFundUsageReport auth authenticated admin reviewer input { report_id, action: APPROVE | REJECT, reviewer_notes?, visibility: PUBLIC | PRIVATE } rules only PENDING_REVIEW reports; a rejection forces visibility PRIVATE. 6.5 notifyNewContribution fans out to the owning organisation and the contributor; idempotent per contribution id. 6.6 recommendFundraisersForSponsors scores open fundraisers against a sponsor profile (category, goal size, remaining gap, sponsorship history) and returns ranked matches. 6.7 Vouchers createVoucher { campaign_id, value | discount_amount, expires_at } bulkCreateVouchers { campaign_id, count, value, expires_at } issueVoucherToPurchaser { contribution_id | participant_id, campaign_id } redeemVoucher { voucher_code } enforceVoucherUsageLimits one-per-participant, expiry, campaign scoping. ================================================================================ PART 7 - BACKEND FUNCTIONS: SOURCE ================================================================================ Deno handlers; deploy each as its own function named after its folder. Pin one consistent SDK version in your rebuild (the source mixes 0.8.4 / 0.8.6 / 0.8.25). -------------------------------------------------------------------------------- FILE: base44/functions/contributeFundraiser/entry.ts (153 lines) NOTE: Money in: wallet debit, contribution row, campaign total, notification, tier and badge hooks. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.25'; /** * Contribute to a fundraiser campaign. * Uses createWalletTransaction for proper ledger entries. * Idempotent: deduplicates same participant + amount within 10 seconds. */ Deno.serve(async (req) => { const correlationId = crypto.getRandomValues(new Uint8Array(8)).reduce((a, b) => a + b.toString(16), ''); try { const base44 = createClientFromRequest(req); const user = await base44.auth.me(); if (!user) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } const body = await req.json(); // Support both camelCase (campaignId) and snake_case (campaign_id) from different callers const campaignId = body.campaignId || body.campaign_id; const amount = body.amount; const contributionType = body.contributionType || body.contribution_type; const notes = body.notes || body.message; if (!campaignId || !amount || amount <= 0) { return Response.json({ error: 'campaignId and amount required' }, { status: 400 }); } // Get campaign const campaigns = await base44.asServiceRole.entities.Campaign.filter({ id: campaignId }); if (campaigns.length === 0) { return Response.json({ error: 'Campaign not found' }, { status: 404 }); } const campaign = campaigns[0]; if (campaign.type !== 'FUNDRAISER' && campaign.type !== 'SME_INNOVATION') { return Response.json({ error: 'Campaign does not accept contributions' }, { status: 400 }); } if (campaign.status !== 'PUBLISHED' && campaign.status !== 'ONGOING') { return Response.json({ error: 'Fundraiser is not accepting contributions' }, { status: 400 }); } // Get participant const participants = await base44.asServiceRole.entities.Participant.filter( { user_email: user.email, organisation_id: campaign.organisation_id }, null, 1 ); if (participants.length === 0) { return Response.json({ error: 'Participant not found' }, { status: 404 }); } const participant = participants[0]; // Self-exclusion check const rgSettings = await base44.asServiceRole.entities.ResponsibleGaming.filter({ participant_id: participant.id }); if (rgSettings.length > 0 && rgSettings[0].self_excluded) { const exclusionEnd = rgSettings[0].self_exclusion_end ? new Date(rgSettings[0].self_exclusion_end) : null; if (!exclusionEnd || new Date() < exclusionEnd) { return Response.json({ error: 'You are currently self-excluded.', self_excluded: true }, { status: 403 }); } } // Get wallet const wallets = await base44.asServiceRole.entities.WalletAccount.filter({ participant_id: participant.id, wallet_type: 'PARTICIPANT' }); if (wallets.length === 0) { return Response.json({ error: 'Wallet not found' }, { status: 404 }); } const wallet = wallets[0]; // Available balance check const availableBalance = (wallet.balance || 0) - (wallet.reserved_balance || 0); if (availableBalance < amount) { return Response.json({ error: 'Insufficient balance', available: availableBalance, required: amount }, { status: 400 }); } // Idempotency: prevent duplicate contribution within 10 seconds const idempotencyKey = `contrib-${campaignId}-${participant.id}-${amount}-${Math.floor(Date.now() / 10000)}`; // Debit wallet via createWalletTransaction const txResult = await base44.asServiceRole.functions.invoke('createWalletTransaction', { wallet_account_id: wallet.id, participant_id: participant.id, organisation_id: campaign.organisation_id, transaction_type: 'CAMPAIGN_FUNDS_RESERVED', direction: 'DEBIT', amount, description: `Contribution to "${campaign.title}"${notes ? ': ' + notes : ''}`, related_campaign_id: campaignId, idempotency_key: idempotencyKey, metadata: { contribution_type: contributionType || 'DONATION', notes, correlation_id: correlationId } }); if (!txResult.data?.success) { if (txResult.data?.duplicate) { return Response.json({ error: 'Duplicate contribution detected', error_code: 'DUPLICATE', correlation_id: correlationId }, { status: 409 }); } return Response.json({ error: 'Failed to process contribution', details: txResult.data }, { status: 400 }); } // Create contribution record const contribution = await base44.asServiceRole.entities.Contribution.create({ campaign_id: campaignId, participant_id: participant.id, organisation_id: campaign.organisation_id, amount, currency: wallet.currency, contribution_type: contributionType || 'DONATION', notes: notes || '', message: notes || '', supporter_name: `${participant.first_name || ''} ${participant.last_name || ''}`.trim() || user.email, status: 'COMPLETED', wallet_transaction_id: txResult.data.transaction_id, contributed_at: new Date().toISOString() }); // Update campaign raised amount await base44.asServiceRole.entities.Campaign.update(campaignId, { current_raised_amount: (campaign.current_raised_amount || 0) + amount }); // Notify participant await base44.asServiceRole.entities.Notification.create({ organisation_id: campaign.organisation_id, participant_id: participant.id, type: 'SYSTEM', title: '💚 Contribution Received', message: `Thank you! Your contribution of ${wallet.currency} ${amount.toLocaleString()} to "${campaign.title}" has been processed.`, priority: 'MEDIUM' }); // Tier & badge update try { await base44.asServiceRole.functions.invoke('calculateTierProgress', { participant_id: participant.id }); await base44.asServiceRole.functions.invoke('checkBadgeEligibility', { participant_id: participant.id, organisation_id: campaign.organisation_id }); } catch (_) {} return Response.json({ success: true, contribution_id: contribution.id, amount, currency: wallet.currency, new_balance: txResult.data.new_balance, campaign_id: campaignId, correlation_id: correlationId }); } catch (error) { console.error('Contribution error:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/disburseFundraiserFunds/entry.ts (168 lines) NOTE: Money out: admin payout, 5 percent commission, fee tracking, audit. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.25'; /** * Admin-only: Disburse collected fundraiser funds to the beneficiary's wallet. * Uses createWalletTransaction for proper ledger credit. * Idempotent: campaign.funds_disbursed flag prevents double disbursement. */ Deno.serve(async (req) => { const correlationId = crypto.getRandomValues(new Uint8Array(8)).reduce((a, b) => a + b.toString(16), ''); try { const base44 = createClientFromRequest(req); const user = await base44.auth.me(); if (!user || user.role !== 'admin') { return Response.json({ error: 'Admin access required' }, { status: 403 }); } const { campaignId } = await req.json(); if (!campaignId) { return Response.json({ error: 'campaignId required' }, { status: 400 }); } // Get campaign const campaigns = await base44.asServiceRole.entities.Campaign.filter({ id: campaignId }); if (campaigns.length === 0) { return Response.json({ error: 'Campaign not found' }, { status: 404 }); } const campaign = campaigns[0]; if (campaign.type !== 'FUNDRAISER' && campaign.type !== 'SME_INNOVATION') { return Response.json({ error: 'Campaign does not support fund disbursement' }, { status: 400 }); } // Idempotency: block if already disbursed if (campaign.funds_disbursed) { return Response.json({ error: 'Funds already disbursed', disbursement_date: campaign.disbursement_date }, { status: 409 }); } const disbursementAmount = campaign.current_raised_amount || 0; if (disbursementAmount <= 0) { return Response.json({ error: 'No funds to disburse' }, { status: 400 }); } // For SME_INNOVATION: disburse to organisation wallet; for FUNDRAISER: disburse to beneficiary participant wallet let wallet, beneficiary; if (campaign.type === 'SME_INNOVATION') { // Funds go to the org wallet const orgWallets = await base44.asServiceRole.entities.WalletAccount.filter({ organisation_id: campaign.organisation_id, wallet_type: 'ORGANISATION' }); if (orgWallets.length === 0) { return Response.json({ error: 'Organisation wallet not found' }, { status: 404 }); } wallet = orgWallets[0]; beneficiary = { id: null, email: `org:${campaign.organisation_id}` }; } else { // Fundraiser: beneficiary is a participant const beneficiaryId = campaign.beneficiary_details?.participant_id; if (!beneficiaryId) { return Response.json({ error: 'No beneficiary configured for this fundraiser' }, { status: 400 }); } const beneficiaries = await base44.asServiceRole.entities.Participant.filter({ id: beneficiaryId }); if (beneficiaries.length === 0) { return Response.json({ error: 'Beneficiary participant not found' }, { status: 404 }); } beneficiary = beneficiaries[0]; const wallets = await base44.asServiceRole.entities.WalletAccount.filter({ participant_id: beneficiary.id, wallet_type: 'PARTICIPANT' }); if (wallets.length === 0) { return Response.json({ error: 'Beneficiary wallet not found' }, { status: 404 }); } wallet = wallets[0]; } // Deduct platform commission (5% default for fundraisers) const commissionRate = 0.05; const platformFee = disbursementAmount * commissionRate; const netDisbursement = disbursementAmount - platformFee; // Credit recipient wallet via createWalletTransaction const txPayload = { wallet_account_id: wallet.id, organisation_id: campaign.organisation_id, transaction_type: 'CAMPAIGN_FUNDS_CLAIMED', direction: 'CREDIT', amount: netDisbursement, description: `${campaign.type === 'SME_INNOVATION' ? 'SME' : 'Fundraiser'} disbursement: "${campaign.title}" (after ${commissionRate * 100}% platform commission)`, related_campaign_id: campaignId, idempotency_key: `disburse-${campaignId}`, metadata: { gross_amount: disbursementAmount, platform_fee: platformFee, correlation_id: correlationId } }; if (beneficiary.id) txPayload.participant_id = beneficiary.id; const txResult = await base44.asServiceRole.functions.invoke('createWalletTransaction', txPayload); if (!txResult.data?.success) { return Response.json({ error: 'Failed to credit beneficiary wallet', details: txResult.data }, { status: 400 }); } // Track platform commission fee await base44.asServiceRole.functions.invoke('trackTransactionFee', { organisation_id: campaign.organisation_id, transaction_id: txResult.data?.transaction_id, transaction_type: 'FUNDRAISER_DISBURSEMENT', fee_type: 'PLATFORM_FEE', fee_amount: platformFee, fee_percentage: commissionRate, base_amount: disbursementAmount, currency: wallet.currency, participant_id: beneficiary.id, campaign_id: campaignId }); // Mark campaign as disbursed await base44.asServiceRole.entities.Campaign.update(campaignId, { funds_disbursed: true, disbursement_date: new Date().toISOString() }); // Notify beneficiary (only for participant-based fundraisers) if (beneficiary.id) { await base44.asServiceRole.entities.Notification.create({ organisation_id: campaign.organisation_id, participant_id: beneficiary.id, type: 'SYSTEM', title: campaign.type === 'SME_INNOVATION' ? '💡 SME Funds Received' : '💚 Fundraiser Funds Received', message: `${wallet.currency} ${netDisbursement.toLocaleString()} from "${campaign.title}" has been credited to your wallet.`, priority: 'HIGH' }); } // Audit log await base44.asServiceRole.entities.AuditLog.create({ action: campaign.type === 'SME_INNOVATION' ? 'SME_FUNDS_DISBURSED' : 'FUNDRAISER_FUNDS_DISBURSED', entity_type: 'Campaign', entity_id: campaignId, performed_by: user.email, details: JSON.stringify({ beneficiary_id: beneficiary.id, gross_amount: disbursementAmount, platform_fee: platformFee, net_disbursement: netDisbursement, new_balance: txResult.data.new_balance, correlation_id: correlationId }), severity: 'HIGH' }); return Response.json({ success: true, campaign_id: campaignId, beneficiary_id: beneficiary.id, gross_amount: disbursementAmount, platform_fee: platformFee, net_disbursed: netDisbursement, currency: wallet.currency, new_balance: txResult.data.new_balance, correlation_id: correlationId }); } catch (error) { console.error('Fund disbursement error:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/processMatchingDonations/entry.ts (121 lines) NOTE: Sponsor match engine. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.6'; /** * Process matching donations for active sponsorships * Automatically matches contributions based on sponsorship rules */ Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); const { campaign_id, contribution_id } = await req.json(); // Get contribution const contributions = await base44.asServiceRole.entities.Contribution.filter({ id: contribution_id }); if (contributions.length === 0) { return Response.json({ error: 'Contribution not found' }, { status: 404 }); } const contribution = contributions[0]; // Get active matching sponsorships for this campaign const sponsorships = await base44.asServiceRole.entities.CampaignSponsorship.filter({ campaign_id: campaign_id || contribution.campaign_id, sponsorship_type: 'MATCHING_DONATION', status: 'ACTIVE' }); if (sponsorships.length === 0) { return Response.json({ success: true, matched: false, message: 'No active matching sponsorships' }); } const matchResults = []; for (const sponsorship of sponsorships) { // Check if matching cap reached const existingMatches = await base44.asServiceRole.entities.Contribution.filter({ campaign_id: contribution.campaign_id, metadata: { matched_by_sponsorship_id: sponsorship.id } }); const totalMatched = existingMatches.reduce((sum, c) => sum + (c.amount || 0), 0); if (sponsorship.matching_cap && totalMatched >= sponsorship.matching_cap) { continue; // Cap reached for this sponsorship } // Calculate match amount const matchRatio = sponsorship.matching_ratio || 1.0; let matchAmount = contribution.amount * matchRatio; // Apply cap if needed if (sponsorship.matching_cap) { const remainingCap = sponsorship.matching_cap - totalMatched; matchAmount = Math.min(matchAmount, remainingCap); } if (matchAmount <= 0) continue; // Get campaign const campaigns = await base44.asServiceRole.entities.Campaign.filter({ id: contribution.campaign_id }); const campaign = campaigns[0]; // Get sponsor const sponsors = await base44.asServiceRole.entities.Sponsor.filter({ id: sponsorship.sponsor_id }); const sponsor = sponsors[0]; // Create matching contribution const matchingContribution = await base44.asServiceRole.entities.Contribution.create({ campaign_id: contribution.campaign_id, organisation_id: contribution.organisation_id, participant_id: contribution.participant_id, amount: matchAmount, supporter_name: `${sponsor.name} (Matching Donation)`, is_anonymous: false, metadata: { matched_by_sponsorship_id: sponsorship.id, original_contribution_id: contribution.id, match_ratio: matchRatio } }); // Update campaign raised amount await base44.asServiceRole.entities.Campaign.update(contribution.campaign_id, { current_raised_amount: (campaign.current_raised_amount || 0) + matchAmount }); // Notify participant await base44.asServiceRole.entities.Notification.create({ organisation_id: contribution.organisation_id, participant_id: contribution.participant_id, type: 'CONTRIBUTION_RECEIVED', title: '🎉 Your Donation Was Matched!', message: `${sponsor.name} matched your contribution of ${campaign.currency} ${contribution.amount.toLocaleString()} with ${campaign.currency} ${matchAmount.toLocaleString()}! Total impact: ${campaign.currency} ${(contribution.amount + matchAmount).toLocaleString()}`, priority: 'HIGH' }); matchResults.push({ sponsorship_id: sponsorship.id, sponsor_name: sponsor.name, match_amount: matchAmount, contribution_id: matchingContribution.id }); } return Response.json({ success: true, matched: matchResults.length > 0, matches: matchResults, total_matched: matchResults.reduce((sum, m) => sum + m.match_amount, 0) }); } catch (error) { console.error('Error processing matching donations:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/approveFundUsageReport/entry.ts (116 lines) NOTE: Transparency approval workflow. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.4'; /** * COMPLETE: Approve or reject fund usage report from beneficiary * Admin function with transparency controls */ Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); const user = await base44.auth.me(); if (!user) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } const { report_id, action, // 'APPROVE' or 'REJECT' reviewer_notes, visibility // 'PUBLIC' or 'PRIVATE' } = await req.json(); if (action !== 'APPROVE' && action !== 'REJECT') { return Response.json({ error: 'Invalid action' }, { status: 400 }); } // Get report const reports = await base44.asServiceRole.entities.FundUsageReport.filter({ id: report_id }); if (reports.length === 0) { return Response.json({ error: 'Report not found' }, { status: 404 }); } const report = reports[0]; // Check status if (report.status !== 'PENDING_REVIEW') { return Response.json({ error: 'Report already reviewed' }, { status: 400 }); } // Update report const newStatus = action === 'APPROVE' ? 'APPROVED' : 'REJECTED'; await base44.asServiceRole.entities.FundUsageReport.update(report_id, { status: newStatus, reviewed_by: user.email, reviewed_at: new Date().toISOString(), reviewer_notes: reviewer_notes || '', visibility: action === 'APPROVE' ? (visibility || 'PUBLIC') : 'PRIVATE' }); // Notify beneficiary with dual-channel await base44.asServiceRole.functions.invoke('sendDualNotification', { participant_id: report.beneficiary_participant_id, organisation_id: report.organisation_id, notification_key: action === 'APPROVE' ? 'REPORT_APPROVED' : 'REPORT_REJECTED', template_data: { report_title: report.report_title, visibility: visibility || 'PRIVATE', reviewer_notes: reviewer_notes || 'No notes provided' }, priority: 'HIGH', link_url: `/beneficiary-dashboard`, force_send: true }); // If approved, notify all contributors if (action === 'APPROVE' && visibility === 'PUBLIC') { const contributions = await base44.asServiceRole.entities.Contribution.filter({ campaign_id: report.fundraiser_campaign_id }); const uniqueContributors = [...new Set(contributions.map(c => c.participant_id))]; for (const contributorId of uniqueContributors) { if (contributorId !== report.beneficiary_participant_id) { await base44.asServiceRole.functions.invoke('sendDualNotification', { participant_id: contributorId, organisation_id: report.organisation_id, notification_key: 'REPORT_SUBMITTED', template_data: { report_title: report.report_title, campaign_title: 'campaign you supported' }, priority: 'LOW', link_url: `/fundraiser-detail?id=${report.fundraiser_campaign_id}` }); } } } // Log audit trail await base44.asServiceRole.entities.AuditLog.create({ organisation_id: report.organisation_id, action: `FUND_REPORT_${action}`, performed_by: user.email, details: JSON.stringify({ report_id, campaign_id: report.fundraiser_campaign_id, amount: report.amount_used, visibility }), severity: 'MEDIUM' }); return Response.json({ success: true, status: newStatus, visibility: visibility || 'PRIVATE' }); } catch (error) { console.error('Error approving fund usage report:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/notifyNewContribution/entry.ts (148 lines) NOTE: Notification fan-out. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.25'; function buildEmail({ orgName, primaryColor, secondaryColor, emoji, heading, subheading, body, ctaText, ctaUrl, footerNote, isUnregulated }) { const pc = primaryColor || '#3b82f6'; const sc = secondaryColor || '#1d4ed8'; const year = new Date().getFullYear(); const cta = ctaText && ctaUrl ? `` : ''; const footer = footerNote || `You received this because you have an active campaign on ${orgName}.`; return `
${emoji || '💝'}

${heading}

${subheading ? `

${subheading}

` : ''}

${orgName}

${body}${cta}

${footer}

© ${year} ${orgName}${isUnregulated ? '' : ' · Regulated by NGCB, Papua New Guinea'}

Support  ·  Privacy  ·  Terms

`; } Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); const { contribution_id } = await req.json(); if (!contribution_id) return Response.json({ error: 'Missing contribution_id' }, { status: 400 }); const contributions = await base44.asServiceRole.entities.Contribution.filter({ id: contribution_id }); if (!contributions[0]) return Response.json({ error: 'Contribution not found' }, { status: 404 }); const contribution = contributions[0]; const campaigns = await base44.asServiceRole.entities.Campaign.filter({ id: contribution.campaign_id }); if (!campaigns[0]) return Response.json({ error: 'Campaign not found' }, { status: 404 }); const campaignData = campaigns[0]; const orgs = await base44.asServiceRole.entities.Organisation.filter({ id: campaignData.organisation_id }); const org = orgs[0] || {}; const orgName = org.name || 'DrawBid'; const primaryColor = org.primary_color || '#ec4899'; const secondaryColor = org.secondary_color || '#db2777'; const platformSettings = await base44.asServiceRole.entities.PlatformSettings.filter({ key: 'PLATFORM_MODE' }).catch(() => []); const isUnregulated = (platformSettings[0]?.value || 'UNREGULATED') === 'UNREGULATED'; const contributorName = contribution.supporter_name || (contribution.is_anonymous ? 'Anonymous' : 'A supporter'); const amountStr = `${campaignData.currency} ${Number(contribution.amount).toLocaleString()}`; const isBig = contribution.amount >= 1000; // Notify beneficiary if (campaignData.beneficiary_details?.participant_id) { await base44.asServiceRole.functions.invoke('sendNotification', { participant_id: campaignData.beneficiary_details.participant_id, organisation_id: campaignData.organisation_id, type: 'CONTRIBUTION_RECEIVED', title: '💝 New Contribution Received!', message: `${contributorName} contributed ${amountStr} to your campaign "${campaignData.title}"`, priority: isBig ? 'HIGH' : 'MEDIUM', link_url: `/fundraiser-detail?id=${campaignData.id}`, metadata: { contribution_id, campaign_id: campaignData.id, amount: contribution.amount }, }); const beneficiaries = await base44.asServiceRole.entities.Participant.filter({ id: campaignData.beneficiary_details.participant_id }); if (beneficiaries[0]) { const firstName = beneficiaries[0].first_name || 'there'; const body = `

Hi ${firstName}!

Someone has contributed to your campaign. Every contribution brings your goal closer!

Contributor${contributorName}
Amount${amountStr}
Campaign${campaignData.title}
`; try { const brevoKey = Deno.env.get('BREVO_API_KEY'); await fetch('https://api.brevo.com/v3/smtp/email', { method: 'POST', headers: { 'api-key': brevoKey, 'Content-Type': 'application/json' }, body: JSON.stringify({ sender: { email: 'noreply@drawbid.com', name: 'DrawBid' }, to: [{ email: beneficiaries[0].user_email }], subject: `💝 New Contribution of ${amountStr} — ${campaignData.title}`, htmlContent: buildEmail({ orgName, primaryColor, secondaryColor, emoji: '💝', heading: 'New Contribution!', subheading: 'Someone just supported your campaign', body, ctaText: 'View Campaign', ctaUrl: `https://drawbid.com/fundraiser-detail?id=${campaignData.id}`, isUnregulated }), }) }); } catch (e) { console.error('[notifyNewContribution] Beneficiary email failed:', e.message); } } } // Notify campaign creator if different from beneficiary if (campaignData.created_by) { const creators = await base44.asServiceRole.entities.Participant.filter({ user_email: campaignData.created_by }); if (creators[0] && creators[0].id !== campaignData.beneficiary_details?.participant_id) { await base44.asServiceRole.functions.invoke('sendNotification', { participant_id: creators[0].id, organisation_id: campaignData.organisation_id, type: 'CONTRIBUTION_RECEIVED', title: '📊 Campaign Contribution', message: `A new contribution of ${amountStr} was made to "${campaignData.title}"`, priority: 'MEDIUM', link_url: `/admin-campaign-detail?id=${campaignData.id}`, metadata: { contribution_id, campaign_id: campaignData.id }, }); const firstName = creators[0].first_name || 'there'; const body = `

Hi ${firstName},

A new contribution has been made to one of your campaigns.

Contribution Amount${amountStr}
Campaign${campaignData.title}
`; try { const brevoKey = Deno.env.get('BREVO_API_KEY'); await fetch('https://api.brevo.com/v3/smtp/email', { method: 'POST', headers: { 'api-key': brevoKey, 'Content-Type': 'application/json' }, body: JSON.stringify({ sender: { email: 'noreply@drawbid.com', name: 'DrawBid' }, to: [{ email: creators[0].user_email }], subject: `📊 New Contribution — ${campaignData.title}`, htmlContent: buildEmail({ orgName, primaryColor, secondaryColor, emoji: '📊', heading: 'Campaign Contribution', subheading: campaignData.title, body, ctaText: 'View Campaign Analytics', ctaUrl: `https://drawbid.com/admin-campaign-detail?id=${campaignData.id}`, isUnregulated }), }) }); } catch (e) { console.error('[notifyNewContribution] Creator email failed:', e.message); } } } return Response.json({ success: true }); } catch (error) { console.error('[notifyNewContribution]', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/recommendFundraisersForSponsors/entry.ts (91 lines) NOTE: Sponsor to fundraiser scoring. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.4'; /** * Auto-recommend fundraising campaigns to sponsors based on their preferences * Should be run periodically (e.g., daily) or when new fundraisers are published */ Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); // Get all active sponsors const sponsors = await base44.asServiceRole.entities.Sponsor.filter({ status: 'ACTIVE' }); // Get all published fundraiser campaigns from the last 7 days const sevenDaysAgo = new Date(); sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7); const fundraisers = await base44.asServiceRole.entities.Campaign.filter({ type: 'FUNDRAISER', status: 'PUBLISHED' }); const recentFundraisers = fundraisers.filter(f => new Date(f.created_date) >= sevenDaysAgo ); const notificationsToCreate = []; for (const sponsor of sponsors) { const prefs = sponsor.preferences || {}; const preferredCategories = prefs.categories || []; const minAmount = prefs.min_amount || 0; const maxAmount = prefs.max_amount || Number.MAX_SAFE_INTEGER; for (const fundraiser of recentFundraisers) { // Check if already notified about this fundraiser const existingNotifications = await base44.asServiceRole.entities.Notification.filter({ participant_id: sponsor.user_email, metadata: { campaign_id: fundraiser.id, type: 'sponsor_recommendation' } }); if (existingNotifications.length > 0) continue; // Match preferences const categoryMatch = preferredCategories.length === 0 || preferredCategories.includes(fundraiser.fundraiser_category); const amountMatch = fundraiser.funding_goal_amount >= minAmount && fundraiser.funding_goal_amount <= maxAmount; if (categoryMatch && amountMatch) { // Find the participant associated with this sponsor's user email const participants = await base44.asServiceRole.entities.Participant.filter({ user_email: sponsor.user_email }); if (participants.length > 0) { notificationsToCreate.push({ organisation_id: fundraiser.organisation_id, participant_id: participants[0].id, type: 'NEW_CAMPAIGN', title: `🎯 Sponsorship Opportunity: ${fundraiser.title}`, message: `A ${fundraiser.fundraiser_category} fundraiser matching your preferences needs support. Goal: ${fundraiser.currency} ${fundraiser.funding_goal_amount?.toLocaleString()}`, link_url: `/campaign-detail?id=${fundraiser.id}`, priority: 'MEDIUM', metadata: { campaign_id: fundraiser.id, type: 'sponsor_recommendation' } }); } } } } if (notificationsToCreate.length > 0) { await base44.asServiceRole.entities.Notification.bulkCreate(notificationsToCreate); } return Response.json({ success: true, recommendations_sent: notificationsToCreate.length, sponsors_checked: sponsors.length, fundraisers_evaluated: recentFundraisers.length }); } catch (error) { return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/createVoucher/entry.ts (64 lines) NOTE: Single perk voucher. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.6'; /** * Create fundraiser voucher for campaign perks */ Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); const user = await base44.auth.me(); if (user?.role !== 'admin') { return Response.json({ error: 'Admin access required' }, { status: 403 }); } const { campaignId, code, description, rewardValue, rewardType, maxRedemptions } = await req.json(); if (!campaignId || !code || !rewardValue) { return Response.json({ error: 'campaignId, code, and rewardValue required' }, { status: 400 }); } // Get campaign const campaign = await base44.asServiceRole.entities.Campaign.get(campaignId); if (!campaign) { return Response.json({ error: 'Campaign not found' }, { status: 404 }); } // Create voucher const voucher = await base44.asServiceRole.entities.FundraiserVoucher.create({ campaign_id: campaignId, organisation_id: campaign.organisation_id, code: code.toUpperCase(), description: description || '', reward_type: rewardType || 'DISCOUNT', reward_value: rewardValue, currency: campaign.currency || 'USD', max_redemptions: maxRedemptions || 999, redemption_count: 0, status: 'ACTIVE', created_by: user.email, created_at: new Date().toISOString() }); // Create audit log await base44.asServiceRole.entities.AuditLog.create({ entity_type: 'FundraiserVoucher', entity_id: voucher.id, action: 'VOUCHER_CREATED', performed_by: user.email, details: { campaign_id: campaignId, code, reward_value: rewardValue }, timestamp: new Date().toISOString() }); return Response.json({ voucher_id: voucher.id, code: voucher.code, campaign_id: campaignId, reward_value: rewardValue, status: 'ACTIVE' }); } catch (error) { console.error('Create voucher error:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/bulkCreateVouchers/entry.ts (107 lines) NOTE: Batch perk vouchers. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.6'; /** * Bulk create vouchers for a campaign * Generates multiple unique voucher codes at once */ Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); const user = await base44.auth.me(); if (!user) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } const { campaign_id, sponsor_id, voucher_batches } = await req.json(); if (!campaign_id || !sponsor_id || !voucher_batches || voucher_batches.length === 0) { return Response.json({ error: 'campaign_id, sponsor_id, and voucher_batches required' }, { status: 400 }); } // Get campaign const campaigns = await base44.asServiceRole.entities.Campaign.filter({ id: campaign_id }); if (campaigns.length === 0) { return Response.json({ error: 'Campaign not found' }, { status: 404 }); } const campaign = campaigns[0]; const allVouchers = []; let totalValue = 0; for (const batch of voucher_batches) { const { product_name, description, value, quantity, redemption_instructions, expires_at } = batch; if (!product_name || !value || !quantity) { continue; // Skip invalid batches } for (let i = 0; i < quantity; i++) { const uniqueCode = `${campaign.id.substring(0, 4).toUpperCase()}-${sponsor_id.substring(0, 4).toUpperCase()}-${Date.now()}-${Math.random().toString(36).substring(2, 8).toUpperCase()}`; const voucher = await base44.asServiceRole.entities.FundraiserVoucher.create({ campaign_id, organisation_id: campaign.organisation_id, sponsor_id, product_name, description: description || '', value, unique_code: uniqueCode, status: 'AVAILABLE', redemption_instructions: redemption_instructions || '', expires_at: expires_at || null, quantity_available: 1, quantity_issued: 0 }); allVouchers.push(voucher); totalValue += value; } } // Log audit trail await base44.asServiceRole.entities.AuditLog.create({ organisation_id: campaign.organisation_id, action: 'BULK_VOUCHERS_CREATED', performed_by: user.email, details: JSON.stringify({ campaign_id, sponsor_id, total_vouchers: allVouchers.length, total_value: totalValue, batches: voucher_batches.length }), severity: 'MEDIUM' }); return Response.json({ success: true, vouchers_created: allVouchers.length, total_value: totalValue, vouchers: allVouchers.map(v => ({ code: v.unique_code, product: v.product_name, value: v.value })) }); } catch (error) { console.error('Error bulk creating vouchers:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/issueVoucherToPurchaser/entry.ts (149 lines) NOTE: Issue the tier perk to a contributor. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.6'; /** * Issue voucher to participant who purchased campaign contribution * Can be used as campaign reward or purchase incentive */ Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); const user = await base44.auth.me(); if (!user) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } const { participant_id, campaign_id, contribution_amount, auto_issue } = await req.json(); if (!participant_id || !campaign_id) { return Response.json({ error: 'participant_id and campaign_id required' }, { status: 400 }); } // Get campaign const campaigns = await base44.asServiceRole.entities.Campaign.filter({ id: campaign_id }); if (campaigns.length === 0) { return Response.json({ error: 'Campaign not found' }, { status: 404 }); } const campaign = campaigns[0]; // Get available vouchers for this campaign const availableVouchers = await base44.asServiceRole.entities.FundraiserVoucher.filter({ campaign_id, status: 'AVAILABLE' }); if (availableVouchers.length === 0) { return Response.json({ error: 'No vouchers available for this campaign', issued: false }, { status: 200 }); } // Find appropriate voucher based on contribution amount let selectedVoucher = null; if (contribution_amount) { // Find voucher with value closest to contribution amount selectedVoucher = availableVouchers .filter(v => v.value <= contribution_amount) .sort((a, b) => b.value - a.value)[0]; } if (!selectedVoucher) { selectedVoucher = availableVouchers[0]; // Default to first available } // Issue voucher to participant await base44.asServiceRole.entities.FundraiserVoucher.update(selectedVoucher.id, { status: 'ISSUED', issued_to_participant_id: participant_id, issued_at: new Date().toISOString() }); // Update quantity issued await base44.asServiceRole.entities.FundraiserVoucher.update(selectedVoucher.id, { quantity_issued: (selectedVoucher.quantity_issued || 0) + 1 }); // Get participant info const participants = await base44.asServiceRole.entities.Participant.filter({ id: participant_id }); const participant = participants[0]; // Send notification to participant await base44.asServiceRole.entities.Notification.create({ organisation_id: campaign.organisation_id, participant_id, type: 'SYSTEM', title: '🎁 You Received a Voucher!', message: `Thank you for supporting "${campaign.title}"! You've received a voucher for "${selectedVoucher.product_name}" (value: ${campaign.currency} ${selectedVoucher.value}). Code: ${selectedVoucher.unique_code}`, priority: 'HIGH', metadata: { voucher_id: selectedVoucher.id, voucher_code: selectedVoucher.unique_code } }); // Send email with voucher details if (participant) { await base44.integrations.Core.SendEmail({ to: participant.user_email, subject: `Your Voucher for ${selectedVoucher.product_name}`, body: `Thank you for contributing to "${campaign.title}"!\n\nYou've received a voucher:\n\nProduct: ${selectedVoucher.product_name}\nValue: ${campaign.currency} ${selectedVoucher.value}\nCode: ${selectedVoucher.unique_code}\n\nRedemption Instructions:\n${selectedVoucher.redemption_instructions || 'Contact the campaign organizer to redeem your voucher.'}\n\n${selectedVoucher.expires_at ? `Expires: ${new Date(selectedVoucher.expires_at).toLocaleDateString()}` : ''}` }); } // Award points for receiving voucher try { await base44.asServiceRole.functions.invoke('awardPoints', { participant_id, action_type: 'BADGE_EARNED', organisation_id: campaign.organisation_id, metadata: { voucher_id: selectedVoucher.id, source: 'voucher_reward' } }); } catch (error) { console.error('Error awarding points:', error); } // Log audit trail await base44.asServiceRole.entities.AuditLog.create({ organisation_id: campaign.organisation_id, action: 'VOUCHER_ISSUED', performed_by: user.email, details: JSON.stringify({ voucher_id: selectedVoucher.id, participant_id, campaign_id, voucher_code: selectedVoucher.unique_code, auto_issue: auto_issue || false }), severity: 'LOW' }); return Response.json({ success: true, issued: true, voucher: { id: selectedVoucher.id, code: selectedVoucher.unique_code, product_name: selectedVoucher.product_name, value: selectedVoucher.value, redemption_instructions: selectedVoucher.redemption_instructions } }); } catch (error) { console.error('Error issuing voucher:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/redeemVoucher/entry.ts (112 lines) NOTE: Redeem a voucher code. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.6'; /** * Redeem fundraiser voucher for rewards/benefits */ Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); const user = await base44.auth.me(); if (!user) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } const { voucherCode, campaignId } = await req.json(); if (!voucherCode || !campaignId) { return Response.json({ error: 'voucherCode and campaignId required' }, { status: 400 }); } // Find voucher const vouchers = await base44.asServiceRole.entities.FundraiserVoucher.filter({ code: voucherCode.toUpperCase(), campaign_id: campaignId, status: 'ACTIVE' }); if (!vouchers.length) { return Response.json({ error: 'Voucher not found or expired' }, { status: 404 }); } const voucher = vouchers[0]; // Check redemptions limit if (voucher.redemption_count >= voucher.max_redemptions) { return Response.json({ error: 'Voucher limit reached' }, { status: 400 }); } // Get participant const campaign = await base44.asServiceRole.entities.Campaign.get(campaignId); const participants = await base44.asServiceRole.entities.Participant.filter( { user_email: user.email, organisation_id: campaign.organisation_id }, null, 1 ); if (!participants.length) { return Response.json({ error: 'Participant not found' }, { status: 404 }); } const participant = participants[0]; // Create redemption record const redemption = await base44.asServiceRole.entities.AuditLog.create({ entity_type: 'FundraiserVoucher', entity_id: voucher.id, action: 'VOUCHER_REDEEMED', performed_by: user.email, details: { campaign_id: campaignId, participant_id: participant.id, reward_value: voucher.reward_value, reward_type: voucher.reward_type }, timestamp: new Date().toISOString() }); // Increment redemption count await base44.asServiceRole.entities.FundraiserVoucher.update(voucher.id, { redemption_count: voucher.redemption_count + 1 }); // If reward is credit, add to wallet if (voucher.reward_type === 'CREDIT') { const wallets = await base44.asServiceRole.entities.WalletAccount.filter({ participant_id: participant.id, wallet_type: 'PARTICIPANT' }); if (wallets.length) { const wallet = wallets[0]; await base44.asServiceRole.entities.WalletAccount.update(wallet.id, { balance: wallet.balance + voucher.reward_value }); await base44.asServiceRole.entities.WalletTransaction.create({ wallet_account_id: wallet.id, organisation_id: campaign.organisation_id, participant_id: participant.id, transaction_type: 'PROMOTION_BONUS', direction: 'CREDIT', amount: voucher.reward_value, currency: wallet.currency, description: `Voucher redemption: ${voucherCode}`, created_by_user_email: user.email }); } } return Response.json({ success: true, voucher_code: voucherCode, reward_type: voucher.reward_type, reward_value: voucher.reward_value, currency: voucher.currency, message: `Voucher redeemed! You received ${voucher.reward_type === 'CREDIT' ? `${voucher.currency} ${voucher.reward_value}` : voucher.description}` }); } catch (error) { console.error('Redeem voucher error:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/enforceVoucherUsageLimits/entry.ts (87 lines) NOTE: Voucher abuse guards. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.25'; Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); const user = await base44.auth.me(); if (!user) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } const { voucher_code, participant_id } = await req.json(); if (!voucher_code || !participant_id) { return Response.json( { error: 'voucher_code and participant_id required' }, { status: 400 } ); } // Get voucher const vouchers = await base44.entities.Voucher.filter({ code: voucher_code.toUpperCase(), }); if (vouchers.length === 0) { return Response.json({ error: 'Voucher not found', valid: false }, { status: 404 }); } const voucher = vouchers[0]; // Check 1: Expiry date if (voucher.expiry_date) { const expiryDate = new Date(voucher.expiry_date); if (new Date() > expiryDate) { return Response.json({ success: false, valid: false, message: `Voucher expired on ${expiryDate.toLocaleDateString()}`, error_code: 'VOUCHER_EXPIRED', }, { status: 400 }); } } // Check 2: Max total uses const redemptions = await base44.entities.VoucherRedemption.filter({ voucher_id: voucher.id, }); if (voucher.max_uses && redemptions.length >= voucher.max_uses) { return Response.json({ success: false, valid: false, message: `Voucher has reached maximum uses (${voucher.max_uses})`, error_code: 'MAX_USES_EXCEEDED', }, { status: 400 }); } // Check 3: Max per user const userRedemptions = redemptions.filter( (r) => r.participant_id === participant_id ); if (voucher.max_per_user && userRedemptions.length >= voucher.max_per_user) { return Response.json({ success: false, valid: false, message: `You have already redeemed this voucher ${voucher.max_per_user} time(s)`, error_code: 'MAX_PER_USER_EXCEEDED', }, { status: 400 }); } // All checks passed return Response.json({ success: true, valid: true, message: 'Voucher is valid and can be redeemed', voucher_id: voucher.id, voucher_type: voucher.type, voucher_value: voucher.value, remaining_uses: voucher.max_uses ? voucher.max_uses - redemptions.length : null, }); } catch (error) { console.error('Enforce voucher usage limits error:', error); return Response.json({ error: error.message }, { status: 500 }); } }); -------------------------------------------------------------------------------- FILE: base44/functions/processCampaignEndings/entry.ts (391 lines) NOTE: Closes campaigns and drives end-of-campaign paths. -------------------------------------------------------------------------------- import { createClientFromRequest } from 'npm:@base44/sdk@0.8.25'; Deno.serve(async (req) => { try { const base44 = createClientFromRequest(req); // Use service role for automated operations const now = new Date(); const results = { draws_processed: [], fundraisers_closed: [], errors: [] }; // Find campaigns that have ended but are still ONGOING const endedCampaigns = await base44.asServiceRole.entities.Campaign.filter({ status: 'ONGOING' }); const campaignsToProcess = endedCampaigns.filter(c => c.end_date && new Date(c.end_date) <= now ); console.log(`Found ${campaignsToProcess.length} campaigns to process`); for (const campaign of campaignsToProcess) { try { if (campaign.type === 'DRAW') { await processDrawCampaign(base44, campaign, results); } else if (campaign.type === 'FUNDRAISER') { await processFundraiserCampaign(base44, campaign, results); } else { // AUCTION, SME_INNOVATION, or any other type — just close it console.log(`Closing campaign ${campaign.id} (type: ${campaign.type})`); await base44.asServiceRole.entities.Campaign.update(campaign.id, { status: 'CLOSED' }); results.draws_processed.push({ campaign_id: campaign.id, campaign_title: campaign.title, type: campaign.type, action: 'AUTO_CLOSED' }); } } catch (error) { console.error(`Error processing campaign ${campaign.id}:`, error); results.errors.push({ campaign_id: campaign.id, campaign_title: campaign.title, error: error.message }); } } // Log automation execution await base44.asServiceRole.entities.AutomationLog.create({ task_name: 'Process Campaign Endings', execution_type: 'SCHEDULED', status: results.errors.length === 0 ? 'SUCCESS' : 'PARTIAL', executed_at: now.toISOString(), items_processed: campaignsToProcess.length, errors_count: results.errors.length, result_summary: results }); return Response.json({ success: true, processed: campaignsToProcess.length, results }); } catch (error) { console.error('Error in processCampaignEndings:', error); return Response.json({ success: false, error: error.message }, { status: 500 }); } }); async function processDrawCampaign(base44, campaign, results) { console.log(`Processing draw campaign: ${campaign.title}`); // Check if draw should be executed automatically if (campaign.draw_trigger_mode !== 'AUTO') { console.log(`Campaign ${campaign.id} requires manual draw execution`); // Just update status to CLOSED await base44.asServiceRole.entities.Campaign.update(campaign.id, { status: 'CLOSED' }); return; } // Get all entries for this campaign const entries = await base44.asServiceRole.entities.Entry.filter({ campaign_id: campaign.id, status: 'ACTIVE' }); if (entries.length === 0) { console.log(`No entries for campaign ${campaign.id}, marking as CLOSED`); await base44.asServiceRole.entities.Campaign.update(campaign.id, { status: 'CLOSED' }); // Notify admin await sendEmailNotification(base44, { to: campaign.organisation_id, // Will be resolved to org admin email subject: `Draw Closed - No Entries: ${campaign.title}`, body: `The draw "${campaign.title}" has been automatically closed as it ended with no entries.` }); return; } // Execute the draw const prizes = await base44.asServiceRole.entities.Prize.filter({ campaign_id: campaign.id }); const winners = []; const usedEntryIds = new Set(); for (const prize of prizes) { // Select random entry const availableEntries = entries.filter(e => !usedEntryIds.has(e.id)); if (availableEntries.length === 0) break; const randomIndex = Math.floor(Math.random() * availableEntries.length); const winningEntry = availableEntries[randomIndex]; usedEntryIds.add(winningEntry.id); // Create winner record const winner = await base44.asServiceRole.entities.Winner.create({ campaign_id: campaign.id, prize_id: prize.id, participant_id: winningEntry.participant_id, entry_id: winningEntry.id, organisation_id: campaign.organisation_id, winner_announced_at: new Date().toISOString(), kyc_status: 'NOT_REQUIRED', payout_status: 'PENDING' }); winners.push(winner); // Get participant details for notification const participant = await base44.asServiceRole.entities.Participant.filter({ id: winningEntry.participant_id }); if (participant.length > 0) { // Send winner notification email await sendEmailNotification(base44, { to: participant[0].user_email, subject: `🎉 Congratulations! You Won: ${prize.name}`, body: `

Congratulations!

You are a winner in the draw: ${campaign.title}

Prize: ${prize.name}

Prize Value: ${campaign.currency} ${prize.value ? prize.value.toLocaleString() : 'N/A'}

Please check your account for more details and claim instructions.

Thank you for participating!

` }); // Create in-app notification await base44.asServiceRole.entities.Notification.create({ organisation_id: campaign.organisation_id, participant_id: participant[0].id, type: 'WINNER_ANNOUNCEMENT', title: '🎉 Congratulations - You Won!', message: `You won ${prize.name} in ${campaign.title}`, link_url: `/campaign-detail?id=${campaign.id}`, priority: 'HIGH' }); } } // Update campaign status await base44.asServiceRole.entities.Campaign.update(campaign.id, { status: 'DRAW_COMPLETED' }); // Create draw run record await base44.asServiceRole.entities.DrawRun.create({ campaign_id: campaign.id, organisation_id: campaign.organisation_id, executed_at: new Date().toISOString(), executed_by: 'SYSTEM_AUTO', total_entries: entries.length, winners_selected: winners.length, execution_method: 'AUTOMATED' }); // Notify all participants const allParticipants = await base44.asServiceRole.entities.Participant.filter({ organisation_id: campaign.organisation_id }); const participantIds = [...new Set(entries.map(e => e.participant_id))]; const participantsToNotify = allParticipants.filter(p => participantIds.includes(p.id)); for (const participant of participantsToNotify) { const isWinner = winners.some(w => w.participant_id === participant.id); if (!isWinner) { // Notify non-winners await sendEmailNotification(base44, { to: participant.user_email, subject: `Draw Results: ${campaign.title}`, body: `

Draw Results

The draw for ${campaign.title} has been completed.

Unfortunately, you were not selected as a winner this time.

Thank you for participating! Stay tuned for more exciting campaigns.

` }); } } results.draws_processed.push({ campaign_id: campaign.id, campaign_title: campaign.title, winners_count: winners.length, total_entries: entries.length }); console.log(`Successfully processed draw for campaign ${campaign.id}, ${winners.length} winners selected`); } async function processFundraiserCampaign(base44, campaign, results) { console.log(`Processing fundraiser campaign: ${campaign.title}`); // Get all contributions const contributions = await base44.asServiceRole.entities.Contribution.filter({ campaign_id: campaign.id }); const totalRaised = contributions.reduce((sum, c) => sum + (c.amount || 0), 0); const contributorsCount = new Set(contributions.map(c => c.participant_id)).size; // Generate final report const report = { campaign_title: campaign.title, campaign_id: campaign.id, funding_goal: campaign.funding_goal_amount || 0, total_raised: totalRaised, goal_percentage: ((totalRaised / (campaign.funding_goal_amount || 1)) * 100).toFixed(1), contributors_count: contributorsCount, contributions_count: contributions.length, campaign_duration_days: campaign.start_date && campaign.end_date ? Math.ceil((new Date(campaign.end_date) - new Date(campaign.start_date)) / (1000 * 60 * 60 * 24)) : 0, closed_at: new Date().toISOString() }; // Update campaign status await base44.asServiceRole.entities.Campaign.update(campaign.id, { status: 'CLOSED', current_raised_amount: totalRaised }); // Notify beneficiary if (campaign.beneficiary_details?.contact_email) { await sendEmailNotification(base44, { to: campaign.beneficiary_details.contact_email, subject: `Fundraiser Closed: ${campaign.title}`, body: `

Fundraiser Campaign Closed

Your fundraiser ${campaign.title} has ended.

Final Results:

  • Total Raised: ${campaign.currency} ${totalRaised.toLocaleString()}
  • Goal: ${campaign.currency} ${(campaign.funding_goal_amount || 0).toLocaleString()}
  • Achievement: ${report.goal_percentage}% of goal
  • Contributors: ${contributorsCount}
  • Total Contributions: ${contributions.length}

Please log in to your account to manage fund disbursement and submit usage reports.

` }); } // Notify all contributors const allParticipants = await base44.asServiceRole.entities.Participant.filter({ organisation_id: campaign.organisation_id }); const contributorIds = [...new Set(contributions.map(c => c.participant_id))]; const contributors = allParticipants.filter(p => contributorIds.includes(p.id)); for (const contributor of contributors) { const theirContributions = contributions.filter(c => c.participant_id === contributor.id); const theirTotal = theirContributions.reduce((sum, c) => sum + (c.amount || 0), 0); await sendEmailNotification(base44, { to: contributor.user_email, subject: `Thank You for Supporting: ${campaign.title}`, body: `

Fundraiser Campaign Closed

Thank you for supporting ${campaign.title}!

Your contribution: ${campaign.currency} ${theirTotal.toLocaleString()}

Final Campaign Results:

  • Total Raised: ${campaign.currency} ${totalRaised.toLocaleString()}
  • Goal: ${campaign.currency} ${(campaign.funding_goal_amount || 0).toLocaleString()}
  • Achievement: ${report.goal_percentage}% of goal
  • Total Contributors: ${contributorsCount}

Your support makes a real difference. Thank you!

` }); // Create in-app notification await base44.asServiceRole.entities.Notification.create({ organisation_id: campaign.organisation_id, participant_id: contributor.id, type: 'CAMPAIGN_STATUS_CHANGE', title: 'Fundraiser Closed', message: `${campaign.title} has ended. Total raised: ${campaign.currency} ${totalRaised.toLocaleString()}`, link_url: `/fundraiser-detail?id=${campaign.id}`, priority: 'MEDIUM' }); } // Notify organisation admins const orgUsers = await base44.asServiceRole.entities.OrgUser.filter({ organisation_id: campaign.organisation_id, status: 'ACTIVE' }); for (const orgUser of orgUsers) { if (['ORG_ADMIN', 'SUPER_ADMIN'].includes(orgUser.role)) { await sendEmailNotification(base44, { to: orgUser.user_email, subject: `Fundraiser Closed - Final Report: ${campaign.title}`, body: `

Fundraiser Campaign Final Report

Campaign: ${campaign.title}

Final Statistics:

  • Total Raised: ${campaign.currency} ${totalRaised.toLocaleString()}
  • Goal: ${campaign.currency} ${(campaign.funding_goal_amount || 0).toLocaleString()}
  • Achievement: ${report.goal_percentage}% of goal
  • Contributors: ${contributorsCount}
  • Total Contributions: ${contributions.length}
  • Campaign Duration: ${report.campaign_duration_days} days

Campaign has been automatically closed. Please review and process fund disbursement.

` }); } } results.fundraisers_closed.push({ campaign_id: campaign.id, campaign_title: campaign.title, total_raised: totalRaised, contributors_count: contributorsCount, report }); console.log(`Successfully closed fundraiser ${campaign.id}, raised ${totalRaised}`); } async function sendEmailNotification(base44, { to, subject, body }) { try { // If 'to' looks like an entity ID, resolve to org admin email let recipientEmail = to; if (to && to.length > 20 && to.includes('-')) { const orgUsers = await base44.asServiceRole.entities.OrgUser.filter({ organisation_id: to, status: 'ACTIVE', role: 'ORG_ADMIN' }); if (orgUsers.length > 0) { recipientEmail = orgUsers[0].user_email; } } if (!recipientEmail || !recipientEmail.includes('@')) return; await base44.asServiceRole.functions.invoke('sendBrevoEmail', { to: recipientEmail, subject, html_content: `
${body}
` }); } catch (error) { console.error('Error sending email:', error); } } ================================================================================ PART 8 - QUERY GATEWAY OPERATIONS ================================================================================ The frontend never queries Supabase tables directly for fundraising data; it calls one gateway function that switches on an operation name. Add these operations to your gateway. Each returns { data, pagination } and validates its own filters. Operation Filters Purpose ------------------------------- ----------------------------------- ------------------------------ get_campaign_by_id campaign_id single campaign header get_contributions_by_campaign campaign_id contributor wall + totals get_campaign_sponsorships campaign_id, status sponsor cards get_fund_usage_reports fundraiser_campaign_id, status transparency section get_participant_contributions participant_id (auth derived) my contributions get_participant_vouchers participant_id (auth derived) my perks Source of the fundraising-relevant operations: // ---- get_campaign_sponsorships ------------------------- operation === 'get_campaign_sponsorships') { const { campaign_id, status } = filters; if (!campaign_id) return Response.json({ error: 'campaign_id required' }, { status: 400 }); let query = supabase.from('campaign_sponsorships').select('*').eq('campaign_id', campaign_id); if (status) query = query.eq('status', status); query = query.order('created_at', { ascending: false }).range(offset, offset + limit - 1); const { data, error } = await query; if (error) { const h = handleErr(error); if (h.pending) return emptyList(); return Response.json({ error: h.message }, { status: 400 }); } return Response.json({ data, page, limit, hasMore: data.length === limit }); } // ---- get_fund_usage_reports ---------------------------- operation === 'get_fund_usage_reports') { const { fundraiser_campaign_id, status } = filters; if (!fundraiser_campaign_id) return Response.json({ error: 'fundraiser_campaign_id required' }, { status: 400 }); let query = supabase.from('fund_usage_reports').select('*').eq('fundraiser_campaign_id', fundraiser_campaign_id); if (status) query = query.eq('status', status); query = query.order('created_at', { ascending: false }).range(offset, offset + limit - 1); const { data, error } = await query; if (error) { const h = handleErr(error); if (h.pending) return emptyList(); return Response.json({ error: h.message }, { status: 400 }); } return Response.json({ data, page, limit, hasMore: data.length === limit }); } // ---- get_contributions_by_campaign --------------------- operation === 'get_contributions_by_campaign') { const { campaign_id } = filters; if (!campaign_id) return Response.json({ error: 'campaign_id required' }, { status: 400 }); const { data, error } = await supabase.from('contributions').select('*').eq('campaign_id', campaign_id).order('created_at', { ascending: false }).range(offset, offset + limit - 1); if (error) { const h = handleErr(error); if (h.pending) return emptyList(); return Response.json({ error: h.message }, { status: 400 }); } return Response.json({ data, page, limit, hasMore: data.length === limit }); } // ---- get_participant_vouchers -------------------------- operation === 'get_participant_vouchers') { const { participant_id } = filters; if (!participant_id) return Response.json({ error: 'participant_id required' }, { status: 400 }); const { data, error } = await supabase.from('fundraiser_vouchers').select('*').eq('issued_to_participant_id', participant_id).order('created_at', { ascending: false }).range(offset, offset + limit - 1); if (error) { const h = handleErr(error); if (h.pending) return emptyList(); return Response.json({ error: h.message }, { status: 400 }); } return Response.json({ data, page, limit, hasMore: data.length === limit }); } // ---- get_participant_contributions --------------------- operation === 'get_participant_contributions') { const { participant_id } = filters; if (!participant_id) return Response.json({ error: 'participant_id required' }, { status: 400 }); const { data, error } = await supabase.from('contributions').select('*').eq('participant_id', participant_id).order('created_at', { ascending: false }).range(offset, offset + limit - 1); if (error) { const h = handleErr(error); if (h.pending) return emptyList(); return Response.json({ error: h.message }, { status: 400 }); } return Response.json({ data, page, limit, hasMore: data.length === limit }); } Security note: participant_id must be derived from the authenticated session in the gateway, never trusted from the request body. The source implementation derives it from the caller for the two get_participant_* operations - keep that property. ================================================================================ PART 9 - FRONTEND PAGES: SOURCE ================================================================================ Routing (react-router-dom, paths registered in App.jsx): /fundraisers -> FundraiserBrowse public list /product-fundraisers -> ProductFundraisers public product browse /fundraiser -> FundraiserDetail ?id= /sponsor-fundraiser-browse -> SponsorFundraiserBrowse authenticated, sponsor role /admin-fund-usage-review -> AdminFundUsageReview admin only FundraiserDetail reads through supabaseQuery with four queries: campaign, contributions (limit 50), active sponsorships (limit 20), and approved fund usage reports (limit 30, only fetched once funds_disbursed is true). It does not use a skeleton - it shows a spinner until the campaign resolves. -------------------------------------------------------------------------------- FILE: src/pages/FundraiserBrowse.jsx (259 lines) NOTE: Public discovery list. -------------------------------------------------------------------------------- import React, { useState } from "react"; import { useQuery } from "@tanstack/react-query"; import { base44 } from "@/api/base44Client"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Badge } from "@/components/ui/badge"; import { Progress } from "@/components/ui/progress"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import PageMeta from "@/components/utils/PageMeta"; import { Heart, Search, TrendingUp, Clock } from "lucide-react"; import { Link } from "react-router-dom"; import { createPageUrl } from "@/utils"; import { differenceInDays } from "date-fns"; import { useAppData } from "@/components/providers/AppDataProvider"; import CampaignEmptyState from "@/components/campaigns/CampaignEmptyState"; const CATEGORIES = ["ALL", "MEDICAL", "EDUCATION", "DISASTER", "BUSINESS_IDEA", "COMMUNITY", "OTHER"]; const categoryLabels = { ALL: "All Categories", MEDICAL: "🏥 Medical", EDUCATION: "📚 Education", DISASTER: "🆘 Disaster Relief", BUSINESS_IDEA: "💼 Business Idea", COMMUNITY: "🤝 Community", OTHER: "Other", }; const categoryColors = { MEDICAL: "bg-red-500/20 text-destructive border border-red-500/30", EDUCATION: "bg-blue-500/20 text-info-subtle-foreground border border-blue-500/30", DISASTER: "bg-orange-500/20 text-orange-300 border border-orange-500/30", BUSINESS_IDEA: "bg-yellow-500/20 text-yellow-300 border border-yellow-500/30", COMMUNITY: "bg-green-500/20 text-green-300 border border-green-500/30", OTHER: "bg-slate-500/20 text-slate-300 border border-slate-500/30", }; export default function FundraiserBrowse() { const { organisation } = useAppData(); const currency = organisation?.default_currency || 'PGK'; const [searchTerm, setSearchTerm] = useState(""); const [selectedCategory, setSelectedCategory] = useState("ALL"); const [sortBy, setSortBy] = useState("NEWEST"); const sbQuery = async (operation, filters = {}, pagination = {}) => { const res = await base44.functions.invoke('supabaseQuery', { operation, filters, pagination }); return res?.data ?? null; }; const { data: fundraisers = [] } = useQuery({ queryKey: ["fundraisersV2"], queryFn: async () => { const result = await sbQuery('get_public_campaigns', { type: 'FUNDRAISER', status: 'PUBLISHED,ONGOING' }, { limit: 200 }); return result?.data ?? []; }, }); const filtered = fundraisers .filter((c) => { const matchSearch = c.title.toLowerCase().includes(searchTerm.toLowerCase()) || c.description?.toLowerCase().includes(searchTerm.toLowerCase()) || c.beneficiary_details?.name?.toLowerCase().includes(searchTerm.toLowerCase()); const matchCat = selectedCategory === "ALL" || c.fundraiser_category === selectedCategory; return matchSearch && matchCat; }) .sort((a, b) => { if (sortBy === "NEWEST") return new Date(b.created_date || b.created_at) - new Date(a.created_date || a.created_at); if (sortBy === "MOST_FUNDED") return (b.current_raised_amount || 0) - (a.current_raised_amount || 0); if (sortBy === "MOST_PROGRESS") { const ap = (a.current_raised_amount || 0) / (a.funding_goal_amount || 1); const bp = (b.current_raised_amount || 0) / (b.funding_goal_amount || 1); return bp - ap; } if (sortBy === "ENDING_SOON") return new Date(a.end_date) - new Date(b.end_date); return 0; }); // Featured: 25-75% funded const featured = filtered .filter((c) => { const pct = ((c.current_raised_amount || 0) / (c.funding_goal_amount || 1)) * 100; return pct >= 25 && pct < 100; }) .slice(0, 3); return (
{/* Hero */}

Fundraiser Hub

Support people and communities in need. Every contribution makes a real difference.

{/* Category Pills */}
{CATEGORIES.map((cat) => ( ))}
{/* Featured */} {featured.length > 0 && (

Momentum Campaigns

{featured.map((c) => { const pct = Math.min(((c.current_raised_amount || 0) / (c.funding_goal_amount || 1)) * 100, 100); const daysLeft = c.end_date ? differenceInDays(new Date(c.end_date), new Date()) : null; return ( {categoryLabels[c.fundraiser_category] || c.fundraiser_category}

{c.title}

{c.beneficiary_details?.name && (

For: {c.beneficiary_details.name}

)}
{pct.toFixed(0)}% funded
{currency} {(c.current_raised_amount || 0).toLocaleString()} {daysLeft !== null && daysLeft >= 0 && ( {daysLeft}d left )}
); })}
)} {/* All Fundraisers */} All Fundraisers
setSearchTerm(e.target.value)} className="pl-10 bg-slate-800/60 border-slate-700 text-white" />
{filtered.map((c) => { const pct = Math.min(((c.current_raised_amount || 0) / (c.funding_goal_amount || 1)) * 100, 100); const daysLeft = c.end_date ? differenceInDays(new Date(c.end_date), new Date()) : null; return ( {c.banner_image_url && (
{c.title}
)} {categoryLabels[c.fundraiser_category] || c.fundraiser_category}

{c.title}

{c.beneficiary_details?.name && (

For: {c.beneficiary_details.name}

)}

{c.subtitle || c.description?.replace(/<[^>]*>/g, '')}

{currency} {(c.current_raised_amount || 0).toLocaleString()} {pct.toFixed(0)}% of {currency} {(c.funding_goal_amount || 0).toLocaleString()}
{daysLeft !== null && daysLeft >= 0 &&
{daysLeft} days left
}
); })}
{filtered.length === 0 && ( { setSearchTerm(""); setSelectedCategory("ALL"); }} /> )}
); } -------------------------------------------------------------------------------- FILE: src/pages/FundraiserDetail.jsx (367 lines) NOTE: The campaign page. Primary surface of the module. -------------------------------------------------------------------------------- import React, { useState, useEffect } from "react"; import { base44 } from "@/api/base44Client"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Badge } from "@/components/ui/badge"; import { Label } from "@/components/ui/label"; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, } from "@/components/ui/dialog"; import { Heart, Users, DollarSign, Calendar, Share2, CheckCircle, ArrowLeft, Building2 } from "lucide-react"; import SponsorCard from "@/components/fundraiser/SponsorCard"; import ReactMarkdown from "react-markdown"; import { toast } from "sonner"; import { format } from "date-fns"; import TopContributorsWidget from "@/components/fundraiser/TopContributorsWidget"; import ContributionPackagesCard from "@/components/fundraiser/ContributionPackagesCard"; import ContactInfoCard from "@/components/fundraiser/ContactInfoCard"; import EventDetailsCard from "@/components/fundraiser/EventDetailsCard"; import FundraiserProgressBar from "@/components/fundraiser/FundraiserProgressBar"; import DirectDonationDialog from "@/components/fundraiser/DirectDonationDialog"; import FundraiserShareTools from "@/components/fundraiser/FundraiserShareTools"; import SponsorCampaignDialog from "@/components/fundraiser/SponsorCampaignDialog"; import FundraiserHeroStats from "@/components/fundraiser/FundraiserHeroStats"; import FundraiserTrustBadges from "@/components/fundraiser/FundraiserTrustBadges"; import FundraiserProgressSection from "@/components/fundraiser/FundraiserProgressSection"; import CampaignTypeIndicator from "@/components/campaigns/CampaignTypeIndicator"; import CampaignUrgencyBadges from "@/components/campaigns/CampaignUrgencyBadges"; import ProjectTimeline from "@/components/project/ProjectTimeline"; import FundraiserMilestoneTracker from "@/components/fundraiser/FundraiserMilestoneTracker"; import { useAppData } from "@/components/providers/AppDataProvider"; export default function FundraiserDetail() { const urlParams = new URLSearchParams(window.location.search); const campaignId = urlParams.get('id'); const queryClient = useQueryClient(); const [showDonationDialog, setShowDonationDialog] = useState(false); const [showSponsorDialog, setShowSponsorDialog] = useState(false); const { participant, organisation, wallet, sponsor } = useAppData(); const walletBalance = wallet?.balance || 0; const sbQuery = async (operation, filters = {}, pagination = {}) => { const res = await base44.functions.invoke('supabaseQuery', { operation, filters, pagination }); return res?.data ?? null; }; const { data: campaign } = useQuery({ queryKey: ['campaign', campaignId], queryFn: async () => { const result = await sbQuery('get_campaign_by_id', { campaign_id: campaignId }); return result?.data ?? null; }, enabled: !!campaignId, staleTime: 5 * 60 * 1000, }); const { data: contributions = [] } = useQuery({ queryKey: ['contributions', campaignId], queryFn: async () => { const result = await sbQuery('get_contributions_by_campaign', { campaign_id: campaignId }, { limit: 50 }); return result?.data ?? []; }, enabled: !!campaignId, initialData: [], staleTime: 3 * 60 * 1000, }); const { data: sponsorships = [] } = useQuery({ queryKey: ['sponsorships', campaignId], queryFn: async () => { const result = await sbQuery('get_campaign_sponsorships', { campaign_id: campaignId, status: 'ACTIVE' }, { limit: 20 }); return result?.data ?? []; }, enabled: !!campaignId, initialData: [], staleTime: 5 * 60 * 1000, }); const { data: fundReports = [] } = useQuery({ queryKey: ['fundReports', campaignId], queryFn: async () => { const result = await sbQuery('get_fund_usage_reports', { fundraiser_campaign_id: campaignId, status: 'APPROVED' }, { limit: 30 }); return result?.data ?? []; }, enabled: !!campaignId && campaign?.funds_disbursed, initialData: [], staleTime: 10 * 60 * 1000, }); const handleDonationSuccess = () => { queryClient.invalidateQueries({ queryKey: ['campaign'] }); queryClient.invalidateQueries({ queryKey: ['contributions'] }); }; const handleSponsorshipSuccess = () => { queryClient.invalidateQueries({ queryKey: ['campaign'] }); queryClient.invalidateQueries({ queryKey: ['sponsorships'] }); }; if (!campaign) { return (
); } const currency = organisation?.default_currency || 'PGK'; const daysLeft = campaign && campaign.end_date ? Math.ceil((new Date(campaign.end_date) - new Date()) / (1000 * 60 * 60 * 24)) : null; const daysActive = campaign && (campaign.created_at || campaign.created_date) ? Math.floor((new Date() - new Date(campaign.created_at || campaign.created_date)) / (1000 * 60 * 60 * 24)) : 0; return (
{campaign.banner_image_url ? ( {campaign.title} ) : (
)}
{campaign.fundraiser_category}

{campaign.title}

{campaign.subtitle && (

{campaign.subtitle}

)}
{campaign.funding_mode && (
Funding mode: {campaign.funding_mode === 'ALL_OR_NOTHING' ? '🎯 All-or-Nothing — funds only released if goal is met' : '✅ Flexible — funds released regardless of whether the goal is met'}
)}
{sponsor && ( )}
{campaign.beneficiary_details && ( About the Beneficiary

{campaign.beneficiary_details.name}

{campaign.beneficiary_details.story}

)} Campaign Story
{sponsorships && Array.isArray(sponsorships) && sponsorships.length > 0 && ( Our Sponsors
{sponsorships.map(sponsorship => ( ))}
)} {/* Milestone Tracker */} {campaign.sme_milestones_json && campaign.sme_milestones_json.length > 0 && (
)} {/* Project Timeline */}

Project Updates & Reports

{fundReports && Array.isArray(fundReports) && fundReports.length > 0 && ( Fund Usage Reports {fundReports.map(report => (

{report.report_title}

{report.description_of_use}

Verified {format(new Date(report.date_reported), 'MMM d, yyyy')} {currency} {((report?.amount_used ?? 0) || 0).toLocaleString()}
))}
)} {contributions && Array.isArray(contributions) && contributions.length > 0 && ( Recent Contributors
{contributions.slice(0, 10).map(contribution => (

{contribution.is_anonymous ? "Anonymous Supporter" : (contribution.supporter_name || "Contributor")}

{contribution.message && (

"{contribution.message}"

)}

{format(new Date(contribution.created_at || contribution.created_date), 'MMM d, yyyy')}

{currency} {((contribution?.amount ?? 0) || 0).toLocaleString()}
))}
)}
{sponsor && ( )}
); } -------------------------------------------------------------------------------- FILE: src/pages/ProductFundraisers.jsx (242 lines) NOTE: Product-level browse entry. -------------------------------------------------------------------------------- import React from "react"; import { useQuery } from "@tanstack/react-query"; import { base44 } from "@/api/base44Client"; import { Link } from "react-router-dom"; import { Heart, CheckCircle, ArrowRight, Target, Users, Shield } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import PageMeta from "@/components/utils/PageMeta"; import HomeHeader from "@/components/home/HomeHeader"; import { useAuth } from "@/lib/AuthContext"; import { motion } from "framer-motion"; import SponsorEarningsCalculator from "@/components/sponsor/SponsorEarningsCalculator"; import ProductCrossNav from "@/components/products/ProductCrossNav"; import ProductEmptyState from "@/components/products/ProductEmptyState"; const FEATURES = [ "Category-based compliance requirements", "Optional charity registration verification", "Flexible contribution packages", "All-or-Nothing or Flexible funding modes", "2.5% platform fee — lowest on DrawBid", "Full fund usage reporting & transparency", ]; const CATEGORIES = [ { label: "Medical", color: "bg-red-900/40 text-red-300 border-red-700/40" }, { label: "Education", color: "bg-blue-900/40 text-blue-300 border-blue-700/40" }, { label: "Disaster Relief", color: "bg-orange-900/40 text-orange-300 border-orange-700/40" }, { label: "Community", color: "bg-green-900/40 text-green-300 border-green-700/40" }, { label: "Business Idea", color: "bg-violet-900/40 text-violet-300 border-violet-700/40" }, { label: "Other", color: "bg-slate-800 text-slate-300 border-slate-700" }, ]; const HERO_STATS = [ { label: "Platform Fee", value: "2.5%" }, { label: "Funding Modes", value: "2" }, { label: "Categories", value: "6" }, { label: "Fund Reports", value: "100%" }, ]; export default function ProductFundraisers() { const { isAuthenticated, user } = useAuth(); const sbQuery = async (operation, filters = {}, pagination = {}) => { const res = await base44.functions.invoke('supabaseQuery', { operation, filters, pagination }); return res?.data ?? null; }; const { data: campaigns = [] } = useQuery({ queryKey: ['fundraiserCampaigns'], queryFn: async () => { const result = await sbQuery('get_public_campaigns', { type: 'FUNDRAISER', status: 'PUBLISHED,ONGOING' }, { limit: 50 }); return result?.data ?? []; }, staleTime: 2 * 60 * 1000, }); return (
{/* Hero */}
🟡 Compliant with Charity & Tax Laws 2.5% Platform Fee

Fundraisers

Compliant with Charity & Tax Laws

Support causes that matter — medical emergencies, education, disaster relief, and community projects across Papua New Guinea. Transparent, accountable, and impactful.

{!isAuthenticated && ( )}
{/* Stats strip */}
{HERO_STATS.map(({ label, value }) => (

{value}

{label}

))}
{/* Active Fundraisers — top 3 pinned below hero */} {campaigns.length > 0 && (

Active Fundraisers

View all
{campaigns.slice(0, 3).map(c => (
{c.banner_image_url && {c.title}}

{c.title}

{c.description?.replace(/<[^>]*>/g, '') || ''}

{c.fundraiser_category || 'Community'} {c.funding_goal_amount && ( Goal: {c.currency || 'PGK'} {c.funding_goal_amount?.toLocaleString()} )}
))}
)}
{/* Categories */}

Fundraiser Categories

{CATEGORIES.map(({ label, color }) => ( {label} ))}
{/* How it works */}
{[ { icon: Heart, num: "01", title: "Choose a Cause", desc: "Browse verified fundraisers for medical needs, education, disaster relief, and community projects." }, { icon: Target, num: "02", title: "Contribute", desc: "Make a one-time contribution or select a package. Every kina goes directly to the cause." }, { icon: Users, num: "03", title: "Track Impact", desc: "Follow the campaign's progress, see fund usage reports, and celebrate milestones together." }, ].map(({ icon: Icon, num, title, desc }) => (
{num}

{title}

{desc}

))}
{/* Sponsor Earnings Calculator */} {/* Compliance Box */}

Compliant with Charity & Tax Laws

Fundraiser compliance varies by category and contribution structure. Charity verification may be required. Tax treatment depends on beneficiary type and fund usage reporting.

{FEATURES.map(f => (
{f}
))}
{/* Active Fundraisers or empty state */}

Active Fundraisers

{campaigns.length > 0 ? ( <>
{campaigns.slice(0, 6).map(c => (
{c.banner_image_url && {c.title}}

{c.title}

{c.description?.replace(/<[^>]*>/g, '') || ''}

{c.fundraiser_category || 'Community'} {c.funding_goal_amount && ( Goal: {c.currency || 'PGK'} {c.funding_goal_amount?.toLocaleString()} )}
))}
) : ( )}
{/* Cross nav */}
); } -------------------------------------------------------------------------------- FILE: src/pages/SponsorFundraiserBrowse.jsx (179 lines) NOTE: Sponsor-side discovery. -------------------------------------------------------------------------------- import React, { useState } from 'react'; import { base44 } from '@/api/base44Client'; import supabase from '@/services/supabaseClient'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Badge } from '@/components/ui/badge'; import { Progress } from '@/components/ui/progress'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Textarea } from '@/components/ui/textarea'; import { Heart, Search, TrendingUp } from 'lucide-react'; import DashboardHeader from '@/components/dashboard/DashboardHeader'; export default function SponsorFundraiserBrowse() { const [searchTerm, setSearchTerm] = useState(''); const [selectedCampaign, setSelectedCampaign] = useState(null); const [sponsorshipAmount, setSponsorshipAmount] = useState(''); const queryClient = useQueryClient(); const { data: user } = useQuery({ queryKey: ['user'], queryFn: () => base44.auth.me() }); const { data: sponsor } = useQuery({ queryKey: ['sponsor', user?.email], queryFn: () => (async () => { if (!supabase) return []; const { data } = await supabase.from('sponsors').select('*').eq('user_email', user?.email).order('null', { ascending: true }).limit(1); return data || []; })().then(s => s[0]), enabled: !!user }); const { data: fundraisers = [] } = useQuery({ queryKey: ['fundraisers'], queryFn: () => (async () => { if (!supabase) return []; const { data } = await supabase.from('campaigns').select('*').eq('type', 'FUNDRAISER').neq('status', 'CLOSED').order('created_date', { ascending: false }).limit(50); return data || []; })(), staleTime: 30000 }); const sponsorMutation = useMutation({ mutationFn: () => base44.functions.invoke('sponsorCampaign', { campaignId: selectedCampaign.id, sponsorId: sponsor.id, amount: parseFloat(sponsorshipAmount), notes: 'Sponsor contribution to fundraiser' }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['fundraisers'] }); setSelectedCampaign(null); setSponsorshipAmount(''); } }); const filteredFundraisers = fundraisers.filter(f => f.title?.toLowerCase().includes(searchTerm.toLowerCase()) || f.description?.toLowerCase().includes(searchTerm.toLowerCase()) ); const CampaignCard = ({ campaign }) => { const progressPercent = campaign.funding_goal_amount ? Math.min(100, (campaign.current_raised_amount || 0) / campaign.funding_goal_amount * 100) : 0; return (

{campaign.title}

{campaign.beneficiary_details?.name || 'Beneficiary'}

{campaign.fundraiser_category || 'Fundraiser'}

{campaign.description}

Progress ${campaign.current_raised_amount?.toLocaleString() || 0} / ${campaign.funding_goal_amount?.toLocaleString()}

Remaining

${Math.max(0, campaign.funding_goal_amount - campaign.current_raised_amount).toLocaleString()}

Ends

{new Date(campaign.end_date).toLocaleDateString()}

{selectedCampaign?.id === campaign.id && ( Sponsor {campaign.title}
$ setSponsorshipAmount(e.target.value)} placeholder="1000" className="pl-7" min="1" step="100" />
)}
); }; return (
setSearchTerm(e.target.value)} className="pl-10" />
{filteredFundraisers.length === 0 ? (

No fundraisers match your search

) : ( filteredFundraisers.map(campaign => ( )) )}
); } -------------------------------------------------------------------------------- FILE: src/pages/AdminFundUsageReview.jsx (296 lines) NOTE: Admin approval queue for usage reports. -------------------------------------------------------------------------------- import React, { useState, useEffect } from "react"; import { base44 } from "@/api/base44Client"; import { supabase } from "@/services/supabaseClient"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Label } from "@/components/ui/label"; import { Badge } from "@/components/ui/badge"; import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { CheckCircle, X, FileText, ExternalLink } from "lucide-react"; import { toast } from "sonner"; import { format } from "date-fns"; import PermissionGate from "@/components/permissions/PermissionGate"; export default function AdminFundUsageReview() { const queryClient = useQueryClient(); const [organisation, setOrganisation] = useState(null); const [selectedReport, setSelectedReport] = React.useState(null); const [reviewNotes, setReviewNotes] = React.useState(""); useEffect(() => { loadOrganisation(); }, []); const loadOrganisation = async () => { if (!supabase) return; const currentUser = await base44.auth.me(); const { data: orgUsers } = await supabase.from('org_users') .select('*') .eq('user_email', currentUser.email); if (orgUsers && orgUsers.length > 0) { const { data: orgs } = await supabase.from('organisations') .select('*') .eq('id', orgUsers[0].organisation_id); if (orgs && orgs.length > 0) { setOrganisation(orgs[0]); } } }; const { data: reports } = useQuery({ queryKey: ['fundReports', organisation?.id], queryFn: async () => { if (!organisation || !supabase) return []; const { data, error } = await supabase.from('fund_usage_reports') .select('*') .eq('organisation_id', organisation.id) .order('created_date', { ascending: false }); if (error) throw error; return data || []; }, enabled: !!organisation, initialData: [], }); const approveMutation = useMutation({ mutationFn: async ({ reportId, notes }) => { if (!supabase) throw new Error('Database not available'); const { error } = await supabase.from('fund_usage_reports').update({ status: 'APPROVED', reviewed_at: new Date().toISOString(), reviewer_notes: notes }).eq('id', reportId); if (error) throw error; }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['fundReports'] }); setSelectedReport(null); setReviewNotes(""); toast.success("Report approved!"); } }); const rejectMutation = useMutation({ mutationFn: async ({ reportId, notes }) => { if (!supabase) throw new Error('Database not available'); const { error } = await supabase.from('fund_usage_reports').update({ status: 'REJECTED', reviewed_at: new Date().toISOString(), reviewer_notes: notes }).eq('id', reportId); if (error) throw error; }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['fundReports'] }); setSelectedReport(null); setReviewNotes(""); toast.success("Report rejected"); } }); const pendingReports = reports.filter(r => r.status === 'PENDING_REVIEW'); const approvedReports = reports.filter(r => r.status === 'APPROVED'); const statusColors = { PENDING_REVIEW: "bg-warning-subtle text-warning-subtle-foreground", APPROVED: "bg-success-subtle text-success-subtle-foreground", REJECTED: "bg-destructive/10 text-destructive", REQUIRES_REVISION: "bg-warning-subtle text-warning-subtle-foreground" }; return (

Fund Usage Reports

Review beneficiary fund usage transparency

Pending Review

{pendingReports.length}

Approved

{approvedReports.length}

Total Reports

{reports.length}

Pending Reviews ({pendingReports.length})
{pendingReports.map(report => (

{report.report_title}

{report.status.replace(/_/g, ' ')}

{report.description_of_use}

Amount Used

{organisation?.default_currency || 'ZMW'} {report.amount_used.toLocaleString()}

Reported On

{format(new Date(report.date_reported), 'MMM d, yyyy')}

{report.supporting_documents_urls?.length > 0 && (

Supporting Documents

{report.supporting_documents_urls.map((url, idx) => ( Document {idx + 1} ))}
)}
))} {pendingReports.length === 0 && (

No pending reports

)}
setSelectedReport(null)}> Review Fund Usage Report {selectedReport && (

{selectedReport.report_title}

{selectedReport.description_of_use}

Amount

{organisation?.default_currency || 'ZMW'} {selectedReport.amount_used.toLocaleString()}

Date

{format(new Date(selectedReport.date_reported), 'PPP')}