Eyewear Brand Ecosystem

Interactive Architecture — Click any component to drill down into sub-components

Sales Channels
All revenue touchpoints unified into a single order flow — retail POS, online store, D2C marketplaces, and B2B wholesale.
Retail POSE-CommerceB2B
Inventory & WMS
Multi-echelon inventory engine tracking stock across central warehouses, regional hubs, and retail stores with real-time sync.
Real-Time SyncMulti-LocationReorder Logic
Manufacturing
End-to-end production management from BOM to finished goods — lens cutting, coating, frame assembly, QC, and job tracking.
BOMMRPQC
Supply Chain
Procurement, import logistics, local sourcing, and distribution — managing the flow from raw material suppliers to finished goods.
ImportLocalLogistics

Unified Order Engine (OMS)

The central nervous system — receives orders from all channels, routes to fulfillment, and orchestrates inventory, manufacturing, and logistics

Real-Time Inventory Sync
Smart Fulfillment Routing
Unified Invoicing
Order Analytics
Integration Layer
Shared API Gateway connecting all modules to external services — payments, shipping, labs, marketing, notifications.
API GatewayEvent BusConnectors
Clinical & Prescription
EHR/EMR for patient records, digital prescription capture, doctor onboarding, and lens fitting workflows.
EHRRx ValidationDoctor Portal
Customer Experience
CRM with 360-degree customer view, multi-channel communication engine, loyalty programs, and self-service portals.
CRMLoyaltyPortals
Compliance & Governance
Multi-jurisdiction regulatory compliance — healthcare data (HIPAA), privacy (GDPR/DPDP/PDPL), financial, and product safety.
HIPAAGDPRDPDP
Analytics & Reporting
Four-layer analytics — descriptive dashboards, diagnostic root-cause, predictive forecasting, and prescriptive optimization.
BIMLKPIs

Sales Channels

A. Retail Stores
In-store POS with prescription-linked sales, offline mode, split payments, and clienteling.
  • Barcode/RFID scanning
  • Split payments (deposit + balance)
  • Frame try-on tracking
  • Store associate clienteling app
  • Appointment booking
B. Online Store (Own)
Brand-owned e-commerce with AR virtual try-on, prescription upload, and lens configurator.
  • AR Virtual Try-On
  • Prescription upload & verification
  • Lens configurator
  • Subscription (contact lenses)
  • BOPIS (Buy Online Pickup In-Store)
C. D2C Marketplaces
Unified catalog sync across Amazon, Flipkart, Instagram Shopping, WhatsApp Commerce.
  • Amazon MWS integration
  • Flipkart Seller API
  • Instagram Shopping
  • WhatsApp Commerce
  • Location-specific channels (Lazada, etc.)
D. B2B Wholesale
Distributor portal with tiered pricing, credit limits, bulk ordering, and white-label support.
  • Tiered pricing & MOQ
  • Credit limits & invoicing
  • Bulk ordering workflows
  • White-label / private label
  • Distributor network management

Inventory & Warehouse Management

Inventory Engine
The central real-time stock system. Decrements stock instantly across ALL channels when any sale occurs.
  • Real-time sync across all channels
  • Available-to-Promise (ATP) calculation
  • Soft reservations & hard allocations
  • Multi-location stock visibility
  • Serial/lot tracking for lenses & frames
Reorder Logic
Auto-triggers purchase orders when stock hits predefined thresholds. Prevents stockouts and overstocking.
  • Reorder Point (ROP) calculation
  • Economic Order Quantity (EOQ)
  • Lead time + safety stock buffer
  • Seasonal demand adjustment
  • Auto-PO generation to suppliers
Cycle Counting
Periodic physical stock verification without shutting down operations. "Little and often" vs. annual stock-take.
  • ABC classification (A=weekly, B=monthly, C=quarterly)
  • Random sampling vs. targeted counts
  • Variance reporting & root cause
  • Shrinkage tracking
  • Count reconciliation workflow
Multi-Location Model
Four-tier inventory architecture for optimal fulfillment and stock positioning.
  • Central Warehouse (bulk, receiving, B2B)
  • Regional Hubs (fast fulfillment, returns)
  • Store Stock (immediate customer access)
  • Lab Inventory (WIP materials)
Stock Transfers
Inter-location movement with approval workflows, in-transit tracking, and cost allocation.
  • Transfer request & approval
  • Pick-pack-ship workflow
  • In-transit tracking
  • Cost allocation between locations
  • Transfer SLA monitoring
Inventory Hierarchy
Four levels of stock classification from raw materials to finished goods.
  • Level 1: Raw Materials (resins, metals, coatings)
  • Level 2: Work-in-Progress (cut lenses, partial frames)
  • Level 3: Finished Goods (frames, complete eyewear)
  • Level 4: Consignment / On-Order

Manufacturing & Production

BOM Management
Bill of Materials for every SKU — raw materials, sub-assemblies, labor operations, and routing.
  • Multi-level BOM (parent to sub-assembly to component)
  • Revision control & change management
  • Cost rollup (material + labor + overhead)
  • Where-used queries
Lens Cutting & Surfacing
Precision lens manufacturing from blank to finished prescription lens.
  • Blank selection by Rx power & material
  • CNC surfacing & polishing
  • Edging to frame shape
  • Drilling for rimless frames
Lens Coating
Multi-layer coating — hard coat, anti-reflective, UV, blue light filter, photochromic.
  • Hard coat (scratch resistance)
  • AR coating (anti-reflective)
  • UV protection layer
  • Photochromic / Blue light treatment
Frame Assembly
Assembling frame components — front, temples, hinges, nose pads, screws.
  • Front frame + temple attachment
  • Hinge installation & alignment
  • Nose pad fitting
  • Final adjustment & alignment check
QC & Testing
Quality control checkpoints ensuring optical and mechanical standards.
  • Optical power verification (focimeter)
  • Frame durability & hinge test
  • Coating adhesion test
  • Final visual inspection
Job Tracking
Work order lifecycle tracking from receipt to dispatch with real-time status.
  • Work order creation & scheduling
  • Station-level status updates
  • Operator assignment & time tracking
  • Job completion & dispatch

Supply Chain & Logistics

Sourcing Strategy
Strategic procurement decisions — import vs. local, single vs. dual sourcing.
  • Optical resins: Import (Japan/Korea)
  • Frame materials: Import (Japan/Italy)
  • Small parts: Local (India/China)
  • Packaging: Local vendors
Import Logistics
International procurement — sea/air freight, customs clearance, duty optimization.
  • Sea freight (bulk, cost-efficient)
  • Air freight (urgent, high-value)
  • Customs clearance & HS codes
  • Bonded warehouse options
Local Procurement
Domestic supplier management with JIT delivery and VMI arrangements.
  • Vendor-managed inventory (VMI)
  • Just-in-time (JIT) delivery
  • Milk runs for small parts
  • Local quality audits
Distribution Logistics
Last-mile delivery for B2C/B2B and inter-warehouse transfers.
  • Courier integration (Blue Dart, Delhivery)
  • Same-day delivery zones
  • Bulk B2B palletized shipping
  • Reverse logistics (returns)

Clinical & Prescription

EHR / EMR System
Comprehensive electronic health records for eye care patients with full clinical history.
  • Patient demographics & consent management
  • Ocular & systemic history tracking
  • Examination records (VA, refraction, IOP)
  • Retinal imaging & OCT storage
Rx Capture & Validation
Digital prescription entry with automated validation and compliance checks.
  • Structured Rx entry (SPH, CYL, AXIS, ADD, PD)
  • Rx expiry validation (1-2 years)
  • Power range & consistency checks
  • Doctor license verification
Doctor Portal
Optometrist/ophthalmologist workspace for scheduling, Rx, and patient management.
  • License verification & onboarding
  • Schedule & appointment management
  • Digital Rx pad with templates
  • Commission tracking
Lens Fitting
Precise measurements for optimal lens positioning and comfort.
  • Monocular & binocular PD
  • Fitting height (segment height)
  • Pantoscopic tilt measurement
  • Vertex distance

Customer Experience

CRM & 360° View
Unified customer profile across all touchpoints and channels.
  • Order history across all channels
  • Prescription history & expiry tracking
  • Segmentation (VIP, Regular, At-Risk)
  • Lifetime Value (LTV) calculation
Communication Engine
Multi-channel automated and personalized customer communications.
  • Email (order, shipping, Rx reminders)
  • SMS (appointments, OTP, delivery)
  • WhatsApp (catalog, support, tracking)
  • Push notifications (offers, alerts)
Self-Service Portals
Customer-facing portals for order management and account services.
  • B2C Customer Portal (orders, Rx, reorder)
  • B2B Distributor Portal (pricing, bulk orders)
  • Doctor Portal (scheduling, Rx)
  • Store Associate Portal (clienteling)
Loyalty & Rewards
Retention program driving repeat purchases and referrals.
  • Points-based earning system
  • Tiered status (Bronze/Silver/Gold/Platinum)
  • Referral credits
  • Birthday & anniversary rewards

Compliance & Governance

Healthcare Compliance
Regulations governing patient data and clinical practice.
  • HIPAA (US healthcare data)
  • PHIPA (Canada)
  • NHS GOS (UK)
  • Clinical audit trails
Data Privacy
Multi-jurisdiction privacy regulations for customer and patient data.
  • GDPR (EU — right to erasure, portability)
  • DPDP Act 2023 (India — consent framework)
  • PDPL (UAE/Saudi — data localization)
  • Consent management platform
Financial Compliance
Tax, accounting, and financial reporting standards.
  • GST/VAT per country
  • E-invoicing (India IRN)
  • IND AS / IFRS reporting
  • SOX controls (if US-listed)
Product Safety
Standards ensuring eyewear quality and safety.
  • ISO 12870 (Frame durability)
  • ISO 14889 (Lens impact resistance)
  • CE Marking (EU conformity)
  • BIS certification (India)

Analytics & Reporting

Descriptive Analytics
What happened? Real-time dashboards and historical reporting.
  • Sales dashboard (revenue by channel)
  • Inventory dashboard (stock levels, aging)
  • Customer dashboard (acquisition, retention)
  • Operational dashboard (fulfillment, lab TAT)
Diagnostic Analytics
Why did it happen? Root cause and correlation analysis.
  • Root cause analysis (stockouts, returns)
  • Cohort analysis (customer behavior)
  • Funnel analysis (cart abandonment)
  • Correlation (weather vs. sunglasses)
Predictive Analytics
What will happen? ML-powered forecasting and risk detection.
  • Demand forecasting (seasonal, trend)
  • Churn prediction (at-risk customers)
  • Rx expiry prediction (proactive outreach)
  • Inventory optimization (safety stock)
Prescriptive Analytics
What should we do? AI-driven recommendations and automation.
  • Dynamic pricing optimization
  • Assortment planning (SKU placement)
  • Marketing spend optimization
  • Supply chain routing optimization

Integration Layer & API Gateway

API Gateway
Central entry point for all internal and external API traffic — auth, rate limiting, routing, versioning.
  • Authentication & Authorization (OAuth 2.0, JWT)
  • Rate limiting & throttling
  • API versioning & deprecation
  • Request/response transformation
  • API analytics & monitoring
Event Bus (Kafka)
Real-time event streaming for async communication between modules — inventory sync, order updates, notifications.
  • Order events (created, paid, shipped, delivered)
  • Inventory events (stock changed, reserved, released)
  • Customer events (profile updated, consent changed)
  • Dead letter queue for failed events
  • Event replay & audit
Payment Connectors
Unified payment abstraction used by Sales, Clinical, B2B, and D2C channels.
  • Razorpay (India — UPI, Cards, Netbanking)
  • Stripe (International — Cards, Wallets)
  • PayPal (Global — Express checkout)
  • COD (Cash on Delivery)
  • B2B Credit (Net 30/60/90 invoicing)
Shipping & Logistics
Multi-carrier shipping API used by Inventory, Sales, and Supply Chain modules.
  • Blue Dart (pan-India, premium)
  • Delhivery (cost-effective, 18K+ pincodes)
  • Shiprocket (multi-carrier aggregator)
  • DHL/FedEx (international express)
  • Same-day hyperlocal (Dunzo, Swiggy)
Notification Services
Shared communication infrastructure used by Customer Experience, Clinical, and Sales modules.
  • Email (SendGrid, AWS SES, MSG91)
  • SMS (Twilio, MSG91, Exotel)
  • WhatsApp Business API
  • Push notifications (Firebase, OneSignal)
  • Voice/IVR (Twilio, Exotel)
ERP / Accounting
Financial backbone integration for invoicing, GST, inventory valuation, and reporting.
  • Odoo / SAP / NetSuite connector
  • GL entries (sales, purchases, transfers)
  • GST e-invoicing (IRN generation)
  • Accounts payable / receivable sync
  • Financial reporting & consolidation
Labs / Optical Partners
Integration with external lens labs and optical partners for outsourced manufacturing.
  • Lab order submission (Rx, frame, lens specs)
  • Job status tracking (received, in-progress, shipped)
  • Quality report ingestion
  • Invoice reconciliation
  • Partner performance dashboard
Marketing Platforms
Integration with ad platforms, CDP, and analytics for customer acquisition and retention.
  • Google Ads / Meta Ads API
  • Customer Data Platform (Segment, mParticle)
  • Affiliate network tracking
  • Influencer campaign management
  • SEO / content platform integration

Inventory Engine — Deep Dive

What is the Inventory Engine?

The Inventory Engine is the real-time stock management core of the entire ecosystem. It is a centralized service that maintains a single source of truth for all stock levels across every location and channel. When any sale happens — whether in a retail store, on your website, via Amazon, or through a B2B order — the engine instantly decrements available stock and propagates the update to all connected systems.

How It Works

Order Placed
Any channel
Reservation
Soft hold
Fulfillment
Pick & pack
Stock Decrement
Real-time sync
Broadcast
All channels updated

Key Capabilities

CapabilityDescriptionBusiness Impact
Real-Time SyncStock updates propagate to all channels within milliseconds via event streaming (Kafka/EventBridge)Prevents overselling across Amazon, Flipkart, and retail simultaneously
Available-to-Promise (ATP)Calculates sellable quantity = On-Hand minus Reserved minus Safety Stock plus InboundAccurate delivery promises to customers
Soft ReservationsTemporarily holds stock when item is in cart (e.g., 15-min timeout)Reduces abandoned cart stock blocking
Hard AllocationsPermanently reserves stock upon order confirmationGuarantees fulfillment for paid orders
Multi-Location ViewAggregated view across central warehouse, regional hubs, and all storesIntelligent fulfillment routing
Serial/Lot TrackingTracks individual lens blanks and frame batches by lot numberRecall management and expiry control

Simplified Architecture

// Inventory Engine — Core Flow function processOrder(order) { // 1. Check ATP (Available-to-Promise) const atp = calculateATP(order.sku, order.location); if (atp < order.quantity) { return { status: "OUT_OF_STOCK", alternatives: suggestAlternatives(order.sku) }; } // 2. Create hard allocation const allocation = createAllocation({ orderId: order.id, sku: order.sku, quantity: order.quantity, location: order.fulfillmentLocation, reservedAt: now() }); // 3. Decrement available stock decrementStock(order.sku, order.fulfillmentLocation, order.quantity); // 4. Broadcast update to all channels broadcastStockUpdate({ sku: order.sku, location: order.fulfillmentLocation, newQuantity: getCurrentStock(order.sku, order.fulfillmentLocation), timestamp: now() }); return { status: "ALLOCATED", allocationId: allocation.id }; }

Reorder Logic — Deep Dive

What is Reorder Logic?

Reorder Logic is the automated system that determines when and how much to restock each SKU. Instead of manually checking stock levels, the system continuously monitors inventory and triggers purchase orders when predefined thresholds are crossed. This prevents both stockouts (lost sales) and overstocking (tied-up capital).

The Reorder Point Formula

// Reorder Point (ROP) = Lead Time Demand + Safety Stock // Lead Time Demand = Average Daily Sales * Lead Time (in days) // Safety Stock = Z-score * Std Dev of Demand * sqrt(Lead Time) Example: Average Daily Sales = 5 units/day Lead Time = 14 days Std Dev of Demand = 2 units Z-score (95%) = 1.65 Lead Time Demand = 5 * 14 = 70 units Safety Stock = 1.65 * 2 * sqrt(14) = 12.3 ~ 13 units Reorder Point (ROP) = 70 + 13 = 83 units // When stock drops to 83 units -> trigger purchase order

Reorder Strategies by Category

CategoryStrategyReorder TriggerLead Time
Fast-Moving Frames (Ray-Ban, popular own-brand)Continuous ReviewROP reached7-14 days
Lens Blanks (imported resins)Periodic Review + ForecastMonthly MRP run45-60 days
Seasonal Items (sunglasses)Demand-DrivenPre-season forecast30-45 days
Small Parts (screws, nose pads)Two-Bin System / VMIBin empty3-7 days
Contact LensesEOQ ModelROP + batch optimization14-21 days

Automated Workflow

Monitor
Real-time stock
Trigger
ROP hit
Generate PO
Auto-draft
Approval
Manager review
Send to Vendor
Email/API

Cycle Counting — Deep Dive

What is Cycle Counting?

Cycle Counting is a method of auditing inventory where you count a small subset of items on a regular schedule throughout the year, rather than doing one massive annual stock-take that shuts down operations. Think of it as "little and often" — you verify a few SKUs every day or week so your inventory records stay accurate without disrupting business.

Cycle Count vs. Annual Stock-Take

AspectCycle CountingAnnual Stock-Take
FrequencyDaily/weekly small batchesOnce a year, everything at once
Business ImpactNo disruption — operations continueWarehouse/store may need to close
AccuracyHigher — issues caught earlyLower — errors accumulate all year
Root CauseImmediate investigation possibleToo late to find causes
Staffing1-2 people, part of daily routineAll hands on deck, overtime
CostLower — spread over timeHigher — concentrated effort

ABC Classification for Cycle Counting

Not all inventory is equally important. ABC analysis classifies items by value and velocity to prioritize counting effort:

ClassCriteria% of SKUs% of ValueCount Frequency
A — High ValueFast-moving, high-margin, critical~20%~80%Weekly or bi-weekly
B — Medium ValueModerate velocity and margin~30%~15%Monthly
C — Low ValueSlow-moving, low-margin, generic~50%~5%Quarterly or semi-annually

Example for an eyewear brand:

Counting Methods

Random Sampling

System randomly selects a set number of SKUs to count each day. Good for overall accuracy but may miss problem areas.

Targeted Counting

Focus on high-risk items: those with frequent adjustments, high shrinkage history, or near reorder points.

Stock Transfers — Deep Dive

Inter-Location Stock Movement

Stock transfers move inventory between warehouses, hubs, and stores to balance supply and demand. When Store A is running low on a popular frame but Store B has excess, a transfer optimizes stock without placing a new purchase order.

Transfer Workflow

Identify Need
Low stock alert
Create Request
Source store selected
Approval
Manager authorizes
Pick & Pack
Source location
In Transit
Tracking active
Receive
Destination confirms

Cost Allocation

When stock moves between locations, the system must decide how to value it:

MethodDescriptionBest For
Original CostTransfer at the original purchase priceSame-company transfers, accurate margin tracking
Weighted AverageTransfer at the current weighted average cost of the source locationMultiple POs with different prices
Transfer PricePre-defined internal transfer price (may include markup)Franchise or subsidiary transfers
Current Replacement CostTransfer at current market replacement valueInsurance or audit purposes

BOM Management — Deep Dive

Bill of Materials Structure

A BOM defines every component, material, and operation needed to manufacture one unit of a finished product. For eyewear, this spans optical materials, mechanical parts, coatings, packaging, and labor.

SKU: EYE-2026-001 // Titanium Round Frame, Black FRAME ASSEMBLY (Sub-Assembly): - Front Frame (Titanium) x 1 [Import - Japan] - Temple Arms (Titanium) x 2 [Import - Japan] - Hinges (Stainless Steel) x 2 [Local - Mumbai] - Nose Pads (Silicone) x 2 [Local - Mumbai] - Screws x 4 [Local - Mumbai] - Brand Logo Plate x 1 [Local - Mumbai] LENS ASSEMBLY (Sub-Assembly): - Lens Blank (MR-8, 1.60) x 2 [Import - Korea] - Hard Coating x 2 [Import - Korea] - AR Coating x 2 [Import - Korea] - UV Coating x 2 [Import - Korea] PACKAGING: - Branded Case x 1 [Local - Delhi] - Microfiber Cloth x 1 [Local - Delhi] - Warranty Card x 1 [Local - Delhi] LABOR OPERATIONS: - Frame Assembly -> 15 min [Assembly Station] - Lens Cutting/Edging -> 20 min [CNC Machine] - Lens Coating -> 30 min [Coating Chamber] - Final Assembly -> 10 min [Assembly Station] - QC Inspection -> 10 min [QC Station] - Packaging -> 5 min [Pack Station] TOTAL LABOR: 90 minutes per unit

Multi-Level BOM

LevelTypeExamplePurpose
Level 0Finished GoodComplete Eyewear SKUSellable product
Level 1Sub-AssemblyFrame Assembly, Lens AssemblyModular manufacturing
Level 2ComponentFront Frame, Lens BlankPurchased or made parts
Level 3Raw MaterialTitanium sheet, Optical resinBase materials

EHR / EMR System — Deep Dive

Patient EHR Data Model

PATIENT EHR RECORD DEMOGRAPHICS & CONSENT - Name, DOB, Gender, Contact, Emergency Contact - ID Verification (Aadhaar/Passport for India) - Communication Preferences (SMS, Email, WhatsApp, Call) - Marketing Consent (GDPR/DPDP compliant opt-in) - Data Sharing Consent (with labs, insurers, etc.) CLINICAL HISTORY - Previous Prescriptions (Rx history with dates) - Ocular History (Surgeries, Conditions, Allergies) - Systemic History (Diabetes, Hypertension affecting eyes) - Family History (Glaucoma, Macular Degeneration) - Medications EXAMINATION RECORDS - Visual Acuity (Uncorrected, Corrected, Pinhole) - Refraction (Subjective & Objective) * Sphere, Cylinder, Axis (Right Eye, Left Eye) * Add (for progressive/bifocal) * Prism (if prescribed) * PD (Pupillary Distance) - Monocular & Binocular - Keratometry (for contact lens fitting) - Slit Lamp Findings - Intraocular Pressure (IOP) - Fundus Examination - OCT/Retinal Imaging (linked files) PRESCRIPTION (Rx) - Rx Date, Validity Period (typically 1-2 years) - Prescribing Doctor (licensed optometrist/ophthalmologist) - Rx Details (per eye: SPH, CYL, AXIS, ADD, Prism) - Lens Recommendation (Single Vision, Bifocal, Progressive) - Coatings Recommended (AR, Blue Light, Photochromic) DISPENSING RECORDS - Frame Selected (SKU, color, size) - Lens Ordered (material, index, coatings) - Measurements Taken (PD, fitting height, pantoscopic tilt) - Lab Order ID - Collection Date & Follow-up Schedule

Data Security & Compliance

ControlImplementationRegulation
Encryption at RestAES-256 encryption for all patient dataHIPAA, GDPR
Encryption in TransitTLS 1.3 for all API and web trafficHIPAA, GDPR
Access ControlsRBAC — doctors see only their patientsHIPAA, DPDP
Audit LogsEvery view, edit, export logged immutablyHIPAA, GDPR
Data RetentionAuto-archive after 7 years (configurable)Local healthcare laws
AnonymizationPII stripped for analytics/ML trainingGDPR, DPDP

Data Privacy — Deep Dive

Multi-Jurisdiction Privacy Matrix

RegulationJurisdictionKey RequirementsSystem Impact
GDPREU / EEAConsent, right to erasure, data portability, DPOConsent platform, data export API, 72hr breach notification
DPDP Act 2023IndiaConsent framework, data fiduciaries, grievance mechanismConsent manager, data principal rights portal
PDPLUAE / SaudiData localization, cross-border transfer rulesIn-region data centers, transfer impact assessments
LGPDBrazilSimilar to GDPR, legal basis for processingConsent + legitimate interest documentation
PIPEDACanadaConsent, accountability, breach notificationPrivacy policy, opt-out mechanisms

Consent Management Platform

Every customer interaction requires granular, revocable consent:

Collect Consent
Granular opt-in
Timestamp
Version tracked
Store
Immutable record
Enforce
Block if no consent
Withdrawal
One-click opt-out

Predictive Analytics — Deep Dive

ML Models for Eyewear

Use CaseModel TypeInput FeaturesOutput
Demand ForecastingTime Series (Prophet, LSTM)Sales history, seasonality, promotions, weatherWeekly SKU-level demand forecast
Churn PredictionClassification (XGBoost, Random Forest)Recency, frequency, Rx expiry, support ticketsChurn probability score (0-100)
Rx Expiry PredictionSurvival AnalysisRx date, patient age, condition typeDays until Rx expires per patient
Inventory OptimizationReinforcement LearningDemand variance, lead time, holding costOptimal safety stock per SKU-location
Dynamic PricingPrice Elasticity ModelCompetitor prices, demand elasticity, marginRecommended price per SKU

Proactive Customer Outreach

Example: Rx Expiry Campaign

Detect Expiry
ML predicts 30 days out
Segment
High-value vs at-risk
Personalized Offer
WhatsApp/Email/SMS
Book Appointment
In-store or online
Convert
New Rx + purchase

API Gateway — Deep Dive

API Gateway Architecture

The API Gateway is the single entry point for all internal and external API traffic. It handles authentication, rate limiting, routing, and monitoring so that individual modules don't have to.

// API Gateway Configuration routes: { "/api/v1/orders": { service: "oms-service", auth: "jwt", rateLimit: 1000/min }, "/api/v1/inventory": { service: "inventory-engine", auth: "jwt", rateLimit: 5000/min }, "/api/v1/patients": { service: "ehr-service", auth: "jwt+hipaa", rateLimit: 500/min }, "/api/v1/payments": { service: "payment-service", auth: "api-key", rateLimit: 2000/min }, "/webhooks/amazon": { service: "marketplace-connector", auth: "hmac", rateLimit: unlimited } } middleware: [ "requestLogging", "authentication", "authorization", "rateLimiting", "requestTransformation", "responseCaching", "circuitBreaker" ]

Security & Governance

FeaturePurposeImplementation
OAuth 2.0 / JWTAuthenticate API consumersKeycloak / Auth0 / Cognito
RBACAuthorize based on roleStore manager vs warehouse staff vs doctor
Rate LimitingPrevent abuse and DDoSToken bucket per client per endpoint
Circuit BreakerFail fast when downstream is downAuto-open after 5 errors, retry after 30s
API VersioningSupport multiple versions simultaneously/v1/, /v2/ in path or header
Request/Response LoggingAudit and debugELK stack, 90-day retention

Retail Stores — Deep Dive

In-Store POS Architecture

The retail POS is the frontline revenue engine. It must handle prescription-linked sales, split payments, offline resilience, and seamless integration with inventory and clinical modules.

Customer Arrives
Check-in / Walk-in
Eye Exam
Clinical module
Frame Selection
Try-on, scan SKU
Lens Config
Prescription applied
Payment
Split, EMI, COD
Fulfillment
Ready-made or lab

POS Feature Matrix

FeatureDescriptionBusiness Value
Barcode/RFID ScanningInstant SKU lookup with stock check and pricingSpeeds checkout, eliminates manual entry errors
Split PaymentsDeposit + balance, multiple cards, cash + card, EMIFlexibility increases conversion rate
Offline ModeLocal SQLite cache; syncs when connection restoredNever lose a sale due to connectivity
Clienteling AppStore associate sees customer history, preferences, RxPersonalized service drives loyalty
Appointment BookingIntegrated eye exam scheduling with doctor calendarOptimizes doctor utilization
Frame Try-On TrackingLogs frames tried, photos taken, favorites savedRetargeting and preference learning

Offline Resilience Design

// Offline-First POS Architecture class OfflinePOS { constructor() { this.localDB = new IndexedDB('pos-cache'); this.syncQueue = []; } async processSale(sale) { // 1. Validate locally using cached catalog const valid = await this.validateLocally(sale); if (!valid) return { error: "Invalid sale" }; // 2. Generate local receipt ID const receiptId = generateLocalID(); // 3. Queue for sync this.syncQueue.push({ ...sale, receiptId, timestamp: now() }); // 4. Print receipt immediately this.printReceipt(receiptId); // 5. Attempt background sync if (navigator.onLine) this.syncNow(); return { status: "SALE_RECORDED", receiptId }; } }

Online Store (Own) — Deep Dive

Brand-Owned E-Commerce Platform

The Online Store is the brand's direct-to-consumer digital flagship. Unlike marketplace listings, this channel offers full control over branding, customer data, margins, and experience. For eyewear, it must solve the fundamental challenge: how do you buy glasses online without trying them on?

Core Features & Customer Journey

Discovery
SEO, ads, social
AR Try-On
Virtual fitting
Rx Upload
Verify & parse
Lens Config
Customize
Checkout
Pay & confirm
Fulfillment
Lab → ship

AR Virtual Try-On Technology

AR Try-On is the conversion catalyst for online eyewear. It uses facial mapping and 3D frame rendering to simulate how glasses look on the customer's face in real-time.

TechnologyHow It WorksImpact
Facial Landmark Detection68-point facial mesh mapping via device cameraPrecise frame positioning on face
3D Frame RenderingPhotogrammetry-scanned frames rendered in WebGL/MetalRealistic texture, reflection, scale
Pupillary Distance (PD) EstimationAI estimates PD from facial proportions (±2mm accuracy)Ensures lens optical center alignment
Lighting AdaptationReal-time environment lighting matched to frame renderingNatural appearance in any room
Multi-Angle ViewSide profile, front view, tilt detectionComplete confidence before purchase
// AR Try-On — Simplified Flow async function initVirtualTryOn(frameSku) { // 1. Request camera permission const stream = await navigator.mediaDevices.getUserMedia({ video: true }); // 2. Load 3D frame model (GLB/USDZ) const frameModel = await loadFrameModel(frameSku); // 3. Initialize face tracking const faceMesh = await initializeFaceMesh(stream); // 4. Real-time rendering loop renderLoop(() => { const landmarks = faceMesh.getLandmarks(); const pose = faceMesh.getHeadPose(); frameModel.positionOnFace(landmarks, pose); frameModel.render(); }); // 5. Capture PD and recommend size const estimatedPD = calculatePD(landmarks); return { pd: estimatedPD, recommendedSize: getSizeRecommendation(frameSku, estimatedPD) }; }

Prescription Upload & Verification

Customers upload a photo of their prescription or enter values manually. The system validates format, checks expiry, and flags inconsistencies before order confirmation.

StepActionValidation
1. UploadPhoto of physical Rx or manual entryFile type, clarity, completeness
2. OCR ExtractionGoogle Vision / AWS Textract reads SPH, CYL, AXIS, ADD, PDField presence, format check
3. Expiry CheckCompare Rx date against validity period (1-2 years per jurisdiction)Flag expired prescriptions
4. Power Range CheckValidate SPH/CYL within manufacturable range (e.g., ±12.00D)Block impossible orders
5. Doctor VerificationCross-check doctor license number against registryFraud prevention
6. Customer ConfirmDisplay parsed Rx for customer approvalHuman-in-the-loop accuracy

Lens Configurator

The lens configurator guides customers through lens options with real-time pricing and visual explanations. It ensures the right lens is ordered for the prescription and lifestyle.

Lens Type

  • Single Vision (distance, reading, computer)
  • Bifocal (lined segment)
  • Progressive (no-line multifocal)
  • Plano (non-prescription / blue light)

Lens Material

  • CR-39 (standard, economical)
  • Polycarbonate (impact resistant)
  • Trivex (lightweight, high clarity)
  • High-Index 1.60/1.67/1.74 (thinner for high Rx)

Coatings & Add-Ons

CoatingFunctionPrice Impact
Hard CoatScratch resistanceIncluded
Anti-Reflective (AR)Reduces glare, improves clarity+$20-40
Blue Light FilterBlocks 400-450nm (screen protection)+$15-30
PhotochromicDarkens in sunlight (Transitions®)+$80-120
PolarizedGlare reduction for sunglasses+$50-80
UV ProtectionBlocks 100% UVA/UVBIncluded

BOPIS (Buy Online, Pickup In-Store)

BOPIS bridges online convenience with immediate gratification. The system checks store inventory in real-time, reserves the item, and notifies the store for pickup preparation.

Customer Orders
Selects BOPIS
Stock Reserved
At chosen store
Store Alert
Pick & stage
Ready Notification
SMS/Email/WhatsApp
In-Store Pickup
QR code scan

Subscription Model — Contact Lenses

Recurring revenue through contact lens subscriptions. Customers set delivery frequency; the system auto-fulfills based on consumption patterns and Rx validity.

ComponentDescription
Subscription PlansMonthly, quarterly, bi-annual delivery of contact lens boxes
Rx Validity CheckAuto-pause shipment if Rx expires; prompt for renewal
Flexible FrequencyCustomer adjusts delivery date ±7 days; skip a shipment
Loyalty IntegrationSubscription customers earn 2x loyalty points
Churn PreventionML predicts cancellation risk; proactive retention offers

D2C Marketplaces — Deep Dive

Multi-Channel Marketplace Strategy

D2C Marketplaces extend the brand's reach beyond its own website to platforms where customers already shop. The challenge is maintaining brand consistency, inventory accuracy, and pricing discipline across channels while leveraging each platform's unique audience and tools.

Supported Channels

ChannelAudienceKey IntegrationStrategic Role
AmazonMass market, high intentAmazon MWS/SP-APIVolume driver, search visibility
FlipkartIndia Tier 1-3 citiesFlipkart Seller APIDomestic market penetration
MyntraFashion-conscious millennialsMyntra Seller PortalBrand positioning, discovery
Instagram ShoppingGen Z, visual-firstMeta Commerce APIInspiration-driven impulse buys
WhatsApp CommerceConversational, trust-basedWhatsApp Business APIHigh-touch, personalized sales
Lazada / ShopeeSoutheast AsiaRegional marketplace APIsInternational expansion

Unified Catalog Sync

A single product catalog feeds all marketplaces. The sync engine maps internal SKUs to each platform's taxonomy, enforces channel-specific pricing, and maintains real-time inventory levels to prevent overselling.

// Unified Catalog Sync — Simplified class MarketplaceSync { constructor() { this.channels = { amazon: new AmazonConnector(), flipkart: new FlipkartConnector(), instagram: new MetaCommerceConnector(), whatsapp: new WhatsAppCommerceConnector() }; } async syncProduct(sku, channel) { const baseProduct = await getMasterCatalog(sku); // Map to channel-specific taxonomy const channelProduct = this.mapToChannel(baseProduct, channel); // Apply channel pricing rules channelProduct.price = this.applyPricingRules(baseProduct.mrp, channel); // Check inventory availability channelProduct.stock = await getAvailableStock(sku, channel); // Push to marketplace return await this.channels[channel].upsertProduct(channelProduct); } applyPricingRules(mrp, channel) { const rules = { amazon: { minMargin: 0.25, commission: 0.15 }, flipkart: { minMargin: 0.22, commission: 0.18 }, instagram: { minMargin: 0.30, commission: 0.05 } }; const rule = rules[channel]; const minPrice = mrp * (1 - rule.minMargin); return Math.max(minPrice, mrp * (1 - rule.commission - 0.05)); } }

Amazon MWS / Selling Partner API Integration

Amazon is typically the highest-volume marketplace. Deep integration ensures automated listing, inventory sync, order ingestion, and fulfillment coordination.

FeatureAPI EndpointFrequency
Product ListingsPUT /listings/2021-08-01/items/{sellerId}/{sku}On catalog change
Inventory SyncPATCH /listings/2021-08-01/items/{sellerId}/{sku}Real-time (webhook)
Order RetrievalGET /orders/v0/ordersEvery 2 minutes
Shipping ConfirmPOST /orders/v0/orders/{orderId}/shipmentOn dispatch
FBA InboundPOST /fba/inbound/v0/plansWeekly replenishment
Reports (Sales)GET /reports/2021-06-30/reportsDaily

WhatsApp Commerce

WhatsApp Commerce transforms messaging into a sales channel. Customers browse catalogs, ask questions, and complete purchases within the chat interface — ideal for high-consideration products like prescription eyewear.

Customer Initiates
Clicks WhatsApp ad
AI Assistant
Qualifies need
Catalog Share
Curated frames
AR Try-On Link
Web-based AR
In-Chat Payment
UPI/razorpay link
Order Tracking
Live updates

Cross-Channel Performance

MetricOwn WebsiteAmazonInstagramWhatsApp
Avg. Order Value$180$145$120$200
Return Rate8%12%15%5%
Customer Acquisition Cost$35$25$18$12
Margin (after fees)55%28%42%48%
Repeat Purchase Rate35%18%22%45%

B2B Wholesale — Deep Dive

Distributor & Wholesale Portal

The B2B Wholesale channel serves optical shops, department stores, and regional distributors who resell the brand's products. Unlike B2C, this channel requires tiered pricing, credit management, bulk workflows, and white-label capabilities.

Distributor Tier Structure

TierAnnual VolumeDiscountPayment TermsBenefits
Platinum$500K+45% off MRPNet 90Exclusive territory, co-marketing, priority stock
Gold$200K–$500K38% off MRPNet 60Seasonal previews, training support
Silver$50K–$200K30% off MRPNet 30Standard catalog access, online ordering
Bronze<$50K22% off MRPPrepaidBasic catalog, no exclusivity

Credit Management & Invoicing

B2B transactions rely on credit lines rather than instant payment. The system tracks credit limits, outstanding balances, aging reports, and auto-holds orders when limits are breached.

// Credit Check & Order Validation function validateB2BOrder(distributorId, order) { const distributor = getDistributor(distributorId); const credit = distributor.creditLimit; const outstanding = distributor.outstandingBalance; const orderValue = order.calculateTotal(); // Check credit availability if (outstanding + orderValue > credit) { return { status: "CREDIT_HOLD", message: `Credit limit exceeded. Available: $${credit - outstanding}`, action: "REQUEST_CREDIT_INCREASE_OR_PREPAY" }; } // Check MOQ per SKU for (const item of order.items) { if (item.quantity < item.sku.minOrderQty) { return { status: "MOQ_VIOLATION", sku: item.sku.id, required: item.sku.minOrderQty, ordered: item.quantity }; } } // All checks passed — approve distributor.outstandingBalance += orderValue; return { status: "APPROVED", orderId: generateOrderId() }; }

Bulk Ordering Workflows

B2B orders are large and complex. The portal supports CSV upload, quick-reorder from history, and visual assortment planning tools.

FeatureDescriptionBenefit
CSV UploadUpload 100+ SKUs at once with quantitiesSpeed for large seasonal orders
Quick ReorderOne-click reorder from last 3 months' historyReduces ordering time by 80%
Assortment PlannerVisual grid: frame styles × colors × sizes with stock availabilityOptimized SKU mix per store
Pre-BookingReserve upcoming collections before launchGuarantees allocation for hot items
Split ShipmentOne PO, multiple delivery addresses (store network)Centralized buying, decentralized receiving

White-Label / Private Label Support

The system supports white-label manufacturing where distributors sell frames under their own brand. This requires separate BOMs, packaging, and catalog segregation.

Customization Options

  • Frame color & material (from approved range)
  • Temple engraving (logo/text)
  • Custom packaging & case design
  • Warranty card branding
  • Price tag & barcode format

Catalog Segregation

  • Private SKUs invisible to other distributors
  • Separate pricing tables per white-label contract
  • Exclusive designs (territory-locked)
  • MOQ commitments enforced
  • Royalty tracking for licensed designs

Distributor Network Management

Geographic exclusivity prevents channel conflict. The system maps distributor territories, tracks performance, and flags potential violations.

Territory TypeDefinitionEnforcement
ExclusiveSole distributor for a city/region; no other B2B sales thereGeo-fenced order validation
Semi-ExclusivePrimary distributor + brand-owned stores allowedChannel conflict alerts
Non-ExclusiveMultiple distributors; price competition expectedPerformance-based tier upgrades
Online-OnlyDistributor sells only via their own e-commerceMarketplace listing monitoring

Multi-Location Model — Deep Dive

Four-Tier Inventory Architecture

The Multi-Location Model positions inventory across four tiers to optimize for speed, cost, and customer experience. Each tier serves a distinct purpose in the fulfillment network, from bulk storage to immediate customer access.

TierTypePurposeStock ProfileTypical Count
Tier 1Central WarehouseBulk receiving, B2B fulfillment, seasonal overflowDeep stock (3-6 months), all SKUs1 per country/region
Tier 2Regional HubFast fulfillment for online orders, returns processingFast-movers (1-2 months), top 40% SKUs3-5 per country
Tier 3Store StockImmediate customer access, BOPIS, same-day pickupDisplay + safety stock, curated assortment50-200 stores
Tier 4Lab InventoryWork-in-progress materials for lens manufacturingLens blanks, coatings, consumables1-3 per region

Fulfillment Routing Logic

When an order arrives, the OMS evaluates all locations to determine the optimal fulfillment source based on stock availability, proximity, cost, and SLA.

// Fulfillment Routing Algorithm function routeFulfillment(order) { const candidates = getLocationsWithStock(order.sku, order.quantity); const scored = candidates.map(loc => ({ location: loc, score: calculateScore(loc, order) })).sort((a, b) => b.score - a.score); return scored[0].location; } function calculateScore(location, order) { let score = 0; // Proximity to customer (higher = better) score += (1000 - location.distanceToCustomer) * 0.4; // Stock depth (prefer locations with more buffer) score += location.availableStock * 0.2; // Cost to fulfill (shipping + handling) score -= location.fulfillmentCost * 0.25; // SLA capability (can meet delivery promise?) score += location.canMeetSLA(order.deliveryPromise) ? 200 : 0; // Store preference for BOPIS if (order.type === "BOPIS" && location.type === "STORE") { score += 500; } // Regional hub preference for speed if (order.shippingSpeed === "EXPRESS" && location.type === "HUB") { score += 300; } return score; }

Central Warehouse Operations

The Central Warehouse is the backbone of the network. It receives bulk imports, handles B2B orders, and replenishes regional hubs and stores.

Receiving

  • Container unloading & ASN matching
  • Quality inspection (random sampling)
  • Put-away to bulk or pick zones
  • Import documentation & customs clearance

B2B Fulfillment

  • Case picking (full cartons)
  • Pallet building & stretch wrapping
  • Freight booking (LTL/FTL)
  • Delivery scheduling with distributors

Replenishment Triggers

DestinationTriggerMethodFrequency
Regional HubHub stock below 2-week coverFull pallet transfersWeekly
StoreStore reorder point hitCarton/box transfersBi-weekly
LabMRP run based on production planComponent kitsDaily

Store Stock Management

Store inventory is the most customer-critical tier. It must balance display aesthetics (variety) with availability (depth) while minimizing carrying costs.

ConceptDescriptionImplementation
Display StockFrames on shelves for try-on (1 per style/color)Non-sellable until customer selects; tracked separately
Backroom StockSellable inventory in store backroomReal-time sync with central engine; auto-replenish triggers
Endless AisleOrder from warehouse for store pickupKiosk or associate tablet; ships from hub to store
Store-to-Store TransferMove stock between nearby storesSame-day courier for urgent customer needs
Cycle CountDaily spot checks on high-value itemsAssociate app with barcode scanning

Lab Inventory (WIP Materials)

Lab inventory is unique — it tracks raw materials and work-in-progress for lens manufacturing rather than finished goods for sale.

CategoryItemsTracking MethodReorder Trigger
Lens BlanksMR-8, MR-10, polycarbonate, high-index resinsLot number, expiry date, power rangeMRP run based on production schedule
Coating ChemicalsHard coat, AR stack, UV monomersBatch number, shelf life, consumption rateMin-max levels with safety buffer
ConsumablesPolishing pads, blocking wax, edging wheelsPar level systemTwo-bin or Kanban
Work-in-ProgressCut lenses awaiting coating, coated awaiting assemblyJob ID tracking through stationsProduction queue monitoring

Inventory Hierarchy — Deep Dive

Four Levels of Stock Classification

The Inventory Hierarchy classifies stock into four levels based on its state in the value chain. Each level has distinct tracking requirements, valuation methods, and compliance implications.

Level 1
Raw Materials
Level 2
Work-in-Progress
Level 3
Finished Goods
Level 4
Consignment / On-Order

Level 1: Raw Materials

Raw materials are the base inputs for manufacturing. For eyewear, this includes optical resins, metals, acetate sheets, and small hardware.

MaterialSourceUnitShelf LifeValuation
Optical Resin (MR-8)Import — Japan/KoreaSheet/bulk24 monthsWeighted average cost
Titanium SheetImport — JapanSheetIndefiniteWeighted average cost
Acetate BlocksImport — Italy/ChinaBlockIndefiniteFIFO
Stainless SteelLocal — IndiaSheet/barIndefiniteWeighted average cost
Silicone Nose PadsLocal — IndiaPack of 100036 monthsFIFO
Screws & HingesLocal — IndiaPack of 500IndefiniteFIFO

Level 2: Work-in-Progress (WIP)

WIP represents inventory that has entered production but is not yet a finished sellable product. Tracking WIP is critical for production planning and cost accounting.

Lens Manufacturing WIP

  • Surfaced lenses (awaiting polishing)
  • Polished lenses (awaiting coating)
  • Coated lenses (awaiting edging)
  • Edged lenses (awaiting assembly)
  • Rejected lenses (QC failure)

Frame Manufacturing WIP

  • Cut frame fronts (awaiting hinge drilling)
  • Drilled fronts (awaiting temple attachment)
  • Assembled frames (awaiting QC)
  • QC-failed frames (rework or scrap)
  • Frames awaiting packaging

WIP Valuation

// WIP Cost Rollup function calculateWIPValue(jobId) { const job = getJob(jobId); const materialCost = job.materials.reduce((sum, m) => sum + (m.quantity * m.unitCost), 0 ); const laborCost = job.operations.reduce((sum, op) => sum + (op.minutes * op.laborRate / 60), 0 ); const overhead = (materialCost + laborCost) * 0.15; // 15% overhead return materialCost + laborCost + overhead; }

Level 3: Finished Goods

Finished goods are sellable products ready for dispatch to customers or stores. This is the most actively managed inventory level with direct revenue impact.

CategoryExamplesTrackingTurnover Target
Optical FramesRay-Ban, own-brand titanium, acetateSerial number, color, size6-8x per year
SunglassesPolarized, photochromic, fashionSerial number, UV rating4-6x per year (seasonal)
Complete EyewearFrame + lens assembled to RxJob ID, Rx referenceMade-to-order (no stock)
Contact LensesDaily, monthly, toric, multifocalLot number, expiry, power12x per year
AccessoriesCases, cloths, chains, solutionsSKU-level8-10x per year

Level 4: Consignment & On-Order

Level 4 inventory is not physically in the company's warehouses but is still tracked for visibility and commitment management.

Consignment Stock

  • Definition: Goods at distributor/store; ownership retained until sold
  • Tracking: Serial numbers, location, consignment agreement terms
  • Billing: Auto-invoice when POS sale occurs
  • Reconciliation: Monthly physical count vs. system records
  • Return: Unsold stock returnable per agreement (e.g., 90 days)

On-Order / In-Transit

  • Open POs: Purchase orders placed but not yet received
  • In-Transit: Goods shipped from supplier, customs pending
  • Expected Receipt: ETA-based ATP calculation
  • Pre-Booked: Customer orders awaiting stock arrival
  • Backorders: Customer orders for out-of-stock items

On-Order Impact on ATP

// Available-to-Promise with On-Order function calculateATP(sku, location) { const onHand = getOnHand(sku, location); const reserved = getReserved(sku, location); const safetyStock = getSafetyStock(sku, location); const inTransit = getInTransit(sku, location); // Expected within lead time const backorders = getBackorders(sku, location); return onHand - reserved - safetyStock + inTransit - backorders; }

Lens Cutting & Surfacing — Deep Dive

From Blank to Prescription Lens

Lens Cutting & Surfacing transforms a flat optical blank into a precision-curved prescription lens. This is the most technically demanding step in eyewear manufacturing, requiring sub-micron accuracy to ensure optical clarity and comfort.

Blank Selection
Material & power
Surfacing
CNC curve generation
Polishing
Optical clarity
Edging
Shape to frame
Power Verify
Focimeter check

Blank Selection by Prescription

The right blank ensures manufacturability, optical quality, and minimal edge thickness. Selection depends on prescription power, material, and desired coatings.

ParameterLow Power (-2.00 to +2.00)Medium Power (-4.00 to -2.00)High Power (<-4.00 or >+3.00)
MaterialCR-39 or MR-8MR-8 or PolycarbonateMR-10 or 1.74 High-Index
Blank Diameter65mm70mm75-80mm
Base Curve4.00D (standard)4.00-6.00D6.00-8.00D (steep)
Center Thickness1.5-2.0mm2.0-3.0mm3.0-5.0mm (minimize edge)
Edge Thickness2-3mm3-5mm5-8mm (cosmetic concern)

CNC Surfacing Process

Computer Numerical Control (CNC) surfacing machines cut the prescription curve into the lens blank with diamond-tipped tools. Accuracy is within ±0.01 diopter.

Surfacing Parameters

  • Spherical Power (SPH): Overall lens curvature
  • Cylindrical Power (CYL): Astigmatism correction
  • Axis: Orientation of cylinder (0-180°)
  • Add Power: Reading addition for progressives
  • Prism: Deviation correction (base direction)

Quality Checks

  • Surface roughness < 0.5nm Ra
  • Power accuracy ±0.05D
  • Axis alignment ±2°
  • No tool marks or scratches
  • Thickness within spec
// Lens Surfacing Job Parameters const job = { rx: { rightEye: { sph: -3.50, cyl: -1.25, axis: 180, add: null }, leftEye: { sph: -3.25, cyl: -0.75, axis: 90, add: null }, pd: { right: 32.0, left: 31.5 } }, blank: { material: "MR-8", index: 1.60, diameter: 70, baseCurve: 4.00 }, surfacing: { toolPath: "toric_generator", polishGrade: "optical_fine", targetThickness: { center: 2.2, edge: 4.5 } } };

Edging & Drilling

After surfacing, the lens must be edged to fit the specific frame shape. For rimless frames, holes are drilled for mounting.

Frame TypeEdging MethodKey ParametersQuality Check
Full RimBevel edging (groove for frame rim)Bevel angle, groove depth, edge polishFit test in frame, no gaps
Semi-Rimless (Nylon Cord)Groove edging + nylon grooveGroove position, cord tensionSecure hold, no lens pop-out
Rimless (Drilled)Flat polish + precision drillingHole diameter, hole position, countersinkNo cracks, screw torque correct
High-Wrap (Sports)Wrapped edging with base curve matchWrap angle, pantoscopic tiltOptical center alignment

Lens Coating — Deep Dive

Multi-Layer Coating Stack

Lens Coating applies multiple thin-film layers to the lens surface, each serving a specific optical or protective function. A premium lens may have 10-15 distinct layers applied in a vacuum deposition chamber.

Hard Coat
Base protection
AR Stack
Anti-reflective
UV Block
100% UVA/UVB
Hydrophobic
Water repellent
Oleophobic
Smudge resistant

Layer-by-Layer Breakdown

LayerMaterialThicknessFunctionTest Standard
Hard CoatSilica-based organosilane3-5 μmScratch resistance, adhesion promoterISO 8980-4 (steel wool test)
AR Stack (MgF₂/SiO₂/TiO₂)Metal oxides via vacuum deposition100-200 nm per layerReduce surface reflection from 8% to <1%ISO 8980-4 (reflectance <1.5%)
UV BlockerOrganic UV absorbersIntegrated in substrate or coatingBlock 100% UVA (315-400nm) & UVB (280-315nm)ISO 8980-3 (UV transmittance)
Blue Light FilterSelective absorption dyeIntegrated in substrateBlock 20-40% of 400-450nm (HEV)ISO 12312-1 (blue light hazard)
Hydrophobic TopcoatFluoropolymer10-20 nmWater beads up, easy cleaningContact angle >110°
Oleophobic TopcoatFluorinated silane5-10 nmFingerprint resistanceOil repellency test

Vacuum Deposition Process

The coating chamber operates under high vacuum (10⁻⁵ mbar) where metal oxides are vaporized and deposited onto the lens surface in precise nanometer layers.

Process Steps

  1. Pre-cleaning: Ultrasonic wash + plasma treatment
  2. Loading: Lenses mounted on rotating planetary drum
  3. Pump-down: Chamber evacuated to 10⁻⁵ mbar
  4. Hard coat: Spin-coat + UV cure (if wet process)
  5. AR deposition: Electron beam evaporation of oxides
  6. Optical monitoring: In-situ reflectance measurement
  7. Topcoat: Plasma-enhanced chemical vapor deposition
  8. Unload & inspect: Visual + spectral check

Coating Defects & Causes

  • Pinholes: Contamination on lens surface
  • Color shift: Incorrect layer thickness
  • Peeling: Insurface preparation or adhesion failure
  • Streaks: Uneven deposition rate
  • Cloudiness: Moisture ingress during process

Photochromic & Blue Light Technologies

TechnologyMechanismActivationPerformance
Photochromic (Transitions®)Silver halide molecules darken in UVUV exposure (outdoor)Clear indoors → 85% dark outdoors in 30s; fade in 3-5 min
Blue Light FilterSelective absorption of 400-450nmAlways activeBlocks 20-40% HEV; minimal color distortion
PolarizedVertical alignment filter blocks horizontal glareAlways active99% glare reduction; ideal for driving/water
Mirror CoatingThin metallic reflective layerAlways activeReduces light transmission 10-60%; fashion + function

Frame Assembly — Deep Dive

Frame Assembly Workflow

Frame Assembly brings together all mechanical components of the eyewear frame — front, temples, hinges, nose pads, and screws — into a functional, adjustable unit ready for lens fitting.

Front Prep
Hinge drilling
Hinge Install
Screw/barrel
Temple Attach
Alignment
Nose Pad Fit
Comfort & grip
Alignment
Geometric check

Component Specifications

ComponentMaterialsKey SpecsQuality Check
Front FrameAcetate, titanium, stainless steel, TR-90Rim width, bridge width, lens heightDimensional accuracy ±0.5mm
Temple ArmsSame as front + beta-titanium for flexibilityLength (135-150mm), drop angle, tip widthSpring hinge tension test
HingesStainless steel, monel, titaniumBarrel count (3-7), screw size (1.2-1.4mm)10,000 open/close cycles
Nose PadsSilicone, PVC, titanium pad armsSize (S/M/L), shape (symmetrical/ergo)Skin contact biocompatibility
ScrewsStainless steel, titaniumThread pitch, head type, lengthTorque test, no stripping
Logo PlatesMetal alloy, enamel fillPosition, adhesion, legibilityScratch resistance, alignment

Geometric Alignment Standards

Proper alignment ensures optical centers align with the patient's pupils and the frame sits comfortably without pressure points.

Horizontal Alignment

  • Face form angle: 5-8° wrap (frontal curvature)
  • Temporal distance: Equal on both sides
  • Bridge symmetry: Centered, no twist
  • Frame width: Slightly wider than face (2-3mm each side)

Vertical Alignment

  • Pantoscopic tilt: 8-12° (top closer to face)
  • Retroscopic tilt: 0-5° (bottom closer — rare)
  • Vertex distance: 12-14mm (lens to cornea)
  • Equal lens height: Both eyes at same level
// Frame Alignment Check Protocol function checkFrameAlignment(frame) { const checks = { faceFormAngle: { min: 5, max: 8, unit: "degrees" }, pantoscopicTilt: { min: 8, max: 12, unit: "degrees" }, vertexDistance: { min: 12, max: 14, unit: "mm" }, bridgeSymmetry: { tolerance: 0.5, unit: "mm" }, hingeTorque: { min: 0.8, max: 1.2, unit: "Nm" } }; const results = {}; for (const [check, spec] of Object.entries(checks)) { const measured = frame.measurements[check]; results[check] = { measured, passed: measured >= spec.min && measured <= spec.max, spec }; } return results; }

Assembly Station Tools & Jigs

ToolPurposePrecision
Drilling JigPositions hinge holes on front frame±0.1mm hole position
Tapping MachineCreates screw threads in barrel hingesM1.2 × 0.25 pitch
Spring Hinge PressInstalls spring hinge assembliesControlled force, no deformation
Nose Pad PliersAdjusts pad angle and position0.5° angle control
Temple BenderAdjusts temple curve for ear fit5° increment steps
Torque ScrewdriverTightens screws to exact torque0.5-2.0 Nm range

QC & Testing — Deep Dive

Quality Control Checkpoints

QC & Testing ensures every pair of eyewear meets optical, mechanical, and cosmetic standards before reaching the customer. Defects caught in manufacturing cost $5 to fix; defects caught by the customer cost $50+ in returns and reputation damage.

Incoming QC
Raw materials
In-Process QC
WIP stations
Final Optical QC
Power & clarity
Final Mechanical QC
Durability & fit
Packaging QC
Cosmetic & docs

Optical Quality Tests

TestEquipmentStandardAcceptance Criteria
Power VerificationFocimeter (lensometer)ISO 8980-1SPH ±0.09D, CYL ±0.09D, AXIS ±2°
Prismatic PowerFocimeterISO 8980-1≤ 0.25Δ for single vision; ≤ 0.50Δ for progressives
TransmittanceSpectrophotometerISO 8980-3Clear: ≥ 85%; Sunglasses: category-specific
UV ProtectionUV spectrometerISO 8980-3≤ 1% transmittance below 380nm
AR Coating QualityReflectometerISO 8980-4Reflectance < 1.5% at 550nm
Surface DefectsVisual inspection + magnifierInternalNo scratches, bubbles, or inclusions in visual zone

Mechanical Durability Tests

TestMethodStandardPass Criteria
Hinge EnduranceAutomated open/close cycle machineISO 1287010,000 cycles; no fracture, no loosening
Frame Drop TestDrop from 1.27m onto steel surfaceISO 12870No fracture; hinge function intact
Lens Impact Resistance16g steel ball from 1.27mISO 14889 / FDA 21 CFR 801.410No fracture or detachment from frame
High-Temperature Stability55°C for 2 hoursISO 12870No deformation, coating intact
Corrosion Resistance24h salt spray (5% NaCl)ISO 12870No visible corrosion on metal parts
Nose Pad Adhesion10N pull forceInternalNo detachment or tearing

QC Documentation & Traceability

Every unit receives a unique serial number linking it to the complete manufacturing history — materials, operators, machines, test results, and timestamps.

// QC Record for Unit SN: EYE-2026-089234 const qcRecord = { serialNumber: "EYE-2026-089234", sku: "TITAN-ROUND-BLK-52", batchId: "BATCH-2026-W28-A", manufacturing: { surfacingMachine: "CNC-03", coatingChamber: "VAC-07", assemblyStation: "ASM-12", operators: ["OP-441", "OP-203", "OP-089"], timestamps: { surfacingStart: "2026-07-08T06:23:00Z", coatingStart: "2026-07-08T08:15:00Z", assemblyStart: "2026-07-08T10:45:00Z", finalQC: "2026-07-08T12:30:00Z" } }, testResults: { optical: { sphR: -3.51, sphL: -3.24, cylR: -1.24, cylL: -0.76, passed: true }, mechanical: { hingeCycles: 10000, dropTest: "PASS", impact: "PASS" }, cosmetic: { scratches: 0, coatingDefects: 0, alignment: "PASS" } }, disposition: "PASSED", shippedAt: null, customerOrderId: "ORD-2026-77234" };

Job Tracking — Deep Dive

Work Order Lifecycle

Job Tracking follows every work order from receipt through production to dispatch. Real-time visibility into job status enables proactive customer communication, capacity planning, and bottleneck identification.

Order Received
Rx + frame + lens specs
Scheduled
Priority + capacity
In Production
Station-level tracking
QC Complete
All tests passed
Pack & Dispatch
Ship to customer/store

Turnaround Time (TAT) by Complexity

Order TypeStationsStandard TATExpress TATRush TAT
Single Vision — Stock LensEdging → Assembly → QC → Pack4 hours2 hours1 hour
Single Vision — Custom SurfacedSurfacing → Coating → Edging → Assembly → QC24 hours12 hours6 hours
Progressive — StandardSurfacing → Coating → Edging → Assembly → QC48 hours24 hours12 hours
Progressive — Premium (Freeform)Digital surfacing → Multi-coat → Edging → Assembly → QC72 hours48 hours24 hours
Rimless / DrilledSurfacing → Coating → Drilling → Assembly → QC48 hours24 hours12 hours
High-Power (>±6.00D)Surfacing → Coating → Edging → Centering → Assembly → QC72 hours48 hoursN/A (quality priority)

Real-Time Job Dashboard

The production floor operates on a digital job board showing every active order, its current station, operator, elapsed time, and predicted completion.

// Job Status Update — Station Scan async function updateJobStatus(jobId, stationId, operatorId, action) { const job = await getJob(jobId); const station = getStation(stationId); const timestamp = new Date().toISOString(); switch (action) { case "START": job.stations[stationId] = { status: "IN_PROGRESS", operator: operatorId, startedAt: timestamp, estimatedComplete: addMinutes(timestamp, station.avgCycleTime) }; job.currentStation = stationId; break; case "COMPLETE": job.stations[stationId].status = "COMPLETE"; job.stations[stationId].completedAt = timestamp; job.stations[stationId].actualTime = diffMinutes( job.stations[stationId].startedAt, timestamp ); break; case "QC_FAIL": job.stations[stationId].status = "QC_FAIL"; job.status = "REWORK_REQUIRED"; await alertSupervisor(jobId, stationId, "QC failure"); break; } // Broadcast update to customer-facing tracking await broadcastJobUpdate(job); return job; }

Exception Handling & Alerts

Exception TypeTriggerAuto-ActionEscalation
TAT Breach RiskCurrent station elapsed > 80% of targetAlert supervisor; suggest resource reallocationFloor manager if >100%
Material ShortageBlank or coating chemical below min levelAuto-PO to procurement; flag jobs affectedProduction planner immediately
Machine DownCNC or coating chamber error codeAuto-reroute jobs to backup machine; alert maintenancePlant manager + customer service
QC FailureOptical or mechanical test failQuarantine unit; trigger rework or remakeQuality manager for pattern analysis
Rx AmbiguityPrescription values outside normal rangeHold job; request doctor clarificationClinical team + customer notification

Sourcing Strategy — Deep Dive

Strategic Sourcing Matrix

Sourcing Strategy determines where and how raw materials and components are procured. For eyewear, this involves balancing cost, quality, lead time, and geopolitical risk across a global supplier base.

Material CategoryPrimary SourceSecondary SourceStrategyRisk Mitigation
Optical Resins (MR-8, MR-10)Japan (Mitsui Chemicals)Korea (KOC)Dual-source with 70/30 split6-month safety stock; annual contract
Titanium SheetJapan (Kobe Steel)China (Baoji)Premium from Japan; volume from ChinaPre-negotiated surge capacity
Acetate BlocksItaly (Mazzucchelli)China (Jinyi)Fashion from Italy; basic from ChinaSeasonal pre-booking for colors
Stainless SteelIndia (Jindal)China (Tsingshan)Local-first for speedVMI arrangement with local mill
Hinges & Small HardwareChina (Wenzhou)India (Mumbai)China for cost; India for speed2-week rolling forecast shared
PackagingIndia (Delhi/Ahmedabad)Local print shopsLocal for JIT; custom for premium3-supplier panel per category

Import vs. Local Decision Framework

The make-vs-buy and import-vs-local decisions are driven by total landed cost, quality requirements, and strategic importance.

Import Criteria

  • Proprietary technology not available locally
  • Quality standards exceed local capability
  • Volume justifies container shipping economics
  • Brand positioning requires origin story
  • Long-term contract locks in favorable pricing

Local Criteria

  • Speed to market is critical (JIT)
  • Small lot sizes / frequent changes
  • Simple manufacturing, no IP dependency
  • Government incentives for local sourcing
  • Currency volatility makes imports risky
// Total Landed Cost Calculator function calculateLandedCost(source) { const components = { unitPrice: source.quotedPrice, freight: source.shippingMode === "sea" ? source.volumeCbm * 80 // $80/CBM sea freight : source.weightKg * 6.5, // $6.5/kg air freight insurance: source.unitPrice * 0.015, // 1.5% of value customsDuty: source.unitPrice * source.hsCode.dutyRate, clearance: 150, // Fixed per-shipment inlandTransport: source.distanceKm * 0.08, financing: source.unitPrice * 0.03 * (source.leadTimeDays / 30), // 3% monthly carrying cost qualityRisk: source.defectRate * source.unitPrice * 2.5 // Cost of rework/return }; return Object.values(components).reduce((a, b) => a + b, 0); }

Supplier Relationship Tiers

TierRelationshipEngagementPerformance Review
Strategic PartnerJoint development, shared forecasts, co-investmentMonthly business reviews, quarterly roadmapScorecard: quality 40%, delivery 30%, cost 20%, innovation 10%
Preferred SupplierMulti-year contract, volume commitmentBi-monthly reviews, annual negotiationScorecard: quality 35%, delivery 35%, cost 25%, service 5%
Approved SupplierTransactional, PO-basedQuarterly review, issue-driven contactPass/fail on delivery and quality thresholds
ProvisionalTrial period, limited volumeMonthly during trial, then upgrade or exit100% inspection, detailed capability audit

Import Logistics — Deep Dive

International Freight Modes

Import Logistics manages the movement of goods from overseas suppliers to domestic warehouses. Mode selection balances speed, cost, and cargo characteristics.

ModeCost per kgTransit TimeBest ForExample Cargo
Sea FCL (Full Container)$0.50-1.5025-40 daysBulk, non-urgent, cost-sensitive20ft container of acetate blocks
Sea LCL (Less than Container)$1.50-3.0030-50 daysMedium volume, no full container5 CBM of titanium sheets
Air Freight$4.00-8.003-7 daysUrgent, high-value, perishableLens resin for production rush
Air Courier (DHL/FedEx)$8.00-15.002-5 daysDocuments, samples, small parcelsPrototype frames, lab samples
Sea-Air Combo$2.50-4.5015-20 daysBalance of speed and costMid-season replenishment

Customs Clearance & HS Codes

Proper classification ensures correct duty rates, avoids delays, and maintains compliance. Eyewear spans multiple HS chapters depending on material and state.

ProductHS CodeDescriptionTypical Duty Rate (India)
Plastic Frames9003.11Frames & mountings of plastics15% + 10% SWS
Metal Frames9003.19Frames & mountings of other materials15% + 10% SWS
Corrective Lenses (Glass)9001.40Spectacle lenses of glass10% + 10% SWS
Corrective Lenses (Plastic)9001.50Spectacle lenses of other materials10% + 10% SWS
Optical Resin Blanks9001.30Contact lens & spectacle lens blanks10% + 10% SWS
Sunglasses9004.10Sunglasses20% + 10% SWS

Bonded Warehouse Strategy

Bonded warehouses allow duty deferral — customs duty is paid only when goods leave the warehouse for domestic consumption, improving cash flow and enabling re-export without duty payment.

Benefits

  • Duty payment deferred until sale
  • Re-export without duty (regional hub strategy)
  • Bulk import, gradual release
  • Quality inspection before duty payment
  • Consolidation of multiple suppliers

Constraints

  • Limited storage period (typically 1 year)
  • Customs supervision & record keeping
  • No manufacturing/value-add allowed
  • Repackaging/relabeling may require approval
  • Security deposit or bank guarantee required

Import Shipment Tracking Dashboard

// Import Shipment Status const shipment = { blNumber: "MAEU123456789", vessel: "EVER GIVEN", route: { origin: "Yokohama", destination: "JNPT Mumbai" }, timeline: [ { event: "BOOKED", date: "2026-06-01", location: "Yokohama" }, { event: "LOADED", date: "2026-06-05", location: "Yokohama" }, { event: "DEPARTED", date: "2026-06-07", location: "Yokohama" }, { event: "ARRIVED", date: "2026-07-02", location: "JNPT Mumbai" }, { event: "CUSTOMS_HOLD", date: "2026-07-03", location: "JNPT", reason: "DOCUMENT_VERIFICATION", etaClearance: "2026-07-05" } ], documents: { commercialInvoice: "UPLOADED", packingList: "UPLOADED", certificateOfOrigin: "PENDING", billOfLading: "UPLOADED" }, duty: { assessableValue: 45000, dutyRate: 0.15, dutyPayable: 6750 } };

Local Procurement — Deep Dive

Domestic Supplier Management

Local Procurement sources components and services from domestic vendors. The focus is on speed, flexibility, and reducing import dependency for non-critical items.

CategoryLocal SuppliersLead TimeMOQQuality Grade
Stainless SteelJindal, SAIL, local mills3-7 days500 kg304/316 grade certified
Packaging (Cases)Delhi NCR, Ahmedabad7-14 days1,000 unitsCustom design, BIS compliant
Microfiber ClothsTirupur, Surat5-10 days5,000 units200 GSM, edge-sealed
Printing & LabelsLocal print shops2-5 days500 unitsUV-resistant ink
Logistics ServicesBlue Dart, Delhivery, local couriersSame day - 3 daysN/ASLA-based, insured
Maintenance PartsLocal distributors1-3 daysAs neededOEM or equivalent

Vendor-Managed Inventory (VMI)

VMI shifts inventory ownership and replenishment responsibility to the supplier. The supplier monitors stock levels and replenishes automatically, reducing the buyer's working capital and administrative burden.

Share Data
Daily stock levels
Auto-Replenish
Supplier decides when/what
Deliver
To agreed location
Consume
Pay on use
Invoice
Monthly consolidated
VMI ElementBuyer ResponsibilitySupplier Responsibility
Stock MonitoringProvide real-time consumption dataAnalyze trends, predict demand
Reorder DecisionSet min/max levels, review quarterlyTrigger replenishment, manage lead time
Inventory OwnershipOwns stock upon receiptOwns stock in transit
PaymentPay on consumption (monthly)Invoice based on consumption report
QualityInspect on receipt, reject defects100% pre-ship inspection

Just-in-Time (JIT) & Milk Runs

JIT minimizes inventory by receiving goods only as needed. Milk runs consolidate pickups from multiple local suppliers into a single delivery route, reducing transportation costs.

JIT Implementation

  • Daily production schedule shared with suppliers by 6 PM
  • Next-day morning delivery for consumables
  • 2-hour delivery window for critical items
  • Quality at source — supplier certifies, buyer spot-checks
  • Kanban cards or electronic signals trigger replenishment

Milk Run Schedule

  • Route A (North): Delhi NCR packaging suppliers — Mon/Wed/Fri
  • Route B (West): Mumbai hardware & consumables — Tue/Thu
  • Route C (South): Chennai/Tirupur textiles — Weekly
  • Consolidated truck capacity: 80% utilized minimum
  • Cross-dock at central warehouse for sorting

Local Quality Audits

Audit TypeFrequencyScopePass Criteria
Initial QualificationBefore onboardingFacility, process, quality system, financial healthScore ≥ 80%; no critical findings
Annual RequalificationYearlyFull system review, CAPA verificationScore ≥ 75%; all CAPAs closed
Process AuditBi-annuallySpecific process (e.g., coating, printing)CPK ≥ 1.33 for critical dimensions
Surveillance VisitQuarterlySpot check, random samplingNo major non-conformances
Issue-Driven AuditAs neededRoot cause of quality/delivery failureCorrective action verified

Distribution Logistics — Deep Dive

Last-Mile Delivery Ecosystem

Distribution Logistics covers the final leg of delivery — from warehouse to customer doorstep or retail store. For eyewear, this includes B2C e-commerce parcels, B2B bulk shipments, and inter-warehouse transfers.

CarrierStrengthCoverageCost ProfileBest Use Case
Blue DartReliability, premium service35,000+ pincodesHighPremium eyewear, express delivery
DelhiveryScale, cost-efficiency18,000+ pincodesMediumStandard e-commerce, bulk
ShiprocketMulti-carrier aggregationAll major carriersOptimizedRate shopping, SMB orders
DHL/FedExInternational expressGlobalPremiumCross-border B2C/B2B
Dunzo/SwiggyHyperlocal same-dayMetro citiesPer-kmSame-day delivery, store transfers
Own FleetControl, brandingCity limitsFixed costB2B distributor drops, BOPIS

Same-Day Delivery Zones

Same-day delivery is a competitive differentiator for urban customers. The system defines delivery zones based on warehouse/store proximity, carrier capability, and order cut-off times.

// Same-Day Delivery Zone Logic function getDeliveryOptions(order) { const customerPincode = order.shippingAddress.pincode; const orderTime = new Date(order.createdAt); const nearestHub = findNearestHub(customerPincode); const distance = calculateDistance(nearestHub.location, customerPincode); const options = []; // Same-day: within 15km, order before 2 PM if (distance <= 15 && orderTime.getHours() < 14) { options.push({ type: "SAME_DAY", carrier: "HYPERLOCAL", cost: 99, eta: "Today by 8 PM", cutoff: "2:00 PM" }); } // Next-day: within 50km, order before 5 PM if (distance <= 50 && orderTime.getHours() < 17) { options.push({ type: "NEXT_DAY", carrier: "BLUE_DART_EXPRESS", cost: 49, eta: "Tomorrow by 8 PM", cutoff: "5:00 PM" }); } // Standard: all other cases options.push({ type: "STANDARD", carrier: "DELHIVERY", cost: order.total > 2000 ? 0 : 29, eta: "3-5 business days", cutoff: null }); return options; }

Reverse Logistics (Returns)

Eyewear has a 5-12% return rate depending on channel. Reverse logistics must handle returns efficiently while minimizing fraud and maximizing resale value.

Return Reasons & Disposition

Reason% of ReturnsDisposition
Wrong fit / uncomfortable35%Resellable — restock
Not as described20%Resellable — restock
Defective / damaged15%QC → repair or scrap
Changed mind18%Resellable — restock
Rx error8%Remake — lens only
Fraud / abuse4%Blacklist customer

Return Process

  1. Customer initiates return via portal/app
  2. System validates return window (7-30 days)
  3. Auto-generates reverse pickup label
  4. Carrier collects from customer
  5. Return hub receives & inspects
  6. QC grades: A (resell), B (refurb), C (scrap)
  7. Refund processed per payment method
  8. Analytics updates return reason codes

B2B Bulk Shipping

B2B shipments to distributors and retail chains require palletization, freight booking, and delivery scheduling rather than parcel delivery.

ElementSpecificationSystem Integration
Pallet Standard1200×1000mm Euro pallet, max 500kgWMS auto-palletization logic
Carton LabelingSSCC barcode, batch number, SKU listLabel generation at pack station
Freight BookingLTL (1-5 pallets) or FTL (6+ pallets)Integration with freight marketplace
Delivery AppointmentScheduled dock appointment with distributorCalendar sync + SMS confirmation
Proof of DeliveryDigitally signed BOL with photoDriver app capture, auto-archive
Damage ClaimPhotograph + claim within 48 hoursAuto-trigger insurance workflow

Rx Capture & Validation — Deep Dive

Digital Prescription Architecture

Rx Capture & Validation ensures that every prescription entered into the system is accurate, valid, and legally compliant before it drives lens manufacturing. A single digit error in sphere or cylinder can render lenses unusable and costly to remake.

Capture
Photo or manual entry
OCR Parse
Extract values
Validate
Range & logic checks
Doctor Verify
License check
Customer Confirm
Human-in-loop

Structured Rx Data Model

// Prescription Data Structure (ISO 13606 compliant) const prescription = { rxId: "RX-2026-084721", patientId: "PAT-441289", // Prescribing Doctor doctor: { name: "Dr. Ananya Sharma", licenseNumber: "OPT-MH-2018-4521", registrationBody: "Maharashtra Optometry Council", clinicName: "Sharma Eye Care", verified: true, verifiedAt: "2026-07-08T10:00:00Z" }, // Prescription Values rightEye: { sph: -3.50, // Sphere: -20.00 to +20.00, step 0.25 cyl: -1.25, // Cylinder: -6.00 to +6.00, step 0.25 axis: 180, // Axis: 1 to 180, integer add: null, // Addition: +0.75 to +3.50 (progressives) prism: { value: null, base: null } // Prism: 0.5 to 10.0 }, leftEye: { sph: -3.25, cyl: -0.75, axis: 90, add: null, prism: { value: null, base: null } }, // Measurements pd: { binocular: 63.5, right: 32.0, left: 31.5 }, // Metadata rxDate: "2026-06-15", expiryDate: "2028-06-15", // 2 years from Rx date lensType: "SINGLE_VISION", // SINGLE_VISION | BIFOCAL | PROGRESSIVE // Validation Status validation: { ocrConfidence: 0.94, rangeCheck: "PASS", consistencyCheck: "PASS", doctorVerified: "PASS", customerConfirmed: "PENDING" } };

Validation Rules Engine

RuleLogicAction on Fail
Range Check — SPH-20.00 ≤ SPH ≤ +20.00, step 0.25Flag for manual review; block order
Range Check — CYL-6.00 ≤ CYL ≤ +6.00, step 0.25Flag for manual review; block order
Range Check — AXIS1 ≤ AXIS ≤ 180, integer onlyAuto-correct if obvious (e.g., 181→1); else flag
CYL-Axis DependencyIf CYL = 0, AXIS must be null or 0Auto-clear AXIS; notify customer
Anisometropia Check|SPH_R - SPH_L| ≤ 3.00D (comfort warning if >2.50D)Warning: may cause adaptation issues
Add Power LogicIf lensType = PROGRESSIVE, ADD required and ≥ +0.75Block order; request complete Rx
Rx ExpiryCurrent date ≤ Rx date + validity periodBlock order; prompt for new exam
Doctor LicenseLicense number matches active registry entryBlock order; request valid Rx
PD Range50mm ≤ PD ≤ 80mm (adult); 40mm ≤ PD ≤ 60mm (child)Flag for manual measurement verification

OCR & Image Processing Pipeline

When customers upload a photo of their prescription, the system uses OCR (Optical Character Recognition) to extract structured data with confidence scoring.

// OCR Pipeline for Prescription Images async function processPrescriptionImage(imageBuffer) { // 1. Pre-processing const enhanced = await enhanceImage(imageBuffer, { denoise: true, deskew: true, contrast: true }); // 2. Text detection & extraction const ocrResult = await googleVision.documentTextDetection(enhanced); // 3. Structured parsing using regex + NLP const parsed = parseRxFields(ocrResult.text); // Example: "OD: -3.50 / -1.25 x 180" → { eye: "right", sph: -3.50, cyl: -1.25, axis: 180 } // 4. Confidence scoring per field const confidence = { sph: ocrResult.confidence * fieldClarityScore(parsed.sph), cyl: ocrResult.confidence * fieldClarityScore(parsed.cyl), axis: ocrResult.confidence * fieldClarityScore(parsed.axis) }; // 5. Human review trigger if low confidence const needsReview = Object.values(confidence).some(c => c < 0.85); return { parsed, confidence, needsReview }; }

Doctor Portal — Deep Dive

Optometrist / Ophthalmologist Workspace

The Doctor Portal is the clinical workspace for eye care professionals. It handles everything from patient scheduling to digital prescription writing, with full integration into the eyewear ordering flow.

Onboarding
License verify
Scheduling
Manage calendar
Examination
Record findings
Digital Rx
Write & sign
Order Link
Direct to store

Doctor Onboarding & Verification

StepActionSystem CheckTimeline
1. RegistrationDoctor submits profile, credentials, clinic detailsDuplicate check, email verificationInstant
2. License UploadUpload registration certificate, degreeOCR extraction of license number5 minutes
3. Registry VerificationSystem queries state optometry council APILicense active? Valid until? Disciplinary actions?Real-time
4. Background CheckManual review for high-risk flagsSanctions list, malpractice history24-48 hours
5. TrainingPlatform walkthrough, Rx digital signing tutorialCompletion tracking1 hour
6. ActivationAccount enabled, commission tier assignedFull audit trail of activationInstant post-approval

Appointment & Schedule Management

Scheduling Features

  • Multi-location clinic support
  • Recurring availability templates
  • Buffer time between appointments (configurable)
  • Online booking by patients (with confirmation)
  • Walk-in queue management
  • Waitlist & auto-fill for cancellations
  • SMS/WhatsApp reminders (24h + 1h before)

Commission Structure

  • Per-Rx Commission: ₹50-200 per prescription written
  • Frame Sales: 5-10% of frame value sold
  • Lens Upgrade: 3-5% for premium lens recommendations
  • Monthly Bonus: Tiered based on Rx volume
  • Annual Retainer: For exclusive in-store doctors
  • Real-time commission dashboard in portal

Digital Rx Pad with Templates

The digital prescription pad pre-fills patient data, suggests lens types based on age/Rx, and enforces validation rules to prevent errors.

// Digital Rx Pad — Smart Suggestions function suggestLensType(patientAge, rx) { const suggestions = []; // Age-based recommendations if (patientAge >= 40 && rx.add) { suggestions.push({ type: "PROGRESSIVE", reason: "Presbyopia correction with seamless near-far transition", premium: true }); suggestions.push({ type: "BIFOCAL", reason: "Cost-effective near addition", premium: false }); } else { suggestions.push({ type: "SINGLE_VISION", reason: "Standard distance or near correction", premium: false }); } // High-power recommendation if (Math.abs(rx.sph) > 4.00) { suggestions.push({ coating: "HIGH_INDEX_167", reason: "Thinner, lighter lenses for comfort and aesthetics" }); } // Screen time recommendation if (patient.screenTimeHours > 6) { suggestions.push({ coating: "BLUE_LIGHT_FILTER", reason: "Reduces digital eye strain from prolonged screen use" }); } return suggestions; }

Lens Fitting — Deep Dive

Precision Measurements for Optimal Vision

Lens Fitting captures the precise geometric relationship between the patient's eyes and the selected frame. These measurements ensure the optical center of each lens aligns with the patient's pupil, maximizing visual comfort and acuity.

PD Measurement
Monocular & binocular
Fitting Height
Segment position
Pantoscopic Tilt
Frame angle
Vertex Distance
Lens-to-eye gap
Digital Record
Linked to order

Pupillary Distance (PD)

PD is the distance between the centers of the pupils. For precision optics, monocular PD (per eye) is preferred over binocular PD because most people's nose is not perfectly centered.

MeasurementMethodAccuracyBest Practice
Binocular PDPD ruler or digital pupillometer±1mmQuick check; acceptable for low powers
Monocular PDDigital pupillometer or corneal reflection±0.5mmRequired for high powers (>±3.00D) and progressives
Near PDBinocular PD minus 2-3mm (convergence)±1mmUsed for reading glasses and computer lenses
Digital PD (App)Smartphone camera + credit card reference±2mmAcceptable for online orders; flag if >65mm or <50mm
// PD Impact on Lens Decentration // Decentration = (Frame PD - Patient PD) / 2 // Prism induced = Decentration (cm) × Power (D) function calculateInducedPrism(framePD, patientPD, lensPower) { const decentration = (framePD - patientPD) / 2; // in mm const decentrationCm = decentration / 10; const inducedPrism = decentrationCm * lensPower; // in prism diopters return { decentration: decentration.toFixed(1) + "mm", inducedPrism: inducedPrism.toFixed(2) + "Δ", acceptable: Math.abs(inducedPrism) <= 0.25 }; } // Example: Frame PD = 64mm, Patient PD = 61mm, Power = -4.00D // Decentration = (64-61)/2 = 1.5mm per eye // Induced Prism = 0.15cm × 4.00D = 0.60Δ — EXCEEDS tolerance!

Fitting Height & Progressive Lens Positioning

For progressive and bifocal lenses, the fitting height determines where the reading segment sits relative to the pupil. Incorrect fitting height causes neck strain and blurred near vision.

Lens TypeFitting Height ReferenceMeasurement MethodTolerance
Single VisionOptical center at pupil centerMark pupil position on demo lens±1mm
Bifocal (Flat-Top)Top of segment 2mm below pupil centerMark pupil; measure down to segment top±1mm
Progressive (Standard)Fitting cross at pupil centerDigital centration device or manual marking±0.5mm
Progressive (Short Corridor)Fitting cross at pupil centerCritical — reduced reading zone±0.5mm
Computer / Office LensIntermediate zone at screen heightMeasure at patient's working distance±1mm

Pantoscopic Tilt & Vertex Distance

Pantoscopic Tilt

The angle between the lens plane and the vertical when the frame is worn. Standard is 8-12°.

  • Too steep (>15°): Induces base-up prism; image distortion
  • Too flat (<5°): Eyelashes touch lens; reduced field of view
  • Measurement: Digital angle gauge or smartphone app
  • Adjustment: Heat frame temples, bend nose pads

Vertex Distance

Distance from the back surface of the lens to the cornea. Standard is 12-14mm.

  • Too close (<10mm): Eyelashes touch; fogging
  • Too far (>16mm): Effective power changes; reduced field
  • High-power impact: Every 1mm change alters effective power by ~0.05D at ±5.00D
  • Measurement: Vertex gauge or ruler
// Vertex Distance Compensation // When vertex distance changes from fitting to wearing, effective power changes function compensateForVertex(prescribedPower, fittedVertex, actualVertex) { // Formula: F_effective = F_prescribed / (1 - d × F_prescribed) // where d = change in vertex distance (in meters) const d = (actualVertex - fittedVertex) / 1000; // convert mm to meters const effectivePower = prescribedPower / (1 - d * prescribedPower); return { prescribed: prescribedPower.toFixed(2) + "D", effective: effectivePower.toFixed(2) + "D", compensationNeeded: Math.abs(effectivePower - prescribedPower) > 0.12 }; }

CRM & 360° View — Deep Dive

Unified Customer Profile

The 360° Customer View aggregates every interaction, transaction, and preference across all channels into a single golden record. This enables personalized service, predictive engagement, and lifetime value optimization.

Orders
All channels
Rx History
Clinical data
Interactions
Comm history
Preferences
Style, fit, price
Golden Record
Single source

Customer Data Model

// 360° Customer Profile — Unified Schema const customerProfile = { identity: { customerId: "CUST-2026-089234", email: "priya.sharma@email.com", phone: "+91-98765-43210", name: "Priya Sharma", dob: "1988-03-15", gender: "F", segment: "GOLD" // BRONZE | SILVER | GOLD | PLATINUM }, orders: { totalOrders: 12, totalRevenue: 2847.00, avgOrderValue: 237.25, firstOrderDate: "2022-08-14", lastOrderDate: "2026-06-22", channels: { online: 7, retail: 4, b2b: 1 }, favoriteCategories: ["Titanium Frames", "Blue Light Lenses"] }, prescriptions: { currentRx: "RX-2026-084721", rxHistory: ["RX-2024-065432", "RX-2022-041289"], rxExpiryDate: "2028-06-15", lastEyeExam: "2026-06-15", preferredDoctor: "Dr. Ananya Sharma" }, engagement: { emailOpenRate: 0.42, smsClickRate: 0.18, lastLogin: "2026-07-08T09:23:00Z", preferredChannel: "WhatsApp", appInstalled: true, pushEnabled: true }, lifetimeValue: { predictedLTV: 5200.00, churnRisk: 0.12, // 12% probability of not returning nextPurchasePredicted: "2026-09-15", recommendedAction: "RX_EXPIRY_CAMPAIGN" } };

Customer Segmentation

SegmentCriteriaSizeRevenue ShareEngagement Strategy
PlatinumLTV >$5K, 5+ orders/year, brand advocate3%22%Personal stylist, early access, exclusive events
GoldLTV $2K-$5K, 3+ orders/year, high engagement12%35%VIP discounts, priority support, birthday rewards
SilverLTV $500-$2K, 1-2 orders/year, moderate engagement35%32%Targeted offers, Rx reminder campaigns, upsell
BronzeLTV <$500, 1 order, low engagement40%9%Win-back offers, referral incentives, education
At-RiskNo purchase in 18+ months, churn risk >60%10%2%Deep discount + personalized outreach, survey

Lifetime Value (LTV) Calculation

// LTV Prediction Model function calculateLTV(customer) { // Historical component const avgOrderValue = customer.totalRevenue / customer.totalOrders; const purchaseFrequency = customer.totalOrders / customer.daysSinceFirstOrder() * 365; // Predicted component const predictedRetentionYears = predictRetention({ recency: customer.daysSinceLastOrder(), frequency: purchaseFrequency, monetary: avgOrderValue, engagement: customer.engagement.emailOpenRate, rxExpiryRisk: customer.daysUntilRxExpiry() < 90 }); // LTV = AOV × Purchase Frequency × Predicted Lifespan × Margin const grossLTV = avgOrderValue * purchaseFrequency * predictedRetentionYears; const netLTV = grossLTV * 0.55; // 55% blended margin return { grossLTV: grossLTV.toFixed(2), netLTV: netLTV.toFixed(2), predictedRetentionYears: predictedRetentionYears.toFixed(1), confidence: predictConfidence(customer.dataCompleteness) }; }

Communication Engine — Deep Dive

Multi-Channel Communication Orchestration

The Communication Engine delivers the right message through the right channel at the right time. It unifies email, SMS, WhatsApp, and push notifications into a single campaign and journey management platform.

ChannelBest Use CaseOpen RateCost per MessageRich Media
EmailOrder confirmations, newsletters, detailed offers22-28%₹0.05-0.20HTML, images, links
SMSOTP, delivery alerts, appointment reminders95-98%₹0.15-0.30Text + short link
WhatsAppSupport, catalog sharing, personalized offers70-85%₹0.40-0.80Images, catalogs, buttons
Push NotificationFlash sales, cart abandonment, app engagement15-25%Free (Firebase)Rich cards, deep links
Voice/IVRAppointment confirmations, payment reminders60-70% answer rate₹1.50-3.00Audio only

Automated Journey Triggers

Welcome
Day 0: Onboarding
First Purchase
Day 3: Tips + review
Replenish
Day 90: Reorder nudge
Rx Expiry
Day 600: Exam reminder
Birthday
Annual: Special offer
Win-Back
Day 545: At-risk

Trigger-Based Message Templates

TriggerChannelTimingMessage
Order PlacedEmail + WhatsAppImmediate"Thanks for your order! Your [Frame] with [Lens] is confirmed. Track: [link]"
Lab StartedSMSWhen job status = IN_PROGRESS"Your lenses are being crafted! Estimated completion: [date]"
ShippedEmail + SMS + WhatsAppOn dispatch"Your order is on the way! Track: [link]. Expected: [date]"
Out for DeliverySMS + PushMorning of delivery"Your eyewear is out for delivery today. Be ready!"
DeliveredWhatsApp + Email1 hour post-delivery"How do your new glasses fit? Reply for adjustments or leave a review: [link]"
Rx Expiring (30d)Email + WhatsApp30 days before expiry"Your prescription expires on [date]. Book a free eye exam: [link]"
Cart AbandonedEmail → Push → SMS1h, 24h, 72h"You left something behind! Complete your order and get 10% off: [code]"
BirthdayEmail + WhatsAppDay of birthday"Happy Birthday! Here's ₹500 off your next pair. Valid for 7 days: [code]"

Smart Channel Selection

// Channel Selection Algorithm function selectChannel(customer, messageType, urgency) { const preferences = customer.engagement; const history = customer.channelPerformance; // Priority matrix const channelScores = { whatsapp: history.whatsappOpenRate * 0.3 + (preferences.preferredChannel === "WhatsApp" ? 0.3 : 0) + (messageType === "SUPPORT" ? 0.2 : 0), email: history.emailOpenRate * 0.3 + (messageType === "NEWSLETTER" ? 0.3 : 0), sms: 0.95 * 0.3 + // SMS has near-universal reach (urgency === "HIGH" ? 0.4 : 0), push: preferences.pushEnabled ? 0.2 : 0 }; // For urgent messages, guarantee delivery via SMS fallback if (urgency === "HIGH") { return ["sms", "whatsapp"]; // Multi-channel blast } return Object.entries(channelScores) .sort((a, b) => b[1] - a[1]) .slice(0, 2) .map(x => x[0]); }

Self-Service Portals — Deep Dive

Portal Ecosystem

The platform serves four distinct user types through tailored portals, each with role-appropriate data access, workflows, and integrations.

PortalUsersKey FeaturesIntegrations
B2C Customer PortalEnd consumersOrder history, Rx management, reorder, returns, loyalty dashboard, appointment bookingOMS, EHR, Inventory, Loyalty
B2B Distributor PortalWholesale buyersCatalog with tiered pricing, bulk ordering, credit status, invoice history, performance reportsOMS, ERP, Inventory, Credit Engine
Doctor PortalOptometrists, ophthalmologistsPatient scheduling, digital Rx pad, commission tracking, patient communicationEHR, OMS, Clinical
Store Associate PortalRetail staffClienteling, inventory lookup, order creation, appointment management, sales targetsPOS, Inventory, CRM, Clinical

B2C Customer Portal Features

Order Management

  • Full order history with status tracking
  • Real-time production progress (lab job status)
  • Shipping tracking with map visualization
  • One-click reorder from past purchases
  • Return initiation with reason capture
  • Invoice download (GST-compliant PDF)

Prescription Hub

  • Upload and store multiple prescriptions
  • Rx expiry alerts (30/60/90 days)
  • Share Rx with family members
  • Book eye exam appointments
  • View examination history & images
  • Rx comparison across visits

Loyalty Dashboard

// Customer Loyalty Dashboard Data const loyaltyDashboard = { tier: "GOLD", pointsBalance: 2840, pointsEarnedThisYear: 1560, pointsToNextTier: 1160, nextTier: "PLATINUM", benefits: { current: ["Free shipping", "10% off all orders", "Priority support"], upcoming: ["Personal stylist", "Early access to sales", "Free lens upgrades"] }, activity: [ { date: "2026-07-01", action: "EARNED", points: 150, reason: "Purchase: Titanium Frame" }, { date: "2026-06-22", action: "REDEEMED", points: -500, reason: "Discount on order" }, { date: "2026-06-15", action: "EARNED", points: 200, reason: "Referral: Amit K." } ] };

B2B Distributor Portal Features

FeatureDescriptionBusiness Value
Tiered CatalogPrices auto-adjusted to distributor's negotiated tierNo manual quoting; prevents pricing errors
Credit DashboardReal-time credit limit, outstanding balance, aging reportTransparency reduces payment disputes
Bulk Order UploadCSV upload for large seasonal orders80% faster than line-by-line ordering
Assortment PlannerVisual grid with sell-through data to optimize SKU mixData-driven buying reduces dead stock
Performance ReportsSell-through, margin, inventory turns by SKUDistributor self-service insights
Marketing CollateralDownloadable POS materials, images, specsBrand consistency across channels

Loyalty & Rewards — Deep Dive

Tiered Loyalty Program

The Loyalty & Rewards program drives repeat purchases through a points-based system with escalating benefits across four tiers. Members earn on every purchase and engagement action.

TierEntry RequirementEarn RateKey BenefitsRetention Rate
BronzeSign up1 pt per ₹10Newsletter, birthday reward25%
Silver₹5,000 spent or 2 orders1.5 pt per ₹10+ Free shipping, early sale access40%
Gold₹15,000 spent or 5 orders2 pt per ₹10+ 10% off, priority support, free case60%
Platinum₹40,000 spent or 10 orders3 pt per ₹10+ Personal stylist, free lens upgrades, exclusive events80%

Points Earning Mechanics

Purchase-Based Earning

  • Base earn: 1-3 points per ₹10 spent (tier-dependent)
  • Bonus: 2x on first purchase of the month
  • Bonus: 3x on birthday month
  • Bonus: 1.5x for premium lens upgrades
  • Bonus: 2x for contact lens subscriptions

Engagement-Based Earning

  • Complete profile: 100 points
  • Upload Rx: 50 points
  • Write a review: 75 points
  • Refer a friend (first purchase): 500 points
  • Social share (verified): 25 points
  • App download: 200 points
  • Eye exam booking: 150 points

Redemption Options

RewardPoints RequiredValueRestrictions
₹100 Off Coupon500 points₹100Min order ₹1,000; 1 per order
Free Shipping200 points₹49Standard delivery only
Free Premium Case300 points₹350In-stock designs only
AR Coating Upgrade800 points₹800With lens purchase only
Blue Light Filter Upgrade600 points₹600With lens purchase only
Free Eye Exam1,000 points₹500At partner clinics only
₹500 Birthday VoucherAuto-issued₹500Valid 30 days; no min order

Referral Program

The referral engine turns customers into acquisition channels. Both referrer and referee receive rewards, creating a viral loop.

Share Link
Unique code
Friend Signs Up
Uses code
First Purchase
Min ₹1,500
Both Rewarded
₹500 each
Referral MetricTargetCurrent Performance
Referral Share Rate15% of active customers/month12%
Friend Conversion Rate25% of referred friends purchase22%
Average Referral ValueReferred customer LTV 1.3x organic1.25x
Cost per Acquisition₹500 (voucher cost)₹500
Program ROI4:1 (LTV / reward cost)3.5:1

Healthcare Compliance — Deep Dive

Multi-Jurisdiction Healthcare Regulations

Healthcare Compliance governs how patient data is collected, stored, shared, and retained. For eyewear brands with clinical operations, this spans HIPAA in the US, PHIPA in Canada, NHS standards in the UK, and local healthcare laws in every operating market.

RegulationJurisdictionScopeKey RequirementsPenalty for Breach
HIPAAUnited StatesPHI — all identifiable health dataPrivacy Rule, Security Rule, Breach Notification, Business Associate Agreements$100-$50,000 per violation; up to $1.5M/year; criminal liability
PHIPAOntario, CanadaPersonal health informationConsent for collection, use, disclosure; access rights; accountabilityUp to CAD $500,000 (individuals); CAD $1M (organizations)
NHS GOSUnited KingdomNHS-funded eye care servicesAccredited practitioner, approved equipment, claim validation, fraud preventionDe-registration from GOS; recovery of fraudulent claims
MoHFW IndiaIndiaClinical establishmentsRegistration under CEA; patient rights charter; standard treatment protocolsLicense suspension; fines up to ₹5 lakhs
TGAAustraliaMedical devices (including contact lenses)ARTG listing; Good Manufacturing Practice; adverse event reportingProduct recall; criminal prosecution

HIPAA Technical Safeguards

HIPAA's Security Rule mandates specific technical controls for electronic Protected Health Information (ePHI). These are non-negotiable for any system handling US patient data.

Access Control (§164.312(a))

  • Unique user IDs for every system user
  • Role-based access control (RBAC)
  • Automatic logoff after 15 min inactivity
  • Emergency access procedures
  • Encryption and decryption of ePHI

Audit Controls (§164.312(b))

  • Every access to ePHI logged immutably
  • Log retention: 6 years minimum
  • Real-time anomaly detection
  • Quarterly access review reports
  • Failed access attempt alerts

Integrity (§164.312(c))

  • Digital signatures on all Rx records
  • Checksums for data integrity verification
  • Version control for all record changes
  • Immutable audit trail (blockchain/WORM)

Transmission Security (§164.312(e))

  • TLS 1.3 for all data in transit
  • End-to-end encryption for messaging
  • VPN for all remote access
  • Network segmentation (ePHI isolated VLAN)

Clinical Audit Trail

Every clinical action — from viewing a patient record to modifying a prescription — must be logged with who, what, when, and where for regulatory compliance and malpractice protection.

// Clinical Audit Log Entry const auditEntry = { eventId: "AUD-2026-07-08-089234", timestamp: "2026-07-08T14:23:15.342Z", actor: { userId: "DOC-441289", name: "Dr. Ananya Sharma", role: "OPTOMETRIST", licenseNumber: "OPT-MH-2018-4521", ipAddress: "203.192.12.45", deviceId: "DEV-CLINIC-MUM-03" }, action: { type: "PRESCRIPTION_CREATED", resource: "RX-2026-084721", patientId: "PAT-441289", details: { previousValue: null, newValue: { sphR: -3.50, cylR: -1.25, axisR: 180 }, reason: "Annual eye examination — patient reported headaches" } }, outcome: "SUCCESS", integrity: { hash: "sha256:a3f7c2...", previousHash: "sha256:e8b1d4..." } };

Business Associate Agreement (BAA)

Under HIPAA, any vendor that handles PHI on behalf of the covered entity must sign a BAA. This includes cloud providers, email services, analytics platforms, and payment processors.

Vendor TypeExampleBAA Required?Key BAA Terms
Cloud InfrastructureAWS, Azure, GCPYesData encryption, access logging, breach notification within 24h
Email ServiceSendGrid, AWS SESYesHIPAA-compliant sending, no data mining, secure transmission
AnalyticsGoogle Analytics (without IP), MixpanelMaybeNo PHI in events; aggregate only; data deletion on contract end
Payment ProcessorStripe, RazorpayNo (if only transaction data)PCI-DSS compliance; no PHI access
ShippingBlue Dart, DelhiveryNoStandard SLA; no PHI (name/address only)

Financial Compliance — Deep Dive

Tax & E-Invoicing Compliance

Financial Compliance ensures accurate tax calculation, proper invoicing, and adherence to accounting standards across all jurisdictions where the brand operates.

CountryTax SystemE-InvoicingReporting StandardKey Requirements
IndiaGST (CGST + SGST/IGST)Mandatory for B2B (IRN via GSTN)IND ASGSTR-1 (outward), GSTR-3B (summary), e-way bills for inter-state transfers
UAEVAT 5%Voluntary (phase-in planned)IFRSFTA registration, quarterly filing, Arabic invoice requirement
UKVAT 20%Making Tax Digital (MTD)UK GAAP / IFRSDigital VAT returns, real-time reporting for >£85K turnover
USSales tax (state-dependent)No federal mandateUS GAAPNexus determination, marketplace facilitator laws, 1099-K for >$600
SingaporeGST 9%InvoiceNow (PEPPOL)SFRS / IFRSQuarterly filing, GST registration at S$1M turnover

India GST E-Invoicing (IRN Generation)

India mandates e-invoicing for B2B transactions above ₹5 crore turnover (threshold reducing over time). Every invoice must be registered with the Invoice Registration Portal (IRP) to receive a unique Invoice Reference Number (IRN).

Generate Invoice
ERP/OMS creates JSON
Upload to IRP
GSTN portal
IRN Generated
Unique hash
QR Code
Signed + embedded
Send to Buyer
With IRN + QR
// E-Invoice JSON Structure (GST India) const eInvoice = { Version: "1.1", TranDtls: { TaxSch: "GST", SupTyp: "B2B", RegRev: "N", EcmGstin: null }, DocDtls: { Typ: "INV", No: "EYE/2026/089234", Dt: "08/07/2026" }, SellerDtls: { Gstin: "27AABCU9603R1ZX", LglNm: "Eyewear Brand Pvt Ltd", Addr1: "123 Business Park", Loc: "Mumbai", Pin: 400001, Stcd: "27" // Maharashtra }, BuyerDtls: { Gstin: "29AABCU9603R1ZY", LglNm: "Optical Distributors Ltd", Pos: "29", // Karnataka — determines IGST Addr1: "456 Commercial Street", Loc: "Bangalore", Pin: 560001 }, ItemList: [{ SlNo: "1", PrdDesc: "Titanium Round Frame — Black", IsServc: "N", HsnCd: "9003", Qty: 10, Unit: "NOS", UnitPrice: 2500.00, TotAmt: 25000.00, AssAmt: 25000.00, GstRt: 18, IgstAmt: 4500.00, // IGST because inter-state TotItemVal: 29500.00 }], ValDtls: { AssVal: 25000.00, IgstVal: 4500.00, TotInvVal: 29500.00 } };

Accounting Standards: IND AS / IFRS

StandardApplicationKey Impact on Eyewear Business
IND AS 115 / IFRS 15Revenue RecognitionRecognize frame revenue at delivery; lens revenue at fitting completion; subscription revenue over time
IND AS 2 / IAS 2InventoriesValuation at lower of cost or NRV; WIP valuation includes labor + overhead allocation
IND AS 16 / IAS 16PPE (Plant, Property, Equipment)CNC machines, coating chambers capitalized and depreciated over useful life (10-15 years)
IND AS 37 / IAS 37ProvisionsWarranty provision (1-2% of sales), return provision based on historical rate
IND AS 109 / IFRS 9Financial InstrumentsCredit loss provisioning for B2B receivables; expected credit loss model

SOX Controls (US-Listed Entities)

If the company is US-listed or preparing for IPO, Sarbanes-Oxley (SOX) compliance requires documented internal controls over financial reporting (ICFR).

Control AreaControl ActivityFrequencyEvidence
Revenue RecognitionAutomated three-way match (order, shipment, payment)Per transactionSystem log + audit trail
Access ControlsSegregation of duties: sales cannot approve refundsContinuousRBAC configuration + quarterly review
Inventory ValuationMonthly reconciliation of system stock vs. GLMonthlyReconciliation report + sign-off
DisbursementsDual approval for payments >$10,000Per paymentApproval workflow log
Period-End CloseCut-off procedures for revenue and expensesMonthlyClose checklist + management review

Product Safety — Deep Dive

Eyewear Safety Standards Matrix

Product Safety ensures that every frame and lens meets international standards for optical performance, mechanical durability, and biological safety. Non-compliance can result in market bans, recalls, and liability claims.

StandardScopeKey TestsMarking RequiredMarkets
ISO 12870Ophthalmic frames — fundamental requirementsEndurance, hinge fatigue, bridge deformation, corrosion, flammabilityCE (EU), manufacturer, materialGlobal baseline
ISO 14889Uncut finished spectacle lensesImpact resistance, refractive power tolerance, transmittance, abrasionImpact resistance marking, optical classGlobal baseline
ISO 8980-1 to -4Finished spectacle lenses (uncut)Power tolerance, transmittance, surface quality, coating adhesionPower range, material, coating typeGlobal baseline
EN 166Personal eye protectionField of view, optical quality, robustness, resistance to UV, infraredCE + standard number + protection levelEU (PPE regulation)
21 CFR 801.410Impact-resistant lenses (US FDA)Drop ball test (5/8" steel ball from 50")"Impact Resistant" or supplier identificationUnited States
BIS IS 14246Spectacle lenses (India)Refractive power, impact resistance, transmittanceISI mark (mandatory for local sale)India
AS/NZS 1067Sunglasses and fashion spectaclesUV transmittance, luminous transmittance, traffic signal recognitionCategory number (0-4)Australia, NZ

Biological Safety & Material Compliance

Beyond mechanical tests, eyewear materials must be safe for prolonged skin contact and not release harmful substances.

Skin Contact Safety

  • Nickel Release (EN 1811): <0.5 μg/cm²/week for metal frames in EU
  • Cadmium Content: <0.01% by weight (EU REACH)
  • Lead Content: <0.1% by weight (CPSIA — US children's products)
  • Phthalates: Banned in children's eyewear (DEHP, DBP, BBP)
  • Latex: Declare if present; offer latex-free alternatives

Coating Chemical Safety

  • Hexavalent Chromium: Prohibited in coatings (EU REACH Annex XVII)
  • PFAS: Restricted in water-repellent coatings (EU)
  • Biocides: Only approved substances for anti-fog coatings
  • VOC Emissions: Limits on solvent-based coatings
  • RoHS Compliance: No restricted substances in electronic components (smart glasses)

Product Recall Management

Despite rigorous QC, recalls may be necessary. A structured recall process minimizes harm and regulatory exposure.

Issue Detected
QC fail / complaint
Risk Assessment
Severity × scope
Regulatory Notify
FDA/MHRA/CDSCO
Customer Notify
Email/SMS/call
Collection
Free return + replacement
Root Cause
CAPA + prevention

Batch Traceability & Recall Scope

// Batch Recall Scope Query function getRecallScope(batchId, defectType) { // 1. Identify all units in batch const units = getUnitsByBatch(batchId); // e.g., 5,000 units // 2. Map to customers const customerOrders = units.map(u => ({ customerId: u.order.customerId, orderId: u.order.id, shipDate: u.order.shipDate, contact: u.customer.contact })); // 3. Categorize by risk const riskCategories = { highRisk: customerOrders.filter(o => defectType === "LENS_IMPACT_FAILURE" && o.shipDate < "2026-06-01" ), mediumRisk: customerOrders.filter(o => defectType === "COATING_DEFECT" ), lowRisk: customerOrders.filter(o => defectType === "COSMETIC_SCRATCH" ) }; return { totalUnits: units.length, totalCustomers: new Set(customerOrders.map(o => o.customerId)).size, riskBreakdown: riskCategories, estimatedRecallCost: units.length * 45 // $45 per unit (shipping + replacement) }; }

Descriptive Analytics — Deep Dive

Real-Time Operational Dashboards

Descriptive Analytics answers "What happened?" through dashboards and reports that visualize historical and real-time data. This is the foundation layer — every other analytics type builds on accurate descriptive data.

Data Ingestion
Events + transactions
Processing
ETL + aggregation
Visualization
Dashboards + reports
Alerting
Threshold triggers
Action
Human decision

Sales Dashboard KPIs

KPIDefinitionTargetFrequencyDrill-Down
RevenueGross sales minus returnsMonthly growth 8%Real-timeChannel, region, SKU, customer segment
Average Order Value (AOV)Revenue / Number of orders₹3,500DailyChannel, lens type, frame material
Conversion RateOrders / Sessions2.5%HourlyTraffic source, device, campaign
Units per Transaction (UPT)Items sold / Orders1.3DailyStore, associate, time of day
Return RateReturn value / Gross sales<8%DailyReason, SKU, channel, fit issue
Revenue per StoreStore revenue / Number of stores₹15L/monthWeeklyStore, associate, day-of-week

Inventory Dashboard KPIs

KPIDefinitionTargetFrequencyDrill-Down
Stock AvailabilitySKUs in stock / Total active SKUs>95%Real-timeLocation, category, supplier
Inventory TurnoverCOGS / Average inventory value6x/yearMonthlyCategory, SKU, location
Days of InventoryAverage inventory / Avg daily COGS<60 daysWeeklyCategory, supplier, season
Stockout RateStockout SKUs / Total SKUs<2%DailyChannel, category, fast-mover flag
Shrinkage Rate(Book stock - Physical stock) / Book stock<0.5%MonthlyLocation, category, count method
Dead Stock %Stock with no movement in 180 days / Total stock<5%WeeklyCategory, season, price band

Customer Dashboard KPIs

KPIDefinitionTargetFrequencyDrill-Down
Customer Acquisition Cost (CAC)Marketing spend / New customers<₹800WeeklyChannel, campaign, geography
Customer Lifetime Value (LTV)Predicted total revenue per customer>₹8,000MonthlySegment, channel, first purchase
LTV:CAC RatioLTV / CAC>3:1MonthlyCampaign, channel, cohort
Net Promoter Score (NPS)% Promoters - % Detractors>50QuarterlyStore, channel, product, service touchpoint
Repeat Purchase RateCustomers with 2+ orders / Total customers>35%MonthlySegment, time since first purchase
Churn RateCustomers inactive 18+ months / Total<15%/yearMonthlySegment, channel, last purchase category

Operational Dashboard KPIs

KPIDefinitionTargetFrequencyDrill-Down
Lab Turnaround Time (TAT)Order received to dispatch<48 hours (standard)HourlyJob type, complexity, station
Order Fulfillment RateOrders shipped on first promise / Total>95%DailyChannel, location, SKU
Perfect Order RateOn-time + accurate + undamaged / Total>92%DailyCarrier, warehouse, SKU fragility
Return Processing TimeReturn received to refund issued<72 hoursDailyReason, channel, payment method
Store UtilizationRevenue-generating hours / Total hours>75%WeeklyStore, day-of-week, time slot
Doctor UtilizationExam slots booked / Total available>80%DailyClinic, doctor, day-of-week

Diagnostic Analytics — Deep Dive

Root Cause Analysis Framework

Diagnostic Analytics answers "Why did it happen?" by drilling into descriptive data to find correlations, patterns, and root causes. This layer transforms dashboards into actionable intelligence.

Anomaly Detected
KPI breach
Drill Down
Segment data
Correlate
Find patterns
Hypothesize
Root cause
Validate
A/B or test

Root Cause Analysis: Stockouts

HypothesisData to CheckAnalysis MethodTypical Finding
Demand spikeSales velocity vs. forecast, marketing campaigns, seasonalityTime-series comparison, event correlationSocial media influencer post drove 3x normal demand
Forecast errorForecast vs. actual by SKU, forecast accuracy trendMAPE calculation, bias analysisSystem under-forecasted by 40% for new frame launch
Supplier delayPO delivery dates vs. promised, supplier OTIFSupplier scorecard, lead time varianceSupplier shipment delayed 2 weeks due to port congestion
Reorder point too lowROP vs. actual demand during lead time, safety stock adequacyROP sensitivity analysis, service level simulationSafety stock calculated with 2-week lead time; actual is 4 weeks
Inventory record errorBook stock vs. physical count, adjustment historyVariance analysis, shrinkage trendSystem showed 50 units; physical count = 12; theft suspected
Channel conflictSales by channel, inventory allocation rulesChannel-wise stock depletion rateAmazon oversold due to sync lag; safety stock consumed

Cohort Analysis: Customer Behavior

Cohort analysis groups customers by their first purchase month and tracks their behavior over time. It reveals true retention patterns obscured by aggregate metrics.

// Cohort Analysis — Retention by First Purchase Month // Rows = Cohort month, Columns = Months since first purchase const cohortRetention = { "2025-01": [100, 35, 28, 24, 22, 20, 19, 18, 17, 16, 15, 15], // Baseline "2025-04": [100, 38, 31, 27, 25, 23, 22, 21, 20, 19, 18, null], // Improved onboarding "2025-07": [100, 42, 36, 32, 29, 27, 25, 24, 23, null, null, null], // Loyalty program launch "2025-10": [100, 45, 39, 35, 32, 30, null, null, null, null, null, null], // WhatsApp engagement "2026-01": [100, 48, 42, 38, null, null, null, null, null, null, null, null] // AR try-on + personalized Rx }; // Insight: Month-1 retention improved from 35% (Jan 2025) to 48% (Jan 2026) // Driver: Combined effect of loyalty program + WhatsApp + AR try-on

Funnel Analysis: Cart Abandonment

Funnel StageUsersDrop-offDrop-off RateTop Reasons (Survey + Analytics)
Product View100,000
Add to Cart12,00088,00088%Browsing, price shock, no AR try-on
Enter Prescription6,5005,50046%No Rx handy, prescription upload friction, manual entry tedious
Configure Lens5,2001,30020%Confusing options, unexpected price increase, no guidance
Enter Shipping4,1001,10021%No guest checkout, address validation errors
Payment3,20090022%Payment failure, no preferred method, security concerns
Order Confirmed2,50070022%
Overall Conversion2,50097,50097.5%2.5% conversion rate (industry avg: 2-3%)

Correlation Analysis: Weather vs. Sunglasses

External data correlation reveals hidden demand drivers. Sunglasses sales spike with UV index and temperature, enabling proactive inventory positioning.

// Weather-Demand Correlation Model function predictSunglassDemand(city, date) { const weather = await getWeatherForecast(city, date); const baseDemand = getHistoricalAverage(city, date); // Seasonal baseline // Weather multipliers (derived from regression analysis) const multipliers = { uvIndex: weather.uvIndex > 7 ? 1.4 : weather.uvIndex > 5 ? 1.2 : 1.0, temperature: weather.maxTemp > 35 ? 1.3 : weather.maxTemp > 30 ? 1.15 : 1.0, sunshine: weather.sunshineHours > 8 ? 1.2 : 1.0, rain: weather.rainProbability > 0.6 ? 0.7 : 1.0 }; const combinedMultiplier = Object.values(multipliers).reduce((a, b) => a * b, 1); return { predictedDemand: Math.round(baseDemand * combinedMultiplier), confidence: 0.78, factors: multipliers, recommendation: combinedMultiplier > 1.3 ? "INCREASE_STORE_STOCK" : combinedMultiplier < 0.8 ? "REDUCE_DISPLAY_STOCK" : "MAINTAIN" }; }

Prescriptive Analytics — Deep Dive

AI-Driven Decision Optimization

Prescriptive Analytics answers "What should we do?" by using optimization algorithms and simulation to recommend the best course of action from many possibilities. It goes beyond prediction to decision-making.

Define Objective
Maximize margin
Constraints
Inventory, budget, capacity
Optimize
Algorithm runs
Recommend
Best action
Auto-Execute
Or human approve

Dynamic Pricing Optimization

Pricing is optimized in real-time based on demand elasticity, competitor pricing, inventory levels, and customer segment willingness-to-pay.

FactorWeightData SourceImpact on Price
Demand Elasticity30%Historical sales at different price pointsHigh elasticity → lower price; low elasticity → higher price
Competitor Price25%Web scraping (Amazon, Flipkart, brand sites)Match or undercut by 5-10% on comparable SKUs
Inventory Level20%Real-time stock position + agingOverstock → discount; scarce → premium
Customer Segment15%CRM loyalty tier, purchase historyVIP sees lower prices; new customer sees intro offer
Seasonality10%Time of year, weather, eventsSunglasses premium in summer; clearance in winter
// Dynamic Pricing Engine function calculateOptimalPrice(sku, context) { const basePrice = sku.mrp * 0.7; // 30% off MRP as starting point const minPrice = sku.cost * 1.15; // 15% minimum margin const maxPrice = sku.mrp; // Elasticity adjustment const elasticity = sku.priceElasticity; // -2.5 = elastic, -0.8 = inelastic const demandSignal = context.demandForecast / sku.avgDailySales; let priceMultiplier = 1 + (demandSignal - 1) / Math.abs(elasticity); // Competitor guardrail const competitorPrice = context.competitorPrices.median(); if (basePrice * priceMultiplier > competitorPrice * 1.1) { priceMultiplier = competitorPrice * 1.05 / basePrice; } // Inventory pressure if (context.daysOfInventory > 90) { priceMultiplier *= 0.9; // 10% clearance discount } else if (context.daysOfInventory < 14) { priceMultiplier *= 1.05; // 5% scarcity premium } const optimalPrice = Math.max(minPrice, Math.min(maxPrice, basePrice * priceMultiplier)); return { price: Math.round(optimalPrice), margin: ((optimalPrice - sku.cost) / optimalPrice * 100).toFixed(1) + "%", expectedDemand: Math.round(sku.avgDailySales * demandSignal * Math.pow(optimalPrice / basePrice, elasticity)) }; }

Assortment Planning: SKU Placement Optimization

Which SKUs should be stocked at which stores? Prescriptive analytics uses store demographics, sales history, and space constraints to optimize assortment.

InputDataOptimization Goal
Store DemographicsAge, income, occupation, fashion index of catchment areaMatch frame styles to local taste
Sales History2-year sell-through by SKU-store combinationStock proven performers; test new SKUs
Space ConstraintsDisplay slots, backroom capacity, planogram rulesMaximize revenue per square foot
Margin MixGross margin by SKU, inventory carrying costBalance volume drivers with margin drivers
SeasonalityMonthly demand patterns by categoryRotate seasonal SKUs at right time
New Product PipelineLaunch calendar, expected sell-throughAllocate test quantities to high-potential stores

Marketing Spend Optimization

Allocate marketing budget across channels to maximize customer acquisition while maintaining LTV:CAC ratio above 3:1.

// Marketing Budget Allocation Optimizer function optimizeMarketingSpend(totalBudget, channels, constraints) { // Channel performance data const channelMetrics = { googleAds: { cac: 650, ltv: 2800, maxSpend: 200000, minSpend: 50000 }, metaAds: { cac: 480, ltv: 2200, maxSpend: 150000, minSpend: 30000 }, influencer: { cac: 350, ltv: 1900, maxSpend: 100000, minSpend: 20000 }, seoContent: { cac: 180, ltv: 3200, maxSpend: 80000, minSpend: 30000 }, whatsApp: { cac: 120, ltv: 3500, maxSpend: 50000, minSpend: 10000 }, retargeting: { cac: 220, ltv: 2600, maxSpend: 60000, minSpend: 15000 } }; // Objective: Maximize total LTV acquired subject to budget and LTV:CAC >= 3 // Greedy approach: Sort by LTV:CAC ratio, allocate until budget exhausted const sortedChannels = Object.entries(channelMetrics) .map(([name, m]) => ({ name, ...m, ratio: m.ltv / m.cac })) .sort((a, b) => b.ratio - a.ratio); let remainingBudget = totalBudget; const allocation = {}; for (const ch of sortedChannels) { const alloc = Math.min(ch.maxSpend, Math.max(ch.minSpend, remainingBudget * 0.3)); allocation[ch.name] = alloc; remainingBudget -= alloc; } return allocation; }

Supply Chain Routing Optimization

Optimize the flow of goods from suppliers through warehouses to stores/customers to minimize total landed cost while meeting service level agreements.

Decision VariableOptimization ApproachExpected Savings
Warehouse LocationMixed-integer linear programming (MILP) minimizing transport + facility costs12-18% logistics cost reduction
Inventory PositioningMulti-echelon inventory optimization (MEIO)20-30% inventory reduction with same service level
Transport Mode SelectionDynamic programming per shipment based on cost, speed, reliability8-15% freight cost reduction
Route OptimizationVehicle routing problem (VRP) solver for last-mile delivery15-25% delivery cost reduction
Production SchedulingConstraint-based scheduling minimizing changeovers and idle time10-20% capacity increase

Event Bus (Kafka) — Deep Dive

Real-Time Event Streaming Architecture

The Event Bus is the asynchronous nervous system of the ecosystem. Instead of services calling each other directly (tight coupling), they publish events to Kafka topics and subscribe to relevant topics. This enables scalability, resilience, and loose coupling.

Order Service
Publishes event
Kafka Topic
Order.Created
Inventory
Reserves stock
Payment
Charges card
Notification
Sends email

Core Event Topics

TopicEventsProducersConsumersVolume
order.eventsCreated, Paid, Confirmed, Shipped, Delivered, Cancelled, ReturnedOMS, Payment, ShippingInventory, Notification, Analytics, CRM~50K/day
inventory.eventsStockChanged, Reserved, Released, Allocated, TransferInitiated, TransferCompletedInventory Engine, WMSOMS, Sales Channels, Reorder, Analytics~200K/day
customer.eventsProfileUpdated, ConsentChanged, SegmentChanged, LoyaltyPointsEarned, TierUpgradedCRM, Loyalty, Consent PlatformMarketing, Analytics, Notification~30K/day
clinical.eventsExamCompleted, RxCreated, RxUpdated, AppointmentBooked, AppointmentCancelledEHR, Doctor PortalOMS, CRM, Notification, Compliance~10K/day
payment.eventsInitiated, Success, Failed, Refunded, DisputedPayment ServiceOMS, Notification, Accounting, Fraud~50K/day
manufacturing.eventsJobCreated, StationStarted, StationCompleted, QCPassed, QCFailed, JobDispatchedMES, Lab StationsOMS, Notification, Analytics~5K/day

Event Schema & Governance

Events follow a strict schema (Avro/Protobuf/JSON Schema) enforced by a schema registry. This prevents breaking changes and ensures backward compatibility.

// Order Created Event Schema (Avro) { "type": "record", "name": "OrderCreated", "namespace": "com.eyewear.events.order", "fields": [ { "name": "eventId", "type": "string" }, { "name": "eventTimestamp", "type": "long", "logicalType": "timestamp-millis" }, { "name": "orderId", "type": "string" }, { "name": "customerId", "type": "string" }, { "name": "channel", "type": { "type": "enum", "name": "Channel", "symbols": ["ONLINE", "RETAIL", "B2B", "MARKETPLACE"] } }, { "name": "items", "type": { "type": "array", "items": { "type": "record", "name": "OrderItem", "fields": [ { "name": "sku", "type": "string" }, { "name": "quantity", "type": "int" }, { "name": "unitPrice", "type": "double" }, { "name": "rxId", "type": ["null", "string"], "default": null } ] }}, { "name": "totalAmount", "type": "double" }, { "name": "currency", "type": "string", "default": "INR" } ] }

Dead Letter Queue & Error Handling

ScenarioHandlingRetry PolicyAlert
Schema Validation FailRoute to DLQ; alert data engineeringNo retry (fix schema first)Immediate PagerDuty
Consumer TimeoutRetry with exponential backoff3 retries: 1s, 5s, 25sAfter 3rd failure
Downstream Service UnavailablePause consumer; queue buildsResume when health check passesAfter 5 min downtime
Duplicate EventIdempotent consumer (eventId dedup)N/AMetric spike only
Out-of-Order EventsEvent sourcing with versioning; reconcileBuffer until dependency arrivesIf buffer > 100 events

Event Replay & Audit

Kafka retains events for a configurable period (default 7 days, extended to 30 days for compliance topics). This enables:

Replay Scenarios

  • New consumer onboarding: Replay historical events to populate state
  • Bug recovery: Replay events after fixing a consumer bug
  • Analytics backfill: Replay to rebuild data warehouse
  • Compliance audit: Replay to verify event sequence

Long-Term Storage

  • Hot: Kafka (7-30 days, millisecond latency)
  • Warm: S3/MinIO (1-2 years, minute latency)
  • Cold: Glacier/Archive (7+ years, hour latency)
  • Compliance: Immutable WORM storage for audit

Payment Connectors — Deep Dive

Unified Payment Abstraction

The Payment Service provides a single API for all payment operations across B2C, B2B, retail, and online channels. It abstracts provider-specific implementations behind a common interface.

ProviderMarketsMethodsSettlementTransaction Fee
RazorpayIndiaUPI, Cards (Visa/MC/RuPay), Netbanking, Wallets (Paytm, PhonePe), EMI, PayLaterT+2 to bank account2.0% + GST
StripeGlobal (excl. India for domestic)Cards, Apple Pay, Google Pay, BNPL (Klarna, Affirm), Bank TransferT+7 (rolling)2.9% + $0.30
PayPalGlobalPayPal balance, Cards, PayPal CreditT+1 to PayPal; T+3 to bank2.9% + fixed fee
Cash on DeliveryIndia, SE Asia, Middle EastCash, card-on-deliveryT+1 (courier remittance)₹30-50 per order + 1%
B2B CreditAll (distributor network)Net 30/60/90 invoicing, letter of creditPer invoice terms1.5-3% financing cost

Payment Service API

// Unified Payment API — Create Payment Intent POST /api/v1/payments/intent Content-Type: application/json Authorization: Bearer {jwt} { "orderId": "ORD-2026-089234", "amount": 3500.00, "currency": "INR", "customer": { "id": "CUST-441289", "email": "priya@email.com", "phone": "+919876543210" }, "methods": ["upi", "card", "netbanking"], // Ordered by preference "metadata": { "channel": "ONLINE", "device": "mobile_web", "utmSource": "google_ads" } } // Response { "paymentIntentId": "pi_3O9xYz2eZvKYlo2C1aBcDeFg", "status": "requires_action", "provider": "razorpay", "clientSecret": "pi_3O9xYz...secret_abc123", "nextAction": { "type": "upi_collect", "upiId": "priya@okaxis", "expiry": "2026-07-08T15:00:00Z" } }

Fraud Prevention & Risk Scoring

SignalRisk WeightMitigation
VelocityHighMax 3 attempts per card per hour; block after 5 failed attempts
Device FingerprintMediumFlag new devices, VPNs, emulators; require OTP for high-risk
Address VerificationMediumMatch billing address with card issuer record (AVS)
3D SecureHighMandatory for cards >₹2,000; optional for trusted customers
Behavioral BiometricsMediumTyping speed, mouse movements, session duration anomalies
BIN CheckLowValidate card country vs. shipping country; flag mismatches
BlacklistCriticalBlock known fraud cards, devices, emails instantly

Refund & Dispute Management

Refund Types

  • Full Refund: Entire order amount returned to original payment method
  • Partial Refund: Specific item or shipping cost only
  • Store Credit: Issued as loyalty points (non-reversible)
  • Exchange: Return + new order linked; net difference charged/refunded
  • B2B Credit Note: Adjusts outstanding balance instead of cash refund

Chargeback Handling

  • Notification: Auto-alert within 24 hours of chargeback initiation
  • Evidence Collection: Auto-gather order proof, delivery confirmation, customer communication
  • Response Window: 7-21 days depending on card network
  • Representment: Submit evidence to dispute the chargeback
  • Acceptance: If valid, accept and update fraud model
  • Win Rate Target: >65% for legitimate transactions

Shipping & Logistics — Deep Dive

Multi-Carrier Shipping API

The Shipping Service provides a unified interface to multiple carriers, enabling intelligent carrier selection, label generation, tracking, and rate shopping.


International, dangerous goods
CarrierIntegrationStrengthsCoverageAPI Latency
Blue DartREST API + SOAP (legacy)Reliability, premium service, COD support35,000+ pincodes~500ms
DelhiveryREST API (v2)Cost-effective, scale, 18K+ pincodes18,000+ pincodes~300ms
ShiprocketREST APIMulti-carrier rate shopping, NDR managementAll major carriers~400ms
DHL ExpressREST API (MyDHL+)International express, customs expertise220+ countries~600ms
FedExREST API (FedEx Ship Manager)220+ countries~500ms
Dunzo / SwiggyREST APIHyperlocal same-day, instant deliveryMetro cities~200ms

Rate Shopping & Carrier Selection

// Shipping Rate Shopping API POST /api/v1/shipping/rates { "origin": { "pincode": "400001", "country": "IN" }, "destination": { "pincode": "560001", "country": "IN" }, "package": { "weight": 0.3, // kg "dimensions": { "l": 20, "w": 15, "h": 8 }, // cm "declaredValue": 3500, "contents": "EYEWEAR" }, "serviceType": "STANDARD", // STANDARD | EXPRESS | SAME_DAY "cod": false } // Response — Ranked by cost, then speed { "rates": [ { "carrier": "delhivery", "service": "Standard", "cost": 45, "eta": "3-5 days", "codAvailable": true }, { "carrier": "bluedart", "service": "DartSurfaceline", "cost": 89, "eta": "2-3 days", "codAvailable": true }, { "carrier": "bluedart", "service": "DartPlus", "cost": 149, "eta": "Next day", "codAvailable": true } ], "selected": { "carrier": "delhivery", "reason": "lowest_cost_meets_sla" } }

Tracking & NDR Management

StatusMeaningAuto-ActionCustomer Communication
SHIPMENT_CREATEDLabel generated, awaiting pickupSchedule pickup with carrier
PICKED_UPCarrier collected from warehouseUpdate inventory (in-transit)"Your order is on its way!"
IN_TRANSITMoving through carrier networkPoll tracking every 4 hours
OUT_FOR_DELIVERYAt local hub, with delivery agentSMS alert to customer"Arriving today! Be ready."
DELIVEREDSuccessfully deliveredTrigger review request, update order"How was your experience?"
NDR — Customer Not AvailableDelivery attempted, no one homeAuto-schedule re-attempt (max 3)"We missed you! Reschedule: [link]"
NDR — Address IssueIncomplete/invalid addressAuto-call customer for address correction"Please confirm your address"
NDR — COD RefusedCustomer refused to pay/acceptReturn to origin; flag customer account
RTO — Return to OriginUndeliverable after 3 attemptsRestock inventory; process refund"Your order is being returned. Refund in 5-7 days."

Notification Services — Deep Dive

Multi-Channel Notification Platform

The Notification Service is a shared infrastructure for all customer, doctor, and internal communications. It handles templating, personalization, delivery, and compliance across email, SMS, WhatsApp, and push.

ChannelProviderThroughputCostBest For
EmailSendGrid (primary), AWS SES (backup)100K/hour₹0.05-0.20Rich content, attachments, newsletters
SMSMSG91 (India), Twilio (global)50K/hour₹0.15-0.30Urgent alerts, OTP, short messages
WhatsAppWhatsApp Business API (Meta)20K/hour₹0.40-0.80Rich media, two-way support, catalogs
PushFirebase Cloud Messaging, OneSignal500K/hourFree (Firebase)App engagement, flash sales
Voice/IVRTwilio, Exotel5K/hour₹1.50-3.00/minAppointment reminders, payment follow-up

Templating Engine

Messages are generated from templates with dynamic variable substitution, conditional blocks, and multi-language support.

// WhatsApp Order Confirmation Template (Meta-approved) Template: order_confirmation_v2 Language: en "Hello {{customer.firstName}}! 👓" "Your order #{{order.id}} has been confirmed." "" "📦 Items:" "{{#each order.items}}" "• {{this.name}} — ₹{{this.price}}" "{{/each}}" "" "💰 Total: ₹{{order.total}}" "📅 Expected delivery: {{order.estimatedDelivery}}" "" "Track your order: {{order.trackingLink}}" "Need help? Reply here or call {{support.phone}}" // Rendered Output "Hello Priya! 👓" "Your order #ORD-2026-089234 has been confirmed." "" "📦 Items:" "• Titanium Round Frame — ₹2,500" "• Blue Light Filter Lens — ₹1,000" "" "💰 Total: ₹3,500" "📅 Expected delivery: July 12, 2026" "" "Track your order: https://..." "Need help? Reply here or call 1800-123-4567"

Compliance & Consent Enforcement

RegulationRequirementSystem Enforcement
TRAI (India SMS)DND scrubbing, template registration, sender IDAuto-scrub against TRAI DND registry; reject non-template SMS
GDPR (EU)Consent for marketing, right to opt-out, data portabilityCheck consent flag before send; one-click unsubscribe; export API
DPDP (India)Granular consent, data principal rightsConsent manager integration; block send if consent revoked
WhatsApp Policies24-hour session window, template approvalTemplate pre-approval workflow; session window tracking
CAN-SPAM (US)Unsubscribe mechanism, physical address, truthful subjectAuto-append unsubscribe footer; subject line validation

ERP / Accounting — Deep Dive

Financial Backbone Integration

The ERP Connector synchronizes all financial transactions between the operational system (OMS, Inventory, Manufacturing) and the general ledger. This ensures accounting accuracy, tax compliance, and management reporting.

ERP SystemBest ForIntegration MethodSync Frequency
OdooMid-market, modular, open-sourceREST API + Python SDKReal-time (webhook) + nightly batch
SAP S/4HANAEnterprise, complex multi-entityOData API + IDocReal-time + hourly delta
NetSuiteMid-to-large, cloud-nativeREST API + SuiteTalk SOAPReal-time + daily reconciliation
TallyIndia SME, GST complianceTallyPrime XML + ODBCDaily batch (end-of-day)
Zoho BooksSmall-to-mid, cost-effectiveREST APIHourly sync

GL Entry Mapping

Every operational event generates corresponding GL entries. The mapping ensures the chart of accounts reflects business reality.

// GL Entry Generation — Sales Order const glEntries = [ { // Revenue recognition account: "4001-Sales-Revenue", debit: 0, credit: 3500.00, reference: "ORD-2026-089234", description: "Sale: Titanium Frame + Blue Light Lens" }, { // GST Output (CGST + SGST for intra-state) account: "2011-GST-Output-CGST", debit: 0, credit: 315.00, // 9% of 3500 reference: "ORD-2026-089234", description: "CGST @ 9%" }, { account: "2012-GST-Output-SGST", debit: 0, credit: 315.00, reference: "ORD-2026-089234", description: "SGST @ 9%" }, { // Accounts Receivable (if credit) or Cash/Bank (if paid) account: "1001-Cash-Bank", debit: 4130.00, // 3500 + 630 GST credit: 0, reference: "ORD-2026-089234", description: "Razorpay settlement T+2" }, { // COGS — Frame account: "5001-COGS-Frames", debit: 875.00, // 35% of 2500 credit: 0, reference: "ORD-2026-089234", description: "COGS: Titanium Frame" }, { // COGS — Lens account: "5002-COGS-Lenses", debit: 300.00, // 30% of 1000 credit: 0, reference: "ORD-2026-089234", description: "COGS: Blue Light Lens" }, { // Inventory reduction account: "1301-Inventory-Finished-Goods", debit: 0, credit: 1175.00, // 875 + 300 reference: "ORD-2026-089234", description: "Inventory dispatch: SKU-TITAN-BLK" } ];

GST E-Invoicing Integration

StepSystem ActionERP Impact
1. Invoice CreatedOMS generates invoice JSONInvoice queued for IRP upload
2. IRN GeneratedJSON uploaded to GSTN; IRN + QR receivedIRN stored against invoice; QR embedded in PDF
3. GL EntryAuto-post revenue, tax, and receivable entriesTrial balance updated; GST liability recognized
4. GSTR-1 PopulateInvoice data auto-populates GSTR-1 returnMonthly return ready for filing
5. E-Way BillAuto-generate for inter-state transfers >₹50,000Transport compliance; vehicle check at checkpoints
6. ReconciliationMatch GSTR-2A (supplier data) with purchase registerIdentify missing ITC; flag discrepancies

Labs / Optical Partners — Deep Dive

External Lab Integration

Not all lens manufacturing happens in-house. External Lab Integration connects the ecosystem to third-party optical labs for overflow capacity, specialized coatings, or geographic coverage.

Integration TypeData ExchangeFrequencyProtocol
Lab Order SubmissionRx, frame specs, lens material, coating, delivery addressPer order (real-time)REST API or SFTP (XML/JSON)
Job Status TrackingReceived → In Progress → Coating → Edging → QC → ShippedEvery 2 hours + event-drivenWebhook or API polling
Quality ReportPower verification, coating test, visual inspection resultsPer job completionPDF + structured data (JSON)
Shipping NotificationAWB, carrier, ETA, package contentsOn dispatchWebhook or EDI
Invoice ReconciliationLab invoice vs. system job records; variance flaggingWeeklyAPI + manual review for exceptions

Lab Order Submission Format

// Lab Order — JSON Payload { "labOrderId": "LAB-2026-004521", "partnerLab": "VISION_CRAFT_LABS_MUM", "priority": "STANDARD", // STANDARD | EXPRESS | RUSH "patient": { "name": "Priya Sharma", "reference": "CUST-441289", "deliveryAddress": { "line1": "123 Park Avenue", "city": "Mumbai", "pincode": "400001" } }, "prescription": { "rightEye": { "sph": -3.50, "cyl": -1.25, "axis": 180, "add": null }, "leftEye": { "sph": -3.25, "cyl": -0.75, "axis": 90, "add": null }, "pd": { "binocular": 63.5, "right": 32.0, "left": 31.5 }, "fittingHeight": 24, "pantoscopicTilt": 10, "vertexDistance": 13 }, "frame": { "sku": "TITAN-ROUND-BLK-52", "brand": "Own Brand", "material": "Titanium", "shape": "ROUND", "rimType": "FULL_RIM", "templeLength": 140, "bridgeWidth": 19, "lensWidth": 52, "lensHeight": 42 }, "lensSpecification": { "material": "MR-8", "index": 1.60, "type": "SINGLE_VISION", "coatings": ["HARD_COAT", "AR", "BLUE_LIGHT"], "photochromic": false, "polarized": false }, "sla": { "promisedDate": "2026-07-12", "maxDate": "2026-07-14" } }

Partner Performance Dashboard

MetricTargetMeasurementConsequence
On-Time Delivery>95%Promised date vs. actual dispatch<90%: volume reduction; <85%: contract review
Quality Pass Rate>98%QC failures / Total jobs received<95%: 100% incoming inspection; <90%: termination
Rx Accuracy100%Power verification matches submitted RxAny error: root cause + corrective action; repeat: termination
Damage in Transit<0.5%Damaged units / Total shipped>1%: packaging audit; >2%: carrier change
Invoice Accuracy100%Invoice matches agreed pricing and job countDiscrepancy: hold payment until resolved
Communication<2 hours responseAvg time to respond to status query>4 hours: escalation to partner management

Marketing Platforms — Deep Dive

Ad Platform Integration

Marketing platform integrations enable closed-loop attribution — connecting ad spend to actual revenue, not just clicks. This powers ROAS optimization and budget reallocation.

PlatformIntegrationData FlowUse Case
Google AdsGoogle Ads API + Google Analytics 4Offline conversion upload (order value, SKU); audience sync (CRM segments)Search, Shopping, Performance Max campaigns with offline conversion optimization
Meta Ads (FB/IG)Marketing API + Conversions API (CAPI)Server-side event tracking (purchase, addToCart); custom audience from CRMRetargeting, lookalike audiences, dynamic product ads
Amazon DSPAmazon Advertising APISales data sync; campaign performance; inventory-aware adsSponsored Products, Sponsored Brands, display retargeting
ProgrammaticDV360 / The Trade Desk APIAudience segments, conversion data, frequency cappingDisplay, video, CTV campaigns

Customer Data Platform (CDP)

The CDP unifies customer data from all touchpoints and syncs enriched segments back to ad platforms for precise targeting.

// CDP Audience Segment Sync const audienceSegments = { "high_value_likely_churn": { "criteria": { ltv: { "$gt": 3000 }, daysSinceLastPurchase: { "$gt": 180 }, churnRiskScore: { "$gt": 0.6 } }, "size": 12500, "syncDestinations": ["google_ads", "meta_ads", "email"], "campaign": { "google_ads": "win_back_search_campaign", "meta_ads": "win_back_dynamic_ads", "email": "win_back_personalized_offer" } }, "rx_expiry_30d": { "criteria": { rxExpiryDate: { "$lte": "+30d" }, lastPurchaseChannel: { "$in": ["ONLINE", "RETAIL"] } }, "size": 48000, "syncDestinations": ["google_ads", "whatsapp", "email"], "campaign": { "whatsapp": "rx_reminder_with_booking", "email": "rx_expiry_educational" } }, "first_time_buyers_7d": { "criteria": { orderCount: 1, firstOrderDate: { "$gte": "-7d" } }, "size": 3200, "syncDestinations": ["meta_ads", "email"], "campaign": { "email": "welcome_nurture_sequence", "meta_ads": "cross_sell_accessories" } } };

Affiliate & Influencer Tracking

Tracking MethodMechanismAttribution WindowCommission Model
Unique Coupon CodesInfluencer-specific discount code (e.g., PRIYA15)Code usage only10-20% of order value
UTM TrackingURL parameters: utm_source, utm_campaign, utm_content (influencer ID)30 days (last-click)CPA: ₹300-800 per acquisition
Post-Purchase Survey"How did you hear about us?" at checkoutSelf-reportedUsed to validate pixel tracking
Affiliate Network PixelThird-party tracking pixel (Impact, Rakuten)30-90 daysRev share: 8-15%
Social ListeningMonitor mentions, tags, story sharesEngagement-basedFlat fee + performance bonus

SEO & Content Platform Integration

SEO Data Sources

  • Google Search Console: Query performance, click-through rate, index coverage
  • SEMrush / Ahrefs: Keyword rankings, backlink profile, competitor analysis
  • Screaming Frog: Technical SEO audits, broken links, duplicate content
  • PageSpeed Insights: Core Web Vitals, mobile usability

Content Operations

  • CMS Integration: Headless CMS (Contentful/Strapi) for blog, guides, product pages
  • A/B Testing: Optimizely/VWO for landing page optimization
  • Heatmaps: Hotjar/Clarity for user behavior analysis
  • Content Calendar: Auto-publish based on seasonal trends (back-to-school, summer)