﻿# VOZEX Universal Marketplace Fulfillment Plan

## 1) Goal

Build one fulfillment architecture that supports all marketplace products:
- Multi-tenant SaaS products (example: POS SaaS)
- Single-tenant managed apps
- Self-hosted downloadable products (license + files)
- Service/manual delivery products
- Hybrid products (license + managed option)

This plan replaces product-specific logic with a strategy-driven flow.

---

## 2) Core Design Decision

Do not make VOZEX itself tenant-engine for every product.

Instead, VOZEX should be:
- Marketplace + Checkout + Billing + Order orchestration + Customer visibility

Product runtime should be handled by product-specific fulfillment adapters.

---

## 3) Universal Fulfillment Architecture

## 3.1 Product delivery model (required)

Add a clear delivery type per product:
- `saas_multitenant` (external tenant onboarding in product system)
- `saas_singletenant` (dedicated instance provisioning)
- `self_hosted_license` (license generation + download delivery)
- `self_hosted_download` (download only)
- `managed_setup` (manual/ops-assisted)
- `hybrid` (multiple selectable fulfillment paths)

## 3.2 Fulfillment adapter pattern

Create a common interface (conceptually):
- `FulfillmentAdapterInterface`
  - `supports(product)`
  - `fulfill(order, orderItem, paymentPayload)`
  - `syncStatus(reference)`
  - `suspend(reference)`
  - `cancel(reference)`

Concrete adapters:
- `MultiTenantSaasAdapter` (for products like `point-of-sale`)
- `SingleTenantProvisioningAdapter`
- `LicenseDownloadAdapter`
- `ManualFulfillmentAdapter`

VOZEX `ProcessWebhook` only resolves order/payment and delegates to correct adapter.

## 3.3 Payment gateway abstraction (Dodo + PayPal)

Payment must support multiple gateways, not hardcoded Dodo only.

Required payment layer:
- `PaymentGatewayInterface`
  - `createCheckoutSession(order, context)`
  - `verifyWebhook(request)`
  - `normalizeWebhookPayload(payload)`
  - `refund(payment, amount)`
- Concrete gateways:
  - `DodoPaymentGateway`
  - `PayPalPaymentGateway`
- `PaymentGatewayRouter` selects gateway by order/payment config.

Checkout requirements:
- Product/admin can allow one or more gateways (`dodo`, `paypal`).
- Customer chooses gateway at checkout when multiple are enabled.
- Order stores selected gateway in metadata (`payment_gateway`).

---

## 4) End-to-End Universal Flow

1. Customer buys product in VOZEX.
2. Checkout stores normalized order metadata (product delivery type + selected options + selected payment gateway).
3. Gateway-specific webhook (`dodo` or `paypal`) marks order as paid through unified payment router.
4. Fulfillment router selects adapter by product delivery model.
5. Adapter executes delivery:
   - SaaS MT: calls external product onboarding API
   - SaaS ST: creates dedicated installation/provisioning job
   - Self-hosted: generates license + download entitlement
   - Manual: opens ops task/ticket and marks awaiting action
6. Adapter stores external references and normalized fulfillment status.
7. Customer dashboard shows delivery status and next action per product type.

---

## 5) Data Model Changes (VOZEX)

## 5.1 Add/extend product config

Update product schema with:
- `delivery_model` (enum)
- `fulfillment_driver` (adapter key)
- `external_provider` (optional)
- `external_product_ref` (optional)
- `fulfillment_config` (json)
- `enabled_payment_gateways` (json/array; e.g. `["dodo","paypal"]`)
- `default_payment_gateway` (string)

## 5.2 Add fulfillment tracking table

Create table: `fulfillment_records`
- `id`
- `order_id`
- `order_item_id`
- `product_id`
- `driver`
- `status` (`queued`, `processing`, `active`, `awaiting_customer`, `manual_pending`, `failed`, `cancelled`)
- `external_reference_id`
- `external_workspace_url`
- `external_customer_id`
- `attempts`
- `last_error`
- `payload_snapshot` (json)
- timestamps

## 5.3 Optional product-specific link table

If needed for SaaS MT products: `external_tenant_links`
- `fulfillment_record_id`
- `provider`
- `external_tenant_id`
- `external_subscription_id`
- `external_user_id`

## 5.4 Admin product onboarding schema (must change)

Current product add flow is not enough for adapter-based fulfillment.  
Admin product create/edit must save fulfillment metadata explicitly.

Required product-level fields:
- `delivery_model` (enum; required)
- `fulfillment_driver` (enum; required)
- `is_recurring` (bool)
- `supports_trial` (bool)
- `trial_days` (int, conditional)
- `external_provider` (string, conditional)
- `external_product_ref` (string, conditional)
- `fulfillment_config` (json, conditional by driver)

Driver-specific `fulfillment_config` examples:
- `multitenant_saas`:
  - `base_url`
  - `onboard_endpoint`
  - `status_endpoint`
  - `suspend_endpoint` (optional)
  - `cancel_endpoint` (optional)
  - `auth_mode` (`hmac` or `bearer`)
  - `credentials_ref` (secret reference key, not raw secret)
  - `timeout_seconds`
- `singletenant_provisioning`:
  - server template/profile id
  - resource limits profile
  - default domain strategy
- `license_download`:
  - license template/type
  - download artifact source
  - activation policy
- `manual_fulfillment`:
  - internal team queue id
  - SLA hours
  - default instruction template

---

## 6) Backend Update Plan (VOZEX)

## 6.1 Existing files to update

- `backend/app/Http/Controllers/Api/CheckoutController.php`
  - Normalize delivery selections, payment gateway selection, and store deterministic metadata.
- `backend/app/Jobs/ProcessWebhook.php`
  - Replace product-specific branching with `FulfillmentRouterService`.
- `backend/app/Http/Controllers/Api/CustomerController.php`
  - Return unified fulfillment status/actions for dashboard.
- `backend/config/marketplace.php`
  - Add adapter config, provider endpoints, payment gateways, timeouts, retry policy.
- `backend/routes/api.php`
  - Add admin/customer fulfillment status/retry endpoints.
- `backend/app/Http/Controllers/Api/ProductController.php`
  - Add strict validation and normalization for onboarding fields.
- `backend/app/Http/Controllers/Api/ProductPricingMappingController.php`
  - Enforce billing/driver consistency checks.
- `backend/app/Http/Controllers/Api/WebhookController.php`
  - Split/route webhook handlers by gateway (`/webhooks/dodo`, `/webhooks/paypal`).

## 6.2 New files/classes to add

- `backend/app/Services/Fulfillment/FulfillmentRouterService.php`
- `backend/app/Services/Fulfillment/FulfillmentAdapterInterface.php`
- `backend/app/Services/Fulfillment/Adapters/MultiTenantSaasAdapter.php`
- `backend/app/Services/Fulfillment/Adapters/SingleTenantProvisioningAdapter.php`
- `backend/app/Services/Fulfillment/Adapters/LicenseDownloadAdapter.php`
- `backend/app/Services/Fulfillment/Adapters/ManualFulfillmentAdapter.php`
- `backend/app/Models/FulfillmentRecord.php`
- `backend/app/Jobs/RetryFulfillmentJob.php`
- `backend/app/Notifications/FulfillmentReadyNotification.php`
- `backend/app/Notifications/FulfillmentFailedNotification.php`
- `backend/app/Http/Requests/Admin/StoreProductFulfillmentRequest.php`
- `backend/app/Http/Requests/Admin/UpdateProductFulfillmentRequest.php`
- `backend/app/Services/Fulfillment/FulfillmentConfigValidator.php`
- `backend/app/Services/Fulfillment/FulfillmentDriverRegistry.php`
- `backend/app/Services/Payments/PaymentGatewayInterface.php`
- `backend/app/Services/Payments/PaymentGatewayRouter.php`
- `backend/app/Services/Payments/Gateways/DodoPaymentGateway.php`
- `backend/app/Services/Payments/Gateways/PayPalPaymentGateway.php`
- `backend/app/Http/Controllers/Api/PayPalWebhookController.php` (or unified gateway webhook controller)

## 6.3 Migration files to add

- `backend/database/migrations/2026_04_20_000000_add_delivery_model_to_products_table.php`
- `backend/database/migrations/2026_04_20_000100_create_fulfillment_records_table.php`
- `backend/database/migrations/2026_04_20_000200_create_external_tenant_links_table.php` (optional)
- `backend/database/migrations/2026_04_20_000300_add_fulfillment_columns_to_products_table.php`
- `backend/database/migrations/2026_04_20_000400_add_gateway_fields_to_products_and_orders.php`

---

## 7) Frontend Update Plan

## 7.1 Existing files to update

- `frontend/src/pages/Checkout.jsx`
  - Show product-type-specific options plus payment gateway selector (`Dodo`/`PayPal`) when enabled.
- `frontend/src/pages/OrderConfirmation.jsx`
  - Show fulfillment-specific status block and expected SLA.
- `frontend/src/pages/CustomerOrders.jsx`
  - Add fulfillment summary per order item.
- `frontend/src/pages/CustomerInstallations.jsx`
  - Show only when relevant (managed/single-tenant/SaaS).
- `frontend/src/pages/CustomerLicenses.jsx`
  - Show only when relevant (self-hosted/hybrid).
- `frontend/src/pages/CustomerSubscriptions.jsx`
  - Map to recurring products only.
- `frontend/src/components/CustomerDashboardNav.jsx`
  - Conditional tabs by purchased product mix.

## 7.2 New frontend pages/components

- `frontend/src/pages/CustomerFulfillmentCenter.jsx`
- `frontend/src/components/FulfillmentStatusCard.jsx`
- `frontend/src/components/FulfillmentActionPanel.jsx`

## 7.3 Admin product add/edit flow updates (mandatory)

Admin UI must prevent invalid product config combinations.

Update admin product management screens:
- Add onboarding section with:
  - delivery model selector
  - fulfillment driver selector (filtered by model)
  - recurring/trial toggles
  - provider + external reference fields
  - enabled payment gateways multi-select
  - default gateway selector
  - JSON editor/form builder for `fulfillment_config`
- Add real-time validation hints (required fields by driver).
- Add “Test Connection” action for SaaS drivers.
- Add “Test Payment Gateway Connection” action for each enabled gateway.
- Add “Preview checkout options” action to verify customer-side rendering.

Frontend files to update:
- `frontend/src/admin/ProductForm.jsx` (or equivalent product create/edit component)
- `frontend/src/admin/AdminProducts.jsx`
- `frontend/src/services/api.js` (new test-connection endpoint)
- `frontend/src/utils/productFulfillmentValidation.js` (new)

---

## 8) Provider Contract for External SaaS Products

For products like `point-of-sale`, define standard API contract.

Required endpoints on provider side:
- `POST /api/marketplace/onboard`
- `POST /api/marketplace/suspend`
- `POST /api/marketplace/cancel`
- `POST /api/marketplace/upgrade` (optional)
- `GET /api/marketplace/status/{external_reference}`

Contract requirements:
- Signed auth (HMAC or service token)
- Idempotency key (`order_id` + `order_item_id`)
- Deterministic response: external IDs + workspace URL + status

---

## 9) Product Onboarding Checklist (For Every New Product)

- [ ] Define `delivery_model`
- [ ] Configure `fulfillment_driver`
- [ ] Configure pricing mappings + billing model
- [ ] Configure enabled payment gateways (`dodo`, `paypal`) and default gateway
- [ ] Configure adapter-specific `fulfillment_config`
- [ ] Validate admin form with driver-specific rule set
- [ ] Run “Test Connection” (for external SaaS drivers)
- [ ] Run payment gateway connection test for Dodo/PayPal
- [ ] Confirm checkout renders correct options for selected driver/model
- [ ] Validate webhook to fulfillment path in staging
- [ ] Add customer dashboard UX mapping
- [ ] Add failure/retry operational runbook

---

## 10) Universal Operational Checklist

- [ ] Idempotency for all fulfillment writes
- [ ] Idempotency for all payment webhooks (Dodo and PayPal)
- [ ] Retries with backoff for transient provider failures
- [ ] Dead-letter path for repeated failures
- [ ] Admin manual retry endpoint
- [ ] Structured logs with `order_id`, `order_item_id`, `driver`, `external_reference`
- [ ] Structured payment logs with `gateway`, `event_id`, `order_id`, `payment_id`
- [ ] Alerting for failure thresholds

---

## 11) Rollout Plan

## Phase A - Foundation
- [ ] Add product delivery model fields
- [ ] Add `fulfillment_records`
- [ ] Add router + adapter interface

## Phase B - First adapters
- [ ] Implement `LicenseDownloadAdapter`
- [ ] Implement `MultiTenantSaasAdapter` (for `point-of-sale`)

## Phase C - Dashboard unification
- [ ] Add fulfillment center UI
- [ ] Update order confirmation and customer pages

## Phase D - Remaining adapters
- [ ] Add single-tenant + manual adapters
- [ ] Add admin retry/ops tooling

## Phase E - Product-by-product migration
- [ ] Migrate existing products to delivery models
- [ ] Remove hardcoded product-specific fulfillment branches

---

## 12) What Changes for `point-of-sale` Specifically

`point-of-sale` becomes one product onboarded through `MultiTenantSaasAdapter`.

VOZEX side:
- product config:
  - `delivery_model = saas_multitenant`
  - `fulfillment_driver = multitenant_saas`
  - provider endpoint/auth in `fulfillment_config`

POS side:
- expose marketplace onboarding/status APIs
- ensure idempotent tenant creation by external order reference

No need to redesign all VOZEX tables as global tenant-first architecture for this use-case.

---

## 13) Final Decision Summary

Use one universal fulfillment platform in VOZEX.

- VOZEX handles commerce lifecycle.
- Adapters handle product-specific delivery lifecycle.
- Multi-tenant SaaS and non-SaaS products both fit cleanly under same orchestration model.
