# Meta Commerce & Pixel Connector for Shopify

A production-grade Shopify App & SaaS Platform that integrates Shopify stores with Meta Commerce (Facebook & Instagram Catalogs, Shops) and Meta Conversions API (CAPI) with high EMQ event matching scores, automated real-time catalog synchronization, multi-pixel management, official Shopify GraphQL Billing API integration, and a comprehensive Polaris-styled SaaS Admin Panel.

---

## 🚀 Quick Start

### 1. Prerequisites
- **Node.js**: v18.0.0 or higher
- **MySQL**: 5.7+ or 8.0+ (e.g., WAMP, XAMPP, or cloud MySQL)
- **Shopify Partner Account**: For Shopify App client credentials
- **Meta for Developers Account**: For Meta Graph API credentials

### 2. Installation
```bash
npm install
```

### 3. Environment Configuration
Copy the template file `.env.example` to `.env` (or `.env.local`):

```bash
cp .env.example .env
```

Fill in your database, Shopify, Meta, and SaaS Admin credentials as described in the [Environment Variables Guide](#-environment-variables-guide) below.

### 4. Build and Run
```bash
# Development mode
npm run dev

# Production build and start
npm run build
npm start
```

### 5. Running Verification Test Suites
```bash
# Run core unit and integration tests (61 tests)
npx tsx tests/runner.ts

# Run Shopify GraphQL Billing verification (11 tests)
npx tsx tests/billing-verify.ts

# Run SaaS Multi-Store Admin & RBAC verification (13 tests)
npx tsx tests/saas-admin-verify.ts

# Run End-to-End full workflow test suite (26 tests)
npx tsx tests/e2e-verify.ts
```

---

## 🔐 Environment Variables Guide

The application reads configuration through a strongly typed, validated configuration layer defined in [`src/lib/config/env.ts`](file:///c:/wamp/www/meta-ai-fb/src/lib/config/env.ts). Never commit `.env` or `.env.local` to version control; `.gitignore` is preconfigured to exclude them.

### Variable Reference

| Variable Name | Required | Default / Example | Description |
|:---|:---:|:---|:---|
| **Application & Server** | | | |
| `APP_ENV` | Yes | `development` / `production` | Application runtime environment. |
| `PORT` | No | `3000` | Port on which the Next.js server listens. |
| `NEXT_PUBLIC_APP_NAME` | No | `"Meta Commerce & Pixel Con"` | Display name for the application. |
| `NEXT_PUBLIC_APP_URL` | Yes | `http://localhost:3000` | Canonical public URL of the application. |
| `SHOPIFY_APP_URL` | Yes | `http://localhost:3000` | Redirect base URL for Shopify OAuth & callbacks. |
| `LOG_LEVEL` | No | `info` | Logging verbosity (`debug`, `info`, `warn`, `error`). |
| **SaaS Admin Portal** | | | |
| `ADMIN_EMAIL` | Yes | `admin@meta-connector.app` | Super Admin login email for the SaaS Admin Dashboard. |
| `ADMIN_PASSWORD` | Yes | `admin1234` | Super Admin password (change in production!). |
| `ADMIN_NAME` | No | `Sarah Jenkins (SaaS Owner)` | Super Admin display name. |
| `ADMIN_ROLE` | No | `super_admin` | Access role (`super_admin`, `admin`, `support`, `billing_manager`, `viewer`). |
| `ADMIN_SESSION_SECRET` | No | Random 32+ char string | Secret key for signing SaaS Admin session JWT tokens. |
| **Company & Support** | | | |
| `NEXT_PUBLIC_COMPANY_NAME` | No | `Digihorizon` | Organization / Partner company name. |
| `NEXT_PUBLIC_COMPANY_WEBSITE`| No | `https://digihorizon.in` | Partner website. |
| `NEXT_PUBLIC_SUPPORT_EMAIL`| Yes | `ashvin@digihorizon.in` | Support email displayed in app & merchant admin. |
| `NEXT_PUBLIC_SUPPORT_PHONE`| No | `+91 8000361445` | Formatted support telephone number. |
| `NEXT_PUBLIC_SUPPORT_PHONE_RAW`| No | `+918000361445` | E.164 tel link support phone number. |
| **Database & Storage** | | | |
| `DB_HOST` | Yes | `127.0.0.1` | MySQL server host. |
| `DB_PORT` | Yes | `3306` | MySQL port. |
| `DB_USER` | Yes | `root` | Database username. |
| `DB_PASSWORD` | No | `""` | Database password. |
| `DB_NAME` | Yes | `meta_connector` | MySQL database name. |
| `DATABASE_URL` | No | `mysql://root@127.0.0.1:3306/meta_connector` | Standard MySQL connection URI string. |
| **Security & Cryptography** | | | |
| `ENCRYPTION_SECRET` | Yes | 64-character hex string | 32-byte key used for AES-256-GCM token encryption. |
| `COOKIE_SECRET` | Yes | 32+ character string | Secret key for signing session cookies. |
| **Shopify Partner App & Billing** | | | |
| `SHOPIFY_API_KEY` | Yes | 32-character client key | Shopify App Client ID / API Key. |
| `NEXT_PUBLIC_SHOPIFY_API_KEY`| Yes | (matches `SHOPIFY_API_KEY`) | Client ID for frontend App Bridge initialization. |
| `SHOPIFY_API_SECRET` | Yes | `shpss_...` | Shopify App Client Secret. |
| `SHOPIFY_API_VERSION` | Yes | `2024-07` | Target Shopify GraphQL & REST API version. |
| `SHOPIFY_SCOPES` | Yes | `read_products,write_products,...` | OAuth permission scopes requested from stores. |
| `SHOPIFY_WEBHOOK_SECRET` | Yes | Webhook verification key | Secret used for HMAC-SHA256 Shopify webhook validation. |
| `DEFAULT_SHOP_DOMAIN` | No | `your-store.myshopify.com` | Default store domain for development fallback. |
| `SHOPIFY_APP_HANDLE` | No | `meta-connector` | App handle registered in Shopify Partner Dashboard. |
| `SHOPIFY_BILLING_TEST` | No | `true` | When `true`, recurring charges are created in test mode. |
| **Meta Commerce & CAPI** | | | |
| `META_APP_ID` | Yes | Numeric App ID | Meta Developer App ID. |
| `META_APP_SECRET` | Yes | Hex secret string | Meta Developer App Secret. |
| `META_GRAPH_VERSION` | Yes | `v20.0` | Meta Graph API version. |
| `META_BUSINESS_ID` | Yes | Numeric portfolio ID | Meta Business Manager / Portfolio ID. |
| `META_BUSINESS_NAME` | No | Business name | Meta Business Manager display name. |
| `META_CATALOG_ID` | Yes | Numeric catalog ID | Meta Commerce Product Catalog ID. |
| `META_PIXEL_ID` | Yes | Pixel ID string | Default / Master Meta Pixel ID. |
| `META_ACCESS_TOKEN` | No | System User Token | Permanent Meta System User Access Token. |
| `META_TEST_EVENT_CODE` | No | `TEST_DIGI_HORIZON` | Test Event Code for Meta Events Manager testing. |

---

### Generating Cryptographic Secrets

To generate a secure 32-byte (64 hex characters) key for `ENCRYPTION_SECRET`:

```bash
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```

To generate a session cookie secret:

```bash
node -e "console.log(require('crypto').randomBytes(24).toString('base64'))"
```

---

## 🛠️ Environment Validation

Environment variables are validated at startup via [`validateEnvironment()`](file:///c:/wamp/www/meta-ai-fb/src/lib/config/env.ts):

- **Strict Mode (`production`)**: Throws an explicit descriptive error if any required variable (`SHOPIFY_API_KEY`, `SHOPIFY_API_SECRET`, `ENCRYPTION_SECRET`, `DB_NAME`) is missing.
- **Cryptographic Checks**: Verifies `ENCRYPTION_SECRET` has sufficient length for AES-256-GCM cipher security.
- **Admin Password Auditing**: Issues a warning if the SaaS super admin uses a default development password in production.

---

## 🏢 SaaS Store Management Admin Panel

The platform includes an admin dashboard for the SaaS owner to monitor and manage all installed Shopify stores:

- **Route**: `http://localhost:3000/saas-admin`
- **Login Route**: `http://localhost:3000/saas-admin/login`
- **Default Super Admin**:
  - **Email**: `admin@meta-connector.app` (configurable via `ADMIN_EMAIL`)
  - **Password**: `admin1234` (configurable via `ADMIN_PASSWORD`)
- **Features**:
  - Live Store Directory & Real-time Status (Installed, Active, Trial, Cancelled, Uninstalled)
  - Subscription Plan Breakdown (Free, Growth, Advanced, Enterprise) & MRR Calculations
  - Deep-dive Store Detail view with webhook history, sync logs, and billing timeline
  - One-click CSV Export of all store records
  - Role-Based Access Control (Super Admin, Admin, Support, Billing Manager, Viewer)
