# BiznisOS build progress

Plan: 7 phases, about 33 weeks of work. Full plan: the "BiznisOS — Product & Build Plan" doc.

| Phase | Scope | Status |
| --- | --- | --- |
| 1 | Foundation: auth (password, PIN, email code), agency → businesses, roles, team, dashboard, settings | **Code complete — tests written, not yet run (see below)** |
| 2 | CRM: contacts, custom fields, tags, notes, tasks, pipelines (Kanban), forms | **Code complete — tests written, not yet run** |
| 3 | Funnels: GrapesJS page builder, funnel steps, templates, domains | **Code complete — tests written, not yet run** |
| 4 | Email sending + visual automation builder | Not started |
| 5 | WhatsApp, payments (Razorpay/Stripe), bookings | Not started |
| 6 | Courses (LMS) + analytics | Not started |
| 7 | AI features + SaaS admin/billing | Not started |

## Phase 1 — what was built

- **Login:** email + password, email + 6-digit PIN, and passwordless 6-digit email code (hashed, 10-minute expiry, 5-attempt lock, one use). Rate limited. Forgot/reset password.
- **Signup:** creates the user, their agency and first business, with the user as owner.
- **Tenancy:** `BelongsToAccount` trait filters every business-owned table by the current business and fills `account_id` automatically. The current business is resolved before route-model binding.
- **Businesses:** agency owners add businesses up to their plan limit (`max_accounts`) and switch between them from the top bar.
- **Roles:** owner, admin, manager, member, with permissions in `config/biznisos.php`. Owners can't be demoted or removed by non-owners, and a business always keeps at least one owner.
- **Team:** email invitations (7-day expiry), accept as a new or existing user, change roles, remove members.
- **Settings:** business details (logo, GSTIN validation, address, time zone, currency) and personal profile, password and PIN.
- **Dashboard:** KPI tiles (placeholders until Phases 2–5 add data), 14-day activity chart, recent activity, quick actions.
- **Activity log:** searchable and filterable record of logins and changes.
- **Tests:** 52 feature and unit tests covering signup, all three login methods, rate limiting, tenant isolation, invitations, role rules, businesses and settings.

## Phase 2 — what was built

- **Contacts:** list with search, filters (status, tag, owner), sorting, pagination and bulk actions (add/remove tag, status, owner, delete). Profile page with details, tags, custom fields, deals, notes (pin/delete), tasks and a timeline.
- **Duplicates:** contacts are matched on email, then phone, inside each business. Indian mobile numbers are stored as +91XXXXXXXXXX.
- **Import/export:** two-step CSV import (upload, then match columns, with automatic guesses for common headers) running as a queued job. Export follows the current filters and includes custom fields.
- **Custom fields:** text, paragraph, number, date, dropdown, yes/no. **Tags** have colours.
- **Tasks:** due dates, assignees, overdue highlighting; My / All / Overdue / Completed views.
- **Pipelines:** several pipelines, Kanban board with drag-and-drop (SortableJS), stage totals, won/lost, stage editor (rename, colour, probability, reorder, add/remove; deals in removed stages move to the first stage).
- **Forms:** builder (drag to reorder fields, 8 field types, map answers to contact fields or custom fields), hosted page, iframe embed code, UTM tracking, honeypot spam protection, rate limiting, tags and an automatic deal on submit, thank-you message or redirect, submissions list and CSV export.
- **Dashboard:** real numbers for new leads, open pipeline value, deals won this month and tasks due today.
- **Tests:** 23 new tests (75 in total), including cross-business isolation for contacts, bulk actions and deal moves.

## Menu, dashboard and Get Started (matched to the reference screenshots)

- **Menu:** 14 modules in the same order as the reference: Get Started, Dashboard, Lead Generation, Lead Management, Lead Automation, Sales, AI Suite, Operations, Inbox, Calendar, Finance, Community, Settings, Learn. Modules not built yet show "SOON". Modules with several pages get a sub-menu and a tab bar.
- **Dashboard:** 14 KPIs in 6 groups (Marketing & Leads, Sales & Revenue, Operations, Messaging & Engagement, Contacts & CRM, Finance), each marked "in range", "all time" or "snapshot".
  - Date presets plus a custom range, an all-staff / per-staff filter and a time-zone chip.
  - Customize (show/hide) and drag-to-reorder, saved per user.
  - Export report (CSV).
  - Sales calls, bookings, WhatsApp status and MRR read zero until those modules are built.
- **Get Started:** 20 setup tasks with time estimates. 14 tick themselves off from real data; 6 belong to modules still being built. Also a "Define your niche" form and a mobile-app section (the app itself is a later project).
- **Setup banner:** "Finish your setup, X of 20 tasks complete" across the app, which each user can hide.
- **Ad spend:** record spend by channel and campaign, with a monthly total, per-channel split and cost per lead. Feeds the Ad spend KPI.

## Phase 3 — what was built (Lead Generation)

- **Funnels:** create from 4 templates (lead magnet, webinar, sales page, blank). Each page gets its own working form. Reorder pages, page settings and SEO, duplicate, publish/unpublish.
- **Page editor:** GrapesJS drag-and-drop with BiznisOS blocks (hero, text + image, features, checklist, price, FAQ, video, button, lead form), desktop/tablet/mobile preview, undo/redo, autosave every 30 seconds, Ctrl+S.
- **Public pages:** `/p/{business}/{funnel}/{page}` on the pages host, or on a customer's own domain. A form on a funnel page creates the contact and moves the visitor to the next page.
- **Tracking:** unique visitors via cookie, UTM, device and referrer; bots ignored. Per-page visitors, opt-ins, opt-in rate and step-to-step conversion for 7, 30 or 90 days.
- **Custom domains:** add, DNS check (CNAME or A record), one funnel per domain, plus an endpoint Caddy calls before issuing SSL.
- **Tracking codes:** head and body code per funnel (Meta Pixel, Google Analytics).

## Sales module (chunk 4)

The Sales menu now has 5 tabs: Performance, Webinars, IVR Calling, Proposals, Events.

- **Performance:**
  - Team / My view, date range, and totals for verified revenue, actions, calls, average first response and who is active now.
  - Leaderboard sortable by revenue, engagement, calls or response time, with Bronze/Silver/Gold/Platinum levels and per-person counts of actions, messages, tasks, calls and meetings.
  - Incentive settings per staff (admin only): % of revenue or a fixed amount per sale, plus a monthly target.
  - First-response time is recorded automatically the first time a team member acts on a new contact.
- **IVR Calling:**
  - Drivers for Exotel, Twilio, Knowlarity and MyOperator, plus a test driver.
  - Click-to-call rings the agent's mobile first, then the customer; a "Call" button is on every contact.
  - Webhook for call status, recordings and inbound calls; credentials are stored encrypted.
  - Stats for total, connected, missed, talk time, unique clients and active agents.
  - Tabs: Call logs (search and 6 filters), Agents, Recordings (audio player), Providers.
  - Feeds the dashboard "Sales calls" KPI.
- **Proposals:**
  - Builder with text, pricing-table (GST per line: 0/5/12/18/28%) and terms blocks, drag to reorder, brand colour, templates.
  - Statuses: built → published → sent → viewed → approved/declined → converted, plus void.
  - Public link with view tracking; e-signature by typed name or drawn signature, with IP and time recorded.
  - Can be switched off per business.
  - "Convert to revenue" marks the linked deal won.
  - Stats: pipeline value, won value, win rate.
- **Events:**
  - Cover with 4 themes, start/end in the event's time zone; in person, online or hybrid; venue/link.
  - Room capacity and seats sellable online.
  - Several ticket tiers (free or paid, optional limit per tier).
  - Public page with registration that creates the contact and a ticket code.
  - Seat limits are enforced with a database lock.
  - Attendee list, check-in, mark paid, CSV export.
- **Webinars:**
  - Live or recorded, with reminder schedule, public registration page (creates contacts), attendance marking and show-up rate.
- **Tests:** 15 new tests (108 in total), including cross-business checks for proposals and webhooks.

## Lead Automation and Inbox (chunk 5)

- **Workflows** (Lead Automation → Workflows): drag-and-drop builder (Drawflow) with a trigger and steps joined by lines. Autosaves every 20 seconds; a workflow cannot be turned on until every step is filled in.
  - Triggers: form submitted, contact created, tag added, deal moved to stage, deal won, event or webinar registration, WhatsApp keyword, Instagram keyword (DM or comment), new IndiaMART lead, new Meta lead (optionally one form), birthday (daily).
  - Steps: send WhatsApp template, send email, add/remove tag, move deal to stage, remove from pipeline, create task, assign owner (round robin), wait (minutes/hours/days), if/else (has tag, status, has email/phone, source contains, city is), webhook to Zapier/Make etc.
  - Merge fields `{{first_name}}`, `{{full_name}}`, `{{email}}`, `{{phone}}`, `{{business}}`. Test run on a chosen contact (messages logged, not sent). Run log per workflow shows every step.
  - Existing screens now fire triggers: new contact, tags added (single and bulk), deal moved/won, proposal accepted, form submissions, event and webinar registrations.
- **Integrations**: WhatsApp Cloud API (with coexistence switch), Meta Lead Ads, Instagram, IndiaMART (push webhook or 10-minute pull), inbound email. Webhook URL + verify token per business, signature check with the Meta app secret, credentials encrypted.
- **Meta leads**: every Facebook/Instagram form lead with its answers, filter by form; backfill last 90 days.
- **Inbox**: one inbox for WhatsApp, Instagram and email. Open/Mine/Unassigned/Closed filters, search, channel filter, unread counts, assign to a team member, close/reopen, internal notes, quick replies, template sending when the 24-hour window has closed, delivery/read ticks, new messages appear every 5 seconds. Contact panel on the right; "Message" button on every contact.
- **Broadcasts**: WhatsApp template to all opted-in contacts or one tag, now or scheduled; DND and non-opted-in contacts are skipped and counted.
- **WhatsApp templates** (sync from Meta or record by hand) and **Quick replies** pages.
- Dashboard "WhatsApp status" KPI now reads the real connection.
- **Tests:** 13 new tests in `tests/Feature/AutomationAndInboxTest.php` (121 in total): workflow run/wait/if-else, builder validation and permissions, cross-business isolation, WhatsApp webhook verify/receive/dedupe/keyword trigger, signature check, 24-hour rule, notes, broadcast opt-in, IndiaMART push, Meta lead import, encrypted credentials.

## Calendar and Finance (chunk 6)

- **Booking calendars** (Calendar → Booking calendars): one calendar per meeting type with length, slot spacing, buffer before/after, minimum notice, how far ahead, weekly hours (two ranges per day), date overrides (holidays or special hours), questions for the guest, location (phone, in person, Google Meet, Zoom or custom link), colour and a team shared round robin.
  - Public booking page with a date strip and time slots shown in the visitor's own time zone. Creates or updates the contact, tags it, emails the guest and the host, and gives the guest a page to reschedule or cancel.
  - A person is never booked twice at the same time, even across calendars; the last free slot is protected against two people booking at once.
  - Reminder email about a day before; Google Meet or Zoom link created automatically when those apps are connected.
- **Appointments**: list (upcoming / past 90 days), week and month views, filters by calendar, status and "only mine"; mark confirmed, completed or no-show; reschedule from free slots; cancel with a reason. Team members see only their own bookings.
- **Finance**
  - Overview: received this month, MRR, unpaid invoices, 6-month chart, latest payments.
  - Products (one-time or monthly/yearly subscription, price before GST, GST 0/5/12/18/28%, HSN/SAC).
  - Checkout pages for one product with extra questions, thank-you message or redirect; payment through Razorpay (pop-up) or Stripe (hosted checkout), with a test mode.
  - GST invoices: sequential numbers per business (INV-0001…), CGST + SGST within your state and IGST for other states, create from a contact or lead, edit until paid, email to the customer, printable / save as PDF, customer link with a Pay button, record bank/UPI/cash payments, void.
  - Payments and refunds (sent to Razorpay or Stripe for online payments), orders, subscriptions with MRR, renewals recorded by hand, and overdue renewals flagged automatically.
  - A paid order automatically creates a paid GST invoice and makes the contact a customer.
  - Paid event tickets now go to payment and mark the registration paid.
- Payment and booking events start workflows: appointment booked or cancelled, payment received, invoice paid.
- Dashboard: "Calendar bookings", "Total revenue" (money received after refunds; won deals until the first payment) and "MRR" are now live.
- Get Started: Connect Meta, Connect WhatsApp, Publish your pricing, Send your first proposal, Turn on one automation and Set up your booking calendar now tick themselves.
- **Tests:** 13 new tests in `tests/Feature/CalendarAndFinanceTest.php` (134 in total): slots with buffers and time zones, date overrides, no double booking, round robin, public booking + cancel, booking KPI, GST maths, invoice numbering and isolation, checkout with the test gateway, Razorpay webhook signature + duplicate delivery, refunds, MRR, paid event tickets, permissions.

## AI Suite, wallet, operations and finishing touches (chunk 8)

- **AI Agent** (AI Suite → AI Agent, or the "AI Agent" switch in the top bar): full-screen chat that answers questions about the business using live data.
  - Before answering it looks things up with read-only tools: dashboard numbers, recent leads, contact search, pipeline summary, upcoming bookings, tasks, payments and unpaid invoices. It only ever sees the current business and cannot change anything.
  - Chat history with search, filter (last 7 days) and sort; rename and delete; copy and regenerate an answer; attach a text or CSV file; quick prompts; model picker (Fast, Smart, Claude Haiku, Claude Sonnet). Each person sees only their own chats.
  - A floating "Ask AI" button opens a small chat panel on every page.
- **AI Writer**: drafts WhatsApp messages, emails, ad copy, social posts, product descriptions, proposal introductions, follow-ups and replies, in five tones and nine languages (incl. Hindi and Hinglish). Recent drafts are kept.
- **Wallet & credits**: every business gets 50 welcome credits. Answers cost 1 or 5 credits depending on the model. Packs of 500, 1,200 and 3,000 credits are paid through the platform's own Razorpay account (pop-up, signature check, webhook, no double credit). Full ledger, usage this month, low-balance warning in the top bar.
- **Settings → App Store**: a business can connect its own OpenAI or Anthropic key; then no credits are charged. Shortcuts to every other connection (WhatsApp, Meta, IndiaMART, payments, calendars, calling).
- **Operations**: task board with To do / In progress / Done, drag and drop, priorities, filters by person; moving to Done completes the task everywhere (and the old task list moves cards too). Team workload shows open, in-progress, due-today, overdue, high-priority and done-this-week per person, plus unassigned work.
- **What's new** page with a dot on the bell until each person has read the latest entry (`config/whatsnew.php`).
- **Dark mode** (light, dark or match the device), remembered per person.
- **Voice typing**: a microphone button on the AI chat, AI Writer, inbox replies, contact notes and new tasks (browser speech recognition, Indian English by default).
- Without AI keys everything still works with clearly-labelled demo answers, so screens can be tried before keys are added.
- **Tests:** 9 new tests in `tests/Feature/AiWalletOperationsTest.php` (143 in total): wallet never negative and no double credit, test-mode top-up and permissions, platform webhook signature, agent tools + credits + private chats + regenerate, own key not charged and empty wallet refused, tools isolated per business, writer, board/task sync, What's new, dark mode, page rendering.

## Remaining gaps from Phases 1–6 and 8 (closed)

Checked against the screenshots, the "What's new" list and the plan, then built what was still missing:

- **Leads and Contacts** are separate lists. Each has saved, named filters (private or shared with the team) and columns each person chooses: email, phone, company, tags, status, owner, source, UTM source/medium/campaign, city, last activity, created and updated date and time.
- **Pipeline cards** show the fields the business picks: contact, phone, value, close date, owner, lead source, UTM campaign, created, updated, number of notes.
- **Deal notes**: a note can belong to one deal, so each pipeline keeps its own notes. The contact page shows created and updated times and has **Create invoice**.
- **Custom fields in any Indian language**: names in Devanagari, Tamil, etc. get safe keys automatically.
- **Form design**: five themes, page background colour or image, button and text colours, corner rounding, and fonts including Noto Sans and Mukta for Indian scripts.
- **AI form builder**: describe a form and AI drafts its fields. It costs 1 credit, and without an AI key it uses a keyword-based draft.
- **Instagram automation**: the "Instagram DM or comment" trigger can listen to DMs, comments or one post. A new "Reply on Instagram" step sends a private reply or a public comment reply.
- **SMS**: MSG91 (DLT) and Twilio in Integrations, a "Send SMS" workflow step, an SMS do-not-disturb flag on contacts, and optional login codes by SMS.
- **Email campaigns**: next to WhatsApp broadcasts, with audience by tag or status, merge fields, markdown, a test send, scheduling and a one-click unsubscribe link (signed, sets email DND).
- **Sign in with Google** (OAuth/OpenID, no extra package). Existing users are matched by email; new people get a business if sign-ups are open.
- **Media vault** (Settings): "optimise" (photos resized to 1,600 px and compressed) or "keep original", folders, search, copy link. Files can be sent straight into WhatsApp, email or Instagram chats from the inbox. Storage can be this server or S3 / DigitalOcean Spaces.
- **Notifications** (bell): new leads that arrive on their own, contacts, tasks and conversations assigned to you, new bookings with you, and online payments. Mark all read; nobody is notified of their own action.
- **Feedback button** on every page (idea / problem / praise), saved and emailed to support.
- **What's new**: search, module, type and date filters, unread count and "Unread only", mark all read, list or grid view, an ID per entry and a share link.
- **Voice typing**: a "Listening…" overlay with a Stop button and the Esc key.
- **Install as an app**: web app manifest, icons, offline page, an Install button on Get Started (plus Android/iPhone instructions), and help links (Docs, Ask AI, Contact support).
- **Tests:** 9 new tests in `tests/Feature/PlatformGapsTest.php` (152 in total).

## Known limits closed (December 2026)

- **Automatic subscription renewals.** A few days before each renewal date the customer is emailed a payment link (a normal order tied to the subscription), with reminders. Paying it moves the renewal date on and sends a GST invoice. A day after an unpaid renewal date the subscription shows as overdue and owners get a notification; it can also be cancelled automatically after a set number of days. "Record renewal" closes any open link so nobody pays twice. Two new workflow triggers: *renewal link sent* and *renewal overdue*.
- **Two-way Google Calendar sync.** Every booking becomes a Google event (with Meet when chosen); moving or cancelling a booking updates Google. Busy times in Google block booking slots, per team member when they add their own calendar ID. Events moved or deleted in Google move or cancel the booking (checked every 10 minutes). Both directions can be switched off on the integration card.
- **Browser push notifications.** "Alerts on this device" under the bell. Works on Android, desktop, and iPhone once added to the home screen. No extra package: pushes are signed with VAPID and carry no text, and the app fetches the text itself so it never passes through Google's or Apple's push servers.
- **Platform feedback screen** for super admins: filter by status, type and text; set status (new, planned, done, closed), add a note and optionally notify the person.
- **Tests:** 13 new tests in `tests/Feature/RenewalsSyncPushTest.php`, and the smoke test now also visits every page as a platform admin.

Still not possible: native Android/iPhone store apps (the installable web app covers this), and charging saved cards or UPI AutoPay mandates without the customer clicking (needs Razorpay Subscriptions / Stripe Billing to be connected and tested with live accounts).

## Not built yet

- **Community and Learn (Phase 7)** are paused at your request. Start them whenever you like.

## Database file

`database/biznisos.sql` is the complete MySQL schema (73 tables). It was **tested by importing it into MariaDB 10.11** in the build workspace and imports without errors. It also fills the `migrations` table, so `php artisan migrate` will only run newer migrations later.

## Testing

See **TESTING.md** for the full guide. In short there are four layers:

1. **Static QA** – `python3 tools/qa.py` (add `--sql` to import the SQL file into MySQL). Needs no Composer and no database. **Passes** in the build workspace: 242 PHP files, 115 views, 284 route actions, 908 class references, 757 model columns, 72 tables vs the SQL file, 73 tables imported into MariaDB.
2. **Unit and feature tests** – 169 PHPUnit tests covering every module.
3. **Smoke test** – `tests/Feature/SmokeTest.php` opens every page (as owner, as a member and as a visitor) with one record of everything and fails on any crash. New pages are picked up automatically.
4. **CI** – `.github/workflows/tests.yml` runs all of the above on GitHub for every push, on SQLite and on MySQL 8, plus migrations up/down, the demo seeder, the SQL import, compiling every Blade view and caching routes.

**Still not run:** layers 2–4 need `composer install`, and this workspace cannot reach packagist.org, so the PHPUnit tests have never been executed. Expect a first round of small fixes when they run. On any machine with internet:

```bash
composer install
cp .env.example .env && php artisan key:generate
tools/test.sh
```

## Decisions made without asking (change any of them)

| Decision | Choice | Where to change |
| --- | --- | --- |
| Brand colours | Primary `#0b6e99` (deep teal-blue), accent `#f5a524` (amber), dark navy sidebar | `public/css/app.css` `:root` |
| Font | Plus Jakarta Sans (Google Fonts) | `resources/views/partials/head.blade.php` |
| Front-end assets | Bootstrap 5.3, Bootstrap Icons, jQuery 3.7, Chart.js 4 from the jsDelivr CDN (no build step) | `partials/head.blade.php`, `partials/scripts.blade.php` |
| Default plan | `starter`, 3 businesses per agency | tenancy migration |
| Signups | Open to the public | `BIZNISOS_ALLOW_REGISTRATION` |
| Language | English only | — |
| PHP target | 8.2 (Composer platform pinned to 8.2.0) | `composer.json` |
| Multi-tenancy | Single database, `account_id` on every business table | `app/Models/Concerns/BelongsToAccount.php` |

## Open questions for the owner

- Screenshots still needed: Sales → Webinars (built from the plan for now), and every page inside Lead Generation, Lead Management, Lead Automation, AI Suite, Operations, Inbox, Calendar, Finance, Community, Settings, Learn.
- Brand logo and final colours?
- Selling BiznisOS as SaaS to other businesses, or for your own use only? (Decides Phase 7 scope.)
- English only, or Hindi too?
