Skip to content

API Reference

Documentation for the propongo Python modules.

Main Flask application for Propongo.

create_app()

Create and configure the Flask application.

Returns:

Type Description
Flask

Configured Flask application

Source code in app/main.py
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
def create_app() -> Flask:
    """Create and configure the Flask application.

    Returns:
        Configured Flask application
    """
    app = Flask(__name__)
    app.secret_key = Config.SECRET_KEY

    logger.info(f"Starting Propongo v{__version__}")

    app.register_blueprint(export_bp)
    app.register_blueprint(snippets_bp)

    @app.context_processor
    def inject_version():
        """Inject application version into all templates."""
        return {"app_version": __version__}

    app.jinja_env.filters["md"] = lambda text: Markup(markdown_to_html(text))
    app.jinja_env.filters["currency"] = lambda value: f"{value:,.0f}"

    @app.route("/")
    def index():
        """List all proposals on the homepage."""
        proposals = Proposal.list_all()
        return render_template("index.html", proposals=proposals)

    @app.route("/new")
    def new_proposal():
        """Create a new proposal and redirect to its editor."""
        proposal = Proposal()
        proposal.save()
        logger.info(f"Created new proposal: {proposal.id}")
        return redirect(url_for("editor", proposal_id=proposal.id))

    @app.route("/editor/<proposal_id>")
    def editor(proposal_id):
        """Render the proposal editor page."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return redirect(url_for("index"))
        return render_template(
            "base.html",
            proposal=proposal,
            tasks=proposal.tasks,
            budget_items=proposal.budget_items,
        )

    @app.route("/api/proposal/<proposal_id>", methods=["GET"])
    def get_proposal(proposal_id: str) -> Tuple[Response, int]:
        """Return a proposal as JSON."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            logger.warning(f"Proposal not found: {proposal_id}")
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404
        return jsonify(proposal.to_dict()), 200

    @app.route("/api/proposal/<proposal_id>", methods=["PUT"])
    def save_proposal(proposal_id: str) -> Tuple[Response, int]:
        """Update and save an existing proposal."""
        data = request.get_json()
        if not data:
            return jsonify(ERROR_MESSAGES['NO_DATA']), 400

        with _proposal_locks_lock:
            if proposal_id not in _proposal_locks:
                _proposal_locks[proposal_id] = threading.Lock()
            lock = _proposal_locks[proposal_id]

        with lock:
            proposal = Proposal.load(proposal_id)
            if not proposal:
                logger.warning(f"Proposal not found for update: {proposal_id}")
                return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

            if "tasks" in data:
                incoming_tasks = data.pop("tasks")
                existing_by_id = {t.get("id"): t for t in proposal.tasks}
                merged = []
                for t in incoming_tasks:
                    tid = t.get("id", "")
                    if tid in existing_by_id:
                        merged_task = dict(existing_by_id[tid])
                        merged_task.update(t)
                    else:
                        merged_task = t
                    merged.append(merged_task)
                proposal.tasks = merged

            skip_fields = {"id", "title", "created_at"}
            for key, value in data.items():
                if key in skip_fields:
                    continue
                if hasattr(proposal, key):
                    setattr(proposal, key, value)

            proposal.save()
            return jsonify(proposal.to_dict())

    @app.route("/api/proposal/<proposal_id>", methods=["DELETE"])
    def delete_proposal(proposal_id):
        """Delete a proposal by ID."""
        Proposal.delete(proposal_id)
        return jsonify({"ok": True})

    @app.route("/api/proposal/<proposal_id>/save-as", methods=["POST"])
    def save_proposal_as(proposal_id):
        """Create a copy of a proposal with a new title."""
        data = request.get_json()
        title = data.get("title", "").strip()
        if not title:
            return jsonify({"error": "Title required"}), 400

        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        new_id = re.sub(r"[^a-z0-9_-]", "_", title.lower())
        new_id = re.sub(r"_+", "_", new_id).strip("_")
        if not new_id:
            new_id = uuid.uuid4().hex[:8]

        original_id = new_id
        counter = 1
        while Proposal.load(new_id):
            new_id = f"{original_id}_{counter}"
            counter += 1

        new_proposal = Proposal(id=new_id, title=title)
        new_proposal.client_name = proposal.client_name
        new_proposal.subtitle = getattr(proposal, 'subtitle', '') or ''
        new_proposal.project_summary = proposal.project_summary
        new_proposal.scope = getattr(proposal, 'scope', '') or ''
        new_proposal.tasks = list(proposal.tasks)
        new_proposal.qualifications = proposal.qualifications
        new_proposal.budget_items = list(proposal.budget_items)
        new_proposal.budget_item_timings = dict(proposal.budget_item_timings) if proposal.budget_item_timings else {}
        new_proposal.start_date = proposal.start_date
        new_proposal.indirect_percent = getattr(proposal, 'indirect_percent', 0) or 0
        new_proposal.show_budget_description = getattr(proposal, 'show_budget_description', False)
        new_proposal.budget_description = getattr(proposal, 'budget_description', '') or ''
        new_proposal.custom_sections = list(proposal.custom_sections) if proposal.custom_sections else []
        new_proposal.timeline_use_days = proposal.timeline_use_days
        new_proposal.timeline_show_budget = proposal.timeline_show_budget
        new_proposal.end_date = getattr(proposal, 'end_date', '') or ''
        new_proposal.milestones = list(proposal.milestones) if proposal.milestones else []
        new_proposal.reports = list(proposal.reports) if proposal.reports else []
        new_proposal.save()

        return jsonify({"id": new_id}), 201

    @app.route("/api/proposals", methods=["GET"])
    def list_proposals():
        """Return all proposals as JSON."""
        return jsonify(Proposal.list_all())

    @app.route("/templates")
    def templates_page():
        """Render the templates listing page."""
        templates = Proposal.list_templates()
        return render_template("templates.html", templates=templates)

    @app.route("/api/templates", methods=["GET"])
    def list_templates():
        """Return all templates as JSON."""
        return jsonify(Proposal.list_templates())

    @app.route("/api/template/<template_id>", methods=["DELETE"])
    def delete_template(template_id):
        """Delete a template by ID."""
        Proposal.delete(template_id, is_template=True)
        return jsonify({"ok": True})

    @app.route("/api/proposal/<proposal_id>/save-as-template", methods=["POST"])
    def save_as_template(proposal_id):
        """Save a proposal as a reusable template."""
        data = request.get_json()
        template_name = data.get("template_name", "").strip()
        template_category = data.get("template_category", "").strip()
        if not template_name:
            return jsonify({"error": "Template name required"}), 400

        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        new_id = re.sub(r"[^a-z0-9_-]", "_", template_name.lower())
        new_id = re.sub(r"_+", "_", new_id).strip("_")
        if not new_id:
            new_id = uuid.uuid4().hex[:8]

        original_id = new_id
        counter = 1
        while Proposal.load(new_id, is_template=True):
            new_id = f"{original_id}_{counter}"
            counter += 1

        tmpl = Proposal(id=new_id, title=proposal.title)
        tmpl.client_name = proposal.client_name
        tmpl.subtitle = getattr(proposal, 'subtitle', '') or ''
        tmpl.project_summary = proposal.project_summary
        tmpl.scope = getattr(proposal, 'scope', '') or ''
        tmpl.tasks = list(proposal.tasks)
        tmpl.qualifications = proposal.qualifications
        tmpl.budget_items = list(proposal.budget_items)
        tmpl.budget_item_timings = dict(proposal.budget_item_timings) if proposal.budget_item_timings else {}
        tmpl.indirect_percent = getattr(proposal, 'indirect_percent', 0) or 0
        tmpl.show_budget_description = getattr(proposal, 'show_budget_description', False)
        tmpl.budget_description = getattr(proposal, 'budget_description', '') or ''
        tmpl.custom_sections = list(proposal.custom_sections) if proposal.custom_sections else []
        tmpl.timeline_use_days = proposal.timeline_use_days
        tmpl.timeline_show_budget = proposal.timeline_show_budget
        tmpl.is_template = True
        tmpl.template_name = template_name
        tmpl.template_category = template_category
        tmpl.save()

        return jsonify({"id": new_id}), 201

    @app.route("/templates/new-from/<template_id>")
    def new_from_template(template_id):
        """Create a new proposal from a template and redirect to editor."""
        tmpl = Proposal.load(template_id, is_template=True)
        if not tmpl:
            return redirect(url_for("templates_page"))

        new_id = uuid.uuid4().hex[:8]
        proposal = Proposal(id=new_id, title=tmpl.title)
        proposal.client_name = tmpl.client_name
        proposal.subtitle = getattr(tmpl, 'subtitle', '') or ''
        proposal.project_summary = tmpl.project_summary
        proposal.scope = getattr(tmpl, 'scope', '') or ''
        proposal.tasks = list(tmpl.tasks)
        proposal.qualifications = tmpl.qualifications
        proposal.budget_items = list(tmpl.budget_items)
        proposal.budget_item_timings = dict(tmpl.budget_item_timings) if tmpl.budget_item_timings else {}
        proposal.indirect_percent = getattr(tmpl, 'indirect_percent', 0) or 0
        proposal.show_budget_description = getattr(tmpl, 'show_budget_description', False)
        proposal.budget_description = getattr(tmpl, 'budget_description', '') or ''
        proposal.custom_sections = list(tmpl.custom_sections) if tmpl.custom_sections else []
        proposal.timeline_use_days = tmpl.timeline_use_days
        proposal.timeline_show_budget = tmpl.timeline_show_budget
        proposal.save()

        return redirect(url_for("editor", proposal_id=proposal.id))

    @app.route("/scope/<proposal_id>")
    def scope_tab(proposal_id: str) -> Tuple[str, int] | Tuple[Response, int]:
        """Render the scope/editing tab for a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404
        return render_template("scope.html", proposal=proposal, tasks=proposal.tasks)

    @app.route("/budget/<proposal_id>")
    def budget_tab(proposal_id):
        """Render the budget tab with cost breakdowns per task."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        task_budgets = {}
        for task in proposal.tasks:
            items = [b for b in proposal.budget_items if b.get("task_id") == task["id"]]
            subtotal = sum(i.get("cost_per_unit", 0) * i.get("units", 0) for i in items)
            task_budgets[task["id"]] = {
                "task": task,
                "items": items,
                "subtotal": subtotal,
            }

        indirect_percent = getattr(proposal, 'indirect_percent', 0) or 0
        indirect_amount = proposal.total_budget * (indirect_percent / 100)
        total_with_indirect = proposal.total_budget + indirect_amount

        return render_template(
            "budget.html",
            proposal=proposal,
            tasks=proposal.tasks,
            budget_items=proposal.budget_items,
            total_budget=proposal.total_budget,
            task_budgets=task_budgets,
            indirect_percent=indirect_percent,
            indirect_amount=indirect_amount,
            total_with_indirect=total_with_indirect,
        )

    @app.route("/qualifications/<proposal_id>")
    def qualifications_tab(proposal_id):
        """Render the qualifications tab for a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404
        return render_template("qualifications.html", proposal=proposal)

    @app.route("/timeline/<proposal_id>")
    def timeline_tab(proposal_id):
        """Render the timeline tab with scheduling information."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        task_budgets = {}
        timings = proposal.budget_item_timings or {}
        for task in proposal.tasks:
            items = [b for b in proposal.budget_items if b.get("task_id") == task["id"]]
            for item in items:
                t = timings.get(item.get("id", ""), {})
                if t:
                    item["start_month"] = t.get("start_month")
                    item["start_year"] = t.get("start_year")
                    item["duration_months"] = t.get("duration_months", 1)
                    if t.get("lead_entity"):
                        item["lead_entity"] = t["lead_entity"]
                    item["recurring"] = t.get("recurring", False)
                    item["recurring_interval"] = t.get("recurring_interval", 3)
            if items:
                task_budgets[task["id"]] = {
                    "task": task,
                    "items": items,
                }

        try:
            sd = datetime.strptime(proposal.start_date, "%Y-%m-%d")
            start_date_month = sd.month
            start_date_year = sd.year
        except (ValueError, TypeError):
            now = datetime.now()
            start_date_month = now.month
            start_date_year = now.year

        try:
            ed = datetime.strptime(proposal.end_date, "%Y-%m-%d") if proposal.end_date else None
            end_date_month = ed.month if ed else start_date_month
            end_date_year = ed.year if ed else start_date_year + 1
        except (ValueError, TypeError):
            end_date_month = start_date_month
            end_date_year = start_date_year + 1

        return render_template(
            "timeline.html",
            proposal=proposal,
            tasks=proposal.tasks,
            start_date=proposal.start_date,
            start_date_month=start_date_month,
            start_date_year=start_date_year,
            end_date=proposal.end_date,
            end_date_month=end_date_month,
            end_date_year=end_date_year,
            task_budgets=task_budgets,
        )

    @app.route("/custom-sections/<proposal_id>")
    def custom_sections_tab(proposal_id):
        """Render the custom sections tab for a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404
        custom_sections = getattr(proposal, 'custom_sections', [])
        sections = sorted(custom_sections, key=lambda s: s.get("order", 0))
        return render_template(
            "custom_sections.html",
            proposal=proposal,
            sections=sections
        )

    @app.route("/api/section/<proposal_id>", methods=["POST"])
    def add_section(proposal_id):
        """Add a new custom section to a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        data = request.get_json()
        custom_sections = getattr(proposal, 'custom_sections', [])
        new_section = {
            "id": str(uuid.uuid4()),
            "title": data.get("title", "New Section"),
            "content": data.get("content", ""),
            "order": len(custom_sections)
        }
        if not hasattr(proposal, 'custom_sections') or proposal.custom_sections is None:
            proposal.custom_sections = []
        proposal.custom_sections.append(new_section)
        proposal.save()
        return jsonify(new_section), 201

    @app.route("/api/section/<proposal_id>/<section_id>", methods=["PUT"])
    def update_section(proposal_id, section_id):
        """Update an existing custom section."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        data = request.get_json()
        sections = getattr(proposal, 'custom_sections', [])
        for section in sections:
            if section["id"] == section_id:
                section.update({
                    "title": data.get("title", section["title"]),
                    "content": data.get("content", section["content"]),
                    "order": data.get("order", section.get("order", 0))
                })
                break

        proposal.save()
        return jsonify({"ok": True})

    @app.route("/api/section/<proposal_id>/<section_id>", methods=["DELETE"])
    def delete_section(proposal_id, section_id):
        """Delete a custom section from a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        sections = getattr(proposal, 'custom_sections', [])
        proposal.custom_sections = [
            s for s in sections if s["id"] != section_id
        ]
        proposal.save()
        return jsonify({"ok": True})

    @app.route("/api/section/<proposal_id>/import-excel", methods=["POST"])
    def import_excel_section(proposal_id):
        """Import an Excel file as a markdown table custom section."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        if 'file' not in request.files:
            return jsonify({"error": "No file provided"}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "No file selected"}), 400

        if not file.filename.endswith(('.xlsx', '.xls')):
            return jsonify({"error": "Only Excel files (.xlsx, .xls) are supported"}), 400

        try:
            import pandas as pd
            import io
        except ImportError:
            logger.error("Pandas/openpyxl not installed")
            return jsonify(ERROR_MESSAGES['EXCEL_NOT_INSTALLED']), 500

        try:
            # Read Excel file
            excel_data = file.read()
            excel_file = io.BytesIO(excel_data)
            df = pd.read_excel(excel_file, engine='openpyxl' if file.filename.endswith('.xlsx') else 'xlrd')

            # Convert DataFrame to markdown table
            markdown_content = df.to_markdown(index=False)

            # Create new section with Excel data
            custom_sections = getattr(proposal, 'custom_sections', [])
            new_section = {
                "id": str(uuid.uuid4()),
                "title": request.form.get('title', file.filename),
                "content": markdown_content,
                "order": len(custom_sections)
            }

            if not hasattr(proposal, 'custom_sections') or proposal.custom_sections is None:
                proposal.custom_sections = []
            proposal.custom_sections.append(new_section)
            proposal.save()

            logger.info(f"Imported Excel file as section: {new_section['id']}")
            return jsonify(new_section), 201

        except (ValueError, KeyError) as e:
            logger.warning(f"Invalid Excel file: {e}")
            return jsonify({**ERROR_MESSAGES['EXCEL_INVALID_FILE'], 'details': str(e)}), 400
        except Exception as e:
            logger.error(f"Excel import failed: {e}")
            return jsonify(ERROR_MESSAGES['EXCEL_PROCESSING_ERROR']), 500

    @app.route("/api/section/<proposal_id>/reorder", methods=["PUT"])
    def reorder_sections(proposal_id):
        """Reorder custom sections within a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        data = request.get_json()
        section_order = data.get('section_order', [])

        sections = getattr(proposal, 'custom_sections', [])
        section_dict = {s['id']: s for s in sections}

        reordered = []
        for idx, section_id in enumerate(section_order):
            if section_id in section_dict:
                section = section_dict[section_id]
                section['order'] = idx
                reordered.append(section)

        proposal.custom_sections = reordered
        proposal.save()
        return jsonify({"ok": True})

    @app.route("/preview/<proposal_id>")
    def preview_tab(proposal_id):
        """Render the proposal preview page."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        ctx = build_export_context(proposal)
        return render_template("preview.html", **ctx)

    @app.route("/api/task/<proposal_id>", methods=["POST"])
    def add_task(proposal_id):
        """Add a new task to a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        data = request.get_json()
        task = {
            "id": uuid.uuid4().hex[:8],
            "name": data.get("name", ""),
            "description": data.get("description", ""),
            "start_month": data.get("start_month", 1),
            "start_year": data.get("start_year", datetime.now().year),
            "duration_months": data.get("duration_months", 1),
            "lead_months": data.get("lead_months", 0),
            "lead_entity": data.get("lead_entity", ""),
            "recurring": data.get("recurring", False),
            "recurring_interval": data.get("recurring_interval", 3),
        }
        proposal.tasks.append(task)
        proposal.save()
        return jsonify(task), 201

    @app.route("/api/task/<proposal_id>/<task_id>", methods=["DELETE"])
    def delete_task(proposal_id, task_id):
        """Delete a task and its associated budget items."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        proposal.tasks = [t for t in proposal.tasks if t.get("id") != task_id]
        proposal.budget_items = [b for b in proposal.budget_items if b.get("task_id") != task_id]
        proposal.save()
        return "", 200

    @app.route("/api/budget/<proposal_id>", methods=["POST"])
    def add_budget_item(proposal_id):
        """Add a new budget item to a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        data = request.get_json()
        try:
            item = {
                "id": uuid.uuid4().hex[:8],
                "task_id": data.get("task_id", ""),
                "name": data.get("name", ""),
                "cost_per_unit": validate_numeric(data.get("cost_per_unit", 0), "cost_per_unit", min_val=0.0),
                "units": validate_numeric(data.get("units", 1), "units", min_val=0.0),
            }
        except ValueError as e:
            logger.warning(f"Invalid budget item data: {e}")
            return jsonify({**ERROR_MESSAGES['INVALID_NUMERIC'], 'details': str(e)}), 400

        proposal.budget_items.append(item)
        proposal.save()
        logger.debug(f"Added budget item {item['id']} to proposal {proposal_id}")
        return jsonify(item), 201

    @app.route("/api/budget/<proposal_id>/<item_id>", methods=["DELETE"])
    def delete_budget_item(proposal_id, item_id):
        """Delete a budget item from a proposal."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        proposal.budget_items = [b for b in proposal.budget_items if b.get("id") != item_id]
        proposal.save()
        return jsonify({"ok": True})

    @app.route("/api/budget/<proposal_id>/<item_id>", methods=["PUT"])
    def update_budget_item(proposal_id: str, item_id: str) -> Tuple[Response, int]:
        """Update an existing budget item."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        data = request.get_json()
        if not data:
            return jsonify(ERROR_MESSAGES['NO_DATA']), 400

        for item in proposal.budget_items:
            if item.get("id") == item_id:
                try:
                    item["task_id"] = data.get("task_id", item.get("task_id", ""))
                    item["name"] = data.get("name", item.get("name", ""))
                    item["cost_per_unit"] = validate_numeric(
                        data.get("cost_per_unit", item.get("cost_per_unit", 0)),
                        "cost_per_unit",
                        min_val=0.0
                    )
                    item["units"] = validate_numeric(
                        data.get("units", item.get("units", 1)),
                        "units",
                        min_val=0.0
                    )
                except ValueError as e:
                    logger.warning(f"Invalid budget item data: {e}")
                    return jsonify({**ERROR_MESSAGES['INVALID_NUMERIC'], 'details': str(e)}), 400
                break
        else:
            return jsonify(ERROR_MESSAGES['BUDGET_ITEM_NOT_FOUND']), 404

        proposal.save()
        logger.debug(f"Updated budget item {item_id} in proposal {proposal_id}")
        return jsonify({"ok": True}), 200

    @app.route("/api/proposal/<proposal_id>/import-budget", methods=["POST"])
    def import_budget(proposal_id):
        """Import budget items and tasks from an Excel file."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

        if 'file' not in request.files:
            return jsonify({"error": "No file provided"}), 400

        file = request.files['file']
        if file.filename == '':
            return jsonify({"error": "No file selected"}), 400

        if not file.filename.endswith(('.xlsx', '.xls')):
            return jsonify({"error": "Only Excel files (.xlsx, .xls) are supported"}), 400

        try:
            from openpyxl import load_workbook
            import io
        except ImportError:
            return jsonify({"error": "openpyxl not installed"}), 500

        try:
            excel_data = file.read()
            wb = load_workbook(io.BytesIO(excel_data), read_only=True)
            ws = wb.active

            rows = list(ws.iter_rows(values_only=True))
            if len(rows) < 2:
                return jsonify({"error": "File has no data rows"}), 400

            header = [str(c).strip().lower() if c else "" for c in rows[0]]
            if not all(h in header for h in ["task", "item", "cost/unit", "units"]):
                return jsonify({"error": "Required columns: Task, Item, Cost/Unit, Units"}), 400

            task_idx = header.index("task")
            item_idx = header.index("item")
            cost_idx = header.index("cost/unit")
            units_idx = header.index("units")

            existing_tasks = {t["name"].strip().lower(): t for t in proposal.tasks}
            created_tasks = 0
            created_items = 0

            for row in rows[1:]:
                task_name = str(row[task_idx]).strip() if row[task_idx] else ""
                item_name = str(row[item_idx]).strip() if row[item_idx] else ""

                if not task_name or not item_name:
                    continue

                task_key = task_name.lower()
                if task_key not in existing_tasks:
                    new_task = {
                        "id": uuid.uuid4().hex[:8],
                        "name": task_name,
                        "description": "",
                        "start_month": 1,
                        "start_year": datetime.now().year,
                        "duration_months": 12,
                    }
                    proposal.tasks.append(new_task)
                    existing_tasks[task_key] = new_task
                    created_tasks += 1

                try:
                    cost = float(row[cost_idx]) if row[cost_idx] else 0
                    units = float(row[units_idx]) if row[units_idx] else 1
                except (ValueError, TypeError):
                    cost = 0
                    units = 1

                budget_item = {
                    "id": uuid.uuid4().hex[:8],
                    "task_id": existing_tasks[task_key]["id"],
                    "name": item_name,
                    "cost_per_unit": cost,
                    "units": units,
                }
                proposal.budget_items.append(budget_item)
                created_items += 1

            wb.close()
            proposal.save()

            return jsonify({
                "ok": True,
                "created_tasks": created_tasks,
                "created_items": created_items,
            }), 200

        except Exception as e:
            logger.error(f"Budget import failed: {e}")
            return jsonify({"error": f"Failed to process file: {str(e)}"}), 500

    @app.route("/api/budget-template", methods=["GET"])
    def download_budget_template():
        """Download a sample Excel budget template."""
        from openpyxl import Workbook
        import io

        wb = Workbook()
        ws = wb.active
        ws.title = "Budget Template"
        ws.append(["Task", "Item", "Cost/Unit", "Units"])
        ws.append(["Scoping", "Initial meeting", 200, 6])
        ws.append(["Scoping", "Data collection", 200, 20])
        ws.append(["Analysis", "Forest valuation", 300, 40])
        ws.append(["Results", "Report writing", 250, 30])

        buf = io.BytesIO()
        wb.save(buf)
        buf.seek(0)

        return Response(
            buf.getvalue(),
            mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            headers={"Content-Disposition": "attachment; filename=budget_template.xlsx"}
        )

    @app.route("/tracker/<proposal_id>")
    def tracker(proposal_id):
        """Render the project tracker page with progress and milestones."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return redirect(url_for("index"))

        indirect_percent = getattr(proposal, 'indirect_percent', 0) or 0
        indirect_amount = proposal.total_budget * (indirect_percent / 100)
        total_with_indirect = proposal.total_budget + indirect_amount

        task_budgets = {}
        timings = proposal.budget_item_timings or {}
        for task in proposal.tasks:
            items = [b for b in proposal.budget_items if b.get("task_id") == task["id"]]
            for item in items:
                t = timings.get(item.get("id", ""), {})
                if t:
                    item["actual_cost"] = t.get("actual_cost", 0)
            subtotal = sum(i.get("cost_per_unit", 0) * i.get("units", 0) for i in items)
            actual_total = sum(i.get("actual_cost", 0) for i in items)
            task_budgets[task["id"]] = {
                "task": task,
                "items": items,
                "subtotal": subtotal,
                "actual_total": actual_total,
            }

        milestones = getattr(proposal, 'milestones', []) or []
        reports = getattr(proposal, 'reports', []) or []

        completed_tasks = sum(1 for t in proposal.tasks if t.get("status") == "completed")
        total_tasks = len(proposal.tasks)
        overall_pct = round(completed_tasks / total_tasks * 100) if total_tasks else 0

        return render_template(
            "tracker.html",
            proposal=proposal,
            tasks=proposal.tasks,
            task_budgets=task_budgets,
            total_budget=proposal.total_budget,
            indirect_percent=indirect_percent,
            indirect_amount=indirect_amount,
            total_with_indirect=total_with_indirect,
            milestones=milestones,
            reports=reports,
            overall_pct=overall_pct,
        )

    @app.route("/api/tracker/<proposal_id>/task/<task_id>", methods=["PUT"])
    def update_tracker_task(proposal_id, task_id):
        """Update task progress, status, or notes in the tracker."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        data = request.get_json()
        for task in proposal.tasks:
            if task.get("id") == task_id:
                if "status" in data:
                    task["status"] = data["status"]
                if "progress_pct" in data:
                    task["progress_pct"] = int(data["progress_pct"])
                if "actual_start" in data:
                    task["actual_start"] = data["actual_start"]
                if "actual_end" in data:
                    task["actual_end"] = data["actual_end"]
                if "notes" in data:
                    task["notes"] = data["notes"]
                break
        else:
            return jsonify({"error": "Task not found"}), 404

        proposal.save()
        return jsonify({"ok": True})

    @app.route("/api/tracker/<proposal_id>/budget/<item_id>", methods=["PUT"])
    def update_tracker_budget(proposal_id, item_id):
        """Update the actual cost for a budget item in the tracker."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        data = request.get_json()
        timings = proposal.budget_item_timings or {}
        if item_id not in timings:
            timings[item_id] = {}
        if "actual_cost" in data:
            timings[item_id]["actual_cost"] = float(data["actual_cost"])
        proposal.budget_item_timings = timings
        proposal.save()
        return jsonify({"ok": True})

    @app.route("/api/tracker/<proposal_id>/milestone", methods=["POST"])
    def add_milestone(proposal_id):
        """Add a new milestone to the tracker."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        data = request.get_json()
        milestones = getattr(proposal, 'milestones', []) or []
        milestone = {
            "id": uuid.uuid4().hex[:8],
            "name": data.get("name", ""),
            "date": data.get("date", ""),
            "completed": False,
        }
        milestones.append(milestone)
        proposal.milestones = milestones
        proposal.save()
        return jsonify(milestone), 201

    @app.route("/api/tracker/<proposal_id>/milestone/<milestone_id>", methods=["PUT"])
    def update_milestone(proposal_id, milestone_id):
        """Update a milestone's name, date, or completion status."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        data = request.get_json()
        milestones = getattr(proposal, 'milestones', []) or []
        for m in milestones:
            if m["id"] == milestone_id:
                if "name" in data:
                    m["name"] = data["name"]
                if "date" in data:
                    m["date"] = data["date"]
                if "completed" in data:
                    m["completed"] = data["completed"]
                break
        else:
            return jsonify({"error": "Milestone not found"}), 404

        proposal.milestones = milestones
        proposal.save()
        return jsonify({"ok": True})

    @app.route("/api/tracker/<proposal_id>/milestone/<milestone_id>", methods=["DELETE"])
    def delete_milestone(proposal_id, milestone_id):
        """Delete a milestone from the tracker."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        milestones = getattr(proposal, 'milestones', []) or []
        proposal.milestones = [m for m in milestones if m["id"] != milestone_id]
        proposal.save()
        return jsonify({"ok": True})

    @app.route("/api/tracker/<proposal_id>/report", methods=["POST"])
    def add_report(proposal_id):
        """Add a new progress report to the tracker."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        data = request.get_json()
        reports = getattr(proposal, 'reports', []) or []
        report = {
            "id": uuid.uuid4().hex[:8],
            "date": data.get("date", datetime.now().strftime("%Y-%m-%d")),
            "title": data.get("title", ""),
            "content": data.get("content", ""),
        }
        reports.append(report)
        proposal.reports = reports
        proposal.save()
        return jsonify(report), 201

    @app.route("/api/tracker/<proposal_id>/report/<report_id>", methods=["PUT"])
    def update_report(proposal_id, report_id):
        """Update a progress report's content, title, or date."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        data = request.get_json()
        reports = getattr(proposal, 'reports', []) or []
        for r in reports:
            if r["id"] == report_id:
                if "title" in data:
                    r["title"] = data["title"]
                if "date" in data:
                    r["date"] = data["date"]
                if "content" in data:
                    r["content"] = data["content"]
                break
        else:
            return jsonify({"error": "Report not found"}), 404

        proposal.reports = reports
        proposal.save()
        return jsonify({"ok": True})

    @app.route("/api/tracker/<proposal_id>/report/<report_id>", methods=["DELETE"])
    def delete_report(proposal_id, report_id):
        """Delete a progress report from the tracker."""
        proposal = Proposal.load(proposal_id)
        if not proposal:
            return jsonify({"error": "Not found"}), 404

        reports = getattr(proposal, 'reports', []) or []
        proposal.reports = [r for r in reports if r["id"] != report_id]
        proposal.save()
        return jsonify({"ok": True})

    return app

markdown_to_html(text)

Convert Markdown text to HTML using the markdown library.

Parameters:

Name Type Description Default
text str

Markdown formatted text

required

Returns:

Type Description
str

HTML formatted string

Source code in app/main.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def markdown_to_html(text: str) -> str:
    """Convert Markdown text to HTML using the markdown library.

    Args:
        text: Markdown formatted text

    Returns:
        HTML formatted string
    """
    if not text:
        return ""
    return markdown.markdown(
        text,
        extensions=['tables', 'nl2br', 'fenced_code', 'sane_lists']
    )

run_server()

Run the development server.

Source code in app/main.py
1030
1031
1032
1033
1034
1035
1036
1037
def run_server() -> None:
    """Run the development server."""
    import logging as _logging
    _logging.getLogger("werkzeug").setLevel(_logging.WARNING)
    app = create_app()
    print("\n ✨✨✨ 🔌 Server started ✨✨✨")
    print(f"  👉  http://localhost:{Config.PORT}  👈\n")
    app.run(debug=Config.DEBUG, host=Config.HOST, port=Config.PORT)

validate_numeric(value, name, min_val=0.0)

Validate and convert a numeric value.

Parameters:

Name Type Description Default
value Any

Value to validate

required
name str

Name of the field (for error messages)

required
min_val float

Minimum allowed value

0.0

Returns:

Type Description
float

Validated float value

Raises:

Type Description
ValueError

If value is invalid

Source code in app/main.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def validate_numeric(value: Any, name: str, min_val: float = 0.0) -> float:
    """Validate and convert a numeric value.

    Args:
        value: Value to validate
        name: Name of the field (for error messages)
        min_val: Minimum allowed value

    Returns:
        Validated float value

    Raises:
        ValueError: If value is invalid
    """
    try:
        num = float(value)
        if not math.isfinite(num):
            raise ValueError(f"{name} must be a finite number")
        if num < min_val:
            raise ValueError(f"{name} must be >= {min_val}")
        return num
    except (ValueError, TypeError) as e:
        raise ValueError(f"Invalid {name}: {str(e)}")

Data models for Propongo.

Tasks and budget items are stored as dictionaries with the following structure:

Task dict

{ 'id': str, # UUID 'name': str, # Task name 'description': str, # Task description 'lead_entity': str, # Organization responsible 'start_month': int, # Start month (1-12) 'start_year': int, # Start year 'duration_months': int, # Duration in months }

BudgetItem dict

{ 'id': str, # UUID 'task_id': str, # Associated task UUID 'name': str, # Item name 'cost_per_unit': float, # Unit cost 'units': float, # Number of units }

Custom Section dict

{ 'id': str, # UUID 'title': str, # Section title 'content': str, # Markdown content 'order': int, # Display order }

Proposal dataclass

A project proposal containing tasks, budget items, and custom sections.

Source code in app/models.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@dataclass
class Proposal:
    """A project proposal containing tasks, budget items, and custom sections."""
    id: str = field(default_factory=lambda: str(uuid.uuid4()))
    title: str = "Untitled Proposal"
    client_name: str = ""
    subtitle: str = ""
    created_at: str = field(default_factory=lambda: datetime.now().isoformat())
    updated_at: str = field(default_factory=lambda: datetime.now().isoformat())

    project_summary: str = ""
    scope: str = ""
    tasks: list = field(default_factory=list)
    qualifications: str = ""

    budget_items: list = field(default_factory=list)
    budget_item_timings: dict = field(default_factory=dict)
    start_date: str = field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d"))
    end_date: str = ""
    indirect_percent: float = 0.0
    show_budget_description: bool = False
    budget_description: str = ""
    timeline_use_days: bool = False
    timeline_show_budget: bool = False
    custom_sections: list = field(default_factory=list)

    is_template: bool = False
    template_name: str = ""
    template_category: str = ""

    milestones: list = field(default_factory=list)
    reports: list = field(default_factory=list)

    def to_dict(self) -> dict:
        """Serialize the proposal to a dictionary."""
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict) -> "Proposal":
        """Create a Proposal from a dictionary, ignoring unknown fields."""
        return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})

    def save(self):
        """Save the proposal to disk as a JSON file."""
        ensure_dirs()
        self.updated_at = datetime.now().isoformat()
        target_dir = TEMPLATES_DIR if self.is_template else PROPOSALS_DIR
        filepath = os.path.join(target_dir, f"{self.id}.json")
        tmp = filepath + ".tmp"
        with open(tmp, "w") as f:
            json.dump(self.to_dict(), f, indent=2)
            f.write("\n")
        os.replace(tmp, filepath)

    @classmethod
    def load(cls, proposal_id: str, is_template: bool = False) -> Optional["Proposal"]:
        """Load a proposal or template by ID from disk."""
        target_dir = TEMPLATES_DIR if is_template else PROPOSALS_DIR
        filepath = os.path.join(target_dir, f"{proposal_id}.json")
        if not os.path.exists(filepath):
            return None
        try:
            with open(filepath, "r") as f:
                return cls.from_dict(json.load(f))
        except (json.JSONDecodeError, OSError):
            return None

    @classmethod
    def list_all(cls) -> list:
        """List all proposals, returning summaries sorted by most recent."""
        ensure_dirs()
        proposals = []
        for filename in sorted(os.listdir(PROPOSALS_DIR)):
            if filename.endswith(".json"):
                try:
                    with open(os.path.join(PROPOSALS_DIR, filename), "r") as f:
                        data = json.load(f)
                        proposals.append({
                            "id": data.get("id", filename.replace(".json", "")),
                            "title": data.get("title", "Untitled"),
                            "client_name": data.get("client_name", ""),
                            "subtitle": data.get("subtitle", ""),
                            "updated_at": data.get("updated_at", ""),
                        })
                except (json.JSONDecodeError, OSError):
                    continue
        return sorted(proposals, key=lambda x: x["updated_at"], reverse=True)

    @classmethod
    def list_templates(cls) -> list:
        """List all templates, returning summaries sorted by most recent."""
        ensure_dirs()
        templates = []
        for filename in sorted(os.listdir(TEMPLATES_DIR)):
            if filename.endswith(".json"):
                try:
                    with open(os.path.join(TEMPLATES_DIR, filename), "r") as f:
                        data = json.load(f)
                        templates.append({
                            "id": data.get("id", filename.replace(".json", "")),
                            "title": data.get("title", "Untitled"),
                            "template_name": data.get("template_name", ""),
                            "template_category": data.get("template_category", ""),
                            "updated_at": data.get("updated_at", ""),
                        })
                except (json.JSONDecodeError, OSError):
                    continue
        return sorted(templates, key=lambda x: x["updated_at"], reverse=True)

    @classmethod
    def delete(cls, proposal_id: str, is_template: bool = False) -> bool:
        """Delete a proposal or template by ID. Returns True if deleted."""
        target_dir = TEMPLATES_DIR if is_template else PROPOSALS_DIR
        filepath = os.path.join(target_dir, f"{proposal_id}.json")
        if os.path.exists(filepath):
            os.remove(filepath)
            return True
        return False

    @property
    def total_budget(self) -> float:
        """Compute total budget as the sum of cost_per_unit * units for all items."""
        return sum(
            item.get("cost_per_unit", 0) * item.get("units", 0)
            for item in self.budget_items
        )

total_budget property

Compute total budget as the sum of cost_per_unit * units for all items.

delete(proposal_id, is_template=False) classmethod

Delete a proposal or template by ID. Returns True if deleted.

Source code in app/models.py
178
179
180
181
182
183
184
185
186
@classmethod
def delete(cls, proposal_id: str, is_template: bool = False) -> bool:
    """Delete a proposal or template by ID. Returns True if deleted."""
    target_dir = TEMPLATES_DIR if is_template else PROPOSALS_DIR
    filepath = os.path.join(target_dir, f"{proposal_id}.json")
    if os.path.exists(filepath):
        os.remove(filepath)
        return True
    return False

from_dict(data) classmethod

Create a Proposal from a dictionary, ignoring unknown fields.

Source code in app/models.py
106
107
108
109
@classmethod
def from_dict(cls, data: dict) -> "Proposal":
    """Create a Proposal from a dictionary, ignoring unknown fields."""
    return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})

list_all() classmethod

List all proposals, returning summaries sorted by most recent.

Source code in app/models.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@classmethod
def list_all(cls) -> list:
    """List all proposals, returning summaries sorted by most recent."""
    ensure_dirs()
    proposals = []
    for filename in sorted(os.listdir(PROPOSALS_DIR)):
        if filename.endswith(".json"):
            try:
                with open(os.path.join(PROPOSALS_DIR, filename), "r") as f:
                    data = json.load(f)
                    proposals.append({
                        "id": data.get("id", filename.replace(".json", "")),
                        "title": data.get("title", "Untitled"),
                        "client_name": data.get("client_name", ""),
                        "subtitle": data.get("subtitle", ""),
                        "updated_at": data.get("updated_at", ""),
                    })
            except (json.JSONDecodeError, OSError):
                continue
    return sorted(proposals, key=lambda x: x["updated_at"], reverse=True)

list_templates() classmethod

List all templates, returning summaries sorted by most recent.

Source code in app/models.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
@classmethod
def list_templates(cls) -> list:
    """List all templates, returning summaries sorted by most recent."""
    ensure_dirs()
    templates = []
    for filename in sorted(os.listdir(TEMPLATES_DIR)):
        if filename.endswith(".json"):
            try:
                with open(os.path.join(TEMPLATES_DIR, filename), "r") as f:
                    data = json.load(f)
                    templates.append({
                        "id": data.get("id", filename.replace(".json", "")),
                        "title": data.get("title", "Untitled"),
                        "template_name": data.get("template_name", ""),
                        "template_category": data.get("template_category", ""),
                        "updated_at": data.get("updated_at", ""),
                    })
            except (json.JSONDecodeError, OSError):
                continue
    return sorted(templates, key=lambda x: x["updated_at"], reverse=True)

load(proposal_id, is_template=False) classmethod

Load a proposal or template by ID from disk.

Source code in app/models.py
123
124
125
126
127
128
129
130
131
132
133
134
@classmethod
def load(cls, proposal_id: str, is_template: bool = False) -> Optional["Proposal"]:
    """Load a proposal or template by ID from disk."""
    target_dir = TEMPLATES_DIR if is_template else PROPOSALS_DIR
    filepath = os.path.join(target_dir, f"{proposal_id}.json")
    if not os.path.exists(filepath):
        return None
    try:
        with open(filepath, "r") as f:
            return cls.from_dict(json.load(f))
    except (json.JSONDecodeError, OSError):
        return None

save()

Save the proposal to disk as a JSON file.

Source code in app/models.py
111
112
113
114
115
116
117
118
119
120
121
def save(self):
    """Save the proposal to disk as a JSON file."""
    ensure_dirs()
    self.updated_at = datetime.now().isoformat()
    target_dir = TEMPLATES_DIR if self.is_template else PROPOSALS_DIR
    filepath = os.path.join(target_dir, f"{self.id}.json")
    tmp = filepath + ".tmp"
    with open(tmp, "w") as f:
        json.dump(self.to_dict(), f, indent=2)
        f.write("\n")
    os.replace(tmp, filepath)

to_dict()

Serialize the proposal to a dictionary.

Source code in app/models.py
102
103
104
def to_dict(self) -> dict:
    """Serialize the proposal to a dictionary."""
    return asdict(self)

ensure_dirs()

Ensure data directories exist.

Source code in app/models.py
63
64
65
66
def ensure_dirs() -> None:
    """Ensure data directories exist."""
    os.makedirs(PROPOSALS_DIR, exist_ok=True)
    os.makedirs(TEMPLATES_DIR, exist_ok=True)

Export functionality for PDF, HTML, and DOCX generation.

ensure_export_dir()

Ensure export directory exists.

Source code in app/export.py
31
32
33
def ensure_export_dir() -> None:
    """Ensure export directory exists."""
    os.makedirs(EXPORT_DIR, exist_ok=True)

export_docx(proposal_id)

Export proposal as DOCX file.

Source code in app/export.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
@export_bp.route("/export/docx/<proposal_id>")
def export_docx(proposal_id: str) -> Tuple[Response, int] | Response:
    """Export proposal as DOCX file."""
    proposal = Proposal.load(proposal_id)
    if not proposal:
        logger.warning(f"Proposal not found for DOCX export: {proposal_id}")
        return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

    try:
        buf = _build_proposal_docx(proposal)
    except ImportError:
        return jsonify({"error": "python-docx not installed"}), 500
    except Exception as e:
        logger.error(f"DOCX export failed: {e}")
        return jsonify({"error": f"DOCX export failed: {str(e)}"}), 500

    return send_file(
        buf,
        mimetype="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        as_attachment=True,
        download_name=f"{proposal.title or 'proposal'}.docx",
    )

export_html(proposal_id)

Export proposal as HTML file.

Source code in app/export.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
@export_bp.route("/export/html/<proposal_id>")
def export_html(proposal_id: str) -> Tuple[Response, int] | Response:
    """Export proposal as HTML file."""
    proposal = Proposal.load(proposal_id)
    if not proposal:
        logger.warning(f"Proposal not found for HTML export: {proposal_id}")
        return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

    ctx = build_export_context(proposal)
    html_content = render_template("export_proposal.html", **ctx)

    return Response(
        html_content,
        mimetype="text/html",
        headers={"Content-Disposition": "inline"},
    )

export_pdf(proposal_id)

Export proposal as PDF.

Source code in app/export.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
@export_bp.route("/export/pdf/<proposal_id>")
def export_pdf(proposal_id: str) -> Tuple[Response, int] | Response:
    """Export proposal as PDF."""
    if HTML is None:
        return jsonify({"error": GTK3_MISSING_MSG}), 500

    proposal = Proposal.load(proposal_id)
    if not proposal:
        logger.warning(f"Proposal not found for PDF export: {proposal_id}")
        return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

    ctx = build_export_context(proposal)
    html_content = render_template("export_proposal.html", **ctx)

    ensure_export_dir()
    pdf_path = os.path.join(EXPORT_DIR, f"{proposal_id}.pdf")
    HTML(string=html_content, base_url=request.host_url).write_pdf(pdf_path)

    return send_file(
        pdf_path,
        mimetype="application/pdf",
        as_attachment=True,
        download_name=f"{proposal.title or 'proposal'}.pdf",
    )

export_tracker_docx(proposal_id)

Export tracker as DOCX.

Source code in app/export.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
@export_bp.route("/export/tracker/docx/<proposal_id>")
def export_tracker_docx(proposal_id: str) -> Tuple[Response, int] | Response:
    """Export tracker as DOCX."""
    proposal = Proposal.load(proposal_id)
    if not proposal:
        return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

    ctx = build_tracker_export_context(proposal)

    try:
        buf = _build_tracker_docx(proposal, ctx)
    except ImportError:
        return jsonify({"error": "python-docx not installed"}), 500
    except Exception as e:
        logger.error(f"Tracker DOCX export failed: {e}")
        return jsonify({"error": f"DOCX export failed: {str(e)}"}), 500

    return send_file(
        buf,
        mimetype="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        as_attachment=True,
        download_name=f"{proposal.title or 'project'}_tracker.docx",
    )

export_tracker_html(proposal_id)

Export tracker as HTML.

Source code in app/export.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
@export_bp.route("/export/tracker/html/<proposal_id>")
def export_tracker_html(proposal_id: str) -> Tuple[Response, int] | Response:
    """Export tracker as HTML."""
    proposal = Proposal.load(proposal_id)
    if not proposal:
        return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

    ctx = build_tracker_export_context(proposal)
    html_content = render_template("export_tracker.html", **ctx)

    return Response(
        html_content,
        mimetype="text/html",
        headers={"Content-Disposition": "inline"},
    )

export_tracker_pdf(proposal_id)

Export tracker as PDF.

Source code in app/export.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
@export_bp.route("/export/tracker/pdf/<proposal_id>")
def export_tracker_pdf(proposal_id: str) -> Tuple[Response, int] | Response:
    """Export tracker as PDF."""
    if HTML is None:
        return jsonify({"error": GTK3_MISSING_MSG}), 500

    proposal = Proposal.load(proposal_id)
    if not proposal:
        return jsonify(ERROR_MESSAGES['PROPOSAL_NOT_FOUND']), 404

    ctx = build_tracker_export_context(proposal)
    html_content = render_template("export_tracker.html", **ctx)

    ensure_export_dir()
    pdf_path = os.path.join(EXPORT_DIR, f"tracker_{proposal_id}.pdf")
    HTML(string=html_content, base_url=request.host_url).write_pdf(pdf_path)

    return send_file(
        pdf_path,
        mimetype="application/pdf",
        as_attachment=True,
        download_name=f"{proposal.title or 'project'}_tracker.pdf",
    )

Snippet management for reusable text blocks.

add_snippet(category)

Add a new snippet to the given category.

Source code in app/snippets.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@snippets_bp.route("/snippets/<category>", methods=["POST"])
def add_snippet(category):
    """Add a new snippet to the given category."""
    data = request.get_json()
    if not data or "title" not in data or "content" not in data:
        return jsonify({"error": "title and content required"}), 400

    snippet = {
        "id": data.get("id", uuid.uuid4().hex[:8]),
        "title": data["title"],
        "content": data["content"],
        "category": category,
    }

    if category == "custom":
        ensure_dirs()
        filepath = os.path.join(CUSTOM_DIR, f"{snippet['id']}.json")
        with open(filepath, "w") as f:
            json.dump(snippet, f, indent=2)
    elif category in ("organization", "deliverables"):
        snippets = load_snippets(f"{category}.json")
        snippets.append(snippet)
        save_snippets(f"{category}.json", snippets)
    else:
        return jsonify({"error": "Invalid category"}), 400

    return jsonify(snippet), 201

delete_snippet(category, snippet_id)

Delete a snippet by category and ID.

Source code in app/snippets.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
@snippets_bp.route("/snippets/<category>/<snippet_id>", methods=["DELETE"])
def delete_snippet(category, snippet_id):
    """Delete a snippet by category and ID."""
    if category == "custom":
        filepath = os.path.join(CUSTOM_DIR, f"{snippet_id}.json")
        if os.path.exists(filepath):
            os.remove(filepath)
            return jsonify({"ok": True})
    elif category in ("organization", "deliverables"):
        snippets = load_snippets(f"{category}.json")
        snippets = [s for s in snippets if s.get("id") != snippet_id]
        save_snippets(f"{category}.json", snippets)
        return jsonify({"ok": True})

    return jsonify(ERROR_MESSAGES['SECTION_NOT_FOUND']), 404

ensure_dirs()

Ensure snippet directories exist.

Source code in app/snippets.py
24
25
26
27
def ensure_dirs():
    """Ensure snippet directories exist."""
    os.makedirs(SNIPPETS_DIR, exist_ok=True)
    os.makedirs(CUSTOM_DIR, exist_ok=True)

get_all_snippets()

Return all snippets grouped by category.

Source code in app/snippets.py
58
59
60
61
62
63
64
65
@snippets_bp.route("/snippets")
def get_all_snippets():
    """Return all snippets grouped by category."""
    return jsonify({
        "organization": load_snippets("organization.json"),
        "deliverables": load_snippets("deliverables.json"),
        "custom": load_custom_snippets(),
    })

import_snippet()

Import a snippet from a .md, .txt, or .docx file.

Source code in app/snippets.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
@snippets_bp.route("/snippets/import", methods=["POST"])
def import_snippet():
    """Import a snippet from a .md, .txt, or .docx file."""
    if "file" not in request.files:
        return jsonify(ERROR_MESSAGES['NO_FILE']), 400

    file = request.files["file"]
    if not file.filename:
        return jsonify(ERROR_MESSAGES['NO_FILE']), 400

    filename = file.filename.lower()
    title = request.form.get("title", "").strip()
    if not title:
        title = os.path.splitext(file.filename)[0]

    try:
        if filename.endswith(".md") or filename.endswith(".markdown") or filename.endswith(".txt"):
            content = file.read().decode("utf-8")
        elif filename.endswith(".docx"):
            from docx import Document
            doc = Document(file)
            content = "\n\n".join(p.text for p in doc.paragraphs if p.text.strip())
        else:
            return jsonify({"error": "Unsupported file type. Use .md, .txt, or .docx"}), 400
    except Exception as e:
        return jsonify({"error": f"Failed to read file: {str(e)}"}), 400

    if not content.strip():
        return jsonify({"error": "File is empty"}), 400

    snippet = {
        "id": uuid.uuid4().hex[:8],
        "title": title,
        "content": content,
        "category": "custom",
    }

    ensure_dirs()
    filepath = os.path.join(CUSTOM_DIR, f"{snippet['id']}.json")
    with open(filepath, "w") as f:
        json.dump(snippet, f, indent=2)

    return jsonify(snippet), 201

load_custom_snippets()

Load all user-created custom snippets.

Source code in app/snippets.py
47
48
49
50
51
52
53
54
55
def load_custom_snippets():
    """Load all user-created custom snippets."""
    ensure_dirs()
    snippets = []
    for filename in sorted(os.listdir(CUSTOM_DIR)):
        if filename.endswith(".json"):
            with open(os.path.join(CUSTOM_DIR, filename), "r") as f:
                snippets.append(json.load(f))
    return snippets

load_snippets(filename)

Load stock snippets from the package directory.

Source code in app/snippets.py
30
31
32
33
34
35
36
def load_snippets(filename):
    """Load stock snippets from the package directory."""
    filepath = os.path.join(_PKG_DIR, filename)
    if os.path.exists(filepath):
        with open(filepath, "r") as f:
            return json.load(f)
    return []

save_snippets(filename, data)

Save snippets to a JSON file.

Source code in app/snippets.py
39
40
41
42
43
44
def save_snippets(filename, data):
    """Save snippets to a JSON file."""
    ensure_dirs()
    filepath = os.path.join(SNIPPETS_DIR, filename)
    with open(filepath, "w") as f:
        json.dump(data, f, indent=2)

Configuration settings for Propongo.

Config

Application configuration.

Source code in app/config.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Config:
    """Application configuration."""

    # Server settings
    HOST = os.environ.get('HOST', '0.0.0.0')
    PORT = int(os.environ.get('PORT', 5000))
    DEBUG = os.environ.get('DEBUG', 'True').lower() in ('true', '1', 'yes')

    # Security
    SECRET_KEY = os.environ.get('FLASK_SECRET_KEY', os.urandom(24).hex())

    # File paths
    if sys.platform == "win32":
        DATA_DIR = os.path.join(os.path.expanduser("~"), "Documents", "Propongo")
    else:
        DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data')
    PROPOSALS_DIR = os.path.join(DATA_DIR, 'proposals')
    EXPORTS_DIR = os.path.join(DATA_DIR, 'exports')

    # Logging
    LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')

Utility functions for Propongo.

build_export_context(proposal)

Build context dictionary for export and preview templates.

Parameters:

Name Type Description Default
proposal

Proposal object

required

Returns:

Name Type Description
dict Dict[str, Any]

Context dictionary with all necessary template variables

Source code in app/utils.py
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def build_export_context(proposal) -> Dict[str, Any]:
    """Build context dictionary for export and preview templates.

    Args:
        proposal: Proposal object

    Returns:
        dict: Context dictionary with all necessary template variables
    """
    indirect_percent = getattr(proposal, 'indirect_percent', 0) or 0
    indirect_amount = proposal.total_budget * (indirect_percent / 100)
    total_with_indirect = proposal.total_budget + indirect_amount

    tasks_with_timing = []
    for t in proposal.tasks:
        tasks_with_timing.append({
            "id": t.get("id", ""),
            "name": t.get("name", ""),
            "description": t.get("description", ""),
            "lead_entity": t.get("lead_entity", ""),
            "start_month": t.get("start_month"),
            "start_year": t.get("start_year"),
            "duration_months": t.get("duration_months", 1),
            "recurring": t.get("recurring", False),
            "recurring_interval": t.get("recurring_interval", 3),
        })

    budget_with_timing = []
    timings = proposal.budget_item_timings or {}
    for item in proposal.budget_items:
        item_id = item.get("id", "")
        timing = timings.get(item_id, {})
        budget_with_timing.append({
            **item,
            "start_month": timing.get("start_month"),
            "start_year": timing.get("start_year"),
            "duration_months": timing.get("duration_months", 1),
            "task_id": item.get("task_id", ""),
            "recurring": timing.get("recurring", False),
            "recurring_interval": timing.get("recurring_interval", 3),
        })

    from datetime import datetime as _dt
    try:
        sd = _dt.strptime(proposal.start_date, "%Y-%m-%d")
        proj_start_month = sd.month
        proj_start_year = sd.year
    except (ValueError, TypeError):
        proj_start_month = 1
        proj_start_year = 2025

    try:
        ed = _dt.strptime(proposal.end_date, "%Y-%m-%d") if proposal.end_date else None
        proj_end_month = ed.month if ed else proj_start_month
        proj_end_year = ed.year if ed else proj_start_year + 1
    except (ValueError, TypeError):
        proj_end_month = proj_start_month
        proj_end_year = proj_start_year + 1

    if proposal.end_date:
        timeline_total_months = max((proj_end_year - proj_start_year) * 12 + (proj_end_month - proj_start_month) + 1, 1)
    else:
        max_end = 0
        for t in tasks_with_timing:
            sm = t.get("start_month") or proj_start_month
            sy = t.get("start_year") or proj_start_year
            offset = (sy - proj_start_year) * 12 + (sm - proj_start_month)
            dur = t.get("duration_months") or 1
            if t.get("recurring"):
                interval = t.get("recurring_interval") or 3
                last = offset
                while last < 120:
                    end = last + dur
                    if end > max_end:
                        max_end = end
                    last += interval
            else:
                end = offset + dur
                if end > max_end:
                    max_end = end
        for bi in budget_with_timing:
            sm = bi.get("start_month") or proj_start_month
            sy = bi.get("start_year") or proj_start_year
            offset = (sy - proj_start_year) * 12 + (sm - proj_start_month)
            dur = bi.get("duration_months") or 1
            if bi.get("recurring"):
                interval = bi.get("recurring_interval") or 3
                last = offset
                while last < 120:
                    end = last + dur
                    if end > max_end:
                        max_end = end
                    last += interval
            else:
                end = offset + dur
                if end > max_end:
                    max_end = end
        timeline_total_months = max(max_end, 1)
    if timeline_total_months <= 12:
        timeline_granularity = "months"
    elif timeline_total_months <= 36:
        timeline_granularity = "quarters"
    else:
        timeline_granularity = "years"

    task_bi_data = {}
    for bi in budget_with_timing:
        tid = bi.get("task_id", "")
        if not tid:
            continue
        sm = bi.get("start_month") or proj_start_month
        sy = bi.get("start_year") or proj_start_year
        bi_offset = (sy - proj_start_year) * 12 + (sm - proj_start_month)
        bi_dur = bi.get("duration_months") or 1
        if tid not in task_bi_data:
            task_bi_data[tid] = {"min_offset": bi_offset, "max_end": bi_offset + bi_dur}
        else:
            task_bi_data[tid]["min_offset"] = min(task_bi_data[tid]["min_offset"], bi_offset)
            task_bi_data[tid]["max_end"] = max(task_bi_data[tid]["max_end"], bi_offset + bi_dur)

    all_rows = []
    for t in tasks_with_timing:
        sm = t.get("start_month") or proj_start_month
        sy = t.get("start_year") or proj_start_year
        offset = (sy - proj_start_year) * 12 + (sm - proj_start_month)
        dur = t.get("duration_months") or 1
        tid = t.get("id", "")
        recurring = t.get("recurring", False)
        interval = t.get("recurring_interval") or 3

        if tid in task_bi_data:
            offset = task_bi_data[tid]["min_offset"]
            dur = task_bi_data[tid]["max_end"] - task_bi_data[tid]["min_offset"]
            if dur < 1:
                dur = 1
            recurring = False

        if recurring:
            bars = []
            r_offset = offset
            while r_offset < timeline_total_months:
                bars.append({"offset": r_offset, "duration": dur})
                r_offset += interval
            all_rows.append({
                "name": t.get("name", ""),
                "bars": bars,
                "is_indent": False,
                "lead_entity": t.get("lead_entity", ""),
            })
        else:
            all_rows.append({
                "name": t.get("name", ""),
                "bars": [{"offset": offset, "duration": dur}],
                "is_indent": False,
                "lead_entity": t.get("lead_entity", ""),
            })

        for bi in budget_with_timing:
            if bi.get("task_id") == tid:
                bi_sm = bi.get("start_month") or sm
                bi_sy = bi.get("start_year") or sy
                bi_offset = (bi_sy - proj_start_year) * 12 + (bi_sm - proj_start_month)
                bi_dur = bi.get("duration_months") or 1
                bi_recurring = bi.get("recurring", False)
                bi_interval = bi.get("recurring_interval") or 3
                if bi_recurring:
                    bars = []
                    br_offset = bi_offset
                    while br_offset < timeline_total_months:
                        bars.append({"offset": br_offset, "duration": bi_dur})
                        br_offset += bi_interval
                    all_rows.append({
                        "name": bi.get("name", ""),
                        "bars": bars,
                        "is_indent": True,
                        "lead_entity": "",
                    })
                else:
                    all_rows.append({
                        "name": bi.get("name", ""),
                        "bars": [{"offset": bi_offset, "duration": bi_dur}],
                        "is_indent": True,
                        "lead_entity": "",
                    })

    return {
        "proposal": proposal,
        "tasks": tasks_with_timing,
        "budget_items": proposal.budget_items,
        "budget_with_timing": budget_with_timing,
        "total_budget": proposal.total_budget,
        "indirect_percent": indirect_percent,
        "indirect_amount": indirect_amount,
        "total_with_indirect": total_with_indirect,
        "timeline_granularity": timeline_granularity,
        "timeline_total_months": timeline_total_months,
        "all_rows": all_rows,
    }

build_tracker_export_context(proposal)

Build context dictionary for tracker export templates.

Parameters:

Name Type Description Default
proposal

Proposal object

required

Returns:

Name Type Description
dict Dict[str, Any]

Context dictionary with all necessary template variables

Source code in app/utils.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def build_tracker_export_context(proposal) -> Dict[str, Any]:
    """Build context dictionary for tracker export templates.

    Args:
        proposal: Proposal object

    Returns:
        dict: Context dictionary with all necessary template variables
    """
    indirect_percent = getattr(proposal, 'indirect_percent', 0) or 0
    indirect_amount = proposal.total_budget * (indirect_percent / 100)
    total_with_indirect = proposal.total_budget + indirect_amount

    timings = proposal.budget_item_timings or {}
    task_budgets = {}
    for task in proposal.tasks:
        items = [b for b in proposal.budget_items if b.get("task_id") == task["id"]]
        for item in items:
            t = timings.get(item.get("id", ""), {})
            if t:
                item["actual_cost"] = t.get("actual_cost", 0)
        subtotal = sum(i.get("cost_per_unit", 0) * i.get("units", 0) for i in items)
        actual_total = sum(i.get("actual_cost", 0) for i in items)
        task_budgets[task["id"]] = {
            "task": task,
            "items": items,
            "subtotal": subtotal,
            "actual_total": actual_total,
        }

    total_actual = sum(tb["actual_total"] for tb in task_budgets.values())

    milestones = getattr(proposal, 'milestones', []) or []
    reports = getattr(proposal, 'reports', []) or []

    completed_tasks = sum(1 for t in proposal.tasks if t.get("status") == "completed")
    total_tasks = len(proposal.tasks)
    overall_pct = round(completed_tasks / total_tasks * 100) if total_tasks else 0

    return {
        "proposal": proposal,
        "tasks": proposal.tasks,
        "task_budgets": task_budgets,
        "total_budget": proposal.total_budget,
        "indirect_percent": indirect_percent,
        "indirect_amount": indirect_amount,
        "total_with_indirect": total_with_indirect,
        "total_actual": total_actual,
        "milestones": milestones,
        "reports": reports,
        "overall_pct": overall_pct,
    }