defmodule CustomerService.Projectors.QuickLead do use Commanded.Projections.Ecto, application: CustomerService.CommandedApp, repo: CustomerService.Repo, name: "CustomerService.Projectors.QuickLead", consistency: :strong alias CustomerService.Events alias CustomerService.Projections.QuickLead alias CustomerService.Aggregates.LeadId project(%Events.QuickLeadCreated{} = event, fn multi -> %CustomerService.Aggregates.LeadId{org_id: org_id, lead_id: lead_id} = event.id Ecto.Multi.insert(multi, :quick_lead, %QuickLead{ id: to_string(event.id), org_id: org_id, lead_id: lead_id, name: event.name, email: event.email, phone: event.phone, company_name: event.company_name, status: to_string(event.status), priority: to_string(event.priority), source: to_string(event.source), notes: event.notes, assigned_to: event.assigned_to, estimated_value: event.estimated_value, expected_close_date: parse_date(event.expected_close_date), status_history: [ %{ status: to_string(event.status), updated_at: DateTime.utc_now(), notes: "Lead created" } ] }) end) project(%Events.QuickLeadUpdated{} = event, _meta, fn multi -> composite_id = to_string(event.id) Ecto.Multi.update_all(multi, :quick_lead, from(q in QuickLead, where: q.id == ^composite_id), set: [ name: event.name, email: event.email, phone: event.phone, company_name: event.company_name, notes: event.notes, assigned_to: event.assigned_to, estimated_value: event.estimated_value, expected_close_date: parse_date(event.expected_close_date) ] ) end) project(%Events.LeadStatusUpdated{} = event, _meta, fn multi -> composite_id = to_string(event.id) Ecto.Multi.update_all(multi, :quick_lead, from(q in QuickLead, where: q.id == ^composite_id), set: [ status: to_string(event.status) ] ) end) defp parse_date(nil), do: nil defp parse_date(%Date{} = d), do: d defp parse_date(str) when is_binary(str) do case Date.from_iso8601(str) do {:ok, d} -> d _ -> nil end end end