From 3cdb9c2ba27f26bc32abdeaced141abda449a6ce Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Sun, 15 Nov 2026 06:24:33 +0100 Subject: [PATCH 1/6] fix(security): clear CodeQL log-injection alerts on credit notes Sanitize logged route IDs and stop echoing exception text to clients so credit-note create/PDF/XML handlers no longer trip log-injection or stack-trace exposure findings. --- app/routes/credit_notes.py | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/app/routes/credit_notes.py b/app/routes/credit_notes.py index 81f44883..cec565fd 100644 --- a/app/routes/credit_notes.py +++ b/app/routes/credit_notes.py @@ -24,6 +24,7 @@ from app import db from app.models import Invoice from app.models.payments import CreditNote +from app.utils.error_handling import DEFAULT_CLIENT_ERROR, sanitize_log_value from app.utils.module_helpers import module_enabled credit_notes_bp = Blueprint("credit_notes", __name__, url_prefix="/credit-notes") @@ -107,10 +108,12 @@ def create_from_invoice(invoice_id): flash(_("Credit note %(cn)s created.", cn=cn.credit_number), "success") return redirect(url_for("credit_notes.view_credit_note", cn_id=cn.id)) - except Exception as exc: + except Exception: db.session.rollback() - logger.exception("Failed to create credit note for invoice %s", invoice_id) - flash(_("Could not create credit note: %(err)s", err=str(exc)), "error") + logger.exception( + "Failed to create credit note for invoice %s", sanitize_log_value(invoice_id) + ) + flash(_("Could not create credit note."), "error") return redirect(url_for("invoices.view_invoice", invoice_id=invoice_id)) @@ -173,9 +176,11 @@ def download_pdf(cn_id): from app.utils.credit_note_pdf import generate_credit_note_pdf pdf_bytes = generate_credit_note_pdf(cn) - except Exception as exc: - logger.exception("Credit note PDF generation failed for cn=%s", cn_id) - abort(500, description=str(exc)) + except Exception: + logger.exception( + "Credit note PDF generation failed for cn=%s", sanitize_log_value(cn_id) + ) + abort(500, description=DEFAULT_CLIENT_ERROR) filename = f"credit-note-{cn.credit_number}.pdf" return send_file( @@ -217,9 +222,11 @@ def download_ubl(cn_id): name=invoice.client_name or "Customer", ) xml_str, _ = build_peppol_ubl_credit_note_xml(cn, invoice, supplier, customer) - except Exception as exc: - logger.exception("UBL credit note XML build failed for cn=%s", cn_id) - abort(500, description=str(exc)) + except Exception: + logger.exception( + "UBL credit note XML build failed for cn=%s", sanitize_log_value(cn_id) + ) + abort(500, description=DEFAULT_CLIENT_ERROR) filename = f"credit-note-{cn.credit_number}-ubl.xml" return Response( @@ -245,9 +252,11 @@ def download_fatturapa(cn_id): settings = Settings.get_settings() client = Client.query.get(invoice.client_id) if invoice.client_id else None xml_bytes, filename = build_fatturapa_credit_note_xml(cn, invoice, settings, client) - except Exception as exc: - logger.exception("FatturaPA credit note XML build failed for cn=%s", cn_id) - abort(500, description=str(exc)) + except Exception: + logger.exception( + "FatturaPA credit note XML build failed for cn=%s", sanitize_log_value(cn_id) + ) + abort(500, description=DEFAULT_CLIENT_ERROR) return Response( xml_bytes, From 1e851131192ee73ada86af78bb65599066af8d6b Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Sun, 15 Nov 2026 08:12:05 +0100 Subject: [PATCH 2/6] feat(crm): close remaining CRM gaps across API, web, and clients Add activities, conversion, pipeline stage moves, forecast, and source analytics to the API; ship pipeline drag-and-drop, communication templates, and calendar reminders on web; fix desktop/mobile field mapping and email-to-deal matching; and prevent Settings timezone lookups from rolling back in-flight CRM mutations. --- app/models/__init__.py | 2 + app/models/crm_communication_template.py | 50 ++++ app/models/deal.py | 16 +- app/models/lead.py | 17 +- app/routes/api_v1.py | 8 + app/routes/api_v1_contacts.py | 46 ++++ app/routes/api_v1_deals.py | 189 +++++++++++++++ app/routes/api_v1_leads.py | 224 ++++++++++++++++- app/routes/contacts.py | 91 +++++++ app/routes/deals.py | 101 +++++++- app/routes/leads.py | 74 +++++- app/services/email_sync_service.py | 22 +- .../contacts/communication_form.html | 39 +++ app/templates/contacts/template_form.html | 56 +++++ app/templates/contacts/templates_list.html | 48 ++++ app/templates/deals/forecast.html | 57 +++++ app/templates/deals/list.html | 2 +- app/templates/deals/pipeline.html | 102 +++++++- app/templates/leads/list.html | 2 +- app/templates/leads/source_analytics.html | 51 ++++ app/templates/partials/_sidebar.html | 17 ++ app/utils/crm_calendar.py | 46 ++++ app/utils/timezone.py | 19 +- .../src/renderer-react/src/views/CrmView.jsx | 34 ++- docs/CRM_FEATURES_IMPLEMENTATION.md | 35 +-- docs/CRM_IMPLEMENTATION_SUMMARY.md | 37 +-- docs/FEATURES_COMPLETE.md | 6 +- docs/api/API_TOKEN_SCOPES.md | 30 +++ docs/api/REST_API.md | 39 +++ .../213_crm_communication_templates.py | 51 ++++ mobile/lib/data/api/api_client.dart | 6 +- .../screens/client_detail_screen.dart | 30 ++- .../presentation/screens/crm_hub_screen.dart | 13 +- tests/test_api_crm_v1.py | 225 ++++++++++++++++++ 34 files changed, 1666 insertions(+), 119 deletions(-) create mode 100644 app/models/crm_communication_template.py create mode 100644 app/templates/contacts/template_form.html create mode 100644 app/templates/contacts/templates_list.html create mode 100644 app/templates/deals/forecast.html create mode 100644 app/templates/leads/source_analytics.html create mode 100644 app/utils/crm_calendar.py create mode 100644 migrations/versions/213_crm_communication_templates.py create mode 100644 tests/test_api_crm_v1.py diff --git a/app/models/__init__.py b/app/models/__init__.py index 0a14ed38..36a046bb 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -30,6 +30,7 @@ from .comment_attachment import CommentAttachment from .contact import Contact from .contact_communication import ContactCommunication +from .crm_communication_template import CrmCommunicationTemplate from .currency import Currency, ExchangeRate from .custom_field_definition import CustomFieldDefinition from .custom_report import CustomReportConfig @@ -234,6 +235,7 @@ "PurchaseOrderItem", "Contact", "ContactCommunication", + "CrmCommunicationTemplate", "Deal", "DealActivity", "DeletedUsername", diff --git a/app/models/crm_communication_template.py b/app/models/crm_communication_template.py new file mode 100644 index 00000000..65785214 --- /dev/null +++ b/app/models/crm_communication_template.py @@ -0,0 +1,50 @@ +"""Reusable templates for CRM contact communications.""" + +from app import db +from app.utils.timezone import now_in_app_timezone + + +def local_now(): + return now_in_app_timezone().replace(tzinfo=None) + + +class CrmCommunicationTemplate(db.Model): + """Saved subject/body templates for logging contact communications.""" + + __tablename__ = "crm_communication_templates" + + id = db.Column(db.Integer, primary_key=True) + name = db.Column(db.String(120), nullable=False) + type = db.Column(db.String(50), nullable=False, default="email") # email, call, meeting, note, message + subject = db.Column(db.String(500), nullable=True) + content = db.Column(db.Text, nullable=True) + direction = db.Column(db.String(20), nullable=False, default="outbound") + is_active = db.Column(db.Boolean, nullable=False, default=True) + created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) + created_at = db.Column(db.DateTime, default=local_now, nullable=False) + updated_at = db.Column(db.DateTime, default=local_now, onupdate=local_now, nullable=False) + + creator = db.relationship("User", foreign_keys=[created_by], backref="crm_communication_templates") + + def __init__(self, name, created_by, **kwargs): + self.name = name.strip() + self.created_by = created_by + self.type = (kwargs.get("type") or "email").strip() + self.subject = (kwargs.get("subject") or "").strip() or None + self.content = (kwargs.get("content") or "").strip() or None + self.direction = (kwargs.get("direction") or "outbound").strip() + self.is_active = kwargs.get("is_active", True) + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "type": self.type, + "subject": self.subject, + "content": self.content, + "direction": self.direction, + "is_active": self.is_active, + "created_by": self.created_by, + "created_at": self.created_at.isoformat() if self.created_at else None, + "updated_at": self.updated_at.isoformat() if self.updated_at else None, + } diff --git a/app/models/deal.py b/app/models/deal.py index a23e5b60..5b3a7cf6 100644 --- a/app/models/deal.py +++ b/app/models/deal.py @@ -58,12 +58,24 @@ class Deal(db.Model): # Relationships client = db.relationship("Client", backref="deals") contact = db.relationship("Contact", backref="deals") - lead = db.relationship("Lead", foreign_keys=[lead_id], backref="deals") + lead = db.relationship( + "Lead", + foreign_keys=[lead_id], + primaryjoin="Deal.lead_id==Lead.id", + backref=db.backref("originated_deals", lazy="dynamic"), + ) creator = db.relationship("User", foreign_keys=[created_by], backref="created_deals") owner = db.relationship("User", foreign_keys=[owner_id], backref="owned_deals") related_quote = db.relationship("Quote", foreign_keys=[related_quote_id]) related_project = db.relationship("Project", foreign_keys=[related_project_id]) - activities = db.relationship("DealActivity", backref="deal", lazy="dynamic", cascade="all, delete-orphan") + activities = db.relationship( + "DealActivity", + backref=db.backref("deal", foreign_keys="DealActivity.deal_id"), + lazy="dynamic", + cascade="all, delete-orphan", + foreign_keys="DealActivity.deal_id", + primaryjoin="Deal.id==DealActivity.deal_id", + ) def __init__(self, name, created_by, **kwargs): self.name = name.strip() diff --git a/app/models/lead.py b/app/models/lead.py index 8c36a245..2b0fb9a5 100644 --- a/app/models/lead.py +++ b/app/models/lead.py @@ -58,11 +58,24 @@ class Lead(db.Model): converted_to_client = db.relationship( "Client", foreign_keys=[converted_to_client_id], backref="converted_from_leads" ) - converted_to_deal = db.relationship("Deal", foreign_keys=[converted_to_deal_id]) creator = db.relationship("User", foreign_keys=[created_by], backref="created_leads") owner = db.relationship("User", foreign_keys=[owner_id], backref="owned_leads") converter = db.relationship("User", foreign_keys=[converted_by], backref="converted_leads") - activities = db.relationship("LeadActivity", backref="lead", lazy="dynamic", cascade="all, delete-orphan") + # viewonly read of converted deal (Lead↔Deal also linked via deals.lead_id) + converted_to_deal = db.relationship( + "Deal", + foreign_keys=[converted_to_deal_id], + primaryjoin="Lead.converted_to_deal_id==Deal.id", + viewonly=True, + ) + activities = db.relationship( + "LeadActivity", + backref=db.backref("lead", foreign_keys="LeadActivity.lead_id"), + lazy="dynamic", + cascade="all, delete-orphan", + foreign_keys="LeadActivity.lead_id", + primaryjoin="Lead.id==LeadActivity.lead_id", + ) def __init__(self, first_name, last_name, created_by, **kwargs): self.first_name = first_name.strip() diff --git a/app/routes/api_v1.py b/app/routes/api_v1.py index e1e02b12..7349404c 100644 --- a/app/routes/api_v1.py +++ b/app/routes/api_v1.py @@ -152,8 +152,16 @@ def api_info(): "payments": "/api/v1/payments", "mileage": "/api/v1/mileage", "deals": "/api/v1/deals", + "deal_activities": "/api/v1/deals//activities", + "deal_stage": "/api/v1/deals//stage", + "deals_forecast": "/api/v1/deals/forecast", "leads": "/api/v1/leads", + "lead_activities": "/api/v1/leads//activities", + "lead_convert_client": "/api/v1/leads//convert-to-client", + "lead_convert_deal": "/api/v1/leads//convert-to-deal", + "lead_source_analytics": "/api/v1/leads/analytics/sources", "contacts": "/api/v1/clients//contacts", + "contact_communications": "/api/v1/contacts//communications", "issues": "/api/v1/issues", "time_entry_approvals": "/api/v1/time-entry-approvals", "per_diems": "/api/v1/per-diems", diff --git a/app/routes/api_v1_contacts.py b/app/routes/api_v1_contacts.py index 28d05c4b..f1729142 100644 --- a/app/routes/api_v1_contacts.py +++ b/app/routes/api_v1_contacts.py @@ -134,3 +134,49 @@ def delete_contact(contact_id): contact.is_active = False db.session.commit() return jsonify({"message": "Contact deleted successfully"}) + + +@api_v1_contacts_bp.route("/contacts//communications", methods=["GET"]) +@require_api_token("read:contacts") +def list_contact_communications(contact_id): + """List communications for a contact.""" + blocked = _require_module_enabled_for_api("contacts") + if blocked: + return blocked + from app.models import ContactCommunication + + contact = Contact.query.filter_by(id=contact_id).first_or_404() + communications = ContactCommunication.get_recent_communications(contact_id=contact.id, limit=100) + return jsonify({"communications": [c.to_dict() for c in communications]}) + + +@api_v1_contacts_bp.route("/contacts//communications", methods=["POST"]) +@require_api_token("write:contacts") +def create_contact_communication(contact_id): + """Create a communication log entry for a contact.""" + blocked = _require_module_enabled_for_api("contacts") + if blocked: + return blocked + from app.models import ContactCommunication + from app.routes.api_v1_common import parse_datetime + + contact = Contact.query.filter_by(id=contact_id).first_or_404() + data = request.get_json() or {} + comm_type = (data.get("type") or "note").strip() + communication = ContactCommunication( + contact_id=contact.id, + type=comm_type, + created_by=g.api_user.id, + subject=(data.get("subject") or "").strip() or None, + content=(data.get("content") or "").strip() or None, + direction=(data.get("direction") or "outbound").strip(), + status=(data.get("status") or "completed").strip() or "completed", + communication_date=parse_datetime(data.get("communication_date")) or None, + follow_up_date=parse_datetime(data.get("follow_up_date")), + related_project_id=data.get("related_project_id"), + related_quote_id=data.get("related_quote_id"), + related_deal_id=data.get("related_deal_id"), + ) + db.session.add(communication) + db.session.commit() + return jsonify({"message": "Communication created", "communication": communication.to_dict()}), 201 diff --git a/app/routes/api_v1_deals.py b/app/routes/api_v1_deals.py index e16a1d49..3da71bd6 100644 --- a/app/routes/api_v1_deals.py +++ b/app/routes/api_v1_deals.py @@ -125,6 +125,7 @@ def update_deal(deal_id): if not g.api_user.is_admin and deal.owner_id != g.api_user.id: return forbidden_response("Access denied") data = request.get_json() or {} + old_stage = deal.stage for field in ("name", "description", "stage", "status", "loss_reason", "notes", "currency_code"): if field in data and data[field] is not None: setattr(deal, field, str(data[field]).strip() if isinstance(data[field], str) else data[field]) @@ -148,6 +149,21 @@ def update_deal(deal_id): deal.expected_close_date = _parse_date(data["expected_close_date"]) if "actual_close_date" in data: deal.actual_close_date = _parse_date(data["actual_close_date"]) + if "stage" in data and deal.stage != old_stage: + from app.models import DealActivity + + stage_snapshot = deal.stage + db.session.add( + DealActivity( + deal_id=deal.id, + type="stage_change", + created_by=g.api_user.id, + subject=f"Stage changed from {old_stage} to {stage_snapshot}", + description=f"{old_stage} → {stage_snapshot}", + status="completed", + ) + ) + deal.stage = stage_snapshot db.session.commit() return jsonify({"message": "Deal updated successfully", "deal": deal.to_dict()}) @@ -165,3 +181,176 @@ def delete_deal(deal_id): db.session.delete(deal) db.session.commit() return jsonify({"message": "Deal deleted successfully"}) + + +PIPELINE_STAGES = ["prospecting", "qualification", "proposal", "negotiation", "closed_won", "closed_lost"] + + +@api_v1_deals_bp.route("/deals//activities", methods=["GET"]) +@require_api_token("read:deals") +def list_deal_activities(deal_id): + """List activities for a deal.""" + blocked = _require_module_enabled_for_api("deals") + if blocked: + return blocked + from app.models import DealActivity + + deal = Deal.query.filter_by(id=deal_id).first_or_404() + if not g.api_user.is_admin and deal.owner_id != g.api_user.id: + return forbidden_response("Access denied") + activities = ( + DealActivity.query.filter_by(deal_id=deal_id).order_by(DealActivity.activity_date.desc()).limit(100).all() + ) + return jsonify({"activities": [a.to_dict() for a in activities]}) + + +@api_v1_deals_bp.route("/deals//activities", methods=["POST"]) +@require_api_token("write:deals") +def create_deal_activity(deal_id): + """Create an activity for a deal.""" + blocked = _require_module_enabled_for_api("deals") + if blocked: + return blocked + from app.models import DealActivity + from app.routes.api_v1_common import parse_datetime + + deal = Deal.query.filter_by(id=deal_id).first_or_404() + if not g.api_user.is_admin and deal.owner_id != g.api_user.id: + return forbidden_response("Access denied") + data = request.get_json() or {} + subject = (data.get("subject") or "").strip() or None + description = (data.get("description") or "").strip() or None + due_date = parse_datetime(data.get("due_date")) + activity = DealActivity( + deal_id=deal_id, + type=(data.get("type") or "note").strip(), + created_by=g.api_user.id, + subject=subject, + description=description, + activity_date=parse_datetime(data.get("activity_date")) or None, + due_date=due_date, + status=(data.get("status") or "completed").strip() or "completed", + ) + db.session.add(activity) + if due_date: + from app.utils.crm_calendar import sync_activity_to_calendar + + sync_activity_to_calendar( + user_id=g.api_user.id, + title=subject or f"Deal activity: {deal.name}", + due_date=due_date, + description=description, + client_id=deal.client_id, + ) + db.session.commit() + return jsonify({"message": "Activity created", "activity": activity.to_dict()}), 201 + + +@api_v1_deals_bp.route("/deals//stage", methods=["PUT", "PATCH"]) +@require_api_token("write:deals") +def update_deal_stage(deal_id): + """Move a deal to a pipeline stage (supports drag-and-drop clients).""" + blocked = _require_module_enabled_for_api("deals") + if blocked: + return blocked + from app.models import DealActivity + + deal = Deal.query.filter_by(id=deal_id).first_or_404() + if not g.api_user.is_admin and deal.owner_id != g.api_user.id: + return forbidden_response("Access denied") + data = request.get_json() or {} + new_stage = (data.get("stage") or "").strip() + if new_stage not in PIPELINE_STAGES: + return validation_error_response( + errors={"stage": [f"stage must be one of: {', '.join(PIPELINE_STAGES)}"]}, + message="Invalid stage", + ) + old_stage = deal.stage + if old_stage != new_stage: + deal.stage = new_stage + if new_stage == "closed_won": + deal.close_won() + elif new_stage == "closed_lost": + deal.close_lost(reason=data.get("loss_reason")) + elif deal.status in ("won", "lost") and new_stage not in ("closed_won", "closed_lost"): + deal.status = "open" + deal.closed_at = None + deal.actual_close_date = None + # Snapshot after stage/status mutations; DealActivity sync can clobber parent attrs + stage_snapshot = deal.stage + status_snapshot = deal.status + closed_at_snapshot = deal.closed_at + actual_close_snapshot = deal.actual_close_date + loss_reason_snapshot = deal.loss_reason + db.session.add( + DealActivity( + deal_id=deal.id, + type="stage_change", + created_by=g.api_user.id, + subject=f"Stage changed from {old_stage} to {new_stage}", + description=f"{old_stage} → {new_stage}", + status="completed", + ) + ) + deal.stage = stage_snapshot + deal.status = status_snapshot + deal.closed_at = closed_at_snapshot + deal.actual_close_date = actual_close_snapshot + deal.loss_reason = loss_reason_snapshot + db.session.commit() + return jsonify({"message": "Deal stage updated", "deal": deal.to_dict()}) + + +@api_v1_deals_bp.route("/deals/forecast", methods=["GET"]) +@require_api_token("read:deals") +def deals_forecast(): + """Weighted pipeline forecast by stage for open deals.""" + blocked = _require_module_enabled_for_api("deals") + if blocked: + return blocked + query = Deal.query.filter_by(status="open") + if not g.api_user.is_admin: + query = query.filter_by(owner_id=g.api_user.id) + deals = query.all() + by_stage = {} + total_value = 0.0 + total_weighted = 0.0 + for stage in PIPELINE_STAGES: + if stage.startswith("closed_"): + continue + stage_deals = [d for d in deals if d.stage == stage] + value = sum(float(d.value or 0) for d in stage_deals) + weighted = sum(float(d.weighted_value) for d in stage_deals) + by_stage[stage] = { + "count": len(stage_deals), + "value": value, + "weighted_value": weighted, + } + total_value += value + total_weighted += weighted + return jsonify( + { + "forecast": { + "by_stage": by_stage, + "total_open_value": total_value, + "total_weighted_value": total_weighted, + "open_deal_count": len(deals), + } + } + ) + + +@api_v1_deals_bp.route("/deals//email-threads", methods=["GET"]) +@require_api_token("read:deals") +def list_deal_email_threads(deal_id): + """List synced email threads linked to a deal.""" + blocked = _require_module_enabled_for_api("deals") + if blocked: + return blocked + deal = Deal.query.filter_by(id=deal_id).first_or_404() + if not g.api_user.is_admin and deal.owner_id != g.api_user.id: + return forbidden_response("Access denied") + from app.services.email_sync_service import EmailSyncService + + threads = EmailSyncService().threads_for_deal(deal_id) + return jsonify({"email_threads": [t.to_dict() for t in threads]}) diff --git a/app/routes/api_v1_leads.py b/app/routes/api_v1_leads.py index 2581ef80..b6f15e8b 100644 --- a/app/routes/api_v1_leads.py +++ b/app/routes/api_v1_leads.py @@ -145,7 +145,26 @@ def update_lead(lead_id): if field in data and data[field] is not None: setattr(lead, field, str(data[field]).strip() if isinstance(data[field], str) else data[field]) if "score" in data: - lead.score = int(data["score"]) + new_score = int(data["score"]) + if new_score != lead.score: + from app.models import LeadActivity + + old_score = lead.score + lead.score = new_score + db.session.add( + LeadActivity( + lead_id=lead.id, + type="score_change", + created_by=g.api_user.id, + subject=f"Score changed from {old_score} to {new_score}", + description=f"{old_score} → {new_score}", + status="completed", + ) + ) + # Relationship sync on LeadActivity can clobber dirty parent attrs + lead.score = new_score + else: + lead.score = new_score if "estimated_value" in data: try: lead.estimated_value = ( @@ -172,3 +191,206 @@ def delete_lead(lead_id): db.session.delete(lead) db.session.commit() return jsonify({"message": "Lead deleted successfully"}) + + +@api_v1_leads_bp.route("/leads//activities", methods=["GET"]) +@require_api_token("read:leads") +def list_lead_activities(lead_id): + """List activities for a lead.""" + blocked = _require_module_enabled_for_api("leads") + if blocked: + return blocked + from app.models import LeadActivity + + lead = Lead.query.filter_by(id=lead_id).first_or_404() + if not g.api_user.is_admin and lead.owner_id != g.api_user.id: + return forbidden_response("Access denied") + activities = ( + LeadActivity.query.filter_by(lead_id=lead_id).order_by(LeadActivity.activity_date.desc()).limit(100).all() + ) + return jsonify({"activities": [a.to_dict() for a in activities]}) + + +@api_v1_leads_bp.route("/leads//activities", methods=["POST"]) +@require_api_token("write:leads") +def create_lead_activity(lead_id): + """Create an activity for a lead.""" + blocked = _require_module_enabled_for_api("leads") + if blocked: + return blocked + from app.models import LeadActivity + from app.routes.api_v1_common import parse_datetime + + lead = Lead.query.filter_by(id=lead_id).first_or_404() + if not g.api_user.is_admin and lead.owner_id != g.api_user.id: + return forbidden_response("Access denied") + data = request.get_json() or {} + activity_type = (data.get("type") or "note").strip() + subject = (data.get("subject") or "").strip() or None + description = (data.get("description") or "").strip() or None + due_date = parse_datetime(data.get("due_date")) + activity = LeadActivity( + lead_id=lead_id, + type=activity_type, + created_by=g.api_user.id, + subject=subject, + description=description, + activity_date=parse_datetime(data.get("activity_date")) or None, + due_date=due_date, + status=(data.get("status") or "completed").strip() or "completed", + ) + db.session.add(activity) + if due_date: + from app.utils.crm_calendar import sync_activity_to_calendar + + sync_activity_to_calendar( + user_id=g.api_user.id, + title=subject or f"Lead activity: {lead.display_name}", + due_date=due_date, + description=description, + client_id=lead.converted_to_client_id, + ) + db.session.commit() + return jsonify({"message": "Activity created", "activity": activity.to_dict()}), 201 + + +@api_v1_leads_bp.route("/leads//convert-to-client", methods=["POST"]) +@require_api_token("write:leads") +def api_convert_lead_to_client(lead_id): + """Convert a lead to a client (and primary contact).""" + blocked = _require_module_enabled_for_api("leads") + if blocked: + return blocked + from app.models import Client, Contact + + lead = Lead.query.filter_by(id=lead_id).first_or_404() + if not g.api_user.is_admin and lead.owner_id != g.api_user.id: + return forbidden_response("Access denied") + if lead.is_converted: + return error_response("Lead has already been converted", status_code=400) + + data = request.get_json() or {} + client_name = (data.get("name") or lead.company_name or f"{lead.first_name} {lead.last_name}").strip() + client = Client( + name=client_name, + contact_person=f"{lead.first_name} {lead.last_name}", + email=lead.email, + phone=lead.phone, + description=f"Converted from lead: {lead.display_name}", + ) + db.session.add(client) + client.status = "active" + db.session.flush() + client_id = client.id + contact = Contact( + client_id=client_id, + first_name=lead.first_name, + last_name=lead.last_name, + email=lead.email, + phone=lead.phone, + title=lead.title, + is_primary=True, + created_by=g.api_user.id, + ) + db.session.add(contact) + db.session.flush() + lead.convert_to_client(client_id, g.api_user.id) + lead_payload = lead.to_dict() + contact_payload = contact.to_dict() + client_payload = {"id": client_id, "name": client.name, "email": client.email, "status": "active"} + db.session.commit() + return jsonify( + { + "message": "Lead converted to client", + "lead": lead_payload, + "client": client_payload, + "contact": contact_payload, + } + ) + + +@api_v1_leads_bp.route("/leads//convert-to-deal", methods=["POST"]) +@require_api_token("write:leads") +def api_convert_lead_to_deal(lead_id): + """Convert a lead to a deal.""" + blocked = _require_module_enabled_for_api("leads") + if blocked: + return blocked + from app.models import Deal + from app.routes.api_v1_common import _parse_date + + lead = Lead.query.filter_by(id=lead_id).first_or_404() + if not g.api_user.is_admin and lead.owner_id != g.api_user.id: + return forbidden_response("Access denied") + if lead.is_converted: + return error_response("Lead has already been converted", status_code=400) + + data = request.get_json() or {} + deal_name = (data.get("name") or f"Deal: {lead.display_name}").strip() + deal = Deal( + name=deal_name, + created_by=g.api_user.id, + client_id=data.get("client_id"), + description=(data.get("description") or "").strip() or None, + stage=(data.get("stage") or "prospecting").strip(), + value=lead.estimated_value, + currency_code=lead.currency_code, + probability=int(data.get("probability", 50)), + expected_close_date=_parse_date(data.get("expected_close_date")), + notes=lead.notes, + owner_id=g.api_user.id, + ) + db.session.add(deal) + db.session.flush() + deal.lead_id = lead_id + lead.convert_to_deal(deal.id, g.api_user.id) + db.session.commit() + return jsonify({"message": "Lead converted to deal", "lead": lead.to_dict(), "deal": deal.to_dict()}) + + +@api_v1_leads_bp.route("/leads//email-threads", methods=["GET"]) +@require_api_token("read:leads") +def list_lead_email_threads(lead_id): + """List synced email threads linked to a lead.""" + blocked = _require_module_enabled_for_api("leads") + if blocked: + return blocked + lead = Lead.query.filter_by(id=lead_id).first_or_404() + if not g.api_user.is_admin and lead.owner_id != g.api_user.id: + return forbidden_response("Access denied") + from app.services.email_sync_service import EmailSyncService + + threads = EmailSyncService().threads_for_lead(lead_id) + return jsonify({"email_threads": [t.to_dict() for t in threads]}) + + +@api_v1_leads_bp.route("/leads/analytics/sources", methods=["GET"]) +@require_api_token("read:leads") +def lead_source_analytics(): + """Aggregate lead counts and estimated value by source.""" + blocked = _require_module_enabled_for_api("leads") + if blocked: + return blocked + from sqlalchemy import func + + query = db.session.query( + Lead.source, + func.count(Lead.id), + func.coalesce(func.sum(Lead.estimated_value), 0), + func.avg(Lead.score), + ) + if not g.api_user.is_admin: + query = query.filter(Lead.owner_id == g.api_user.id) + rows = query.group_by(Lead.source).all() + sources = [] + for source, count, total_value, avg_score in rows: + sources.append( + { + "source": source or "unknown", + "count": int(count), + "estimated_value_total": float(total_value or 0), + "average_score": float(avg_score or 0), + } + ) + sources.sort(key=lambda s: s["count"], reverse=True) + return jsonify({"sources": sources, "total_leads": sum(s["count"] for s in sources)}) diff --git a/app/routes/contacts.py b/app/routes/contacts.py index b130e002..ad1df05d 100644 --- a/app/routes/contacts.py +++ b/app/routes/contacts.py @@ -27,6 +27,7 @@ def list_contacts(client_id): @contacts_bp.route("/clients//contacts/create", methods=["GET", "POST"]) @login_required +@module_enabled("contacts") def create_contact(client_id): """Create a new contact for a client""" client = Client.query.get_or_404(client_id) @@ -70,6 +71,7 @@ def create_contact(client_id): @contacts_bp.route("/contacts/") @login_required +@module_enabled("contacts") def view_contact(contact_id): """View a contact""" contact = Contact.query.get_or_404(contact_id) @@ -79,6 +81,7 @@ def view_contact(contact_id): @contacts_bp.route("/contacts//edit", methods=["GET", "POST"]) @login_required +@module_enabled("contacts") def edit_contact(contact_id): """Edit a contact""" contact = Contact.query.get_or_404(contact_id) @@ -117,6 +120,7 @@ def edit_contact(contact_id): @contacts_bp.route("/contacts//delete", methods=["POST"]) @login_required +@module_enabled("contacts") def delete_contact(contact_id): """Delete a contact (soft delete by setting is_active=False)""" contact = Contact.query.get_or_404(contact_id) @@ -136,6 +140,7 @@ def delete_contact(contact_id): @contacts_bp.route("/contacts//set-primary", methods=["POST"]) @login_required +@module_enabled("contacts") def set_primary_contact(contact_id): """Set a contact as primary""" contact = Contact.query.get_or_404(contact_id) @@ -153,6 +158,7 @@ def set_primary_contact(contact_id): @contacts_bp.route("/contacts//communications/create", methods=["GET", "POST"]) @login_required +@module_enabled("contacts") def create_communication(contact_id): """Create a communication record for a contact""" contact = Contact.query.get_or_404(contact_id) @@ -196,3 +202,88 @@ def create_communication(contact_id): flash(_("Error recording communication: %(error)s", error=str(e)), "error") return render_template("contacts/communication_form.html", contact=contact, communication=None) + + +@contacts_bp.route("/crm/communication-templates") +@login_required +@module_enabled("contacts") +def list_communication_templates(): + """List CRM communication templates.""" + from app.models import CrmCommunicationTemplate + + templates = ( + CrmCommunicationTemplate.query.filter_by(is_active=True) + .order_by(CrmCommunicationTemplate.name) + .all() + ) + return render_template("contacts/templates_list.html", templates=templates) + + +@contacts_bp.route("/crm/communication-templates/create", methods=["GET", "POST"]) +@login_required +@module_enabled("contacts") +def create_communication_template(): + """Create a CRM communication template.""" + from app.models import CrmCommunicationTemplate + + if request.method == "POST": + try: + template = CrmCommunicationTemplate( + name=request.form.get("name", "").strip(), + created_by=current_user.id, + type=request.form.get("type", "email").strip(), + subject=request.form.get("subject", "").strip() or None, + content=request.form.get("content", "").strip() or None, + direction=request.form.get("direction", "outbound").strip(), + ) + if not template.name: + flash(_("Name is required"), "error") + else: + db.session.add(template) + if safe_commit(): + flash(_("Template created"), "success") + return redirect(url_for("contacts.list_communication_templates")) + except Exception as e: + db.session.rollback() + flash(_("Error creating template: %(error)s", error=str(e)), "error") + return render_template("contacts/template_form.html", template=None) + + +@contacts_bp.route("/crm/communication-templates//edit", methods=["GET", "POST"]) +@login_required +@module_enabled("contacts") +def edit_communication_template(template_id): + """Edit a CRM communication template.""" + from app.models import CrmCommunicationTemplate + + template = CrmCommunicationTemplate.query.get_or_404(template_id) + if request.method == "POST": + try: + template.name = request.form.get("name", "").strip() + template.type = request.form.get("type", "email").strip() + template.subject = request.form.get("subject", "").strip() or None + template.content = request.form.get("content", "").strip() or None + template.direction = request.form.get("direction", "outbound").strip() + template.updated_at = datetime.utcnow() + if safe_commit(): + flash(_("Template updated"), "success") + return redirect(url_for("contacts.list_communication_templates")) + except Exception as e: + db.session.rollback() + flash(_("Error updating template: %(error)s", error=str(e)), "error") + return render_template("contacts/template_form.html", template=template) + + +@contacts_bp.route("/api/crm/communication-templates") +@login_required +@module_enabled("contacts") +def api_list_communication_templates(): + """JSON list of active communication templates for the communication form.""" + from app.models import CrmCommunicationTemplate + + templates = ( + CrmCommunicationTemplate.query.filter_by(is_active=True) + .order_by(CrmCommunicationTemplate.name) + .all() + ) + return jsonify({"templates": [t.to_dict() for t in templates]}) diff --git a/app/routes/deals.py b/app/routes/deals.py index 3ddaabd3..ef6e2ba0 100644 --- a/app/routes/deals.py +++ b/app/routes/deals.py @@ -67,6 +67,7 @@ def list_deals(): @deals_bp.route("/deals/pipeline") @login_required +@module_enabled("deals") def pipeline_view(): """Visual pipeline view of deals""" owner_id = request.args.get("owner", "") @@ -91,8 +92,86 @@ def pipeline_view(): ) +@deals_bp.route("/deals//stage", methods=["POST"]) +@login_required +@module_enabled("deals") +def update_deal_stage(deal_id): + """Update deal stage (used by pipeline drag-and-drop).""" + deal = Deal.query.get_or_404(deal_id) + data = request.get_json(silent=True) or {} + new_stage = (data.get("stage") or request.form.get("stage") or "").strip() + if new_stage not in PIPELINE_STAGES: + return jsonify({"ok": False, "error": "Invalid stage"}), 400 + old_stage = deal.stage + if old_stage == new_stage: + return jsonify({"ok": True, "deal": deal.to_dict()}) + deal.stage = new_stage + if new_stage == "closed_won": + deal.close_won() + elif new_stage == "closed_lost": + deal.close_lost() + elif deal.status in ("won", "lost") and new_stage not in ("closed_won", "closed_lost"): + deal.status = "open" + deal.closed_at = None + deal.actual_close_date = None + stage_snapshot = deal.stage + status_snapshot = deal.status + closed_at_snapshot = deal.closed_at + actual_close_snapshot = deal.actual_close_date + db.session.add( + DealActivity( + deal_id=deal.id, + type="stage_change", + created_by=current_user.id, + subject=f"Stage changed from {old_stage} to {new_stage}", + description=f"{old_stage} → {new_stage}", + status="completed", + ) + ) + deal.stage = stage_snapshot + deal.status = status_snapshot + deal.closed_at = closed_at_snapshot + deal.actual_close_date = actual_close_snapshot + if not safe_commit(): + db.session.rollback() + return jsonify({"ok": False, "error": "Could not save"}), 500 + return jsonify({"ok": True, "deal": deal.to_dict()}) + + +@deals_bp.route("/deals/forecast") +@login_required +@module_enabled("deals") +def deals_forecast(): + """Deal pipeline forecasting report.""" + query = Deal.query.filter_by(status="open") + if not current_user.is_admin: + query = query.filter_by(owner_id=current_user.id) + deals = query.all() + by_stage = {} + total_value = 0.0 + total_weighted = 0.0 + for stage_name in PIPELINE_STAGES: + if stage_name.startswith("closed_"): + continue + stage_deals = [d for d in deals if d.stage == stage_name] + value = sum(float(d.value or 0) for d in stage_deals) + weighted = sum(float(d.weighted_value) for d in stage_deals) + by_stage[stage_name] = {"deals": stage_deals, "count": len(stage_deals), "value": value, "weighted": weighted} + total_value += value + total_weighted += weighted + return render_template( + "deals/forecast.html", + by_stage=by_stage, + pipeline_stages=[s for s in PIPELINE_STAGES if not s.startswith("closed_")], + total_value=total_value, + total_weighted=total_weighted, + open_count=len(deals), + ) + + @deals_bp.route("/deals/create", methods=["GET", "POST"]) @login_required +@module_enabled("deals") def create_deal(): """Create a new deal""" if request.method == "POST": @@ -159,6 +238,7 @@ def create_deal(): @deals_bp.route("/deals/") @login_required +@module_enabled("deals") def view_deal(deal_id): """View a deal""" deal = Deal.query.get_or_404(deal_id) @@ -185,6 +265,7 @@ def view_deal(deal_id): @deals_bp.route("/deals//edit", methods=["GET", "POST"]) @login_required +@module_enabled("deals") def edit_deal(deal_id): """Edit a deal""" deal = Deal.query.get_or_404(deal_id) @@ -248,6 +329,7 @@ def edit_deal(deal_id): @deals_bp.route("/deals//close-won", methods=["POST"]) @login_required +@module_enabled("deals") def close_won(deal_id): """Close deal as won""" deal = Deal.query.get_or_404(deal_id) @@ -274,6 +356,7 @@ def close_won(deal_id): @deals_bp.route("/deals//close-lost", methods=["POST"]) @login_required +@module_enabled("deals") def close_lost(deal_id): """Close deal as lost""" deal = Deal.query.get_or_404(deal_id) @@ -302,6 +385,7 @@ def close_lost(deal_id): @deals_bp.route("/deals//activities/create", methods=["GET", "POST"]) @login_required +@module_enabled("deals") def create_activity(deal_id): """Create an activity for a deal""" deal = Deal.query.get_or_404(deal_id) @@ -318,18 +402,30 @@ def create_activity(deal_id): due_date_str = request.form.get("due_date", "") due_date = parse_local_datetime_from_string(due_date_str) if due_date_str else None + subject = request.form.get("subject", "").strip() or None + description = request.form.get("description", "").strip() or None activity = DealActivity( deal_id=deal_id, type=request.form.get("type", "note").strip(), created_by=current_user.id, - subject=request.form.get("subject", "").strip() or None, - description=request.form.get("description", "").strip() or None, + subject=subject, + description=description, activity_date=activity_date, due_date=due_date, status=request.form.get("status", "completed").strip() or "completed", ) db.session.add(activity) + if due_date: + from app.utils.crm_calendar import sync_activity_to_calendar + + sync_activity_to_calendar( + user_id=current_user.id, + title=subject or f"Deal activity: {deal.name}", + due_date=due_date, + description=description, + client_id=deal.client_id, + ) if safe_commit(): flash(_("Activity recorded successfully"), "success") @@ -343,6 +439,7 @@ def create_activity(deal_id): @deals_bp.route("/api/deals//contacts") @login_required +@module_enabled("deals") def get_deal_contacts(deal_id): """API endpoint to get contacts for a deal's client""" deal = Deal.query.get_or_404(deal_id) diff --git a/app/routes/leads.py b/app/routes/leads.py index e6ec9659..742200bd 100644 --- a/app/routes/leads.py +++ b/app/routes/leads.py @@ -75,6 +75,7 @@ def list_leads(): @leads_bp.route("/leads/create", methods=["GET", "POST"]) @login_required +@module_enabled("leads") def create_lead(): """Create a new lead""" if request.method == "POST": @@ -120,6 +121,7 @@ def create_lead(): @leads_bp.route("/leads/") @login_required +@module_enabled("leads") def view_lead(lead_id): """View a lead""" lead = Lead.query.get_or_404(lead_id) @@ -138,6 +140,7 @@ def view_lead(lead_id): @leads_bp.route("/leads//edit", methods=["GET", "POST"]) @login_required +@module_enabled("leads") def edit_lead(lead_id): """Edit a lead""" lead = Lead.query.get_or_404(lead_id) @@ -161,7 +164,24 @@ def edit_lead(lead_id): lead.title = request.form.get("title", "").strip() or None lead.source = request.form.get("source", "").strip() or None lead.status = request.form.get("status", "new").strip() - lead.score = int(request.form.get("score", 0)) + new_score = int(request.form.get("score", 0)) + if new_score != lead.score: + old_score = lead.score + lead.score = new_score + db.session.add( + LeadActivity( + lead_id=lead.id, + type="score_change", + created_by=current_user.id, + subject=f"Score changed from {old_score} to {new_score}", + description=f"{old_score} → {new_score}", + status="completed", + ) + ) + # Relationship sync on LeadActivity can clobber dirty parent attrs + lead.score = new_score + else: + lead.score = new_score lead.estimated_value = estimated_value lead.currency_code = request.form.get("currency_code", "EUR").strip() lead.notes = request.form.get("notes", "").strip() or None @@ -181,6 +201,7 @@ def edit_lead(lead_id): @leads_bp.route("/leads//convert-to-client", methods=["GET", "POST"]) @login_required +@module_enabled("leads") def convert_to_client(lead_id): """Convert a lead to a client""" lead = Lead.query.get_or_404(lead_id) @@ -236,6 +257,7 @@ def convert_to_client(lead_id): @leads_bp.route("/leads//convert-to-deal", methods=["GET", "POST"]) @login_required +@module_enabled("leads") def convert_to_deal(lead_id): """Convert a lead to a deal""" lead = Lead.query.get_or_404(lead_id) @@ -295,6 +317,7 @@ def convert_to_deal(lead_id): @leads_bp.route("/leads//mark-lost", methods=["POST"]) @login_required +@module_enabled("leads") def mark_lost(lead_id): """Mark a lead as lost""" lead = Lead.query.get_or_404(lead_id) @@ -313,6 +336,7 @@ def mark_lost(lead_id): @leads_bp.route("/leads//activities/create", methods=["GET", "POST"]) @login_required +@module_enabled("leads") def create_activity(lead_id): """Create an activity for a lead""" lead = Lead.query.get_or_404(lead_id) @@ -329,18 +353,30 @@ def create_activity(lead_id): due_date_str = request.form.get("due_date", "") due_date = parse_local_datetime_from_string(due_date_str) if due_date_str else None + subject = request.form.get("subject", "").strip() or None + description = request.form.get("description", "").strip() or None activity = LeadActivity( lead_id=lead_id, type=request.form.get("type", "note").strip(), created_by=current_user.id, - subject=request.form.get("subject", "").strip() or None, - description=request.form.get("description", "").strip() or None, + subject=subject, + description=description, activity_date=activity_date, due_date=due_date, status=request.form.get("status", "completed").strip() or "completed", ) db.session.add(activity) + if due_date: + from app.utils.crm_calendar import sync_activity_to_calendar + + sync_activity_to_calendar( + user_id=current_user.id, + title=subject or f"Lead activity: {lead.display_name}", + due_date=due_date, + description=description, + client_id=lead.converted_to_client_id, + ) if safe_commit(): flash(_("Activity recorded successfully"), "success") @@ -350,3 +386,35 @@ def create_activity(lead_id): flash(_("Error recording activity: %(error)s", error=str(e)), "error") return render_template("leads/activity_form.html", lead=lead, activity=None) + + +@leads_bp.route("/leads/analytics/sources") +@login_required +@module_enabled("leads") +def lead_source_analytics(): + """Lead source analytics report.""" + from sqlalchemy import func + + query = db.session.query( + Lead.source, + func.count(Lead.id), + func.coalesce(func.sum(Lead.estimated_value), 0), + func.avg(Lead.score), + ) + if not current_user.is_admin: + query = query.filter(Lead.owner_id == current_user.id) + rows = query.group_by(Lead.source).order_by(func.count(Lead.id).desc()).all() + sources = [ + { + "source": source or _("Unknown"), + "count": int(count), + "estimated_value_total": float(total_value or 0), + "average_score": float(avg_score or 0), + } + for source, count, total_value, avg_score in rows + ] + return render_template( + "leads/source_analytics.html", + sources=sources, + total_leads=sum(s["count"] for s in sources), + ) diff --git a/app/services/email_sync_service.py b/app/services/email_sync_service.py index d228660a..7ea9f1e8 100644 --- a/app/services/email_sync_service.py +++ b/app/services/email_sync_service.py @@ -32,24 +32,30 @@ def match_crm(self, addresses: List[str]) -> Tuple[Optional[int], Optional[int], if not normalized: return None, None, None - # Contacts → client + # Prefer open deals linked to a matching contact (more specific than client-only) + deals = Deal.query.filter(Deal.status == "open").all() + for deal in deals: + contact = deal.contact + if contact and contact.email and contact.email.lower() in normalized: + return deal.client_id, None, deal.id + + # Contacts → client (and attach open deal on that client when unique) for contact in Contact.query.filter(Contact.email.isnot(None)).all(): if contact.email and contact.email.lower() in normalized: - return contact.client_id, None, None + client_deals = [d for d in deals if d.client_id == contact.client_id] + deal_id = client_deals[0].id if len(client_deals) == 1 else None + return contact.client_id, None, deal_id for client in Client.query.filter(Client.email.isnot(None)).all(): if client.email and client.email.lower() in normalized: - return client.id, None, None + client_deals = [d for d in deals if d.client_id == client.id] + deal_id = client_deals[0].id if len(client_deals) == 1 else None + return client.id, None, deal_id for lead in Lead.query.filter(Lead.email.isnot(None)).all(): if lead.email and lead.email.lower() in normalized: return getattr(lead, "client_id", None), lead.id, None - for deal in Deal.query.all(): - # Deals may link via contact email on related client - if getattr(deal, "contact_email", None) and deal.contact_email.lower() in normalized: - return getattr(deal, "client_id", None), None, deal.id - return None, None, None def ingest_threads(self, provider: str, threads: List[Dict[str, Any]]) -> Dict[str, int]: diff --git a/app/templates/contacts/communication_form.html b/app/templates/contacts/communication_form.html index 1f2541e6..d5375fcf 100644 --- a/app/templates/contacts/communication_form.html +++ b/app/templates/contacts/communication_form.html @@ -24,6 +24,15 @@
+
+ + +

+ {{ _('Manage templates') }} +

+
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+
+ + {{ _('Cancel') }} +
+ +
+{% endblock %} diff --git a/app/templates/contacts/templates_list.html b/app/templates/contacts/templates_list.html new file mode 100644 index 00000000..695b7348 --- /dev/null +++ b/app/templates/contacts/templates_list.html @@ -0,0 +1,48 @@ +{% extends "base.html" %} +{% from "components/ui.html" import page_header %} + +{% block title %}{{ _('Communication Templates') }} - {{ config.APP_NAME }}{% endblock %} + +{% block content %} +{% set breadcrumbs = [ + {'text': _('CRM')}, + {'text': _('Communication Templates')} +] %} + +{{ page_header( + icon_class='fas fa-file-alt', + title_text=_('Communication Templates'), + subtitle_text=_('Reusable templates when logging contact communications'), + breadcrumbs=breadcrumbs, + actions_html='' + _('New Template') + '' +) }} + +
+ + + + + + + + + + + {% for t in templates %} + + + + + + + {% else %} + + + + {% endfor %} + +
{{ _('Name') }}{{ _('Type') }}{{ _('Subject') }}
{{ t.name }}{{ t.type }}{{ t.subject or '—' }} + {{ _('Edit') }} +
{{ _('No templates yet') }}
+
+{% endblock %} diff --git a/app/templates/deals/forecast.html b/app/templates/deals/forecast.html new file mode 100644 index 00000000..a259f269 --- /dev/null +++ b/app/templates/deals/forecast.html @@ -0,0 +1,57 @@ +{% extends "base.html" %} +{% from "components/ui.html" import page_header %} + +{% block title %}{{ _('Deal Forecast') }} - {{ config.APP_NAME }}{% endblock %} + +{% block content %} +{% set breadcrumbs = [ + {'text': _('Deals'), 'url': url_for('deals.list_deals')}, + {'text': _('Forecast')} +] %} + +{{ page_header( + icon_class='fas fa-chart-line', + title_text=_('Deal Forecast'), + subtitle_text=_('Weighted pipeline value by stage'), + breadcrumbs=breadcrumbs, + actions_html='' + _('Pipeline') + '' +) }} + +
+
+

{{ _('Open deals') }}

+

{{ open_count }}

+
+
+

{{ _('Open pipeline value') }}

+

{{ '%.2f'|format(total_value) }}

+
+
+

{{ _('Weighted forecast') }}

+

{{ '%.2f'|format(total_weighted) }}

+
+
+ +
+ + + + + + + + + + + {% for stage in pipeline_stages %} + + + + + + + {% endfor %} + +
{{ _('Stage') }}{{ _('Deals') }}{{ _('Value') }}{{ _('Weighted') }}
{{ stage|replace('_', ' ')|title }}{{ by_stage[stage].count }}{{ '%.2f'|format(by_stage[stage].value) }}{{ '%.2f'|format(by_stage[stage].weighted) }}
+
+{% endblock %} diff --git a/app/templates/deals/list.html b/app/templates/deals/list.html index 685d80c9..1cd7efff 100644 --- a/app/templates/deals/list.html +++ b/app/templates/deals/list.html @@ -13,7 +13,7 @@ title_text=_('Deals'), subtitle_text=_('Manage your sales pipeline'), breadcrumbs=breadcrumbs, - actions_html='' + _('New Deal') + ' ' + _('Pipeline View') + '' + actions_html='' + _('New Deal') + ' ' + _('Pipeline View') + ' ' + _('Forecast') + '' ) }}
diff --git a/app/templates/deals/pipeline.html b/app/templates/deals/pipeline.html index ce642c95..47b26bcc 100644 --- a/app/templates/deals/pipeline.html +++ b/app/templates/deals/pipeline.html @@ -1,5 +1,5 @@ {% extends "base.html" %} -{% from "components/ui.html" import page_header, breadcrumb_nav %} +{% from "components/ui.html" import page_header %} {% block title %}{{ _('Sales Pipeline') }} - {{ config.APP_NAME }}{% endblock %} @@ -12,26 +12,28 @@ {{ page_header( icon_class='fas fa-columns', title_text=_('Sales Pipeline'), - subtitle_text=_('Visual pipeline view of all deals'), + subtitle_text=_('Drag deals between stages to update the pipeline'), breadcrumbs=breadcrumbs, - actions_html='' + _('New Deal') + '' + actions_html='' + _('Forecast') + '' + _('New Deal') + '' ) }}
-
+
{% for stage in pipeline_stages %}

{{ stage|replace('_', ' ')|title }} - + {{ deals_by_stage[stage]|length }}

-
+
{% for deal in deals_by_stage[stage] %} -
+

{{ deal.name }}

{% if deal.client %}

{{ deal.client.name }}

@@ -54,3 +56,87 @@

{{ deal.name }}

{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/app/templates/leads/list.html b/app/templates/leads/list.html index 32cc59b0..a4a3f921 100644 --- a/app/templates/leads/list.html +++ b/app/templates/leads/list.html @@ -13,7 +13,7 @@ title_text='Leads', subtitle_text='Manage potential clients', breadcrumbs=breadcrumbs, - actions_html='New Lead' + actions_html='New Lead Source Analytics' ) }}
diff --git a/app/templates/leads/source_analytics.html b/app/templates/leads/source_analytics.html new file mode 100644 index 00000000..307dad3f --- /dev/null +++ b/app/templates/leads/source_analytics.html @@ -0,0 +1,51 @@ +{% extends "base.html" %} +{% from "components/ui.html" import page_header %} + +{% block title %}{{ _('Lead Source Analytics') }} - {{ config.APP_NAME }}{% endblock %} + +{% block content %} +{% set breadcrumbs = [ + {'text': _('Leads'), 'url': url_for('leads.list_leads')}, + {'text': _('Source Analytics')} +] %} + +{{ page_header( + icon_class='fas fa-chart-pie', + title_text=_('Lead Source Analytics'), + subtitle_text=_('Counts, estimated value, and average score by source'), + breadcrumbs=breadcrumbs +) }} + +
+ {{ _('Total leads') }}: {{ total_leads }} +
+ +
+ + + + + + + + + + + {% if sources %} + {% for row in sources %} + + + + + + + {% endfor %} + {% else %} + + + + {% endif %} + +
{{ _('Source') }}{{ _('Leads') }}{{ _('Estimated value') }}{{ _('Avg score') }}
{{ row.source }}{{ row.count }}{{ '%.2f'|format(row.estimated_value_total) }}{{ '%.1f'|format(row.average_score) }}
{{ _('No leads yet') }}
+
+{% endblock %} diff --git a/app/templates/partials/_sidebar.html b/app/templates/partials/_sidebar.html index 0b354874..5bf5ce1c 100644 --- a/app/templates/partials/_sidebar.html +++ b/app/templates/partials/_sidebar.html @@ -268,6 +268,11 @@

{{ _('Deals') }} +
  • + + {{ _('Deal Forecast') }} + +
  • {% endif %} {% if is_module_enabled('leads') %}
  • @@ -275,6 +280,18 @@

    {{ _('Leads') }}

  • +
  • + + {{ _('Lead Sources') }} + +
  • + {% endif %} + {% if is_module_enabled('contacts') %} +
  • + + {{ _('Comm. Templates') }} + +
  • {% endif %} {% if is_module_enabled('quotes') %}
  • diff --git a/app/utils/crm_calendar.py b/app/utils/crm_calendar.py new file mode 100644 index 00000000..9c3a5d0c --- /dev/null +++ b/app/utils/crm_calendar.py @@ -0,0 +1,46 @@ +"""Create in-app calendar events from CRM lead/deal activities with due dates.""" + +from __future__ import annotations + +import logging +from datetime import timedelta +from typing import Optional + +from app import db +from app.models import CalendarEvent + +logger = logging.getLogger(__name__) + + +def sync_activity_to_calendar( + *, + user_id: int, + title: str, + due_date, + description: Optional[str] = None, + client_id: Optional[int] = None, + duration_minutes: int = 30, +) -> Optional[CalendarEvent]: + """Create a calendar reminder/meeting for a CRM activity due date. + + Returns the created CalendarEvent, or None if due_date is missing / creation fails. + """ + if not due_date: + return None + try: + end_time = due_date + timedelta(minutes=duration_minutes) + event = CalendarEvent( + user_id=user_id, + title=title[:200], + start_time=due_date, + end_time=end_time, + description=description, + event_type="reminder", + client_id=client_id, + color="#2563EB", + ) + db.session.add(event) + return event + except Exception: + logger.exception("Failed to sync CRM activity to calendar") + return None diff --git a/app/utils/timezone.py b/app/utils/timezone.py index 9749839b..f5f17fb9 100644 --- a/app/utils/timezone.py +++ b/app/utils/timezone.py @@ -176,13 +176,18 @@ def get_app_timezone(): # Check if we have a database connection try: if db.session.is_active and not getattr(db.session, "_flushing", False): - try: - settings = Settings.get_settings() - if settings and settings.timezone: - return settings.timezone - except Exception as e: - # Log the error but continue with fallback - print(f"Warning: Could not get timezone from database: {e}") + # Settings.get_settings() may commit/rollback. Never call it while + # the session has pending work (e.g. Lead.convert_* via local_now()). + has_pending = bool(db.session.new or db.session.dirty or db.session.deleted) + if not has_pending: + try: + with db.session.no_autoflush: + settings = Settings.get_settings() + if settings and getattr(settings, "timezone", None): + return settings.timezone + except Exception as e: + # Log the error but continue with fallback + print(f"Warning: Could not get timezone from database: {e}") except RuntimeError as e: # RuntimeError typically means "Working outside of application context" # Fall back to environment variable diff --git a/desktop/src/renderer-react/src/views/CrmView.jsx b/desktop/src/renderer-react/src/views/CrmView.jsx index 8b318a93..b145d356 100644 --- a/desktop/src/renderer-react/src/views/CrmView.jsx +++ b/desktop/src/renderer-react/src/views/CrmView.jsx @@ -11,7 +11,7 @@ export function CrmView({ clients, apiClient, showToast }) { const [contacts, setContacts] = useState([]); const [notes, setNotes] = useState([]); const [loading, setLoading] = useState(false); - const [form, setForm] = useState({ first_name: '', last_name: '', email: '', company_name: '', name: '', amount: '', content: '' }); + const [form, setForm] = useState({ first_name: '', last_name: '', email: '', company_name: '', name: '', value: '', content: '' }); const loadLeadsDeals = async () => { setLoading(true); @@ -59,10 +59,16 @@ export function CrmView({ clients, apiClient, showToast }) { }, [tab, selectedClientId]); const createLead = async () => { + const firstName = form.first_name.trim(); + const lastName = form.last_name.trim(); + if (!firstName || !lastName) { + showToast('First and last name are required', 'error'); + return; + } try { await apiClient.createLead({ - first_name: form.first_name || 'Lead', - last_name: form.last_name || '', + first_name: firstName, + last_name: lastName, email: form.email || undefined, company_name: form.company_name || undefined, }); @@ -75,14 +81,15 @@ export function CrmView({ clients, apiClient, showToast }) { }; const createDeal = async () => { + const name = form.name.trim() || 'New deal'; try { await apiClient.createDeal({ - name: form.name || 'New deal', - amount: form.amount ? Number(form.amount) : 0, + name, + value: form.value ? Number(form.value) : undefined, client_id: selectedClientId ? Number(selectedClientId) : undefined, }); showToast('Deal created', 'success'); - setForm((f) => ({ ...f, name: '', amount: '' })); + setForm((f) => ({ ...f, name: '', value: '' })); await loadLeadsDeals(); } catch (error) { showToast(classifyAxiosError(error).message, 'error'); @@ -91,13 +98,20 @@ export function CrmView({ clients, apiClient, showToast }) { const createContact = async () => { if (!selectedClientId) return; + const firstName = form.first_name.trim(); + const lastName = form.last_name.trim(); + if (!firstName || !lastName) { + showToast('First and last name are required', 'error'); + return; + } try { await apiClient.createContact(selectedClientId, { - first_name: form.first_name || 'Contact', - last_name: form.last_name || '', + first_name: firstName, + last_name: lastName, email: form.email || undefined, }); showToast('Contact created', 'success'); + setForm((f) => ({ ...f, first_name: '', last_name: '', email: '' })); await loadClientExtras(selectedClientId); } catch (error) { showToast(classifyAxiosError(error).message, 'error'); @@ -153,7 +167,7 @@ export function CrmView({ clients, apiClient, showToast }) {
    setForm((f) => ({ ...f, name: e.target.value }))} /> - setForm((f) => ({ ...f, amount: e.target.value }))} /> + setForm((f) => ({ ...f, value: e.target.value }))} />