diff --git a/apps/api/app/routers/crm.py b/apps/api/app/routers/crm.py index b74b5188..0d31c19c 100644 --- a/apps/api/app/routers/crm.py +++ b/apps/api/app/routers/crm.py @@ -4,7 +4,7 @@ from uuid import UUID from fastapi import APIRouter, Depends, HTTPException, Query -from sqlalchemy import select, or_ +from sqlalchemy import select, or_, func from sqlalchemy.ext.asyncio import AsyncSession from app.auth import get_current_admin @@ -139,3 +139,70 @@ def followup_draft(kind: str) -> str: if kind == "callback_requested": return "Thanks for requesting a callback from SurfaceCoat. Please let us know a convenient time to speak." return "Thanks for your enquiry with SurfaceCoat. Please let us know if you have any questions about your estimate." + + +from pydantic import BaseModel, EmailStr, Field +from fastapi import Request +from sqlalchemy import text +from app.rate_limit import limiter +from app.models.service import SurfaceType +from app.services.notifications.outbox import enqueue_notification + + +class MeasuringVisitRequest(BaseModel): + full_name: str = Field(min_length=2, max_length=200) + email: EmailStr + phone: str = Field(min_length=8, max_length=40) + address_line1: str = Field(min_length=3, max_length=255) + town: str = Field(default="", max_length=120) + postcode: str = Field(min_length=3, max_length=12) + surface_type: SurfaceType + + +@router.post("/measuring-visits") +@limiter.limit("5/minute") +async def request_measuring_visit( + request: Request, body: MeasuringVisitRequest, + db: Annotated[AsyncSession, Depends(get_db)], +) -> dict: + if sum(ch.isdigit() for ch in body.phone) < 8: + raise HTTPException(status_code=422, detail="Please enter a valid telephone number") + territory = await resolve_territory_for_postcode(db, body.postcode, body.town) + if territory is None: + raise HTTPException(status_code=422, detail="Please contact us to check coverage") + # Serialize repeat submissions for this mailbox; no customer data returned. + await db.execute(text("SELECT pg_advisory_xact_lock(hashtext(:key))"), {"key": str(body.email).lower()}) + customer = await db.scalar(select(Customer).where(func.lower(Customer.email) == str(body.email).lower())) + if customer is None: + customer = await upsert_customer(db, email=str(body.email), phone=body.phone, + full_name=body.full_name, source="website") + prop = await ensure_property(db, customer=customer, address_line1=body.address_line1, + address_line2=None, town=body.town, postcode=body.postcode, territory_id=territory.id) + existing = await db.scalar(select(Enquiry.id).where(Enquiry.customer_id == customer.id, + Enquiry.property_id == prop.id, Enquiry.intention == "measuring_visit_requested", + Enquiry.stage == PipelineStage.NEW_ENQUIRY).limit(1)) + if existing: + await db.commit() + return {"received": True} + enquiry = Enquiry(customer_id=customer.id, property_id=prop.id, surface_type=body.surface_type, + intention="measuring_visit_requested", stage=PipelineStage.NEW_ENQUIRY, + callback_phone=body.phone, message="Customer needs a measuring visit before quotation.", + utm_source="website", email_delivery="queued") + db.add(enquiry) + await db.flush() + db.add(OwnerFollowUp(enquiry_id=enquiry.id, customer_id=customer.id, + kind="measuring_visit_requested", title="Contact customer to arrange measuring visit", + due_at=datetime.now(UTC))) + subject = "Your SurfaceCoat measuring visit request" + message = "Thank you for requesting a measuring visit. Our team will contact you to agree a suitable date. No visit is booked yet." + await enqueue_notification(db, channel="workspace_email", category="measuring_visit_acknowledgement", + title=subject, body=message, dedupe_key=f"measuring-email:{enquiry.id}", + payload={"recipient": str(body.email), "subject": subject, "body": message, "enquiry_id": str(enquiry.id)}) + alert = await enqueue_notification(db, channel="telegram", category="measuring_visit", + title="New measuring visit request", body="\n".join([body.full_name, body.phone, str(body.email), + body.address_line1, body.town, body.postcode, body.surface_type.value, + "Contact customer to arrange a visit. No quotation or booking yet."]), + dedupe_key=f"measuring-telegram:{enquiry.id}") + enquiry.telegram_outbox_id = alert.id + await db.commit() + return {"received": True} diff --git a/apps/api/app/routers/quotations.py b/apps/api/app/routers/quotations.py index 7041c635..db804889 100644 --- a/apps/api/app/routers/quotations.py +++ b/apps/api/app/routers/quotations.py @@ -118,6 +118,14 @@ async def calculate_provisional_quotation( out.repair_condition_label = repair.get("condition_label") if body.surface_type.value == "tarmac" else None out.total_gbp = pricing.total_inc_vat_gbp out.vat_applied = pricing.vat_charged + try: + from app.services.anonymous_pricing import record_pricing_event + async with db.begin_nested(): + await record_pricing_event(db, body, out, pricing) + await db.commit() + except Exception: + logger.exception("Anonymous pricing event could not be recorded") + await db.rollback() return out @@ -251,6 +259,21 @@ async def list_quotations( return rows +@router.get("/anonymous-pricing") +async def anonymous_pricing_activity( + db: Annotated[AsyncSession, Depends(get_db)], + _: Annotated[User, Depends(get_current_admin)], +) -> dict: + from app.models.notifications import NotificationOutbox + rows = (await db.scalars(select(NotificationOutbox).where( + NotificationOutbox.category == "anonymous_pricing" + ).order_by(NotificationOutbox.created_at.desc()).limit(200))).all() + return {"events": [{"created_at": row.created_at.isoformat(), + **json.loads(row.payload_json).get("pricing_event", {})} + for row in rows], "limit": 200, + "basis": "Deduplicated anonymous calculations, not unique visitors or enquiries"} + + @router.get("/{quotation_id}", response_model=QuotationOut) async def get_quotation( quotation_id: UUID, @@ -399,6 +422,8 @@ async def revise_repair_price( user: Annotated[User, Depends(get_current_admin_writer)], ) -> dict: """Owner-only repair revision. Never sends a customer message or creates a job.""" + if not body.repair_price_gbp.is_finite() or not Decimal("0") <= body.repair_price_gbp <= Decimal("100000"): + raise HTTPException(422, "Enter a valid repair amount in pounds and pence") amount = ManualVolumeDiscountIn._money(body.repair_price_gbp) if (not body.repair_price_gbp.is_finite() or body.repair_price_gbp < 0 or body.repair_price_gbp > Decimal("100000") @@ -451,7 +476,7 @@ async def revise_repair_price( }) breakdown["repair_allowance"] = repair breakdown["customer_total_gbp"] = float(new_total) - breakdown["costs"]["cost_inputs_provisional"] = True + breakdown.setdefault("costs", {})["cost_inputs_provisional"] = True db.add(QuotationCalculation( quotation_id=quotation.id, version=calc.version + 1, breakdown_json=json.dumps(breakdown), @@ -481,7 +506,7 @@ async def accept_quotation( quotation_id: UUID, body: AcceptQuotationIn, db: Annotated[AsyncSession, Depends(get_db)], - _: Annotated[User, Depends(get_current_admin)], + user: Annotated[User, Depends(get_current_admin_writer)], ) -> dict: q = await db.get(Quotation, quotation_id, with_for_update=True) if q is None: @@ -493,6 +518,16 @@ async def accept_quotation( if q.requires_approval: raise HTTPException(409, "Resolve internal pricing approval first") if q.status != QuotationStatus.ACCEPTED: + calc = await db.scalar(select(QuotationCalculation).where( + QuotationCalculation.quotation_id == q.id + ).order_by(QuotationCalculation.version.desc()).limit(1)) + repair = (json.loads(calc.breakdown_json).get("repair_allowance") or {}) if calc else {} + if Decimal(str(repair.get("revised_gbp", repair.get("provisional_gbp", 0)))) > 0 and not repair.get("fixed_price_prepared"): + raise HTTPException(409, "Confirm the fixed repair price before accepting") + await record_audit(db, actor_type="user", actor_id=str(user.id), + action="quotation.customer_agreement_confirmed", entity_type="quotation", + entity_id=q.id, detail={"agreed_total_gbp": str(q.total_inc_vat_gbp), + "calculation_version": calc.version if calc else None}) q.status = QuotationStatus.ACCEPTED if q.enquiry_id: enquiry = await db.get(Enquiry, q.enquiry_id) diff --git a/apps/api/app/services/ai/employees.py b/apps/api/app/services/ai/employees.py index b8532e5b..1e7979e5 100644 --- a/apps/api/app/services/ai/employees.py +++ b/apps/api/app/services/ai/employees.py @@ -27,3 +27,7 @@ def route_employee(text): # Customer operations are scoped again at execution, using the trusted Telegram owner. TOOLS["marketing"] = TOOLS["marketing"] | frozenset({"find_customer_requests", "customer_request_details", "sales_followup_queue", "update_customer_followup", "draft_customer_reply", "marketing_growth_engine", "marketing_attributed_performance", "marketing_meta_campaign_insights", "facebook_groups_today", "facebook_groups_near_jobs"}) TOOLS["finance"] = TOOLS["finance"] | frozenset({"find_customer_requests", "customer_request_details", "sales_followup_queue", "job_cost_review"}) + +# Read-only sales evidence for specialist coordination; runtime owner checks still apply. +TOOLS["marketing"] = TOOLS["marketing"] | frozenset({"quotation_profitability", "outstanding_quotation_profitability"}) +TOOLS["finance"] = TOOLS["finance"] | frozenset({"quotation_profitability", "outstanding_quotation_profitability", "maximum_quotation_discount", "booking_deposit_status"}) diff --git a/apps/api/app/services/ai/quotation_finance_tools.py b/apps/api/app/services/ai/quotation_finance_tools.py index 79a70792..87c95bf7 100644 --- a/apps/api/app/services/ai/quotation_finance_tools.py +++ b/apps/api/app/services/ai/quotation_finance_tools.py @@ -52,14 +52,41 @@ async def saved_quotation(db: AsyncSession, reference: str) -> dict: if not isinstance(reference, str) or not 1 <= len(reference.strip()) <= 20: return {"error": "An exact existing quotation reference is required."} q = await db.scalar(select(Quotation).where( - Quotation.reference == reference.strip(), Quotation.is_test.is_(False))) + Quotation.reference == reference.strip().upper(), Quotation.is_test.is_(False))) if q is None: return {"error": "Quotation not found. Request an exact quotation reference."} calc = await db.scalar( select(QuotationCalculation).where(QuotationCalculation.quotation_id == q.id) .order_by(QuotationCalculation.version.desc()).limit(1) ) - return summarise(q, json.loads(calc.breakdown_json) if calc else {}) + result = summarise(q, json.loads(calc.breakdown_json) if calc else {}) + from app.models.crm import Enquiry, OwnerFollowUp + enquiry = await db.get(Enquiry, q.enquiry_id) if q.enquiry_id else None + if enquiry and not enquiry.is_test: + tasks = (await db.scalars(select(OwnerFollowUp).where( + OwnerFollowUp.enquiry_id == enquiry.id, + OwnerFollowUp.status == "open", + ).order_by(OwnerFollowUp.created_at).limit(10))).all() + result["enquiry"] = { + "stage": enquiry.stage.value, + "intention": enquiry.intention, + "email_delivery": enquiry.email_delivery, + "telegram_notified": enquiry.telegram_notified, + "open_follow_ups": [{"title": task.title, "due_at": task.due_at.isoformat() if task.due_at else None} for task in tasks], + } + from app.models.audit import AuditEvent + assessments = (await db.scalars(select(AuditEvent).where( + AuditEvent.action == "quotation_photo_assessed", + AuditEvent.entity_type == "quotation", + AuditEvent.entity_id == str(q.id), + AuditEvent.actor_type == "system", + ).order_by(AuditEvent.created_at.desc()).limit(5))).all() + result["photo_assessments"] = [ + {"created_at": event.created_at.isoformat(), "untrusted_advisory_text": json.loads(event.detail_json).get("assessment", "")[:2000]} + for event in assessments + ] + result["review_note"] = "Saved estimate only. External messaging photographs are not automatically linked. Confirm final scope and price with owner before booking." + return result async def outstanding_quotations(db: AsyncSession) -> dict: @@ -93,7 +120,7 @@ async def maximum_margin_discount(db: AsyncSession, reference: str, target_margi return row if not target_margin.is_finite() or not D("0") <= target_margin < D("95"): return {"error": "Margin target must be between 0 and 95%."} - q = await db.scalar(select(Quotation).where(Quotation.reference == reference.strip())) + q = await db.scalar(select(Quotation).where(Quotation.reference == reference.strip().upper(), Quotation.is_test.is_(False))) if q.vat_charged: return {"error": "VAT-inclusive discount threshold needs manual tax review."} original = _money(row["original_gbp"]) diff --git a/apps/api/app/services/anonymous_pricing.py b/apps/api/app/services/anonymous_pricing.py new file mode 100644 index 00000000..8dd69c81 --- /dev/null +++ b/apps/api/app/services/anonymous_pricing.py @@ -0,0 +1,52 @@ +"""Anonymous price activity, separate from customer enquiries.""" +from datetime import UTC, datetime +import hashlib +import json +import re + +from sqlalchemy import select +from app.models.notifications import NotificationOutbox +from app.services.notifications.outbox import enqueue_notification +from app.services.quotation_workflow import section_area + + +def pricing_event(body, out, pricing): + postcode = re.sub(r"\s+", "", body.postcode.upper()) + district = postcode[:-3] if len(postcode) > 3 else postcode + sections = [{"length_m": str(s.length_m) if s.length_m else None, + "width_m": str(s.width_m) if s.width_m else None, + "area_sqm": str(section_area(s))} for s in body.sections] + costs = pricing.breakdown.get("costs") or {} + return {"postcode_district": district, "service": body.service_slug, + "surface": body.surface_type.value, "condition": body.surface_condition.value, + "sections": sections, "area_sqm": str(out.total_area_sqm), + "total_gbp": str(out.total_gbp), "discount_percent": str(out.discount_percent), + "estimated_cost_gbp": costs.get("total_cost_gbp"), + "estimated_profit_gbp": costs.get("estimated_profit_gbp"), + "repair_allowance_gbp": str(out.repair_allowance_gbp)} + + +async def record_pricing_event(db, body, out, pricing): + event = pricing_event(body, out, pricing) + # Identical anonymous inputs within a UTC ten-minute bucket are collapsed. + bucket = int(datetime.now(UTC).timestamp()) // 600 + digest = hashlib.sha256(json.dumps(event, sort_keys=True).encode()).hexdigest() + key = f"anonymous-price:{bucket}:{digest}" + existing = await db.scalar(select(NotificationOutbox.id).where(NotificationOutbox.dedupe_key == key)) + if existing: + return + lines = [f"Area: {event['postcode_district']}", f"Service: {event['service']}", + f"Condition: {event['condition']}", f"Total area: {event['area_sqm']} m²"] + for section in event["sections"][:10]: + lines.append(f"Section: {section['length_m']} x {section['width_m']} m; {section['area_sqm']} m²" + if section["length_m"] and section["width_m"] else f"Section: {section['area_sqm']} m²") + lines.extend([f"Estimated price: £{event['total_gbp']}", + f"Volume discount: {event['discount_percent']}%", + f"Provisional repairs: £{event['repair_allowance_gbp']}"]) + for label, field in [("Estimated cost", "estimated_cost_gbp"), ("Estimated profit", "estimated_profit_gbp")]: + if event[field] is not None: + lines.append(f"{label}: £{event[field]}") + lines.append("Anonymous calculation only. No contact details or booking request.") + await enqueue_notification(db, channel="telegram", category="anonymous_pricing", + title="New website price calculation", body="\n".join(lines), + dedupe_key=key, payload={"pricing_event": event}) diff --git a/apps/api/app/services/briefing_service.py b/apps/api/app/services/briefing_service.py index 745dcb89..bfab22c6 100644 --- a/apps/api/app/services/briefing_service.py +++ b/apps/api/app/services/briefing_service.py @@ -80,4 +80,31 @@ async def generate_briefing(db: AsyncSession, kind: BriefingKind) -> BriefingRec record = BriefingRecord(kind=kind, content_json=json.dumps(payload)) db.add(record) await db.flush() - return record \ No newline at end of file + return record + +async def queue_daily_sales_report(db: AsyncSession) -> None: + from app.models.crm import Enquiry, OwnerFollowUp, PipelineStage + from app.services.notifications.outbox import enqueue_notification + now = datetime.now(UTC) + query = select(OwnerFollowUp, Quotation).join( + Enquiry, Enquiry.id == OwnerFollowUp.enquiry_id + ).join(Quotation, Quotation.id == OwnerFollowUp.quotation_id).where( + OwnerFollowUp.status == "open", + OwnerFollowUp.due_at <= now, + Enquiry.is_test.is_(False), + Quotation.is_test.is_(False), + Enquiry.stage.in_([PipelineStage.NEW_ENQUIRY, PipelineStage.AWAITING_INFORMATION, + PipelineStage.AWAITING_PHOTOGRAPHS, PipelineStage.QUOTE_GENERATED, + PipelineStage.QUOTE_SENT, PipelineStage.BOOKING_PENDING]), + Quotation.status.in_([QuotationStatus.PROVISIONAL, QuotationStatus.PENDING_APPROVAL, + QuotationStatus.SENT]), + ) + count = await db.scalar(select(func.count()).select_from(query.subquery())) + rows = (await db.execute(query.order_by(OwnerFollowUp.due_at, OwnerFollowUp.id).limit(10))).all() + lines = [f"Due sales follow-up actions: {count or 0}"] + for task, quote in rows: + lines.append(f"{quote.reference}: £{quote.total_inc_vat_gbp} estimated; {task.title}") + lines.append("Review CRM before contacting customers. No customer messages sent.") + await enqueue_notification(db, channel="telegram", category="quotation", + title="SurfaceCoat daily sales follow-ups", body="\n".join(lines), + dedupe_key=f"daily-sales-followups:{now.astimezone(ZoneInfo('Europe/London')).date()}") diff --git a/apps/api/app/services/notifications/customer_requests.py b/apps/api/app/services/notifications/customer_requests.py index 6bda01ad..787f3d5c 100644 --- a/apps/api/app/services/notifications/customer_requests.py +++ b/apps/api/app/services/notifications/customer_requests.py @@ -15,6 +15,9 @@ def acknowledgement_text(*, name, reference, postcode, service, area, total, bre "repair_review_requested": "We've received your repair quotation request. We'll discuss the damage with you and may request photographs before confirming a fixed quotation.", "estimate_requested": "Thank you for requesting your SurfaceCoat estimate. Here is a copy for your records.", }[intention] + photo_guidance = [] + if intention in {"ready_to_book", "repair_review_requested", "flexible_booking"}: + photo_guidance = ["", "Please send a photograph of the whole driveway and close-ups of any damage. Include your quotation reference. You can reply to this email with photographs, or use the messaging options shown after submitting your enquiry.", ""] discount = breakdown.get("volume_discount") or {} repair = breakdown.get("repair_allowance") or {} lines = [f"Hello {name},", "", introduction, "", f"Reference: {reference}", @@ -29,6 +32,7 @@ def acknowledgement_text(*, name, reference, postcode, service, area, total, bre "This email acknowledges your request. It is not a confirmed appointment or a fixed repair quotation.", "Any repairs, changes to the work and final price will be agreed with you before booking. Coating dates depend on suitable weather and surface conditions.", "", "You can reply to this email with any questions.", "", "SurfaceCoat Ltd", "Restore. Protect. Transform."] + lines[-3:-3] = photo_guidance return "\n".join(lines) diff --git a/apps/api/app/services/quote_conversion.py b/apps/api/app/services/quote_conversion.py index d212269f..814b97a7 100644 --- a/apps/api/app/services/quote_conversion.py +++ b/apps/api/app/services/quote_conversion.py @@ -41,8 +41,8 @@ FOLLOW_UP_TITLES = { FLEXIBLE_BOOKING: "Contact customer to agree discounted price and area-matched dates", - REPAIR_REVIEW_REQUESTED: "Contact customer, request repair photos if needed, confirm fixed quotation", - READY_TO_BOOK: "Contact customer to agree a restoration visit", + REPAIR_REVIEW_REQUESTED: "Review customer photographs and confirm fixed repair quotation", + READY_TO_BOOK: "Review driveway photographs, confirm final price and agree restoration dates", CALLBACK_REQUESTED: "Return the customer's callback request", ESTIMATE_REQUESTED: "Follow up the saved estimate", } @@ -296,7 +296,7 @@ async def build_owner_alert( sections.append(f"{row.label}: {row.area_sqm} m²") measures = "; ".join(sections) or area photos_attached, photo_count = await _photo_status(db, quotation.id) if quotation else (False, 0) - photo_line = f"{photo_count} attached" if photos_attached else "none yet — request during follow-up if needed" + photo_line = f"{photo_count} attached" if photos_attached else "No website uploads recorded; customer may send photos separately by messaging or email" test_line = "TEST RECORD — exclude from revenue and marketing.\n" if enquiry.is_test else "" callback_line = "" if enquiry.intention == CALLBACK_REQUESTED and enquiry.callback_preferred_time: diff --git a/apps/api/app/services/telegram/driveway_vision.py b/apps/api/app/services/telegram/driveway_vision.py index bd21e6a1..865b7ee2 100644 --- a/apps/api/app/services/telegram/driveway_vision.py +++ b/apps/api/app/services/telegram/driveway_vision.py @@ -7,6 +7,19 @@ async def analyse_driveway(db, file_id: str, caption: str) -> str: + import re + from sqlalchemy import select + from app.models.quotation import Quotation + from app.services.audit import record_audit + refs = set(re.findall(r"\bSC-\d{8}-[A-F0-9]{4}\b", caption.upper())) + quote = None + if len(refs) > 1: + return "Please send one quotation reference per photo." + if refs: + quote = await db.scalar(select(Quotation).where( + Quotation.reference == next(iter(refs)), Quotation.is_test.is_(False))) + if quote is None: + return "Quotation reference not found. Check the reference and resend the photo." cfg = get_settings() if not cfg.openai_api_key: return "Photo analysis unavailable: OpenAI is not configured." @@ -31,4 +44,13 @@ async def analyse_driveway(db, file_id: str, caption: str) -> str: usage = payload.get("usage", {}) prompt, completion = int(usage.get("prompt_tokens", 0)), int(usage.get("completion_tokens", 0)) await record_usage(db, provider="openai", model=cfg.openai_model, agent_slug="personal_assistant", prompt_tokens=prompt, completion_tokens=completion, estimated_cost_gbp=estimate_openai_cost_gbp(prompt, completion, cfg.openai_model)) - return "Photo assessment (site inspection required):\n" + (payload["choices"][0]["message"].get("content") or "No assessment available.") + assessment = payload["choices"][0]["message"].get("content") or "" + if not assessment: + return "No assessment available." + if quote is not None: + await record_audit(db, actor_type="system", actor_id=None, + action="quotation_photo_assessed", entity_type="quotation", entity_id=quote.id, + detail={"assessment": assessment[:6000], "reference": quote.reference, + "basis": "Owner-forwarded photo, advisory only"}) + return f"Quotation {quote.reference}: saved advisory assessment.\n" + assessment + return "Photo assessment (site inspection required):\n" + assessment diff --git a/apps/api/app/worker/tasks.py b/apps/api/app/worker/tasks.py index 9c6e3fc5..6ce13357 100644 --- a/apps/api/app/worker/tasks.py +++ b/apps/api/app/worker/tasks.py @@ -185,13 +185,15 @@ def morning_briefing(self) -> dict: try: from app.database import SessionLocal as AsyncSessionLocal from app.models.briefings import BriefingKind - from app.services.briefing_service import generate_briefing + from app.services.briefing_service import generate_briefing, queue_daily_sales_report async def _brief(): async with AsyncSessionLocal() as db: record = await generate_briefing(db, BriefingKind.MORNING) + await queue_daily_sales_report(db) + payload = json.loads(record.content_json) await db.commit() - return json.loads(record.payload_json) + return payload payload = asyncio.run(_brief()) detail = {"sections": list(payload.keys())} diff --git a/apps/api/tests/test_route_auth_allowlist.py b/apps/api/tests/test_route_auth_allowlist.py index afc2490b..e8aa96eb 100644 --- a/apps/api/tests/test_route_auth_allowlist.py +++ b/apps/api/tests/test_route_auth_allowlist.py @@ -9,6 +9,8 @@ from app.rate_limit import client_ip PUBLIC_ROUTES = { + # Public, rate-limited measuring visit submission; no CRM records returned. + ("POST", "/api/v1/crm/measuring-visits"), # Sign-in / sign-out / owner recovery (setup-key gated, compare_digest, 5/min) ("POST", "/api/v1/auth/token"), ("POST", "/api/v1/auth/login"), diff --git a/apps/web/e2e/public-quote-real.spec.ts b/apps/web/e2e/public-quote-real.spec.ts index b5e11ea3..12ee3974 100644 --- a/apps/web/e2e/public-quote-real.spec.ts +++ b/apps/web/e2e/public-quote-real.spec.ts @@ -18,23 +18,24 @@ async function openTarmacQuote(page: Page, condition: "good" | "minor") { } await page.getByRole("button", { name: "Continue" }).click(); await page.getByRole("button", { name: "Continue" }).click(); - await expect(page.getByText("Your estimated quotation", { exact: true })).toBeVisible({ timeout: 30_000 }); + await expect(page.getByText("Your SurfaceCoat quotation", { exact: true })).toBeVisible({ timeout: 30_000 }); + await page.getByText("View price breakdown", { exact: true }).click(); await expect(page.getByText("Original restoration price")).toBeVisible(); await expect(page.getByText("Discounted restoration price")).toBeVisible(); - await expect(page.getByText("Total estimated quotation")).toBeVisible(); + await expect(page.getByText("Total quotation")).toBeVisible(); await expect(page.getByRole("button", { name: "Upload driveway photos" })).toHaveCount(0); } test("undamaged tarmac retains the existing booking request journey without photo friction", async ({ page }) => { await openTarmacQuote(page, "good"); - await expect(page.getByText("Provisional repair allowance")).toBeVisible(); - await expect(page.getByRole("button", { name: "Book me in ASAP" })).toBeVisible(); - await page.getByRole("button", { name: "Book me in ASAP" }).click(); + await expect(page.getByText("Included repair allowance")).toHaveCount(0); + await expect(page.getByRole("button", { name: "Happy with my price" })).toBeVisible(); + await page.getByRole("button", { name: "Happy with my price" }).click(); await page.getByLabel("Your name").fill("Good Driveway Test"); await page.getByLabel("Email").fill("good.driveway@example.co.uk"); await page.getByLabel("Telephone").fill("07123456789"); await page.getByLabel("Property address").fill("1 Test Lane"); - await page.getByRole("button", { name: "Book me in ASAP" }).click(); + await page.getByRole("button", { name: "Send my enquiry" }).click(); const problem = page.locator("p.text-red-700"); const heading = page.getByRole("heading", { name: "Thank you for choosing SurfaceCoat" }); await expect(heading.or(problem)).toBeVisible({ timeout: 30_000 }); @@ -45,15 +46,15 @@ test("undamaged tarmac retains the existing booking request journey without phot test("minor tarmac damage receives separate provisional repair estimate and human follow-up", async ({ page }) => { await openTarmacQuote(page, "minor"); - await expect(page.getByText(/Provisional repair allowance/)).toBeVisible(); - await expect(page.getByText(/may request a few photographs/)).toBeVisible(); - await expect(page.getByRole("button", { name: "Book me in ASAP" })).toHaveCount(0); - await page.getByRole("button", { name: "Request my quotation" }).click(); + await expect(page.getByText("Included repair allowance", { exact: true })).toBeVisible(); + await expect(page.getByText(/Your quotation includes a repair allowance/)).toBeVisible(); + await expect(page.getByRole("button", { name: "Happy with my price" })).toHaveCount(0); + await page.getByRole("button", { name: "Confirm my repair costs" }).click(); await page.getByLabel("Your name").fill("Repair Review Test"); await page.getByLabel("Email").fill("repair.review@example.co.uk"); await page.getByLabel("Telephone").fill("07123456789"); await page.getByLabel("Property address").fill("2 Test Lane"); - await page.getByRole("button", { name: "Request my quotation" }).click(); + await page.getByRole("button", { name: "Send my repair review request" }).click(); const problem = page.locator("p.text-red-700"); const heading = page.getByRole("heading", { name: "Thank you for choosing SurfaceCoat" }); await expect(heading.or(problem)).toBeVisible({ timeout: 30_000 }); diff --git a/apps/web/src/components/quote/quote-wizard.tsx b/apps/web/src/components/quote/quote-wizard.tsx index cc59544e..fef0e60a 100644 --- a/apps/web/src/components/quote/quote-wizard.tsx +++ b/apps/web/src/components/quote/quote-wizard.tsx @@ -141,6 +141,7 @@ const IDEMPOTENCY_KEY = "rmd_quote_idempotency"; export function QuoteWizard() { const searchParams = useSearchParams(); const [step, setStep] = useState(0); + const [measuringVisit, setMeasuringVisit] = useState(false); const [state, setState] = useState(() => defaultState(searchParams.get("postcode") ?? "")); const [loading, setLoading] = useState(false); @@ -366,6 +367,7 @@ export function QuoteWizard() { await calculateProvisional(); } + if (measuringVisit) return setMeasuringVisit(false)} />; return (
@@ -411,7 +413,7 @@ export function QuoteWizard() { )} {step === 1 && } {step === 2 && ( - + <>

Struggling to measure your driveway?

We can arrange a visit to measure your surface and provide a quotation.

)} {step === 3 && } {step === 4 && } @@ -724,96 +726,52 @@ function QuoteResultCard({ result: ProvisionalQuotation; onChoose: (intention: QuoteState["intention"]) => void; }) { + const repairs = Number(result.repair_allowance_gbp ?? 0) > 0; + const money = (value: string | number | null | undefined) => "£" + Number(value ?? 0).toFixed(2); + const cleanTitle = (title: string) => title.replace(/Marl Coatings |Creteprint /g, ""); return ( -
-

Your estimated quotation

- -

- £{Number(result.total_gbp).toFixed(2)} - {result.vat_applied ? ( - including VAT - ) : null} -

-
-
Original restoration price
£{Number(result.original_total_gbp ?? result.total_gbp).toFixed(2)}
-
Surface area discount ({Number(result.discount_percent ?? 0)}%)
−£{Number(result.discount_saving_gbp ?? 0).toFixed(2)}
-
Discounted restoration price
£{Number(result.restoration_discounted_gbp ?? result.total_gbp).toFixed(2)}
- {result.repair_condition_label && ( -
Provisional repair allowance{result.repair_allowance_gbp && Number(result.repair_allowance_gbp) > 0 ? " (subject to assessment)" : ""}
£{Number(result.repair_allowance_gbp ?? 0).toFixed(2)}
- )} -
Total estimated quotation
£{Number(result.total_gbp).toFixed(2)}
-
- {Number(result.repair_allowance_gbp ?? 0) > 0 && ( -

- Happy with your estimated quotation? Simply send us your details and a member of our team will be in touch. - We’ll discuss any necessary repairs and may request a few photographs of your driveway to assess the damage and - confirm your final price before arranging your booking. All repair costs are provisional until assessed. -

- )} -
-
    - {result.included.map((item) => ( -
  • -

    {item.title}

    -

    {item.detail}

    -
  • - ))} -
-
    - {result.visits.map((item) => ( -
  • -

    {item.title}

    -

    {item.detail}

    -
  • - ))} -
- {result.requires_review && ( -
-

Quotation review

-

Any proposed repair allowance must be reviewed before we confirm a fixed quotation or booking.

-
- )} -

{result.repairs_note}

-

{result.customer_note}

-
- {Number(result.repair_allowance_gbp ?? 0) > 0 ? ( - <> - - - - ) : ( - <> - -
-

Flexible on dates? Save on your restoration.

-

If you're happy to arrange your restoration for when we're already working in your area, we'll offer you a discounted price.

-

Our team will contact you personally to discuss available dates and your reduced price.

- -

No obligation to book.

-
- - - - )} +
+
+

Your SurfaceCoat quotation

+

{money(result.total_gbp)}

+ {result.vat_applied &&

Including VAT

} + {Number(result.discount_percent ?? 0) > 0 &&

{Number(result.discount_percent)}% volume discount · You save {money(result.discount_saving_gbp)}

} + {!repairs &&

Fixed restoration price based on your supplied measurements.

}
+ {repairs &&
+
Fixed restoration price
{money(result.restoration_discounted_gbp)}
+
Included repair allowance
{money(result.repair_allowance_gbp)}
+
} +
+

{repairs ? "Let's confirm your repairs" : "Ready to transform your driveway?"}

+

{repairs ? "Your quotation includes a repair allowance. Send us your details and photographs so we can confirm your final price." : "Send us your details and we'll be in touch to arrange your restoration."}

+ {result.requires_review && !repairs &&

Our team will review your quotation before confirming your booking.

} +
+ + +
+

Your price includes

+
    {result.included.map(item =>
  • ✓ {cleanTitle(item.title)}
  • )}
+
+
+ View price breakdown +
+
Original restoration price
{money(result.original_total_gbp ?? result.total_gbp)}
+
Surface area discount
{money(result.discount_saving_gbp)}
+
Discounted restoration price
{money(result.restoration_discounted_gbp ?? result.total_gbp)}
+ {repairs &&
Repair allowance (subject to review)
{money(result.repair_allowance_gbp)}
} +
Total quotation
{money(result.total_gbp)}
+
+
+
+ How your restoration works +
    {result.visits.map(item =>
  • {cleanTitle(item.title)}

    {item.detail}

  • )}
+
+ {!repairs &&
+ Other options + + +
}
); } @@ -877,6 +835,9 @@ function StepContact({
{saved.reference}
+ {["ready_to_book", "repair_review_requested", "flexible_booking"].includes(state.intention) && ( + + )}

What happens next

    {steps.map((item, index) => ( @@ -899,14 +860,14 @@ function StepContact({ } const title = - state.intention === "repair_review_requested" ? "Request your quotation" : state.intention === "ready_to_book" + state.intention === "repair_review_requested" ? "Confirm your repair costs" : state.intention === "ready_to_book" ? "Send a booking request" : state.intention === "callback_requested" ? "Request a callback" : state.intention === "flexible_booking" ? "Request a discounted price" : "Email me my estimate"; const submitLabel = - state.intention === "repair_review_requested" ? "Request my quotation" : state.intention === "ready_to_book" - ? "Book me in ASAP" + state.intention === "repair_review_requested" ? "Send my repair review request" : state.intention === "ready_to_book" + ? "Send my enquiry" : state.intention === "callback_requested" ? "Request my callback" : state.intention === "flexible_booking" ? "Send my flexible booking request" : "Email my estimate"; @@ -1010,4 +971,51 @@ function StepContact({ )}
); -} \ No newline at end of file +} + +function MessagingHandoff({ reference, total }: { reference: string; total: string | number }) { + const rawPhone = (process.env.NEXT_PUBLIC_BUSINESS_MOBILE ?? "").replace(/[\s()-]/g, ""); + const phone = rawPhone.startsWith("07") ? "+44" + rawPhone.slice(1) : rawPhone; + const valid = /^\+447\d{9}$/.test(phone); + const message = "Hi SurfaceCoat, I'd like to discuss my estimated quotation. Reference: " + reference + + ". Estimated price: £" + Number(total).toFixed(2) + + ". I'd like to discuss booking and send photos of my driveway."; + return
+

Send us your driveway photos

+

Please include a photo of the whole surface and close-ups of any cracks, potholes or other damage. We will review them and confirm your final price before booking.

+ {valid ? :

Your enquiry is saved. Our team will contact you to arrange photo review.

} +

No payment or booking is confirmed at this stage.

+
; +} + + +function MeasuringVisitForm({state, onBack}: {state: QuoteState; onBack: () => void}) { + const [details, setDetails] = useState({full_name: state.full_name, email: state.email, phone: state.phone, address_line1: state.address_line1, town: state.town, postcode: state.postcode}); + const [busy, setBusy] = useState(false); + const [received, setReceived] = useState(false); + const [error, setError] = useState(""); + async function submit() { + if (busy) return; + setBusy(true); setError(""); + try { + await apiPost("/api/v1/crm/measuring-visits", {...details, surface_type: state.surface_type}); + setReceived(true); + } catch (err) { setError(err instanceof Error ? err.message : "Please try again."); } + finally { setBusy(false); } + } + return
+ {received ? <>

Measuring visit requested

Thank you. Our team will contact you to arrange a suitable date. No visit is booked yet.

Return to homepage : +
{e.preventDefault(); void submit();}} className="space-y-4"> +

Request a measuring visit

+

Send us your details and we will contact you to arrange a visit.

+ {([["full_name","Your name","text"],["email","Email","email"],["phone","Telephone","tel"],["address_line1","Property address","text"],["town","Town","text"],["postcode","Postcode","text"]] as const).map(([key,label,type]) => )} + {error &&

{error}

} + + +
} +
; +}