Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
83d2f33
Add saved quotation WhatsApp and Messages handoff with configurable b…
cwhel2026 Dec 1, 2026
a8785bd
Include photo handoff guidance in transactional customer acknowledgement
cwhel2026 Dec 1, 2026
4b67338
Align CRM follow-up tasks with manual photo review and final price ag…
cwhel2026 Dec 1, 2026
2c85167
Extend existing quotation lookup with CRM stage and open owner actions
cwhel2026 Dec 1, 2026
a1417e0
Resolve explicit quotation references in Telegram driveway photos and…
cwhel2026 Dec 1, 2026
c88bec1
Persist successful quotation photo assessments with correct audit sig…
cwhel2026 Dec 1, 2026
c4b4a4c
Retrieve recent advisory photo assessments with saved quote
cwhel2026 Dec 1, 2026
a0af665
Require writer authority and fixed repair pricing for recorded custom…
cwhel2026 Dec 1, 2026
73e18c3
Expose existing read-only quotation evidence to Olivia and Arthur
cwhel2026 Dec 1, 2026
a666f2d
Distinguish website photo status from external customer messages
cwhel2026 Dec 1, 2026
2315191
Add bounded daily due-sales report using genuine CRM tasks
cwhel2026 Dec 1, 2026
2e03fb8
Queue daily sales follow-up report in existing morning schedule and f…
cwhel2026 Dec 1, 2026
c835f46
Validate UK mobile numbers and avoid implying flexible estimate accep…
cwhel2026 Dec 1, 2026
1cf0ee1
Persist anonymous pricing events via deduplicated notification outbox
cwhel2026 Dec 1, 2026
bf5647f
Record successful anonymous estimates and expose owner-only activity …
cwhel2026 Dec 1, 2026
f69e861
Update quote journey tests for new estimate CTA labels
cwhel2026 Dec 1, 2026
5fb7a49
Keep contact form submission selectors aligned with actual button labels
cwhel2026 Dec 1, 2026
8ca01b7
Simplify mobile quote result and separate repair confirmation journey
cwhel2026 Dec 1, 2026
6c46f2b
Test compact quotation layout and separate repair review CTA
cwhel2026 Dec 1, 2026
6a340a9
Add public measuring visit request with CRM follow-up and notificatio…
cwhel2026 Dec 1, 2026
8c2d3f1
Add measurement bypass and dedicated customer visit request form
cwhel2026 Dec 1, 2026
54f640e
Allowlist only the public rate-limited measuring visit submission
cwhel2026 Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 68 additions & 1 deletion apps/api/app/routers/crm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}
39 changes: 37 additions & 2 deletions apps/api/app/routers/quotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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:
Expand All @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions apps/api/app/services/ai/employees.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"})
33 changes: 30 additions & 3 deletions apps/api/app/services/ai/quotation_finance_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"])
Expand Down
52 changes: 52 additions & 0 deletions apps/api/app/services/anonymous_pricing.py
Original file line number Diff line number Diff line change
@@ -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})
29 changes: 28 additions & 1 deletion apps/api/app/services/briefing_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
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()}")
4 changes: 4 additions & 0 deletions apps/api/app/services/notifications/customer_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}",
Expand All @@ -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)


Expand Down
Loading
Loading