# Neroplaste Pipe Verification — build prompt

Nov 29, 2026 · @Ramachandran

## The brief

Build a QR-based pipe verification and certificate system for Neroplaste, a UPVC/SWR pipe manufacturer in Tamil Nadu. Every pipe carries a QR label; a customer scans it, enters their mobile number and pincode, and gets a Product Test & Warranty Certificate as a downloadable PDF.

There are two surfaces:

1. **Public verify page** — no login, mobile-first, three fields (serial, mobile, pincode), ends in a PDF download. This is the only part a customer sees.
2. **Admin back office** — authenticated. Plant and QA staff manage products, batches and test results, mint serials, print QR label sheets, block serials, and read the verification log.

How to use this prompt: paste it whole as the opening instruction to the coding agent, then work through the phases in *Build order* one at a time, stopping at each phase's acceptance criteria before moving on. Do not scaffold all phases at once. Where this prompt marks something `[PLACEHOLDER]` or lists it under *Decisions to confirm*, ask rather than invent.

Assume a fresh Laravel 11 application unless told otherwise.

## Stack and conventions

Laravel 11, Blade, Bootstrap 5, jQuery/AJAX where a page needs it, MySQL 8. No SPA framework, no Livewire, no Inertia.

Packages: `barryvdh/laravel-dompdf` for the certificate, `simplesoftwareio/simple-qrcode` for QR generation. Add nothing else without asking.

Conventions to follow:

- **Fat services, thin controllers.** Business logic lives in `app/Services`; controllers validate, delegate, redirect. A controller method over \~40 lines means logic belongs in a service.
- **Form Requests for all validation**, with `prepareForValidation()` doing normalisation (strip non-digits from phone and pincode, uppercase and re-hyphenate the serial) so the rules see clean input.
- **Eloquent relationships, no raw joins** in application code. Reporting queries may use the query builder.
- **Laravel 11 style**: `casts()` method not `$dates`, invokable single-action controllers where there is one action, `bootstrap/app.php` for middleware registration.
- Money and quantities as integers where they exist; dates as Carbon via casts.
- Blade: one layout for the public pages, a separate layout for admin. Bootstrap 5 utility classes, minimal custom CSS.
- Migrations are additive and reversible. Every foreign key is explicit, with `restrictOnDelete()` on anything that certificates depend on.
- Timezone `Asia/Kolkata`, locale `en`, currency not applicable.

## Data model

Seven tables. A certificate is never stored as a row of denormalised text — it is rendered from these on demand, so a corrected test value corrects every certificate reissued afterwards.

| Table | Key columns | Notes |
| --- | --- | --- |
| `products` | name, size, pressure\_class, standard, warranty\_months, is\_active | `warranty_months` drives the warranty-till date on the certificate |
| `batches` | product\_id, batch\_no (unique), serial\_prefix, manufactured\_on, plant, shift, released\_at | `released_at` null or future = serials refuse to verify |
| `batch_tests` | batch\_id, test\_name, requirement, observed, result (pass/fail), sort\_order | Rows print as the certificate's test table; one `fail` blocks the batch |
| `pipe_serials` | batch\_id, serial (unique), token, status (available/claimed/blocked), verification\_count, first\_claimed\_at | `token` is hidden on the model; see *Security* |
| `verifications` | pipe\_serial\_id, certificate\_no (unique), phone, pincode, city, state, consent, pdf\_path, channel (qr/manual), ip, user\_agent, verified\_at | The warranty record; one row per customer claim |
| `pincodes` | pincode (PK, char 6), city, district, state, service\_area | Lookup master, seeded from the dealer territory list |
| `failed_lookups` | serial\_attempted, phone, pincode, reason, ip, user\_agent, created\_at | Feeds the admin abuse queue; no FK, since the serial may not exist |

Relationships: Product hasMany Batch; Batch hasMany PipeSerial and hasMany BatchTest (ordered by `sort_order`); PipeSerial hasMany Verification.

`reason` on `failed_lookups` is an enum: `unknown_serial`, `blocked_serial`, `unreleased_batch`, `reclaim_attempt`, `rate_limited`.

Indexes: `pipe_serials.serial` unique; `verifications.phone`, `verifications.pincode`, and a composite on `(pipe_serial_id, verified_at)`; `batches.(product_id, manufactured_on)`; `failed_lookups.(reason, created_at)`.

## Routes, controllers, services

| Method | URI | Name | Middleware |
| --- | --- | --- | --- |
| GET | `/c` | verify.form | throttle:verify-page |
| POST | `/verify` | verify.store | throttle:verify-submit |
| GET | `/verified/{verification}` | verify.success | session or signed |
| GET | `/certificate/{verification}/download` | certificate.download | signed |
| POST | `/certificate/{verification}/whatsapp` | certificate.whatsapp | throttle:verify-submit |
| — | `/admin/*` | admin.\* | auth |

The QR encodes `/c?s=<serial>&t=<token>`, so the serial arrives pre-filled.

Services, with the signatures to implement:

- `SerialNumberService` — `generateForBatch(Batch $batch, int $quantity, int $startAt): int` (chunked `insertOrIgnore`, wrapped in a transaction), `format(string $prefix, int $sequence): string` producing `NP-7431-00892`, `normalise(?string $input): ?string` turning `np 7431 00892` into the canonical form, `nextSequence(Batch $batch): int`.
- `CertificateService` — `issue(PipeSerial $serial, array $data): Verification` (idempotent, see *Security*), `render(Verification $v): string` returning the stored path, `certificateNumber(PipeSerial $serial): string` producing `NPC-<year>-<day of year>-<sequence>`, `fileName(Verification $v): string`.
- `PincodeService` — `resolve(string $pincode): array` returning city and state from the master, cached for a day; `label(string $pincode): string` for display.
- `FailedLookupService` — `record(string $reason, array $context): void`, called from every refusal path in the controller.

Controllers: `VerificationController` (form, store, success, download), `CertificateWhatsAppController` (invokable), and admin resource controllers listed under *Admin screens*.

## Customer flow

Mobile-first, 390 px up. Header with the brand and the host, footer with a support number. Every input at least 48 px tall.

**1. Verify form** (`GET /c`). Three fields in this order:

| Field | Rules | Behaviour |
| --- | --- | --- |
| Serial number | required, exists in `pipe_serials` | Pre-filled from the QR; editable, for a worn label. Show "filled in from the QR code" only when the token matched |
| Mobile number | required, 10 digits, `/^[6-9]\d{9}$/` | `+91` as a fixed input-group prefix; jQuery strips non-digits as the user types |
| Pincode | required, 6 digits, `/^[1-9]\d{5}$/` | Hint: where the pipe is being used; sets the dealer and service area |

Plus a required consent checkbox, then one primary button: "Verify & generate PDF".

**2. Error state.** Refusals re-render the same form with an inline error on the offending field and every other value kept. Distinct messages, not one generic failure:

- unknown serial — "We could not find this serial. Check the digits — letter O and zero are easy to swap."
- blocked serial — support message with the phone number, no detail about why
- unreleased batch — "This batch has not been released yet. Please try again later or contact your dealer."
- reclaim attempt, when reclaim is off — "This serial is already registered to another number."

Every one of these also writes a `failed_lookups` row.

**3. Success** (`GET /verified/{verification}`). Green "Genuine Neroplaste product" badge, the serial as the heading, then a summary table: product, size and class, batch, manufactured date, warranty-till date, and "registered to" showing the mobile and pincode. A file row naming `<serial>-certificate.pdf`. Primary button downloads the PDF; secondary sends it on WhatsApp when that is enabled. A line stating the link expires in 24 hours.

Reachable only from the session that just submitted, or via a signed link — otherwise 403.

## Admin screens

Authenticated, 1280 px desktop layout: a fixed left sidebar (Dashboard, Batches, Serials, Verifications, Products, Pincodes & dealers, Settings) and a content area with a page header carrying the title, a one-line subtitle of counts, and the page's actions.

**Dashboard.** Four stat tiles — verifications today, serials minted, claim rate (claimed over minted, 90 days), failed lookups. Below them: the latest ten verifications, the top pincodes for 30 days, and a "needs a look" card grouping `failed_lookups` by reason with a count and a review link each.

**Batches** (`index`). Filterable list — batch no, product, manufactured date, status pill, minted count, claimed count. Status is derived, not stored: *Draft* when no serials exist, *Held* when `released_at` is null or future, *Released* otherwise. State the release rule on the page so staff understand why a batch will not verify.

**Batch detail** (`show`). The only screen that changes what prints on a certificate, so it carries four regions:

1. Batch facts — batch no, product, size and class, standard, manufactured, plant and shift, serial range, warranty window.
2. Test results — the editable `batch_tests` table with add and edit per row. An empty cell prints as an em dash; a row marked fail blocks the batch.
3. Mint serials — quantity and start-at, defaulting to the next unused sequence, calling `SerialNumberService`. Show the equivalent artisan command beneath it.
4. QR label sheets — from, to, labels per A4 sheet, then a list of previously generated sheets with download links.

Plus actions in the header: hold the batch, edit it, preview the certificate.

**Serials.** Support-desk search by serial or last five digits, batch, status, or registered mobile. Columns: serial, batch, status, registered to, scan count, first claim. Row actions block and unblock. State on the page that blocking refuses new verifications but leaves issued certificates valid.

**Verifications.** The warranty log, filterable by serial, mobile, certificate number, pincode, channel and date range. Each row links to its PDF. Also show, on the page, which fields are stored and the rate limits in force — this screen doubles as the abuse review view.

Products and Pincodes are plain resource CRUD; no special behaviour.

CSV export on Dashboard, Serials and Verifications, honouring the active filters, streamed rather than built in memory.

## Certificate PDF and QR labels

**Certificate**, A4 portrait, one page, rendered by dompdf from a dedicated Blade view. Use table-based layout and inline styles only — dompdf does not support flexbox or grid. Fonts: DejaVu Sans, so the rupee and degree symbols render.

Layout top to bottom: brand block with company name and plant, and the certificate number top-right, over a 2 px rule; the title "Product Test & Warranty Certificate" with the issuing line beneath it; a bordered two-column grid of eight fields (serial, batch, product, size and class, manufactured date, verification date, registered mobile, pincode of use with the resolved city and state); the test results table with requirement, observed and result columns; a warranty block stating the years and the expiry date; and a footer with a re-verification QR on the left and a signature line for the Quality Assurance Head on the right.

Store at `certificates/<year>/<month>/<certificate_no>.pdf` on the configured disk. Serve only through the signed download route, never a public URL.

**QR label sheet**, A4, default 24 labels per sheet, each 60 × 22 mm: an 18 mm QR on the left, then the brand, "Scan to verify & get certificate", the size and class, and the serial in bold. Labels are floated with an explicit page break every *n*, since dompdf will not paginate a flex row.

Two artisan commands, both of which the admin screens call into:

```markdown
php artisan neroplaste:serials B-2026-0431 5000 [--start=]
php artisan neroplaste:labels B-2026-0431 --from=1 --to=500 --per-page=24
```

The QR payload is the full absolute URL, built with `route()` so it follows `APP_URL`. Generate at error-correction level M and 160 px — a pipe label gets dirty, and M tolerates about 15% damage.

## Security and abuse

The threat is not account takeover — there are no customer accounts. It is serial harvesting: the serial format is human-readable by necessity, so anyone can guess `NP-7431-00893` and pull a certificate that makes counterfeit stock look genuine.

**Hidden token.** Each serial carries a six-character `token` printed only inside the QR, never in human-readable form. A scan passes `?s=&t=` and the form pre-fills; a hand-typed serial still works but is recorded as `channel=manual` and runs into the tighter limits. Generate it from a Crockford-style alphabet with I, O, 0 and 1 removed. Keep it in the model's `$hidden` so it never leaks through serialisation, and never render it in a Blade view.

**Idempotency.** `CertificateService::issue()` is idempotent per serial and phone: the same pipe scanned again from the same number returns the existing verification and re-renders the PDF only if the stored file has gone missing. Wrap the claim in a transaction with `lockForUpdate()` on the serial row, so two simultaneous submissions cannot both insert.

**Rate limits**, registered as named limiters:

| Limiter | Limit |
| --- | --- |
| verify-page, per IP | 30 per minute |
| verify-submit, per IP | 5 per minute, 20 per day |
| verify-submit, per mobile | 10 per day |

**Signed links.** The download route uses `temporarySignedRoute` with a 24-hour expiry, configurable. The success page accepts either the submitting session or a valid signature. Certificates are not publicly readable: keep the disk private and stream through the route.

**Other refusals.** Blocked serials and unreleased batches are refused before any certificate work happens. Reclaim by a different number is allowed by default and recorded; a config flag turns it into a refusal. Every refusal writes `failed_lookups`.

**Privacy.** The customer's number and pincode are personal data held for warranty purposes. Store the consent flag and timestamp, mask the number in admin list views (`98xxxx3210`), and restrict the unmasked value and the CSV export to a role rather than every authenticated user.

No OTP in this build. The number is captured, not verified — see *Decisions to confirm*.

## Build order

Six phases. Finish each one's acceptance criteria before starting the next, and run the migrations and the test for a phase before moving on.

**Phase 1 — schema and models.** All seven migrations, five models with relationships and casts, a demo seeder creating one product, one released batch with four test rows, 1,000 serials and three pincodes.

*Done when:* `migrate:fresh --seed` runs clean, and a tinker session can walk product → batch → serials → tests in both directions.

**Phase 2 — serials and labels.** `SerialNumberService` plus both artisan commands, the label Blade view.

*Done when:* minting 5,000 serials takes under five seconds and is safe to re-run; a label sheet PDF opens with 24 labels per page and a phone can scan one to the right URL.

**Phase 3 — public flow.** Form Request, `VerificationController`, `PincodeService`, `FailedLookupService`, the three Blade views, named rate limiters.

*Done when:* a scanned URL pre-fills the serial; submitting valid input creates one verification row and redirects to success; each of the four refusal messages appears for its own cause and writes a `failed_lookups` row; submitting the same serial and number twice creates exactly one row.

**Phase 4 — certificate PDF.** `CertificateService` and the certificate Blade view, signed download route.

*Done when:* the PDF is one A4 page with every field populated, the embedded QR scans back to the verify URL, the download link 403s after expiry, and no path serves the file unsigned.

**Phase 5 — admin.** Auth, layout and sidebar, the five screens, resource CRUD for products and pincodes, CSV exports.

*Done when:* a batch can be created, given test rows, minted, released and held entirely through the UI; a held batch refuses verification on the public side; blocking a serial refuses new verifications while its existing certificate still downloads.

**Phase 6 — hardening.** WhatsApp send behind its config flag, masked numbers and role-gated export, queue the PDF render if it exceeds about two seconds, and feature tests covering the refusal paths and the idempotency case.

*Done when:* the full flow passes with `php artisan test`, and 1,000 concurrent verify submissions produce no duplicate rows and no unhandled exceptions.

## Placeholders and decisions to confirm

Do not invent values for these. Render them as visible placeholders and raise them.

| Item | Needed from |
| --- | --- |
| Full warranty wording | Legal; the PDF prints `[FULL WARRANTY WORDING TO BE SUPPLIED BY LEGAL]` until supplied |
| Test requirement and observed values | QA sheets per batch; seeded as `[REQUIREMENT]` and `[OBSERVED]` |
| Company legal name, plant address, support number, signatory | Business |
| Pincode and dealer territory master | Sales |
| Product range, sizes and pressure classes | Product |

Four decisions that change the build, to settle before Phase 3:

1. **OTP on the mobile number.** Not in this build, so the number is unverified. If a warranty claim must stand on it, an OTP step slots in between validation and `issue()`. Cost: drop-off on a page with no login.
2. **Reclaim policy.** Default allows a second number to register a used serial, and records it. The alternative refuses and routes to support — safer against resale fraud, worse for a genuine second owner.
3. **Pincode mandatory or optional.** Drawn as mandatory, which gives clean service-area data at some cost in completion. Optional is a one-line change.
4. **Label placement interval.** Assumed every 3 m, so a cut length still carries a QR. Production needs to confirm it, because it sets how many serials a batch consumes.

Also worth deciding early, though it does not block: whether certificates live on the local disk or S3. S3 from the start avoids a migration once volume grows, and the code reads the disk from config either way.
