### Documentation Placeholders Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt Placeholders for documentation files. `buy.html` contains a button linking to a Gumroad purchase page for the 'zatca-pro' product. `quick-start.md` outlines the initial steps for users to install the core SDK, obtain a key, and install the pro version. ```markdown # Quick Start ## Install Core Run the following command to install the core SDK: ```bash npm install @zatca-sdk/core ``` ## Get Key Obtain your Zatca API key from the developer portal. ## Install Pro After installing the core SDK and obtaining your key, install the pro version: ```bash npm install @zatca-sdk/pro ``` ``` -------------------------------- ### Post-install Hint Script Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt A root-level script that runs after npm installation. It provides helpful messages to the user, guiding them on how to run demo commands for both the core and pro versions of the SDK, including instructions for unlocking production features. ```javascript // postinstall.js console.log('✅ Run *npm run core-demo* to clear a sandbox invoice.'); console.log('🔓 Unlock production: *npm run pro-demo -- --licence ZSDK…*.'); ``` -------------------------------- ### GitHub Actions CI Workflow for Publishing Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt Automates the publishing of the '@zatca-sdk/core' package to the npm registry when a Git tag starting with 'v' is created. It sets up Node.js, installs dependencies, and executes the npm publish command using a provided NPM token. ```yaml name: Publish Core Package on: push: tags: - 'v*' jobs: publish: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Set up Node.js uses: actions/setup-node@v3 with: node-version: 18 - name: Install dependencies run: npm ci -w packages/core - name: Publish to npm run: npm publish --access public -w packages/core env: NPM_TOKEN: ${{ secrets.NPM_TOKEN }} ``` -------------------------------- ### Documentation Placeholders Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt Placeholders for documentation files. `buy.html` contains a button linking to a Gumroad purchase page for the 'zatca-pro' product. `quick-start.md` outlines the initial steps for users to install the core SDK, obtain a key, and install the pro version. ```html ``` -------------------------------- ### Installation Commands for End Users Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/FINAL_PUBLISH_INSTRUCTIONS.md These bash commands guide end-users on how to configure their npm environment to install the @mouna-bassim/pro package from GitHub Packages. This includes setting the registry and authenticating using a GitHub token. ```bash # Configure registry echo "@mouna-bassim:registry=https://npm.pkg.github.com" >> ~/.npmrc # Authenticate (users need GitHub token with read:packages) echo "//npm.pkg.github.com/:_authToken=USER_GITHUB_TOKEN" >> ~/.npmrc # Install pro package npm install @mouna-bassim/pro ``` -------------------------------- ### Install Pro Package (Bash) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PUBLISH_PRO_PACKAGE.md Installs the '@zatca-sdk/pro' package from the GitHub Packages registry using npm. This command assumes the registry and authentication have been previously configured. ```bash npm install @zatca-sdk/pro ``` -------------------------------- ### Pushing ZATCA SDK to GitHub Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/DEPLOYMENT.md Commands to add the GitHub remote, stage all files, commit changes with a descriptive message, and push to the origin main branch. This prepares the SDK for deployment. ```bash git remote add origin git@github.com:mouna-bassim/zatca-sdk.git git add . git commit -m "feat: Convert to production-ready npm packages - Core package ready for npm registry - Pro package configured for GitHub Packages - CI/CD pipeline with automated publishing - Gumroad payment integration complete - Demo environment separated from packages - TypeScript build configurations added" git push -u origin main ``` -------------------------------- ### Internationalization (i18n) Setup (JavaScript) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-1-How-the-app-talks-to-the-teacher-ZATCA-Think-of-ZATCA-as-a-website-with-two-locked-doors-Your-1751279030357_1751279030358.txt Provides a basic setup for internationalizing an application using JSON files for different languages. It includes loading language dictionaries, managing the current language, and a translation function. ```javascript const dict = { en: require('./i18n/en.json'), ar: require('./i18n/ar.json') }; let lang = 'en'; app.get('/lang/:id', (req, res) => { lang = req.params.id; res.redirect('/'); }); function t(key) { return dict[lang][key] || key; } ``` -------------------------------- ### Verifying Core Package Installation Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PRE_DEPLOYMENT_CHECKLIST.md Command to install the core ZATCA SDK package from the npm registry. This is a crucial step to ensure the package is publicly available and correctly published. ```bash npm install @zatca-sdk/core ``` -------------------------------- ### Setting Production Environment Variables for ZATCA SDK Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/DEPLOYMENT.md Example bash commands to set essential environment variables for the ZATCA SDK in a production hosting environment. These include Gumroad integration, ZATCA API configuration, and database connection strings. ```bash # Gumroad Integration export GUMROAD_WEBHOOK_SECRET=your-webhook-secret # ZATCA Configuration export ZATCA_API_BASE_URL=https://gw-fatoora.zatca.gov.sa/e-invoicing/developer-portal export ZATCA_VAT_NUMBER=your-vat-number export ZATCA_SELLER_NAME=your-company-name # Database (for purchase tracking) export DATABASE_URL=your-database-connection-string ``` -------------------------------- ### README Version Tagging Instructions Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt Instructions within the root README file on how to tag releases using Git. It specifies the commands for creating a new tag and pushing it to the remote repository, which triggers the CI workflow for publishing. ```markdown Tag releases with **git tag v1.0.0 && git push --tags** to trigger publish. ``` -------------------------------- ### Configure ZATCA SDK Pro Licence Key (Environment Variable) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/docs/quick-start.md Sets the ZATCA SDK Pro license key as an environment variable. This is necessary for enabling production features and accessing ZATCA's live endpoints. The license key is typically provided via email after purchase. ```bash export ZSDK_LICENCE_KEY=ZSDK1234567890ABCDEF ``` -------------------------------- ### Run ZATCA SDK Demo Environment Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/demo/README.md Command to navigate to the demo directory and start the Express server for the ZATCA SDK demo environment. This is used to access the interactive web UI for testing. ```bash cd demo node server.js ``` -------------------------------- ### Testing and Publishing ZATCA Core Package Locally Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/DEPLOYMENT.md Steps to build the core package, perform a dry run of publishing to npm to verify the process, and then publish the package publicly. Assumes you are in the 'packages/core' directory. ```bash cd packages/core npm run build npm publish --dry-run --access public npm publish --access public ``` -------------------------------- ### Node.js: Example Simplified Invoice Clearance Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-Build-a-Node-based-ZATCA-Phase-2-e-Invoice-SDK-that-one-command-npm-start-can-demo-from-i-1751274085830_1751274085831.txt Demonstrates the end-to-end process of creating, signing, generating a QR code, and submitting a dummy simplified e-invoice to the ZATCA sandbox API. This script is intended for a CLI demo. ```javascript // examples/demo-simplified.js import { createCSR, loadCertificate, buildInvoiceXML, signInvoice, generateTLVQR, submitForClearance } from "../src/index.js"; import fs from 'fs'; async function runDemo() { // 1. Generate keys and CSR (assuming ./csr.pem and ./ec-priv.pem exist or are generated) // ... user uploads CSR and gets cert.pem, CSID ... const privateKey = fs.readFileSync('./ec-priv.pem'); const certificate = fs.readFileSync('./cert.pem'); const csid = 'YOUR_CSID_FROM_PORTAL'; // Replace with actual CSID // 2. Build a dummy simplified invoice const invoiceData = { /* ... details for a simplified invoice ... */ }; const xml = buildInvoiceXML(invoiceData); // 3. Sign the invoice const signedXml = await signInvoice(xml, privateKey, certificate); // 4. Generate QR code const qr = generateTLVQR({ /* ... invoice summary data ... */ }); // 5. Submit for clearance const result = await submitForClearance(signedXml, csid, '/clearance/simplified'); console.log(`✅ CSR ready at ./csr.pem -- Upload to ZATCA, paste cert. ✅ Dummy simplified invoice cleared -- ID: ${result.clearedUUID}`); } runDemo(); ``` -------------------------------- ### Run Core Demo (Free Sandbox) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/README.md Installs project dependencies and runs the core demo script to test the ZATCA e-invoicing functionality in the free sandbox environment. ```bash npm install npm run core-demo ``` -------------------------------- ### Setup and Run Core Demo (Free Sandbox) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/README.md Configures environment variables for VAT number and seller name, then runs the core SDK demo to test invoice generation and submission in simulation mode. ```bash export ZATCA_VAT_NUMBER="123456789012345" export ZATCA_SELLER_NAME="Your Company Ltd" npm run core-demo ``` -------------------------------- ### Tag ZATCA SDK Release for Publishing Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/docs/quick-start.md Tags a specific version of the ZATCA SDK for release. Pushing these tags to the Git repository triggers a GitHub Actions workflow that automatically publishes the Core package to npm. This is part of the version management process. ```bash git tag v1.0.1 git push --tags ``` -------------------------------- ### Install @mouna-bassim/pro Package Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/pro/README.md Installs the premium ZATCA SDK package using npm. This is the initial step to integrate the SDK into your Node.js project. ```bash npm install @mouna-bassim/pro ``` -------------------------------- ### Tagging and Pushing First ZATCA SDK Release Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/DEPLOYMENT.md Commands to create a Git tag for version 1.0.0 and push it to the remote repository. This action triggers the CI/CD pipeline for automated publishing. ```bash git tag v1.0.0 git push --tags ``` -------------------------------- ### NPM Package Scripts Configuration Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt Defines essential npm scripts for building and preparing packages for publication. The 'build' script compiles TypeScript, and 'prepublishOnly' ensures the build runs before each npm publish. ```json "scripts": { "build": "tsc -p .", "prepublishOnly": "npm run build" } ``` -------------------------------- ### Core NPM Package Metadata Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt Configuration for the '@zatca-sdk/core' npm package, including its name, description, license, repository link, and files to be included in the published package. The 'files' array specifies which directories and files are distributed. ```json { "name": "@zatca-sdk/core", "description": "Core SDK for Zatca integration.", "license": "MIT", "repository": "git@github.com:mouna-bassim/zatca-sdk.git", "files": [ "dist", "src" ] } ``` -------------------------------- ### Pro NPM Package Metadata Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt Configuration for the '@zatca-sdk/pro' npm package, marking it as private and specifying a 'Commercial' license. It includes a repository link and an internal .npmrc configuration to point to GitHub Packages. ```json { "name": "@zatca-sdk/pro", "private": true, "license": "Commercial", "repository": "git@github.com:mouna-bassim/zatca-sdk.git", "_npmrc": "registry=https://npm.pkg.github.com/" } ``` -------------------------------- ### Gitignore Configuration Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt Specifies files and directories to be ignored by Git, ensuring that sensitive information and build artifacts are not committed to the repository. This includes node_modules, environment files, and certificate files. ```gitignore # Ignore node_modules node_modules # Ignore environment variables .env # Ignore certificates and keys certs/ *.pem *.key ``` -------------------------------- ### Configure GitHub Packages Registry for Installation (Bash) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PUBLISH_PRO_PACKAGE.md Appends the GitHub Packages registry configuration to the user's global '.npmrc' file. This allows npm to find and install packages published to GitHub Packages. ```bash echo "@zatca-sdk:registry=https://npm.pkg.github.com/" >> ~/.npmrc ``` -------------------------------- ### License Webhook Handler Stub Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--GOAL-Convert-the-current-monorepo-Core-Pro-into-production-ready-npm-packages-and-prep-the-1751283307247_1751283307247.txt A placeholder for a license delivery webhook handler. It includes a README explaining the expected Gumroad ping payload and an empty Express router in a .js file, with TODO comments indicating where the implementation should go. ```javascript // webhooks/gumroad/handler.todo.js // TODO: Implement Gumroad webhook handler // This file is a stub for the licence-delivery webhook. // It should handle incoming ping payloads from Gumroad. const express = require('express'); const router = express.Router(); // TODO: Define endpoint to receive Gumroad pings router.post('/gumroad-ping', (req, res) => { console.log('Received Gumroad ping:', req.body); // TODO: Process the payload and update license information res.status(200).send('Webhook received'); }); module.exports = router; ``` -------------------------------- ### Publish Pro Package to GitHub Packages (Bash) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PUBLISH_PRO_PACKAGE.md Publishes the Pro package to the configured npm registry, which is set to GitHub Packages. This command uploads the package, making it available for installation by others with appropriate permissions. ```bash npm publish ``` -------------------------------- ### Complete ZATCA Invoice Workflow Example (JavaScript) Source: https://context7.com/mouna-bassim/zatca-sdk/llms.txt This JavaScript code demonstrates the end-to-end workflow for ZATCA e-invoicing. It covers initializing the SDK, generating credentials (if not existing), building an invoice XML, generating a QR code, signing the invoice, and submitting it for clearance. It requires private key and certificate files, and ZATCA CSID from environment variables. ```javascript import { ZATCAInvoiceSDK } from '@zatca-sdk/core'; import fs from 'fs/promises'; async function completeWorkflow() { try { // Step 1: Initialize SDK const sdk = new ZATCAInvoiceSDK({ vatNumber: '312345678900003', sellerName: 'Test Company Ltd' }); console.log('Step 1: SDK initialized'); // Step 2: Generate device credentials (one-time setup) let credentials; try { await fs.access('./ec-priv.pem'); console.log('Step 2: Using existing credentials'); } catch { credentials = await sdk.generateDeviceCredentials(); console.log('Step 2: New credentials generated'); console.log('→ Upload ./csr.pem to ZATCA portal'); console.log('→ Download certificate and set ZATCA_CSID'); return; // Stop here until manual certificate upload } // Step 3: Build invoice const invoiceData = { type: 'simplified', id: 'INV-' + Date.now(), totalAmount: 115.00, sellerName: 'Test Company Ltd', sellerVAT: '312345678900003', sellerAddress: { street: 'King Fahd Road', buildingNumber: '1234', city: 'Riyadh', postalCode: '12345' }, lineItems: [{ id: '1', quantity: 2, unitPrice: 50.00, itemName: 'Consulting Services' }] }; const xml = sdk.buildInvoiceXML(invoiceData); console.log('Step 3: Invoice XML built'); // Step 4: Generate QR code (simplified invoices only) const qrCode = sdk.generateTLVQR(invoiceData); console.log('Step 4: QR code generated:', qrCode.substring(0, 30) + '...'); // Step 5: Sign invoice const signed = await sdk.signInvoice(xml, './ec-priv.pem', './cert.pem'); console.log('Step 5: Invoice signed'); // Step 6: Submit for clearance const response = await sdk.submitForClearance( signed.signedXML, 'simplified', process.env.ZATCA_CSID ); if (response.success && response.reportingStatus === 'CLEARED') { console.log('Step 6: ✅ Invoice cleared successfully!'); console.log('Cleared UUID:', response.clearedUUID); console.log('Invoice Hash:', response.invoiceHash); // Save cleared invoice await fs.writeFile( `./invoices/cleared-${invoiceData.id}.xml`, signed.signedXML ); return { success: true, invoiceId: invoiceData.id, clearedUUID: response.clearedUUID, qrCode: qrCode }; } else { throw new Error('Clearance failed: ' + JSON.stringify(response.errors)); } } catch (error) { console.error('Workflow failed:', error.message); throw error; } } completeWorkflow() .then(result => console.log('Final result:', result)) .catch(error => console.error('Fatal error:', error)); ``` -------------------------------- ### Set ZATCA SDK Pro Licence Key (CLI/Environment) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/demo/docs/buy.html This snippet shows how to set the ZATCA SDK Pro licence key, either by exporting it as an environment variable or by using a CLI flag with npm. This is necessary to activate premium features. ```bash # Set your licence key export ZSDK_LICENCE_KEY=ZSDK1234567890ABCDEF # Or use CLI flag npm run pro-demo -- --licence ZSDK1234567890ABCDEF ``` -------------------------------- ### Run ZATCA SDK System Diagnostics Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/core/README.md Execute the `doctor` command using the ZATCA SDK CLI to perform system diagnostics and check for potential issues with your setup. ```bash # System diagnostics npx zatca-sdk doctor ``` -------------------------------- ### Authenticate with GitHub Packages for Installation (Bash) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PUBLISH_PRO_PACKAGE.md Appends authentication token configuration to the user's global '.npmrc' file, enabling access to private packages on GitHub Packages. Users must replace 'USER_GITHUB_TOKEN' with their actual GitHub personal access token. ```bash echo "//npm.pkg.github.com/:_authToken=USER_GITHUB_TOKEN" >> ~/.npmrc ``` -------------------------------- ### Migrate from ZATCA Core SDK to ZATCA Pro SDK Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/pro/README.md This example shows the differences in importing and initializing the ZATCA SDK when migrating from the core version to the Pro version. It highlights the addition of a license key and potential changes in environment settings. Core methods remain compatible. ```javascript // Before (Core) import { ZATCAInvoiceSDK } from '@zatca-sdk/core'; const sdk = new ZATCAInvoiceSDK({ environment: 'sandbox' }); // After (Pro) import { ZATCAProSDK } from '@zatca-sdk/pro'; const sdk = new ZATCAProSDK({ licenseKey: 'ZSDK...', environment: 'production' }); // All Core methods remain compatible const credentials = await sdk.generateDeviceCredentials(); const invoice = await sdk.createSimplifiedInvoice(data); ``` -------------------------------- ### Set ZATCA SDK Pro Licence Key (CLI Flag) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/docs/buy.html Shows how to pass the ZATCA SDK Pro licence key as a command-line interface (CLI) flag when running a demo. This method is useful for temporary or specific executions where setting an environment variable might not be desired. ```bash npm run pro-demo -- --licence ZSDK1234567890ABCDEF ``` -------------------------------- ### JavaScript: Load Sample Webhook Payload Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/docs/admin.html Populates a textarea element with a sample JSON payload for testing the webhook functionality. This provides a pre-formatted example for users to test with. Dependencies: 'webhookPayload' textarea element and JSON.stringify. ```javascript function loadSamplePayload() { const samplePayload = { type: "sale", id: "test-" + Date.now(), email: "customer@example.com", product_name: "ZATCA SDK Pro", price: "29", currency: "USD" }; document.getElementById('webhookPayload').value = JSON.stringify(samplePayload, null, 2); } ``` -------------------------------- ### Makefile for Build and Test Automation Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-Why-the-certificate-CSID-matter-Device-keys-CSR-already-generated-when-you-pressed-Run-see-cs-1751278342007_1751278342008.txt This Makefile outlines commands for building the project and running automated tests. It includes targets for cleaning build artifacts, installing dependencies, and executing tests, which are crucial for maintaining a robust development workflow and ensuring the integrity of the ZATCA SDK integration. ```makefile # Makefile example (conceptual) .PHONY: all clean install test all: install test clean: @echo "Cleaning build artifacts..." ifeq ($(OS),Windows_NT) -del /s /q build dist *.pyc __pycache__ else -rm -rf build dist *.pyc __pycache__ endif install: @echo "Installing dependencies..." ifeq ($(OS),Windows_NT) @echo "(Assuming pip is in PATH)" pip install -r requirements.txt else pip3 install -r requirements.txt endif test: @echo "Running tests..." ifeq ($(OS),Windows_NT) @echo "(Assuming python is in PATH)" python -m unittest discover -s tests else python3 -m unittest discover -s tests endif # Example of a specific build target if needed # build: # @echo "Building project..." # # Add build commands here ``` -------------------------------- ### Configure GitHub Packages Authentication Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/pro/README.md Sets up authentication for GitHub Packages, which is necessary for private npm package installations. This involves configuring the .npmrc file with registry details and an authentication token. ```bash # Configure GitHub Packages authentication echo "@mouna-bassim:registry=https://npm.pkg.github.com" >> ~/.npmrc echo "//npm.pkg.github.com/:_authToken=YOUR_GITHUB_TOKEN" >> ~/.npmrc ``` -------------------------------- ### Executing ZATCA SDK Pro Demo with License Check Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PRE_DEPLOYMENT_CHECKLIST.md Command to run the demo for the pro version of the ZATCA SDK, which is expected to require a license key for execution. This verifies the licensing mechanism. ```bash npm run pro-demo ``` -------------------------------- ### Git Commands for Production Push and Release Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PRE_DEPLOYMENT_CHECKLIST.md Standard Git commands to add all project files, commit them with a feature message, set the remote origin, and push to the main branch. It also includes commands for tagging the first release and pushing tags to trigger CI/CD pipelines. ```bash git add . git commit -m "feat: Production-ready ZATCA SDK packages" git remote add origin git@github.com:mouna-bassim/zatca-sdk.git git push -u origin main git tag v1.0.0 git push --tags ``` -------------------------------- ### Setting Gumroad Webhook Secret Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/DEPLOYMENT.md Command to export the Gumroad webhook secret as an environment variable. This is crucial for securing communication between Gumroad and your application. ```bash export GUMROAD_WEBHOOK_SECRET=your-secure-secret-here ``` -------------------------------- ### Get Certificate Status Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/pro/README.md Check the status of your digital certificate, including days until expiry and overall status. ```APIDOC ## Certificate Monitoring ### Description Monitor the status and expiration of your digital certificate. ### Method `getCertificateStatus()` ### Response #### Success Response (200) - **daysUntilExpiry** (number) - Number of days until the certificate expires. - **status** (string) - Certificate status ('active', 'expiring', 'expired'). ### Request Example ```javascript const certStatus = await sdk.getCertificateStatus(); console.log('Expires in:', certStatus.daysUntilExpiry); console.log('Status:', certStatus.status); if (certStatus.daysUntilExpiry <= 30) { await sdk.sendRenewalAlert(); } ``` ``` -------------------------------- ### Get Usage Analytics Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/pro/README.md Retrieve analytics data on invoice processing, success rates, and average processing times over a specified period. ```APIDOC ## Usage Analytics ### Description Fetch key performance metrics related to invoice processing. ### Method `getAnalytics(options: Object)` ### Parameters #### Request Body (options) - **period** (string) - Required - The time period for analytics (e.g., 'last-30-days', 'last-month'). - **metrics** (Array) - Required - List of metrics to retrieve (e.g., 'invoice-count', 'success-rate', 'avg-processing-time'). ### Response #### Success Response (200) - **invoiceCount** (number) - Total number of invoices processed. - **successRate** (number) - The rate of successful invoice processing. - **avgProcessingTime** (number) - Average time taken to process invoices. ### Request Example ```javascript const analytics = await sdk.getAnalytics({ period: 'last-30-days', metrics: ['invoice-count', 'success-rate', 'avg-processing-time'] }); console.log('Invoices processed:', analytics.invoiceCount); console.log('Success rate:', analytics.successRate); console.log('Avg processing time:', analytics.avgProcessingTime); ``` ``` -------------------------------- ### Publishing Commands for @mouna-bassim/pro Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/FINAL_PUBLISH_INSTRUCTIONS.md These bash commands are used to navigate to the pro package directory, verify its configuration in package.json and .npmrc, and then publish the package to GitHub Packages. The expected output after a successful publish is also shown. ```bash cd packages/pro cat package.json | grep name # Should show: "name": "@mouna-bassim/pro", cat .npmrc # Should show: @mouna-bassim:registry=https://npm.pkg.github.com/ npm publish # Expected output: # + @mouna-bassim/pro@1.0.4 ``` -------------------------------- ### Production Demo Execution with Licence Key (Shell) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--PROJECT-TITLE-ZATCA-Phase-2-e-Invoice-SDK-Freemium-Premium--1751280019217_1751280019217.txt Command to run the production demo of the ZATCA SDK, requiring a license key. The license key can be provided via an environment variable or a CLI flag. ```shell npm run pro-demo -- --licence $ZSDK_LICENCE_KEY ``` -------------------------------- ### Initialize ZATCAProSDK with Production Settings Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/pro/README.md Initializes the ZATCAProSDK for production use. This requires a license key, VAT number, seller name, and specifies the 'production' environment. The SDK is essential for interacting with ZATCA's live APIs. ```javascript import { ZATCAProSDK } from '@zatca-sdk/pro'; const sdk = new ZATCAProSDK({ licenseKey: 'ZSDK1234567890ABCDEF', // Your purchased license vatNumber: '399999999800003', sellerName: 'Your Company Name', environment: 'production' // Full production access }); ``` -------------------------------- ### Simulate Purchase Success Alert (JavaScript) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/demo/docs/buy.html This JavaScript code simulates a purchase completion by checking URL parameters. If a 'purchase' parameter with the value 'success' is found, it displays an alert message to the user. This is intended for demonstration purposes. ```javascript document.addEventListener('DOMContentLoaded', function() { const urlParams = new URLSearchParams(window.location.search); if (urlParams.get('purchase') === 'success') { alert('🎉 Purchase successful! Check your email for your licence key.'); } }); ``` -------------------------------- ### Execute Publishing Script (Bash) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PUBLISH_PRO_PACKAGE.md Makes the 'publish-to-github.sh' script executable and then runs it. This provides an automated way to publish the Pro package, simplifying the process. ```bash chmod +x publish-to-github.sh ./publish-to-github.sh ``` -------------------------------- ### Initialize ZATCAInvoiceSDK Programmatically Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/core/README.md Demonstrates initializing the ZATCAInvoiceSDK with various configuration options, including VAT number, seller name, environment, optional API base URL, and CSID. ```javascript import { ZATCAInvoiceSDK } from '@zatca-sdk/core'; const sdk = new ZATCAInvoiceSDK({ vatNumber: 'string', // Your VAT registration number sellerName: 'string', // Legal entity name environment: 'sandbox', // 'sandbox' or 'production' (Pro only) apiBaseUrl: 'string', // Optional: Custom API URL csid: 'string' // Optional: Compliance CSID }); ``` -------------------------------- ### Initialize ZATCA SDK Instance Source: https://context7.com/mouna-bassim/zatca-sdk/llms.txt Initializes the ZATCA e-Invoice SDK with essential configuration like VAT number and seller name. Supports both a free Core package for sandbox testing and a Premium Pro package for production environments, which requires additional environment and argument settings. ```javascript import { ZATCAInvoiceSDK } from '@zatca-sdk/core'; // Free tier - Sandbox only const sdk = new ZATCAInvoiceSDK({ vatNumber: '123456789012345', sellerName: 'Your Company Ltd' }); // Premium tier - Production enabled import { ZATCAInvoiceSDKPro } from '@zatca-sdk/pro'; const sdkPro = new ZATCAInvoiceSDKPro({ vatNumber: '123456789012345', sellerName: 'Your Company Ltd', environment: 'production', args: process.argv // For --licence flag }); // Switch to production mode (Pro only)sdkPro.switchToProduction(); ``` -------------------------------- ### Create and Clear Simplified Invoice in TypeScript Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/core/README.md This TypeScript snippet illustrates how to utilize the ZATCA SDK for creating and clearing simplified e-invoices. It defines interfaces for invoice data and clearance results, showcasing type safety. This requires the '@zatca-sdk/core' package and TypeScript setup. ```typescript import { ZATCAInvoiceSDK, InvoiceData, ClearanceResult } from '@zatca-sdk/core'; const sdk = new ZATCAInvoiceSDK({ vatNumber: '399999999800003', sellerName: 'Test Company' }); const invoiceData: InvoiceData = { invoiceNumber: 'SME00001', issueDate: '2025-01-15', totalAmount: 115.00, vatAmount: 15.00 }; const result: ClearanceResult = await sdk.submitForClearance( invoice.xml, 'simplified' ); ``` -------------------------------- ### Set ZATCA SDK Pro Licence Key (Environment Variable) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/docs/buy.html Demonstrates how to set the ZATCA SDK Pro licence key using an environment variable. This is a common method for configuring SDKs with sensitive keys, ensuring they are not hardcoded directly into the application logic. ```shell # Set your licence key export ZSDK_LICENCE_KEY=ZSDK1234567890ABCDEF ``` -------------------------------- ### Core Demo Execution (Shell) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--PROJECT-TITLE-ZATCA-Phase-2-e-Invoice-SDK-Freemium-Premium--1751280019217_1751280019217.txt Command to run the core demo of the ZATCA SDK, which operates in simulation mode. This is intended for free users to test the sandbox environment. ```shell npm run core-demo ``` -------------------------------- ### Verify Package Publish Configuration (Bash) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/PUBLISH_PRO_PACKAGE.md Displays the 'publishConfig' section from the 'package.json' file to ensure it's correctly set to the GitHub Packages registry. This confirms the package is configured for publishing to the correct location. ```bash cat package.json | grep -A 3 "publishConfig" ``` -------------------------------- ### Create and Clear Simplified Invoice in JavaScript Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/core/README.md This snippet demonstrates the basic workflow for creating and clearing a simplified e-invoice using the ZATCA SDK in JavaScript. It includes generating device credentials, creating the invoice data, and submitting it for clearance. Ensure you have the '@zatca-sdk/core' package installed. ```javascript import { ZATCAInvoiceSDK } from '@zatca-sdk/core'; const sdk = new ZATCAInvoiceSDK({ vatNumber: '399999999800003', sellerName: 'Test Company' }); async function createInvoice() { try { // Generate credentials (one-time setup) await sdk.generateDeviceCredentials(); // Create invoice const invoice = await sdk.createSimplifiedInvoice({ invoiceNumber: 'SME00001', issueDate: new Date().toISOString().split('T')[0], totalAmount: 115.00, vatAmount: 15.00 }); // Submit for clearance const result = await sdk.submitForClearance(invoice.xml, 'simplified'); console.log('Success:', result); } catch (error) { console.error('Error:', error.message); } } createInvoice(); ``` -------------------------------- ### Configuring ZATCA SDK with Offline License Path Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-1-Tighten-the-first-five-minutes-experience-Why-New-devs-skim-docs-if-any-step-feels-fuzzy-they-bo-1751280903855_1751280903855.txt This environment variable configuration is used to specify the path to a locally stored, signed license token for offline activation scenarios. ```bash ZSDK_LICENCE_PATH=/etc/zsdk/lic.pem ``` -------------------------------- ### Run ZATCA SDK Tests Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/README.md Executes the test suite for the ZATCA SDK to ensure all functionalities are working as expected across different environments. ```bash npm test ``` -------------------------------- ### Configure ZATCA SDK for Arabic Language in JavaScript Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/core/README.md This example demonstrates how to configure the ZATCA SDK to support Arabic language for e-invoicing. By setting the 'language' option to 'ar' during SDK initialization, outgoing invoices and communication with ZATCA can be handled in Arabic. This requires the '@zatca-sdk/core' package. ```javascript import { ZATCAInvoiceSDK } from '@zatca-sdk/core'; const sdk = new ZATCAInvoiceSDK({ vatNumber: '399999999800003', sellerName: 'شركة الاختبار', language: 'ar' // Arabic support }); ``` -------------------------------- ### ZATCA SDK Licence Validation (JavaScript) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted--PROJECT-TITLE-ZATCA-Phase-2-e-Invoice-SDK-Freemium-Premium--1751280019217_1751280019217.txt A JavaScript function to validate the format of a ZATCA SDK license token. It checks if the token starts with 'ZSDK' and is followed by 16 alphanumeric characters. This is a stub for more complex validation involving HMAC. ```javascript import crypto from 'crypto'; export function isValid(token){ // TODO: Implement HMAC validation with secret pepper return /^ZSDK[A-Za-z0-9]{16}$/.test(token); } ``` -------------------------------- ### Offline Activation Command for ZATCA SDK Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-1-Tighten-the-first-five-minutes-experience-Why-New-devs-skim-docs-if-any-step-feels-fuzzy-they-bo-1751280903855_1751280903855.txt This command allows enterprise customers to generate an activation file for offline use. It requires the user's email and VAT number. The output is a JSON file that is then emailed for signing. ```bash zatca-sdk activate --email user@corp.sa --vat 3 ``` -------------------------------- ### Configure Real-time Webhooks with ZATCA SDK Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/pro/README.md This snippet shows how to configure real-time webhook notifications for various events such as invoice clearance, rejection, certificate expiration, and system maintenance. It requires providing valid HTTPS URLs for each event type. The example also includes a structure of a typical webhook payload. ```javascript // Configure webhook notifications await sdk.configureWebhooks({ invoiceCleared: 'https://your-domain.com/invoice-cleared', invoiceRejected: 'https://your-domain.com/invoice-rejected', certificateExpiring: 'https://your-domain.com/cert-expiring', systemMaintenance: 'https://your-domain.com/maintenance' }); // Webhook payload example /* { "event": "invoice.cleared", "timestamp": "2025-01-15T10:30:00Z", "data": { "invoiceNumber": "STD00001", "clearedUUID": "12345678-1234-1234-1234-123456789012", "invoiceHash": "abc123...", "clearanceTimestamp": "2025-01-15T10:30:00Z" } } */ ``` -------------------------------- ### Public API Exposure Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-Build-a-Node-based-ZATCA-Phase-2-e-Invoice-SDK-that-one-command-npm-start-can-demo-from-i-1751274085830_1751274085831.txt Defines the main functions exposed by the SDK for programmatic use. ```APIDOC ## Public API ### Description This section outlines the primary functions exposed by the ZATCA SDK that developers can import and use in their Node.js applications. ### Method Not Applicable (Module exports) ### Endpoint Not Applicable ### Parameters None ### Code List - **createCSR()**: Function to generate device keys and CSR. - **loadCertificate(privateKeyPath, certificatePath)**: Function to load the seller's certificate and private key. (Assumed based on signing requirement). - **buildInvoiceXML(invoiceType, invoiceData)**: Function to create the XML e-invoice. - **signInvoice(xmlInvoice, privateKeyPath, certificatePath)**: Function to digitally sign the XML invoice. - **generateTLVQR(qrData)**: Function to generate the Base64 encoded TLV QR code for simplified invoices. - **submitForClearance(signedXml, csid, isSimplified)**: Function to submit the signed invoice to the ZATCA sandbox API. ### Example Usage ```javascript // Import functions from the SDK const { createCSR, buildInvoiceXML, signInvoice, generateTLVQR, submitForClearance } = require('zatca-sdk'); async function runInvoiceProcess() { // 1. Generate Keys and CSR (manual upload step follows) await createCSR(); console.log('CSR generated. Please upload to ZATCA portal and obtain CSID and cert.pem.'); // Assume CSID and cert.pem are obtained and available const csid = 'YOUR_CSID'; // cert.pem is assumed to be in the root directory or specified path // 2. Build Invoice XML const invoiceData = { /* ... invoice details ... */ }; const xmlInvoice = await buildInvoiceXML('Simplified', invoiceData); // 3. Sign Invoice const signedXml = await signInvoice(xmlInvoice); // 4. Generate QR Code (for simplified invoices) const qrData = { /* ... QR data ... */ }; const qrCode = await generateTLVQR(qrData); console.log('Generated QR Code:', qrCode); // 5. Submit for Clearance try { const clearanceResult = await submitForClearance(signedXml, csid, true); console.log('Invoice Cleared:', clearanceResult); } catch (error) { console.error('Failed to clear invoice:', error); } } runInvoiceProcess(); ``` ``` -------------------------------- ### Generate TLV QR Code for Simplified Invoices Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-Build-a-Node-based-ZATCA-Phase-2-e-Invoice-SDK-that-one-command-npm-start-can-demo-from-i-1751274085830_1751274085831.txt Constructs a Base64-encoded TLV (Tag-Length-Value) QR code for Simplified invoices, containing essential invoice summary details. ```APIDOC ## Generate TLV QR Code ### Description Creates a Base64-encoded TLV QR code specifically for Simplified invoices (B2C). The QR code contains key information such as Seller Name, Seller VAT ID, Timestamp, Total Amount with VAT, and VAT Amount, adhering to QR code specification v2.1. ### Method Not Applicable (Function call within the SDK) ### Endpoint Not Applicable ### Parameters #### Request Body - **invoiceData** (object) - Required - Object containing invoice details needed for QR code generation (e.g., sellerName, sellerVAT, issueDateTime, totalWithVAT, vatAmount). ### Request Example ```javascript // Example of calling the SDK function const { generateTLVQR } = require('zatca-sdk'); const qrData = { sellerName: "My Company", sellerVAT: "VATID123", issueDateTime: new Date().toISOString(), totalWithVAT: 115.00, vatAmount: 15.00 }; async function generateQr() { const qrCodeBase64 = await generateTLVQR(qrData); console.log('Base64 Encoded QR Code:', qrCodeBase64); } generateQr(); ``` ### Response #### Success Response - **qrCodeBase64** (string) - The Base64 encoded string of the TLV QR code. #### Response Example ``` [Base64 Encoded QR Code String] ``` ``` -------------------------------- ### Testing ZATCA Integration (Shell) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-1-How-the-app-talks-to-the-teacher-ZATCA-Think-of-ZATCA-as-a-website-with-two-locked-doors-Your-1751279030357_1751279030358.txt Command to run automated tests using Jest. This command verifies the integration and functionality of the ZATCA SDK against the test environment. ```shell npm test ``` -------------------------------- ### Generate Device Keys and CSR Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-Build-a-Node-based-ZATCA-Phase-2-e-Invoice-SDK-that-one-command-npm-start-can-demo-from-i-1751274085830_1751274085831.txt Generates private keys and a Certificate Signing Request (CSR) on the secp256k1 curve, outputting `csr.pem` and `ec-priv.pem`. ```APIDOC ## Generate Device Keys & CSR ### Description Generates the necessary cryptographic keys and a Certificate Signing Request (CSR) required for ZATCA compliance. This is a prerequisite for obtaining a digital certificate from the ZATCA portal. ### Method Not Applicable (Function call within the SDK) ### Endpoint Not Applicable ### Parameters None ### Request Example ```javascript // Example of calling the SDK function const { createCSR } = require('zatca-sdk'); async function generateKeys() { await createCSR(); console.log('CSR and private key generated.'); } generateKeys(); ``` ### Response #### Success Response - **csr.pem** (file) - The generated Certificate Signing Request file. - **ec-priv.pem** (file) - The generated private key file. #### Response Example ``` CSR and private key generated. ``` ``` -------------------------------- ### HTML for Language Switching (HTML) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-1-How-the-app-talks-to-the-teacher-ZATCA-Think-of-ZATCA-as-a-website-with-two-locked-doors-Your-1751279030357_1751279030358.txt Demonstrates how to implement a language switcher in an HTML page. It dynamically sets the HTML lang and dir attributes and provides a link to toggle between English and Arabic. ```html AR / EN ``` -------------------------------- ### Generate and Submit Invoice (Core - Sandbox) Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/README.md Demonstrates generating device credentials, building an invoice in XML format, and submitting it for clearance using the sandbox simulation endpoints. ```javascript // Generate device credentials const credentials = await sdk.generateDeviceCredentials(); // Build and submit invoice (simulation mode) const invoice = { /* invoice data */ }; const xml = sdk.buildInvoiceXML(invoice); const result = await sdk.submitForClearance(xml, 'simplified', 'csid'); ``` -------------------------------- ### ZATCAInvoiceSDK Initialization Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/core/README.md Initialize the ZATCAInvoiceSDK with your company's VAT number, name, and desired environment. ```APIDOC ## ZATCAInvoiceSDK Initialization ### Description Initializes the ZATCA SDK client with essential configuration details. ### Method `constructor` ### Parameters #### Request Body - **vatNumber** (string) - Required - Your VAT registration number. - **sellerName** (string) - Required - The legal entity name of the seller. - **environment** (string) - Required - The environment to use, either 'sandbox' or 'production' (Pro feature). - **apiBaseUrl** (string) - Optional - A custom base URL for the ZATCA API. - **csid** (string) - Optional - Your Compliance CSID. ### Request Example ```javascript import { ZATCAInvoiceSDK } from '@zatca-sdk/core'; const sdk = new ZATCAInvoiceSDK({ vatNumber: '399999999800003', sellerName: 'Your Company Name', environment: 'sandbox' }); ``` ``` -------------------------------- ### Tag and Push Git Releases Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/README.md Tag a release with a version number and push it to trigger automatic publishing of the Core package to npm. ```bash git tag v1.0.0 && git push --tags ``` -------------------------------- ### Submit Invoice for Clearance Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/attached_assets/Pasted-Build-a-Node-based-ZATCA-Phase-2-e-Invoice-SDK-that-one-command-npm-start-can-demo-from-i-1751274085830_1751274085831.txt Submits the signed e-invoice XML to the ZATCA Phase-2 sandbox API for clearance. Supports both standard and simplified invoice types. ```APIDOC ## Submit Invoice for Clearance ### Description Sends the cryptographically signed e-invoice XML to the ZATCA Phase-2 sandbox API for validation and clearance. This endpoint is used for both 'Standard' (B2B/B2G) and 'Simplified' (B2C) invoice types. It requires specific headers including `Compliance-CSID`. ### Method POST ### Endpoint - `/compliance` (for certificate verification, optional) - `/clearance/standard` (for B2B/B2G invoices) - `/clearance/simplified` (for B2C invoices) ### Parameters #### Headers - **Compliance-CSID** (string) - Required - The CSID obtained after uploading the CSR to the ZATCA portal. - **Clearance-Status** (string) - Required - Should be set to `SIMULATION` for the sandbox environment. - **Content-Type** (string) - Required - Must be set to `application/xml`. #### Request Body - **signedXmlInvoice** (string) - Required - The signed e-invoice XML content. - **isSimplified** (boolean) - Required - Indicates if the invoice is simplified (true for B2C, false for B2B/B2G). ### Request Example ```javascript // Example of calling the SDK function const { submitForClearance } = require('zatca-sdk'); const signedInvoiceXml = "..."; // Assume this is the signed XML const csid = "YOUR_OBTAINED_CSID"; async function submitInvoice(xml, isSimplified) { try { const result = await submitForClearance(xml, csid, isSimplified); console.log('Clearance Result:', result); return result; } catch (error) { console.error('Error submitting invoice:', error); throw error; } } // For a simplified invoice: submitInvoice(signedInvoiceXml, true); // For a standard invoice: // submitInvoice(signedInvoiceXml, false); ``` ### Response #### Success Response (200) - **clearedUUID** (string) - The unique identifier assigned to the cleared invoice. - **reportingStatus** (string) - The status of the reporting, expected to be `CLEARED`. - **invoiceHash** (string) - The hash of the submitted invoice, echoed back. #### Response Example ```json { "clearedUUID": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "reportingStatus": "CLEARED", "invoiceHash": "[Calculated Invoice Hash]" } ``` #### Error Response (e.g., 400, 500) - **error** (object) - Contains details about the error encountered during submission. #### Error Response Example ```json { "error": { "code": "INVALID_XML", "message": "The provided XML invoice is not valid according to the ZATCA schema." } } ``` ``` -------------------------------- ### Run ZATCA SDK Tests with npm Source: https://github.com/mouna-bassim/zatca-sdk/blob/main/packages/core/README.md This section provides commands for running tests for the ZATCA SDK using npm. You can execute all tests, run specific test suites by pattern (e.g., 'QR Code'), or generate code coverage reports. These commands are executed in your project's terminal. ```bash # Run all tests npm test # Run specific test suite npm test -- --testNamePattern="QR Code" # Run with coverage npm run test:coverage ```