diff --git a/PROJECT_STATE.md b/PROJECT_STATE.md index c8d7fd6..d089cef 100644 --- a/PROJECT_STATE.md +++ b/PROJECT_STATE.md @@ -1,3 +1,34 @@ +# Project State Update - v0.6.0 +Updated: 2026-04-11 01:49:22 UTC + +## Current Version +v0.6.0 + +## Current Status +OTB Billing is now a service-launch platform, not just billing. + +## Completed This Session +- Added /portal/services page +- Added portal_services.py route module +- Created portal_base.html shared template +- Converted dashboard + services page to shared layout +- Restored consistent branding, nav, footer, toggle +- Added service cards (Follow-me, Video, Miner) +- Fixed external service routing +- Enabled new-tab launch for services + +## Architecture +Using shared base template: +templates/portal_base.html + +All pages now: +{% extends "portal_base.html" %} + +## Next Steps +- Unify client identity across all routes +- Add Follow-me provisioning + billing linkage +- Move inline CSS into shared styles later + ### v0.5.3 - 2026-03-27 21:25:28 - OTB Billing crypto payment flow is now stable end-to-end. diff --git a/README.md b/README.md index f3c2fa7..997b297 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,20 @@ +## v0.6.0 - 2026-04-11 01:49:22 + +### Highlights +- Added authenticated /portal/services page as a service hub +- Introduced modular route backend/routes/portal_services.py +- Created shared templates/portal_base.html layout +- Converted portal pages to base-template architecture +- Added service cards (Follow-me, Video, Miner Rentals) +- Fixed branding, nav, footer, and toggle consistency +- Corrected Follow-me external link +- External services now open in new tabs +- Improved identity display for logged-in user + +### Notes +- portal_base.html is now the standard structure for future pages and projects +- Billing portal is now the launch point for all OTB services + ## v0.5.3 - 2026-03-27 21:25:11 - Fixed stale pending crypto payment lock issue so abandoned wallet attempts no longer trap the invoice diff --git a/VERSION b/VERSION index 4bc4a91..60f6343 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -v0.5.3 +v0.6.0 diff --git a/backend/app.py b/backend/app.py index 7c10541..cbbc1bd 100644 --- a/backend/app.py +++ b/backend/app.py @@ -11,6 +11,7 @@ from decimal import Decimal, InvalidOperation from pathlib import Path from email.message import EmailMessage from dateutil.relativedelta import relativedelta +from routes.portal_services import portal_services_bp from io import BytesIO, StringIO import csv @@ -40,6 +41,7 @@ app = Flask( template_folder="../templates", static_folder="../static", ) +app.register_blueprint(portal_services_bp) app.config["OTB_HEALTH_DB_CONNECTOR"] = get_db_connection TERMS_VERSION = "v1.0" @@ -2425,7 +2427,17 @@ def admin_login(): username = (request.form.get("username") or "").strip() password = (request.form.get("password") or "").strip() - if username == OTB_ADMIN_USER and password == OTB_ADMIN_PASS: + admin_ok = ( + (username == OTB_ADMIN_USER and password == OTB_ADMIN_PASS) or + ( + username == os.getenv("OTB_ADMIN_USER_2", "").strip() and + password == os.getenv("OTB_ADMIN_PASS_2", "").strip() and + os.getenv("OTB_ADMIN_USER_2", "").strip() != "" and + os.getenv("OTB_ADMIN_PASS_2", "").strip() != "" + ) + ) + + if admin_ok: session["admin_authenticated"] = True session["admin_user"] = username return redirect(session.pop("admin_next", "/")) diff --git a/backend/app.py.fix_indent_backup b/backend/app.py.fix_indent_backup new file mode 100644 index 0000000..f677271 --- /dev/null +++ b/backend/app.py.fix_indent_backup @@ -0,0 +1,3075 @@ +from flask import Flask, render_template, request, redirect, send_file, make_response, jsonify +from db import get_db_connection +from utils import generate_client_code, generate_service_code +from datetime import datetime, timezone, date, timedelta +from zoneinfo import ZoneInfo +from decimal import Decimal, InvalidOperation +from pathlib import Path +from email.message import EmailMessage +from dateutil.relativedelta import relativedelta + +from io import BytesIO, StringIO +import csv +import zipfile +import smtplib +import time +import shutil +from reportlab.lib.pagesizes import letter +from reportlab.pdfgen import canvas +from reportlab.lib.utils import ImageReader + +app = Flask( + __name__, + template_folder="../templates", + static_folder="../static", +) + +LOCAL_TZ = ZoneInfo("America/Toronto") + +BASE_DIR = Path(__file__).resolve().parent.parent +APP_START_TIME = time.time() + + +def load_version(): + try: + with open(BASE_DIR / "VERSION", "r") as f: + return f.read().strip() + except Exception: + return "unknown" + +APP_VERSION = load_version() + +@app.context_processor +def inject_version(): + return {"app_version": APP_VERSION} + +@app.context_processor +def inject_app_settings(): + return {"app_settings": get_app_settings()} + +def fmt_local(dt_value): + if not dt_value: + return "" + if isinstance(dt_value, str): + try: + dt_value = datetime.fromisoformat(dt_value) + except ValueError: + return str(dt_value) + if dt_value.tzinfo is None: + dt_value = dt_value.replace(tzinfo=timezone.utc) + return dt_value.astimezone(LOCAL_TZ).strftime("%Y-%m-%d %I:%M:%S %p") + +def to_decimal(value): + if value is None or value == "": + return Decimal("0") + try: + return Decimal(str(value)) + except (InvalidOperation, ValueError): + return Decimal("0") + +def fmt_money(value, currency_code="CAD"): + amount = to_decimal(value) + if currency_code == "CAD": + return f"{amount:.2f}" + return f"{amount:.8f}" + +def refresh_overdue_invoices(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE invoices + SET status = 'overdue' + WHERE due_at IS NOT NULL + AND due_at < UTC_TIMESTAMP() + AND status IN ('pending', 'partial') + """) + conn.commit() + conn.close() + +def recalc_invoice_totals(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, total_amount, due_at, status + FROM invoices + WHERE id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return + + cursor.execute(""" + SELECT COALESCE(SUM(payment_amount), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_id,)) + row = cursor.fetchone() + + total_paid = to_decimal(row["total_paid"]) + total_amount = to_decimal(invoice["total_amount"]) + + if invoice["status"] == "cancelled": + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET amount_paid = %s, + paid_at = NULL + WHERE id = %s + """, ( + str(total_paid), + invoice_id + )) + conn.commit() + conn.close() + return + + if total_paid >= total_amount and total_amount > 0: + new_status = "paid" + paid_at_value = "UTC_TIMESTAMP()" + elif total_paid > 0: + new_status = "partial" + paid_at_value = "NULL" + else: + if invoice["due_at"] and invoice["due_at"] < datetime.utcnow(): + new_status = "overdue" + else: + new_status = "pending" + paid_at_value = "NULL" + + update_cursor = conn.cursor() + update_cursor.execute(f""" + UPDATE invoices + SET amount_paid = %s, + status = %s, + paid_at = {paid_at_value} + WHERE id = %s + """, ( + str(total_paid), + new_status, + invoice_id + )) + + conn.commit() + conn.close() + + + +def format_seconds_short(total_seconds): + total_seconds = int(total_seconds) + days = total_seconds // 86400 + hours = (total_seconds % 86400) // 3600 + minutes = (total_seconds % 3600) // 60 + + parts = [] + if days > 0: + parts.append(f"{days}d") + if hours > 0 or days > 0: + parts.append(f"{hours}h") + parts.append(f"{minutes}m") + + return " ".join(parts) + + +def read_system_uptime_seconds(): + try: + with open("/proc/uptime", "r") as f: + return float(f.read().split()[0]) + except Exception: + return None + + +def read_memory_usage_mb(): + try: + meminfo = {} + with open("/proc/meminfo", "r") as f: + for line in f: + key, value = line.split(":", 1) + meminfo[key.strip()] = value.strip() + + mem_total_kb = int(meminfo["MemTotal"].split()[0]) + mem_available_kb = int(meminfo["MemAvailable"].split()[0]) + mem_used_kb = mem_total_kb - mem_available_kb + + return round(mem_used_kb / 1024), round(mem_total_kb / 1024) + except Exception: + return None, None + + +def get_client_credit_balance(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT COALESCE(SUM(amount), 0) AS balance + FROM credit_ledger + WHERE client_id = %s + """, (client_id,)) + row = cursor.fetchone() + conn.close() + return to_decimal(row["balance"]) + + +def generate_invoice_number(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT invoice_number + FROM invoices + WHERE invoice_number IS NOT NULL + AND invoice_number LIKE 'INV-%' + ORDER BY id DESC + LIMIT 1 + """) + row = cursor.fetchone() + conn.close() + + if not row or not row.get("invoice_number"): + return "INV-0001" + + invoice_number = str(row["invoice_number"]).strip() + + try: + number = int(invoice_number.split("-")[1]) + except (IndexError, ValueError): + return "INV-0001" + + return f"INV-{number + 1:04d}" + + +def ensure_subscriptions_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS subscriptions ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + client_id INT UNSIGNED NOT NULL, + service_id INT UNSIGNED NULL, + subscription_name VARCHAR(255) NOT NULL, + billing_interval ENUM('monthly','quarterly','yearly') NOT NULL DEFAULT 'monthly', + price DECIMAL(18,8) NOT NULL DEFAULT 0.00000000, + currency_code VARCHAR(16) NOT NULL DEFAULT 'CAD', + start_date DATE NOT NULL, + next_invoice_date DATE NOT NULL, + status ENUM('active','paused','cancelled') NOT NULL DEFAULT 'active', + notes TEXT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + KEY idx_subscriptions_client_id (client_id), + KEY idx_subscriptions_service_id (service_id), + KEY idx_subscriptions_status (status), + KEY idx_subscriptions_next_invoice_date (next_invoice_date) + ) + """) + conn.commit() + conn.close() + + +def get_next_subscription_date(current_date, billing_interval): + if isinstance(current_date, str): + current_date = datetime.strptime(current_date, "%Y-%m-%d").date() + + if billing_interval == "yearly": + return current_date + relativedelta(years=1) + if billing_interval == "quarterly": + return current_date + relativedelta(months=3) + return current_date + relativedelta(months=1) + + +def generate_due_subscription_invoices(run_date=None): + ensure_subscriptions_table() + + today = run_date or date.today() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + s.*, + c.client_code, + c.company_name, + srv.service_code, + srv.service_name + FROM subscriptions s + JOIN clients c ON s.client_id = c.id + LEFT JOIN services srv ON s.service_id = srv.id + WHERE s.status = 'active' + AND s.next_invoice_date <= %s + ORDER BY s.next_invoice_date ASC, s.id ASC + """, (today,)) + due_subscriptions = cursor.fetchall() + + created_count = 0 + created_invoice_numbers = [] + + for sub in due_subscriptions: + invoice_number = generate_invoice_number() + due_dt = datetime.combine(today + timedelta(days=14), datetime.min.time()) + + note_parts = [f"Recurring subscription: {sub['subscription_name']}"] + if sub.get("service_code"): + note_parts.append(f"Service: {sub['service_code']}") + if sub.get("service_name"): + note_parts.append(f"({sub['service_name']})") + if sub.get("notes"): + note_parts.append(f"Notes: {sub['notes']}") + + note_text = " ".join(note_parts) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO invoices + ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + subtotal_amount, + tax_amount, + issued_at, + due_at, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, 0, UTC_TIMESTAMP(), %s, 'pending', %s) + """, ( + sub["client_id"], + sub["service_id"], + invoice_number, + sub["currency_code"], + str(sub["price"]), + str(sub["price"]), + due_dt, + note_text, + )) + + next_date = get_next_subscription_date(sub["next_invoice_date"], sub["billing_interval"]) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE subscriptions + SET next_invoice_date = %s + WHERE id = %s + """, (next_date, sub["id"])) + + created_count += 1 + created_invoice_numbers.append(invoice_number) + + conn.commit() + conn.close() + + return { + "created_count": created_count, + "invoice_numbers": created_invoice_numbers, + "run_date": str(today), + } + + +APP_SETTINGS_DEFAULTS = { + "business_name": "OTB Billing", + "business_tagline": "By a contractor, for contractors", + "business_logo_url": "", + "business_email": "", + "business_phone": "", + "business_address": "", + "business_website": "", + "tax_label": "HST", + "tax_rate": "13.00", + "tax_number": "", + "business_number": "", + "default_currency": "CAD", + "report_frequency": "monthly", + "invoice_footer": "", + "payment_terms": "", + "local_country": "Canada", + "apply_local_tax_only": "1", + "smtp_host": "", + "smtp_port": "587", + "smtp_user": "", + "smtp_pass": "", + "smtp_from_email": "", + "smtp_from_name": "", + "smtp_use_tls": "1", + "smtp_use_ssl": "0", + "report_delivery_email": "", +} + +def ensure_app_settings_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS app_settings ( + setting_key VARCHAR(100) NOT NULL PRIMARY KEY, + setting_value TEXT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + ) + """) + conn.commit() + conn.close() + +def get_app_settings(): + ensure_app_settings_table() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT setting_key, setting_value + FROM app_settings + """) + rows = cursor.fetchall() + conn.close() + + settings = dict(APP_SETTINGS_DEFAULTS) + for row in rows: + settings[row["setting_key"]] = row["setting_value"] if row["setting_value"] is not None else "" + + return settings + +def save_app_settings(form_data): + ensure_app_settings_table() + conn = get_db_connection() + cursor = conn.cursor() + + for key in APP_SETTINGS_DEFAULTS.keys(): + if key in {"apply_local_tax_only", "smtp_use_tls", "smtp_use_ssl"}: + value = "1" if form_data.get(key) else "0" + else: + value = (form_data.get(key) or "").strip() + + cursor.execute(""" + INSERT INTO app_settings (setting_key, setting_value) + VALUES (%s, %s) + ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value) + """, (key, value)) + + conn.commit() + conn.close() + + +@app.template_filter("localtime") +def localtime_filter(value): + return fmt_local(value) + +@app.template_filter("money") +def money_filter(value, currency_code="CAD"): + return fmt_money(value, currency_code) + + + + +def get_report_period_bounds(frequency): + now_local = datetime.now(LOCAL_TZ) + + if frequency == "yearly": + start_local = now_local.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) + label = f"{now_local.year}" + elif frequency == "quarterly": + quarter = ((now_local.month - 1) // 3) + 1 + start_month = (quarter - 1) * 3 + 1 + start_local = now_local.replace(month=start_month, day=1, hour=0, minute=0, second=0, microsecond=0) + label = f"Q{quarter} {now_local.year}" + else: + start_local = now_local.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + label = now_local.strftime("%B %Y") + + start_utc = start_local.astimezone(timezone.utc).replace(tzinfo=None) + end_utc = now_local.astimezone(timezone.utc).replace(tzinfo=None) + + return start_utc, end_utc, label + + + +def build_accounting_package_bytes(): + import json +import os + import zipfile + from io import BytesIO + + report = get_revenue_report_data() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.created_at, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + ORDER BY i.created_at DESC + """) + invoices = cursor.fetchall() + + conn.close() + + payload = { + "report": report, + "invoices": invoices + } + + json_bytes = json.dumps(payload, indent=2, default=str).encode() + + zip_buffer = BytesIO() + + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("revenue_report.json", json.dumps(report, indent=2)) + z.writestr("invoices.json", json.dumps(invoices, indent=2, default=str)) + + zip_buffer.seek(0) + + filename = f"accounting_package_{report.get('period_label','report')}.zip" + + return zip_buffer.read(), filename + + + +def get_revenue_report_data(): + settings = get_app_settings() + frequency = (settings.get("report_frequency") or "monthly").strip().lower() + if frequency not in {"monthly", "quarterly", "yearly"}: + frequency = "monthly" + + start_utc, end_utc, label = get_report_period_bounds(frequency) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT COALESCE(SUM(cad_value_at_payment), 0) AS collected + FROM payments + WHERE payment_status = 'confirmed' + AND received_at >= %s + AND received_at <= %s + """, (start_utc, end_utc)) + collected_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS invoice_count, + COALESCE(SUM(total_amount), 0) AS invoiced + FROM invoices + WHERE issued_at >= %s + AND issued_at <= %s + """, (start_utc, end_utc)) + invoiced_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS overdue_count, + COALESCE(SUM(total_amount - amount_paid), 0) AS overdue_balance + FROM invoices + WHERE status = 'overdue' + """) + overdue_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS outstanding_count, + COALESCE(SUM(total_amount - amount_paid), 0) AS outstanding_balance + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + """) + outstanding_row = cursor.fetchone() + + conn.close() + + return { + "frequency": frequency, + "period_label": label, + "period_start": start_utc.isoformat(sep=" "), + "period_end": end_utc.isoformat(sep=" "), + "collected_cad": str(to_decimal(collected_row["collected"])), + "invoice_count": int(invoiced_row["invoice_count"] or 0), + "invoiced_total": str(to_decimal(invoiced_row["invoiced"])), + "overdue_count": int(overdue_row["overdue_count"] or 0), + "overdue_balance": str(to_decimal(overdue_row["overdue_balance"])), + "outstanding_count": int(outstanding_row["outstanding_count"] or 0), + "outstanding_balance": str(to_decimal(outstanding_row["outstanding_balance"])), + } + + +def ensure_email_log_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS email_log ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + email_type VARCHAR(50) NOT NULL, + invoice_id INT UNSIGNED NULL, + recipient_email VARCHAR(255) NOT NULL, + subject VARCHAR(255) NOT NULL, + status VARCHAR(20) NOT NULL, + error_message TEXT NULL, + sent_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + KEY idx_email_log_invoice_id (invoice_id), + KEY idx_email_log_type (email_type), + KEY idx_email_log_sent_at (sent_at) + ) + """) + conn.commit() + conn.close() + + +def log_email_event(email_type, recipient_email, subject, status, invoice_id=None, error_message=None): + ensure_email_log_table() + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + INSERT INTO email_log + (email_type, invoice_id, recipient_email, subject, status, error_message) + VALUES (%s, %s, %s, %s, %s, %s) + """, ( + email_type, + invoice_id, + recipient_email, + subject, + status, + error_message + )) + conn.commit() + conn.close() + + + +def send_configured_email(to_email, subject, body, attachments=None, email_type="system_email", invoice_id=None): + settings = get_app_settings() + + smtp_host = (settings.get("smtp_host") or "").strip() + smtp_port = int((settings.get("smtp_port") or "587").strip() or "587") + smtp_user = (settings.get("smtp_user") or "").strip() + smtp_pass = (settings.get("smtp_pass") or "").strip() + from_email = (settings.get("smtp_from_email") or settings.get("business_email") or "").strip() + from_name = (settings.get("smtp_from_name") or settings.get("business_name") or "").strip() + use_tls = (settings.get("smtp_use_tls") or "0") == "1" + use_ssl = (settings.get("smtp_use_ssl") or "0") == "1" + + if not smtp_host: + raise ValueError("SMTP host is not configured.") + if not from_email: + raise ValueError("From email is not configured.") + if not to_email: + raise ValueError("Recipient email is missing.") + + msg = EmailMessage() + msg["Subject"] = subject + msg["From"] = f"{from_name} <{from_email}>" if from_name else from_email + msg["To"] = to_email + msg.set_content(body) + + for attachment in attachments or []: + filename = attachment["filename"] + mime_type = attachment["mime_type"] + data = attachment["data"] + maintype, subtype = mime_type.split("/", 1) + msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=filename) + + try: + if use_ssl: + with smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=30) as server: + if smtp_user: + server.login(smtp_user, smtp_pass) + server.send_message(msg) + else: + with smtplib.SMTP(smtp_host, smtp_port, timeout=30) as server: + server.ehlo() + if use_tls: + server.starttls() + server.ehlo() + if smtp_user: + server.login(smtp_user, smtp_pass) + server.send_message(msg) + + log_email_event(email_type, to_email, subject, "sent", invoice_id=invoice_id, error_message=None) + except Exception as e: + log_email_event(email_type, to_email, subject, "failed", invoice_id=invoice_id, error_message=str(e)) + raise + +@app.route("/settings", methods=["GET", "POST"]) +def settings(): + ensure_app_settings_table() + + if request.method == "POST": + save_app_settings(request.form) + return redirect("/settings") + + settings = get_app_settings() + return render_template("settings.html", settings=settings) + + + + +@app.route("/reports/accounting-package.zip") +def accounting_package_zip(): + package_bytes, filename = build_accounting_package_bytes() + return send_file( + BytesIO(package_bytes), + mimetype="application/zip", + as_attachment=True, + download_name=filename + ) + +@app.route("/reports/revenue") +def revenue_report(): + report = get_revenue_report_data() + return render_template("reports/revenue.html", report=report) + +@app.route("/reports/revenue.json") +def revenue_report_json(): + report = get_revenue_report_data() + return jsonify(report) + +@app.route("/reports/revenue/print") +def revenue_report_print(): + report = get_revenue_report_data() + return render_template("reports/revenue_print.html", report=report) + + + +@app.route("/invoices/email/", methods=["POST"]) +def email_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return "Invoice not found", 404 + + recipient = (invoice.get("email") or "").strip() + if not recipient: + return "Client email is missing for this invoice.", 400 + + settings = get_app_settings() + + with app.test_client() as client: + pdf_response = client.get(f"/invoices/pdf/{invoice_id}") + if pdf_response.status_code != 200: + return "Could not generate invoice PDF for email.", 500 + + pdf_bytes = pdf_response.data + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + subject = f"Invoice {invoice['invoice_number']} from {settings.get('business_name') or 'OTB Billing'}" + body = ( + f"Hello {invoice.get('contact_name') or invoice.get('company_name') or ''},\n\n" + f"Please find attached invoice {invoice['invoice_number']}.\n" + f"Total: {to_decimal(invoice.get('total_amount')):.2f} {invoice.get('currency_code', 'CAD')}\n" + f"Remaining: {remaining:.2f} {invoice.get('currency_code', 'CAD')}\n" + f"Due: {fmt_local(invoice.get('due_at'))}\n\n" + f"Thank you,\n" + f"{settings.get('business_name') or 'OTB Billing'}" + ) + + try: + send_configured_email( + recipient, + subject, + body, + email_type="invoice", + invoice_id=invoice_id, + attachments=[{ + "filename": f"{invoice['invoice_number']}.pdf", + "mime_type": "application/pdf", + "data": pdf_bytes, + }] + ) + return redirect(f"/invoices/view/{invoice_id}?email_sent=1") + except Exception: + return redirect(f"/invoices/view/{invoice_id}?email_failed=1") + + +@app.route("/reports/revenue/email", methods=["POST"]) +def email_revenue_report_json(): + settings = get_app_settings() + recipient = (settings.get("report_delivery_email") or settings.get("business_email") or "").strip() + if not recipient: + return "Report delivery email is not configured.", 400 + + with app.test_client() as client: + json_response = client.get("/reports/revenue.json") + if json_response.status_code != 200: + return "Could not generate revenue report JSON.", 500 + + report = get_revenue_report_data() + subject = f"Revenue Report {report.get('period_label', '')} from {settings.get('business_name') or 'OTB Billing'}" + body = ( + f"Attached is the revenue report JSON for {report.get('period_label', '')}.\n\n" + f"Frequency: {report.get('frequency', '')}\n" + f"Collected CAD: {report.get('collected_cad', '')}\n" + f"Invoices Issued: {report.get('invoice_count', '')}\n" + ) + + try: + send_configured_email( + recipient, + subject, + body, + email_type="revenue_report", + attachments=[{ + "filename": "revenue_report.json", + "mime_type": "application/json", + "data": json_response.data, + }] + ) + return redirect("/reports/revenue?email_sent=1") + except Exception: + return redirect("/reports/revenue?email_failed=1") + + +@app.route("/reports/accounting-package/email", methods=["POST"]) +def email_accounting_package(): + settings = get_app_settings() + recipient = (settings.get("report_delivery_email") or settings.get("business_email") or "").strip() + if not recipient: + return "Report delivery email is not configured.", 400 + + with app.test_client() as client: + zip_response = client.get("/reports/accounting-package.zip") + if zip_response.status_code != 200: + return "Could not generate accounting package ZIP.", 500 + + subject = f"Accounting Package from {settings.get('business_name') or 'OTB Billing'}" + body = "Attached is the latest accounting package export." + + try: + send_configured_email( + recipient, + subject, + body, + email_type="accounting_package", + attachments=[{ + "filename": "accounting_package.zip", + "mime_type": "application/zip", + "data": zip_response.data, + }] + ) + return redirect("/?pkg_email=1") + except Exception: + return redirect("/?pkg_email_failed=1") + + + +@app.route("/subscriptions") +def subscriptions(): + ensure_subscriptions_table() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + s.*, + c.client_code, + c.company_name, + srv.service_code, + srv.service_name + FROM subscriptions s + JOIN clients c ON s.client_id = c.id + LEFT JOIN services srv ON s.service_id = srv.id + ORDER BY s.id DESC + """) + subscriptions = cursor.fetchall() + conn.close() + + return render_template("subscriptions/list.html", subscriptions=subscriptions) + + +@app.route("/subscriptions/new", methods=["GET", "POST"]) +def new_subscription(): + ensure_subscriptions_table() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + subscription_name = request.form.get("subscription_name", "").strip() + billing_interval = request.form.get("billing_interval", "").strip() + price = request.form.get("price", "").strip() + currency_code = request.form.get("currency_code", "").strip() + start_date_value = request.form.get("start_date", "").strip() + next_invoice_date = request.form.get("next_invoice_date", "").strip() + status = request.form.get("status", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not subscription_name: + errors.append("Subscription name is required.") + if billing_interval not in {"monthly", "quarterly", "yearly"}: + errors.append("Billing interval is required.") + if not price: + errors.append("Price is required.") + if not currency_code: + errors.append("Currency is required.") + if not start_date_value: + errors.append("Start date is required.") + if not next_invoice_date: + errors.append("Next invoice date is required.") + if status not in {"active", "paused", "cancelled"}: + errors.append("Status is required.") + + if not errors: + try: + price_value = Decimal(str(price)) + if price_value <= Decimal("0"): + errors.append("Price must be greater than zero.") + except Exception: + errors.append("Price must be a valid number.") + + if errors: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + conn.close() + + return render_template( + "subscriptions/new.html", + clients=clients, + services=services, + errors=errors, + form_data={ + "client_id": client_id, + "service_id": service_id, + "subscription_name": subscription_name, + "billing_interval": billing_interval, + "price": price, + "currency_code": currency_code, + "start_date": start_date_value, + "next_invoice_date": next_invoice_date, + "status": status, + "notes": notes, + }, + ) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO subscriptions + ( + client_id, + service_id, + subscription_name, + billing_interval, + price, + currency_code, + start_date, + next_invoice_date, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, ( + client_id, + service_id or None, + subscription_name, + billing_interval, + str(price_value), + currency_code, + start_date_value, + next_invoice_date, + status, + notes or None, + )) + + conn.commit() + conn.close() + return redirect("/subscriptions") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + conn.close() + + today_str = date.today().isoformat() + + return render_template( + "subscriptions/new.html", + clients=clients, + services=services, + errors=[], + form_data={ + "billing_interval": "monthly", + "currency_code": "CAD", + "start_date": today_str, + "next_invoice_date": today_str, + "status": "active", + }, + ) + + +@app.route("/subscriptions/run", methods=["POST"]) +def run_subscriptions_now(): + result = generate_due_subscription_invoices() + return redirect(f"/subscriptions?run_count={result['created_count']}") + + + +@app.route("/reports/aging") +def report_aging(): + refresh_overdue_invoices() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + c.id AS client_id, + c.client_code, + c.company_name, + i.invoice_number, + i.due_at, + i.total_amount, + i.amount_paid, + (i.total_amount - i.amount_paid) AS remaining + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY c.company_name, i.due_at + """) + rows = cursor.fetchall() + conn.close() + + today = datetime.utcnow().date() + grouped = {} + totals = { + "current": Decimal("0"), + "d30": Decimal("0"), + "d60": Decimal("0"), + "d90": Decimal("0"), + "d90p": Decimal("0"), + "total": Decimal("0"), + } + + for row in rows: + client_id = row["client_id"] + client_label = f"{row['client_code']} - {row['company_name']}" + + if client_id not in grouped: + grouped[client_id] = { + "client": client_label, + "current": Decimal("0"), + "d30": Decimal("0"), + "d60": Decimal("0"), + "d90": Decimal("0"), + "d90p": Decimal("0"), + "total": Decimal("0"), + } + + remaining = to_decimal(row["remaining"]) + + if row["due_at"]: + due_date = row["due_at"].date() + age_days = (today - due_date).days + else: + age_days = 0 + + if age_days <= 0: + bucket = "current" + elif age_days <= 30: + bucket = "d30" + elif age_days <= 60: + bucket = "d60" + elif age_days <= 90: + bucket = "d90" + else: + bucket = "d90p" + + grouped[client_id][bucket] += remaining + grouped[client_id]["total"] += remaining + + totals[bucket] += remaining + totals["total"] += remaining + + aging_rows = list(grouped.values()) + + return render_template( + "reports/aging.html", + aging_rows=aging_rows, + totals=totals + ) + + + + +@app.route("/health") +def health(): + db_status = "OK" + host_count = 0 + + try: + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute("SELECT COUNT(*) AS total_hosts FROM clients") + host_count = cursor.fetchone()["total_hosts"] + conn.close() + except Exception as e: + db_status = f"ERROR: {e}" + + system_uptime_seconds = read_system_uptime_seconds() + system_uptime = format_seconds_short(system_uptime_seconds) if system_uptime_seconds is not None else "unknown" + + app_uptime_seconds = time.time() - APP_START_TIME + app_uptime = format_seconds_short(app_uptime_seconds) + + try: + load1, load5, load15 = os.getloadavg() + load_text = f"{load1:.2f} / {load5:.2f} / {load15:.2f}" + except Exception: + load_text = "unknown" + + mem_used_mb, mem_total_mb = read_memory_usage_mb() + if mem_used_mb is not None and mem_total_mb is not None: + memory_text = f"{mem_used_mb} / {mem_total_mb} MB" + else: + memory_text = "unknown" + + try: + usage = shutil.disk_usage("/") + used_gb = round((usage.total - usage.free) / (1024**3), 2) + total_gb = round(usage.total / (1024**3), 2) + disk_text = f"{used_gb} / {total_gb} GB" + except Exception: + disk_text = "unknown" + + return render_template( + "health.html", + db_status=db_status, + host_count=host_count, + system_uptime=system_uptime, + app_uptime=app_uptime, + load_text=load_text, + memory_text=memory_text, + disk_text=disk_text, + ) + + +@app.route("/") +def index(): + refresh_overdue_invoices() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute("SELECT COUNT(*) AS total_clients FROM clients") + total_clients = cursor.fetchone()["total_clients"] + + cursor.execute("SELECT COUNT(*) AS active_services FROM services WHERE status = 'active'") + active_services = cursor.fetchone()["active_services"] + + cursor.execute(""" + SELECT COUNT(*) AS outstanding_invoices + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + AND (total_amount - amount_paid) > 0 + """) + outstanding_invoices = cursor.fetchone()["outstanding_invoices"] + + cursor.execute(""" + SELECT COALESCE(SUM(cad_value_at_payment), 0) AS revenue_received + FROM payments + WHERE payment_status = 'confirmed' + """) + revenue_received = to_decimal(cursor.fetchone()["revenue_received"]) + + cursor.execute(""" + SELECT COALESCE(SUM(total_amount - amount_paid), 0) AS outstanding_balance + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + AND (total_amount - amount_paid) > 0 + """) + outstanding_balance = to_decimal(cursor.fetchone()["outstanding_balance"]) + + conn.close() + + app_settings = get_app_settings() + + return render_template( + "dashboard.html", + total_clients=total_clients, + active_services=active_services, + outstanding_invoices=outstanding_invoices, + outstanding_balance=outstanding_balance, + revenue_received=revenue_received, + app_settings=app_settings, + ) + +@app.route("/clients") +def clients(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + c.*, + COALESCE(( + SELECT SUM(i.total_amount - i.amount_paid) + FROM invoices i + WHERE i.client_id = c.id + AND i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ), 0) AS outstanding_balance + FROM clients c + ORDER BY c.company_name + """) + clients = cursor.fetchall() + + conn.close() + return render_template("clients/list.html", clients=clients) + +@app.route("/clients/new", methods=["GET", "POST"]) +def new_client(): + if request.method == "POST": + company_name = request.form["company_name"] + contact_name = request.form["contact_name"] + email = request.form["email"] + phone = request.form["phone"] + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute("SELECT MAX(id) AS last_id FROM clients") + result = cursor.fetchone() + last_number = result["last_id"] if result["last_id"] else 0 + + client_code = generate_client_code(company_name, last_number) + + insert_cursor = conn.cursor() + insert_cursor.execute( + """ + INSERT INTO clients + (client_code, company_name, contact_name, email, phone) + VALUES (%s, %s, %s, %s, %s) + """, + (client_code, company_name, contact_name, email, phone) + ) + conn.commit() + conn.close() + + return redirect("/clients") + + return render_template("clients/new.html") + +@app.route("/clients/edit/", methods=["GET", "POST"]) +def edit_client(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + company_name = request.form.get("company_name", "").strip() + contact_name = request.form.get("contact_name", "").strip() + email = request.form.get("email", "").strip() + phone = request.form.get("phone", "").strip() + status = request.form.get("status", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not company_name: + errors.append("Company name is required.") + if not status: + errors.append("Status is required.") + + if errors: + cursor.execute("SELECT * FROM clients WHERE id = %s", (client_id,)) + client = cursor.fetchone() + client["credit_balance"] = get_client_credit_balance(client_id) + conn.close() + return render_template("clients/edit.html", client=client, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET company_name = %s, + contact_name = %s, + email = %s, + phone = %s, + status = %s, + notes = %s + WHERE id = %s + """, ( + company_name, + contact_name or None, + email or None, + phone or None, + status, + notes or None, + client_id + )) + conn.commit() + conn.close() + return redirect("/clients") + + cursor.execute("SELECT * FROM clients WHERE id = %s", (client_id,)) + client = cursor.fetchone() + conn.close() + + if not client: + return "Client not found", 404 + + client["credit_balance"] = get_client_credit_balance(client_id) + + return render_template("clients/edit.html", client=client, errors=[]) + +@app.route("/credits/") +def client_credits(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + WHERE id = %s + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return "Client not found", 404 + + cursor.execute(""" + SELECT * + FROM credit_ledger + WHERE client_id = %s + ORDER BY id DESC + """, (client_id,)) + entries = cursor.fetchall() + + conn.close() + + balance = get_client_credit_balance(client_id) + + return render_template( + "credits/list.html", + client=client, + entries=entries, + balance=balance, + ) + +@app.route("/credits/add/", methods=["GET", "POST"]) +def add_credit(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + WHERE id = %s + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return "Client not found", 404 + + if request.method == "POST": + entry_type = request.form.get("entry_type", "").strip() + amount = request.form.get("amount", "").strip() + currency_code = request.form.get("currency_code", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not entry_type: + errors.append("Entry type is required.") + if not amount: + errors.append("Amount is required.") + if not currency_code: + errors.append("Currency code is required.") + + if not errors: + try: + amount_value = Decimal(str(amount)) + if amount_value == 0: + errors.append("Amount cannot be zero.") + except Exception: + errors.append("Amount must be a valid number.") + + if errors: + conn.close() + return render_template("credits/add.html", client=client, errors=errors) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO credit_ledger + ( + client_id, + entry_type, + amount, + currency_code, + notes + ) + VALUES (%s, %s, %s, %s, %s) + """, ( + client_id, + entry_type, + amount, + currency_code, + notes or None + )) + conn.commit() + conn.close() + + return redirect(f"/credits/{client_id}") + + conn.close() + return render_template("credits/add.html", client=client, errors=[]) + +@app.route("/services") +def services(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT s.*, c.client_code, c.company_name + FROM services s + JOIN clients c ON s.client_id = c.id + ORDER BY s.id DESC + """) + services = cursor.fetchall() + conn.close() + return render_template("services/list.html", services=services) + +@app.route("/services/new", methods=["GET", "POST"]) +def new_service(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form["client_id"] + service_name = request.form["service_name"] + service_type = request.form["service_type"] + billing_cycle = request.form["billing_cycle"] + currency_code = request.form["currency_code"] + recurring_amount = request.form["recurring_amount"] + status = request.form["status"] + start_date = request.form["start_date"] or None + description = request.form["description"] + + cursor.execute("SELECT MAX(id) AS last_id FROM services") + result = cursor.fetchone() + last_number = result["last_id"] if result["last_id"] else 0 + service_code = generate_service_code(service_name, last_number) + + insert_cursor = conn.cursor() + insert_cursor.execute( + """ + INSERT INTO services + ( + client_id, + service_code, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date, + description + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, + ( + client_id, + service_code, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date, + description + ) + ) + conn.commit() + conn.close() + + return redirect("/services") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + conn.close() + return render_template("services/new.html", clients=clients) + +@app.route("/services/edit/", methods=["GET", "POST"]) +def edit_service(service_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_name = request.form.get("service_name", "").strip() + service_type = request.form.get("service_type", "").strip() + billing_cycle = request.form.get("billing_cycle", "").strip() + currency_code = request.form.get("currency_code", "").strip() + recurring_amount = request.form.get("recurring_amount", "").strip() + status = request.form.get("status", "").strip() + start_date = request.form.get("start_date", "").strip() + description = request.form.get("description", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_name: + errors.append("Service name is required.") + if not service_type: + errors.append("Service type is required.") + if not billing_cycle: + errors.append("Billing cycle is required.") + if not currency_code: + errors.append("Currency code is required.") + if not recurring_amount: + errors.append("Recurring amount is required.") + if not status: + errors.append("Status is required.") + + if not errors: + try: + recurring_amount_value = float(recurring_amount) + if recurring_amount_value < 0: + errors.append("Recurring amount cannot be negative.") + except ValueError: + errors.append("Recurring amount must be a valid number.") + + if errors: + cursor.execute(""" + SELECT s.*, c.company_name + FROM services s + LEFT JOIN clients c ON s.client_id = c.id + WHERE s.id = %s + """, (service_id,)) + service = cursor.fetchone() + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + + conn.close() + return render_template("services/edit.html", service=service, clients=clients, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE services + SET client_id = %s, + service_name = %s, + service_type = %s, + billing_cycle = %s, + status = %s, + currency_code = %s, + recurring_amount = %s, + start_date = %s, + description = %s + WHERE id = %s + """, ( + client_id, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date or None, + description or None, + service_id + )) + conn.commit() + conn.close() + return redirect("/services") + + cursor.execute(""" + SELECT s.*, c.company_name + FROM services s + LEFT JOIN clients c ON s.client_id = c.id + WHERE s.id = %s + """, (service_id,)) + service = cursor.fetchone() + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + conn.close() + + if not service: + return "Service not found", 404 + + return render_template("services/edit.html", service=service, clients=clients, errors=[]) + + + + + + +@app.route("/invoices/export.csv") +def export_invoices_csv(): + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.id, + i.invoice_number, + i.client_id, + c.client_code, + c.company_name, + i.service_id, + i.currency_code, + i.subtotal_amount, + i.tax_amount, + i.total_amount, + i.amount_paid, + i.status, + i.issued_at, + i.due_at, + i.paid_at, + i.notes, + i.created_at, + i.updated_at + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + rows = cursor.fetchall() + conn.close() + + output = StringIO() + writer = csv.writer(output) + writer.writerow([ + "id", + "invoice_number", + "client_id", + "client_code", + "company_name", + "service_id", + "currency_code", + "subtotal_amount", + "tax_amount", + "total_amount", + "amount_paid", + "status", + "issued_at", + "due_at", + "paid_at", + "notes", + "created_at", + "updated_at", + ]) + + for r in rows: + writer.writerow([ + r.get("id", ""), + r.get("invoice_number", ""), + r.get("client_id", ""), + r.get("client_code", ""), + r.get("company_name", ""), + r.get("service_id", ""), + r.get("currency_code", ""), + r.get("subtotal_amount", ""), + r.get("tax_amount", ""), + r.get("total_amount", ""), + r.get("amount_paid", ""), + r.get("status", ""), + r.get("issued_at", ""), + r.get("due_at", ""), + r.get("paid_at", ""), + r.get("notes", ""), + r.get("created_at", ""), + r.get("updated_at", ""), + ]) + + filename = "invoices" + if start_date or end_date or status or client_id or limit_count: + filename += "_filtered" + filename += ".csv" + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = f"attachment; filename={filename}" + return response + + +@app.route("/invoices/export-pdf.zip") +def export_invoices_pdf_zip(): + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + conn.close() + + settings = get_app_settings() + + def build_invoice_pdf_bytes(invoice, settings): + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + terms = settings.get("payment_terms", "") + for chunk_start in range(0, len(terms), 90): + line_text = terms[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + footer = settings.get("invoice_footer", "") + for chunk_start in range(0, len(footer), 90): + line_text = footer[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + return buffer.getvalue() + + zip_buffer = BytesIO() + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf: + for invoice in invoices: + pdf_bytes = build_invoice_pdf_bytes(invoice, settings) + zipf.writestr(f"{invoice['invoice_number']}.pdf", pdf_bytes) + + zip_buffer.seek(0) + + filename = "invoices_export" + if start_date: + filename += f"_{start_date}" + if end_date: + filename += f"_to_{end_date}" + if status: + filename += f"_{status}" + if client_id: + filename += f"_client_{client_id}" + if limit_count: + filename += f"_limit_{limit_count}" + filename += ".zip" + + return send_file( + zip_buffer, + mimetype="application/zip", + as_attachment=True, + download_name=filename + ) + + +@app.route("/invoices/print") +def print_invoices(): + refresh_overdue_invoices() + + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + conn.close() + + settings = get_app_settings() + + filters = { + "start_date": start_date, + "end_date": end_date, + "status": status, + "client_id": client_id, + "limit": limit_count, + } + + return render_template("invoices/print_batch.html", invoices=invoices, settings=settings, filters=filters) + +@app.route("/invoices") +def invoices(): + refresh_overdue_invoices() + + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + COALESCE((SELECT COUNT(*) FROM payments p WHERE p.invoice_id = i.id AND p.payment_status = 'confirmed'), 0) AS payment_count + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id DESC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + ORDER BY company_name ASC + """) + clients = cursor.fetchall() + + conn.close() + + filters = { + "start_date": start_date, + "end_date": end_date, + "status": status, + "client_id": client_id, + "limit": limit_count, + } + + return render_template("invoices/list.html", invoices=invoices, filters=filters, clients=clients) + +@app.route("/invoices/new", methods=["GET", "POST"]) +def new_invoice(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + currency_code = request.form.get("currency_code", "").strip() + total_amount = request.form.get("total_amount", "").strip() + due_at = request.form.get("due_at", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_id: + errors.append("Service is required.") + if not currency_code: + errors.append("Currency is required.") + if not total_amount: + errors.append("Total amount is required.") + if not due_at: + errors.append("Due date is required.") + + if not errors: + try: + amount_value = float(total_amount) + if amount_value <= 0: + errors.append("Total amount must be greater than zero.") + except ValueError: + errors.append("Total amount must be a valid number.") + + if errors: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + + form_data = { + "client_id": client_id, + "service_id": service_id, + "currency_code": currency_code, + "total_amount": total_amount, + "due_at": due_at, + "notes": notes, + } + + return render_template( + "invoices/new.html", + clients=clients, + services=services, + errors=errors, + form_data=form_data, + ) + + invoice_number = generate_invoice_number() + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO invoices + ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + subtotal_amount, + issued_at, + due_at, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, UTC_TIMESTAMP(), %s, 'pending', %s) + """, ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + total_amount, + due_at, + notes + )) + + conn.commit() + conn.close() + + return redirect("/invoices") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + + return render_template( + "invoices/new.html", + clients=clients, + services=services, + errors=[], + form_data={}, + ) + + + + + +@app.route("/invoices/pdf/") +def invoice_pdf(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + conn.close() + + settings = get_app_settings() + + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def draw_line(txt, x=left, font="Helvetica", size=11): + nonlocal y + pdf.setFont(font, size) + pdf.drawString(x, y, str(txt) if txt is not None else "") + y -= 16 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("payment_terms", "")), 90): + line_text = settings.get("payment_terms", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("invoice_footer", "")), 90): + line_text = settings.get("invoice_footer", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + + return send_file( + buffer, + mimetype="application/pdf", + as_attachment=True, + download_name=f"{invoice['invoice_number']}.pdf" + ) + + +@app.route("/invoices/view/") +def view_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + conn.close() + settings = get_app_settings() + return render_template("invoices/view.html", invoice=invoice, settings=settings) + + +@app.route("/invoices/edit/", methods=["GET", "POST"]) +def edit_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT i.*, + COALESCE((SELECT COUNT(*) FROM payments p WHERE p.invoice_id = i.id), 0) AS payment_count + FROM invoices i + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + locked = invoice["payment_count"] > 0 or float(invoice["amount_paid"]) > 0 + + if request.method == "POST": + due_at = request.form.get("due_at", "").strip() + notes = request.form.get("notes", "").strip() + + if locked: + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET due_at = %s, + notes = %s + WHERE id = %s + """, ( + due_at or None, + notes or None, + invoice_id + )) + conn.commit() + conn.close() + return redirect("/invoices") + + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + currency_code = request.form.get("currency_code", "").strip() + total_amount = request.form.get("total_amount", "").strip() + status = request.form.get("status", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_id: + errors.append("Service is required.") + if not currency_code: + errors.append("Currency is required.") + if not total_amount: + errors.append("Total amount is required.") + if not due_at: + errors.append("Due date is required.") + if not status: + errors.append("Status is required.") + + manual_statuses = {"draft", "pending", "cancelled"} + if status and status not in manual_statuses: + errors.append("Manual invoice status must be draft, pending, or cancelled.") + + if not errors: + try: + amount_value = float(total_amount) + if amount_value < 0: + errors.append("Total amount cannot be negative.") + except ValueError: + errors.append("Total amount must be a valid number.") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + if errors: + invoice["client_id"] = int(client_id) if client_id else invoice["client_id"] + invoice["service_id"] = int(service_id) if service_id else invoice["service_id"] + invoice["currency_code"] = currency_code or invoice["currency_code"] + invoice["total_amount"] = total_amount or invoice["total_amount"] + invoice["due_at"] = due_at or invoice["due_at"] + invoice["status"] = status or invoice["status"] + invoice["notes"] = notes + conn.close() + return render_template("invoices/edit.html", invoice=invoice, clients=clients, services=services, errors=errors, locked=locked) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET client_id = %s, + service_id = %s, + currency_code = %s, + total_amount = %s, + subtotal_amount = %s, + due_at = %s, + status = %s, + notes = %s + WHERE id = %s + """, ( + client_id, + service_id, + currency_code, + total_amount, + total_amount, + due_at, + status, + notes or None, + invoice_id + )) + conn.commit() + conn.close() + return redirect("/invoices") + + clients = [] + services = [] + + if not locked: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + return render_template("invoices/edit.html", invoice=invoice, clients=clients, services=services, errors=[], locked=locked) + + + +@app.route("/payments/export.csv") +def export_payments_csv(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + p.id, + p.invoice_id, + i.invoice_number, + p.client_id, + c.client_code, + c.company_name, + p.payment_method, + p.payment_currency, + p.payment_amount, + p.cad_value_at_payment, + p.reference, + p.sender_name, + p.txid, + p.wallet_address, + p.payment_status, + p.received_at, + p.notes + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + ORDER BY p.id ASC + """) + rows = cursor.fetchall() + conn.close() + + output = StringIO() + writer = csv.writer(output) + writer.writerow([ + "id", + "invoice_id", + "invoice_number", + "client_id", + "client_code", + "company_name", + "payment_method", + "payment_currency", + "payment_amount", + "cad_value_at_payment", + "reference", + "sender_name", + "txid", + "wallet_address", + "payment_status", + "received_at", + "notes", + ]) + + for r in rows: + writer.writerow([ + r.get("id", ""), + r.get("invoice_id", ""), + r.get("invoice_number", ""), + r.get("client_id", ""), + r.get("client_code", ""), + r.get("company_name", ""), + r.get("payment_method", ""), + r.get("payment_currency", ""), + r.get("payment_amount", ""), + r.get("cad_value_at_payment", ""), + r.get("reference", ""), + r.get("sender_name", ""), + r.get("txid", ""), + r.get("wallet_address", ""), + r.get("payment_status", ""), + r.get("received_at", ""), + r.get("notes", ""), + ]) + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = "attachment; filename=payments.csv" + return response + +@app.route("/payments") +def payments(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + p.*, + i.invoice_number, + i.status AS invoice_status, + i.total_amount, + i.amount_paid, + i.currency_code AS invoice_currency_code, + c.client_code, + c.company_name + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + ORDER BY p.id DESC + """) + payments = cursor.fetchall() + + conn.close() + return render_template("payments/list.html", payments=payments) + +@app.route("/payments/new", methods=["GET", "POST"]) +def new_payment(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + invoice_id = request.form.get("invoice_id", "").strip() + payment_method = request.form.get("payment_method", "").strip() + payment_currency = request.form.get("payment_currency", "").strip() + payment_amount = request.form.get("payment_amount", "").strip() + cad_value_at_payment = request.form.get("cad_value_at_payment", "").strip() + reference = request.form.get("reference", "").strip() + sender_name = request.form.get("sender_name", "").strip() + txid = request.form.get("txid", "").strip() + wallet_address = request.form.get("wallet_address", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not invoice_id: + errors.append("Invoice is required.") + if not payment_method: + errors.append("Payment method is required.") + if not payment_currency: + errors.append("Payment currency is required.") + if not payment_amount: + errors.append("Payment amount is required.") + if not cad_value_at_payment: + errors.append("CAD value at payment is required.") + + if not errors: + try: + payment_amount_value = Decimal(str(payment_amount)) + if payment_amount_value <= Decimal("0"): + errors.append("Payment amount must be greater than zero.") + except Exception: + errors.append("Payment amount must be a valid number.") + + if not errors: + try: + cad_value_value = Decimal(str(cad_value_at_payment)) + if cad_value_value < Decimal("0"): + errors.append("CAD value at payment cannot be negative.") + except Exception: + errors.append("CAD value at payment must be a valid number.") + + invoice_row = None + + if not errors: + cursor.execute(""" + SELECT + i.id, + i.client_id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + """, (invoice_id,)) + invoice_row = cursor.fetchone() + + if not invoice_row: + errors.append("Selected invoice was not found.") + else: + allowed_statuses = {"pending", "partial", "overdue"} + if invoice_row["status"] not in allowed_statuses: + errors.append("Payments can only be recorded against pending, partial, or overdue invoices.") + else: + remaining_balance = to_decimal(invoice_row["total_amount"]) - to_decimal(invoice_row["amount_paid"]) + entered_amount = to_decimal(payment_amount) + + if remaining_balance <= Decimal("0"): + errors.append("This invoice has no remaining balance.") + elif entered_amount > remaining_balance: + errors.append( + f"Payment amount exceeds remaining balance. Remaining balance is {fmt_money(remaining_balance, invoice_row['currency_code'])} {invoice_row['currency_code']}." + ) + + if errors: + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY i.id DESC + """) + invoices = cursor.fetchall() + conn.close() + + form_data = { + "invoice_id": invoice_id, + "payment_method": payment_method, + "payment_currency": payment_currency, + "payment_amount": payment_amount, + "cad_value_at_payment": cad_value_at_payment, + "reference": reference, + "sender_name": sender_name, + "txid": txid, + "wallet_address": wallet_address, + "notes": notes, + } + + return render_template( + "payments/new.html", + invoices=invoices, + errors=errors, + form_data=form_data, + ) + + client_id = invoice_row["client_id"] + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'confirmed', UTC_TIMESTAMP(), %s) + """, ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference or None, + sender_name or None, + txid or None, + wallet_address or None, + notes or None + )) + + conn.commit() + conn.close() + + recalc_invoice_totals(invoice_id) + + return redirect("/payments") + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY i.id DESC + """) + invoices = cursor.fetchall() + conn.close() + + return render_template( + "payments/new.html", + invoices=invoices, + errors=[], + form_data={}, + ) + + + +@app.route("/payments/void/", methods=["POST"]) +def void_payment(payment_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, invoice_id, payment_status + FROM payments + WHERE id = %s + """, (payment_id,)) + payment = cursor.fetchone() + + if not payment: + conn.close() + return "Payment not found", 404 + + if payment["payment_status"] != "confirmed": + conn.close() + return redirect("/payments") + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'reversed' + WHERE id = %s + """, (payment_id,)) + + conn.commit() + conn.close() + + recalc_invoice_totals(payment["invoice_id"]) + + return redirect("/payments") + + recalc_invoice_totals(payment["invoice_id"]) + + return redirect("/payments") + +@app.route("/payments/edit/", methods=["GET", "POST"]) +def edit_payment(payment_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + p.*, + i.invoice_number, + c.client_code, + c.company_name + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + WHERE p.id = %s + """, (payment_id,)) + payment = cursor.fetchone() + + if not payment: + conn.close() + return "Payment not found", 404 + + if request.method == "POST": + payment_method = request.form.get("payment_method", "").strip() + payment_currency = request.form.get("payment_currency", "").strip() + payment_amount = request.form.get("payment_amount", "").strip() + cad_value_at_payment = request.form.get("cad_value_at_payment", "").strip() + reference = request.form.get("reference", "").strip() + sender_name = request.form.get("sender_name", "").strip() + txid = request.form.get("txid", "").strip() + wallet_address = request.form.get("wallet_address", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not payment_method: + errors.append("Payment method is required.") + if not payment_currency: + errors.append("Payment currency is required.") + if not payment_amount: + errors.append("Payment amount is required.") + if not cad_value_at_payment: + errors.append("CAD value at payment is required.") + + if not errors: + try: + amount_value = float(payment_amount) + if amount_value <= 0: + errors.append("Payment amount must be greater than zero.") + except ValueError: + errors.append("Payment amount must be a valid number.") + + try: + cad_value = float(cad_value_at_payment) + if cad_value < 0: + errors.append("CAD value at payment cannot be negative.") + except ValueError: + errors.append("CAD value at payment must be a valid number.") + + if errors: + payment["payment_method"] = payment_method or payment["payment_method"] + payment["payment_currency"] = payment_currency or payment["payment_currency"] + payment["payment_amount"] = payment_amount or payment["payment_amount"] + payment["cad_value_at_payment"] = cad_value_at_payment or payment["cad_value_at_payment"] + payment["reference"] = reference + payment["sender_name"] = sender_name + payment["txid"] = txid + payment["wallet_address"] = wallet_address + payment["notes"] = notes + conn.close() + return render_template("payments/edit.html", payment=payment, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_method = %s, + payment_currency = %s, + payment_amount = %s, + cad_value_at_payment = %s, + reference = %s, + sender_name = %s, + txid = %s, + wallet_address = %s, + notes = %s + WHERE id = %s + """, ( + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference or None, + sender_name or None, + txid or None, + wallet_address or None, + notes or None, + payment_id + )) + conn.commit() + invoice_id = payment["invoice_id"] + conn.close() + + recalc_invoice_totals(invoice_id) + + return redirect("/payments") + + conn.close() + return render_template("payments/edit.html", payment=payment, errors=[]) + +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5050, debug=True) diff --git a/backend/routes/portal_services.py b/backend/routes/portal_services.py new file mode 100644 index 0000000..23dfed0 --- /dev/null +++ b/backend/routes/portal_services.py @@ -0,0 +1,68 @@ +from flask import Blueprint, render_template, session, redirect, url_for, flash + +portal_services_bp = Blueprint("portal_services", __name__) + +def _portal_user_is_logged_in() -> bool: + return bool( + session.get("portal_user_id") + or session.get("client_user_id") + or session.get("portal_client_id") + or session.get("client_id") + or session.get("user_id") + ) + +@portal_services_bp.route("/portal/services") +def portal_services_home(): + if not _portal_user_is_logged_in(): + flash("Please sign in to access services.", "warning") + return redirect(url_for("portal_login")) + + client = { + "contact_name": session.get("portal_contact_name"), + "company_name": session.get("portal_company_name"), + "email": session.get("portal_email"), + } + + client_name = ( + client.get("contact_name") + or client.get("company_name") + or client.get("email") + or "Client" + ) + + services = [ + { + "key": "follow_me", + "name": "Follow-me Tracker", + "summary": "Create and manage your GPS tracking network. Free for up to 2 users.", + "status": "beta", + "enabled": True, + "href": "https://follow-me.outsidethebox.top", + "button_text": "Open Follow-me", + }, + { + "key": "video_render", + "name": "Video Rendering / Streaming", + "summary": "Submit video rendering, conversion, and hosted streaming jobs.", + "status": "coming_soon", + "enabled": False, + "href": "#", + "button_text": "Coming Soon", + }, + { + "key": "miner_rentals", + "name": "Miner Rentals", + "summary": "Rent available OTB hashpower by time or package.", + "status": "coming_soon", + "enabled": False, + "href": "#", + "button_text": "Coming Soon", + }, + ] + + return render_template( + "portal/services_here.html", + client=client, + client_name=client_name, + services=services, + ) diff --git a/backend/templates/portal/services_here.html b/backend/templates/portal/services_here.html new file mode 100644 index 0000000..2a18693 --- /dev/null +++ b/backend/templates/portal/services_here.html @@ -0,0 +1,142 @@ +{% include "includes/site_nav.html" %} + +
+ +

Services Here

+

Launch available OTB services.

+

Logged in as: {{ client_name }}

+{% block title %}Services Here{% endblock %} + +{% block content %} +
+
+

Services Here

+

+ Launch available OTB services from one place. +

+

+ Logged in as: {{ client_name }} +

+
+ + +
+ +
+ {% for service in services %} +
+
+
+

{{ service.name }}

+

{{ service.summary }}

+
+
+ {% if service.status == 'beta' %} + Beta + {% elif service.status == 'coming_soon' %} + Coming Soon + {% else %} + Available + {% endif %} +
+
+ +
+ {% if service.enabled %} + {{ service.button_text }} + {% else %} + + {% endif %} +
+
+ {% endfor %} +
+ + +{% endblock %} +
diff --git a/backups/css_fix_20260313-024601/base.html b/backups/css_fix_20260313-024601/base.html new file mode 100644 index 0000000..4e5f7ac --- /dev/null +++ b/backups/css_fix_20260313-024601/base.html @@ -0,0 +1,21 @@ + + + + +{{ page_title }} + + + + + +
+

OTB Billing

+
+ +
+

{{ content }}

+
+ + + +{% include "footer.html" %} diff --git a/backups/css_fix_20260313-024601/dashboard.html b/backups/css_fix_20260313-024601/dashboard.html new file mode 100644 index 0000000..d8712ed --- /dev/null +++ b/backups/css_fix_20260313-024601/dashboard.html @@ -0,0 +1,69 @@ + + + +OTB Billing Dashboard + + + + +
+ {% if app_settings.business_logo_url %} +
+ Logo +
+ {% endif %} + +

{{ app_settings.business_name or 'OTB Billing' }} Dashboard

+ + {% if request.args.get('pkg_email') == '1' %} +
+ Accounting package emailed successfully. +
+ {% endif %} + + {% if request.args.get('pkg_email_failed') == '1' %} +
+ Accounting package email failed. Check SMTP settings or server log. +
+ {% endif %} + + + +
+ +
+ + + + + + + + + + + + + + + + +
Total ClientsActive ServicesOutstanding InvoicesOutstanding Balance (CAD)Revenue Received (CAD)
{{ total_clients }}{{ active_services }}{{ outstanding_invoices }}{{ outstanding_balance|money('CAD') }}{{ revenue_received|money('CAD') }}
+ +

Displayed times are shown in Eastern Time (Toronto).

+
+ +{% include "footer.html" %} + + diff --git a/backups/css_fix_20260313-024601/footer.html b/backups/css_fix_20260313-024601/footer.html new file mode 100644 index 0000000..1d67be7 --- /dev/null +++ b/backups/css_fix_20260313-024601/footer.html @@ -0,0 +1,376 @@ + + +
+ Theme + +
+ +
+ + + diff --git a/backups/css_fix_20260313-024601/health.html b/backups/css_fix_20260313-024601/health.html new file mode 100644 index 0000000..a75be20 --- /dev/null +++ b/backups/css_fix_20260313-024601/health.html @@ -0,0 +1,139 @@ + + + + + + System Health - OTB Billing + + + + +
+ + + + +
+
+

Status

+ {% if health.status == "ok" %} +

Healthy

+ {% else %} +

Degraded

+ {% endif %} +

App: {{ health.app_name }}

+

Host: {{ health.hostname }}

+

Toronto Time: {{ health.server_time_toronto }}

+

UTC Time: {{ health.server_time_utc }}

+
+ +
+

Database

+ {% if health.database.ok %} +

Connected

+ {% else %} +

Connection Error

+ {% endif %} +

Error: {{ health.database.error or "None" }}

+
+ +
+

Uptime

+

Application: {{ health.app_uptime_human }}

+

Server: {{ health.server_uptime_human }}

+
+ +
+

Load Average

+

1 min: {{ health.load_average["1m"] }}

+

5 min: {{ health.load_average["5m"] }}

+

15 min: {{ health.load_average["15m"] }}

+
+ +
+

Memory

+

Total: {{ health.memory.total_mb }} MB

+

Available: {{ health.memory.available_mb }} MB

+

Used: {{ health.memory.used_mb }} MB

+

Used %: {{ health.memory.used_percent }}%

+
+ +
+

Disk /

+

Total: {{ health.disk_root.total_gb }} GB

+

Used: {{ health.disk_root.used_gb }} GB

+

Free: {{ health.disk_root.free_gb }} GB

+

Used %: {{ health.disk_root.used_percent }}%

+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/css_fix_20260313-024601/portal_dashboard.html b/backups/css_fix_20260313-024601/portal_dashboard.html new file mode 100644 index 0000000..34f50ef --- /dev/null +++ b/backups/css_fix_20260313-024601/portal_dashboard.html @@ -0,0 +1,151 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + +
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
+
+

Total Outstanding

+
{{ total_outstanding }}
+
+
+

Total Paid

+
{{ total_paid }}
+
+
+ +

Invoices

+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} + {{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+ +{% include "footer.html" %} + + diff --git a/backups/css_fix_20260313-024601/portal_forgot_password.html b/backups/css_fix_20260313-024601/portal_forgot_password.html new file mode 100644 index 0000000..7ac8d24 --- /dev/null +++ b/backups/css_fix_20260313-024601/portal_forgot_password.html @@ -0,0 +1,81 @@ + + + + + + Forgot Portal Password - OutsideTheBox + + + + +
+
+

Reset Portal Password

+

Enter your email address and a new single-use access code will be sent if your account exists.

+ + {% if error %} +
{{ error }}
+ {% endif %} + + {% if message %} +
{{ message }}
+ {% endif %} + +
+
+ + +
+ +
+ + Back to Portal Login + Contact Support +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/css_fix_20260313-024601/portal_invoice_detail.html b/backups/css_fix_20260313-024601/portal_invoice_detail.html new file mode 100644 index 0000000..b61289f --- /dev/null +++ b/backups/css_fix_20260313-024601/portal_invoice_detail.html @@ -0,0 +1,166 @@ + + + + + + Invoice Detail - OutsideTheBox + + + + +
+
+
+

Invoice Detail

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ +
+
+

Invoice

+
{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}
+
+
+

Status

+ {% set s = (invoice.status or "")|lower %} + {% if s == "paid" %} + {{ invoice.status }} + {% elif s == "pending" %} + {{ invoice.status }} + {% elif s == "overdue" %} + {{ invoice.status }} + {% else %} + {{ invoice.status }} + {% endif %} +
+
+

Created

+
{{ invoice.created_at }}
+
+
+

Total

+
{{ invoice.total_amount }}
+
+
+

Paid

+
{{ invoice.amount_paid }}
+
+
+

Outstanding

+
{{ invoice.outstanding }}
+
+
+ +

Invoice Items

+ + + + + + + + + + + {% for item in items %} + + + + + + + {% else %} + + + + {% endfor %} + +
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
+ + {% if pdf_url %} + + {% endif %} +
+ +{% include "footer.html" %} + + diff --git a/backups/css_fix_20260313-024601/portal_login.html b/backups/css_fix_20260313-024601/portal_login.html new file mode 100644 index 0000000..8e195ac --- /dev/null +++ b/backups/css_fix_20260313-024601/portal_login.html @@ -0,0 +1,95 @@ + + + + + + Client Portal - OutsideTheBox + + + + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Home + Contact Support +
+
+ + + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ +{% include "footer.html" %} + + diff --git a/backups/css_fix_20260313-024601/portal_set_password.html b/backups/css_fix_20260313-024601/portal_set_password.html new file mode 100644 index 0000000..a308c25 --- /dev/null +++ b/backups/css_fix_20260313-024601/portal_set_password.html @@ -0,0 +1,75 @@ + + + + + + Set Portal Password - OutsideTheBox + + + + +
+
+

Create Your Portal Password

+

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/css_fix_20260313-024601/settings.html b/backups/css_fix_20260313-024601/settings.html new file mode 100644 index 0000000..aeabb82 --- /dev/null +++ b/backups/css_fix_20260313-024601/settings.html @@ -0,0 +1,202 @@ + + + +Settings + + + + +

Settings / Config

+ +

Home

+ +
+
+
+

Business Identity

+ + Business Name
+
+ + Business Logo URL
+
+ Example: /static/favicon.png or https://site.com/logo.png
+ + {% if settings.business_logo_url %} +
+ Business Logo Preview +
+ {% endif %} + + Slogan / Tagline
+
+ + Business Email
+
+ + Business Phone
+
+ + Business Address
+
+ + Website
+
+ + Business Number / Registration Number
+
+ + Default Currency
+ + + Report Frequency
+ +
+ +
+

Tax Settings

+ + Local Country
+
+ + Tax Label
+
+ + Tax Rate (%)
+
+ + Tax Number
+
+ +
+ +
+ + Payment Terms
+
+ + Invoice Footer
+
+
+ +
+

Advanced / Email / SMTP

+ + SMTP Host
+
+ + SMTP Port
+
+ + SMTP Username
+
+ + SMTP Password
+
+ + From Email
+
+ + From Name
+
+ + Report / Accounting Delivery Email
+
+ +
+ +
+ +
+ +
+
+ +
+

Notes

+

+ Branding, tax identity, and SMTP values are stored here for this installation. +

+

+ Logo can be a local static path like /static/favicon.png or a full external/IPFS URL. +

+

+ Email sending is not wired yet, but these SMTP settings are stored now so the next step can use them. +

+
+
+ +
+ +
+
+ +{% include "footer.html" %} + + diff --git a/backups/footer-flag-20260322-045513/portal_dashboard.html b/backups/footer-flag-20260322-045513/portal_dashboard.html new file mode 100644 index 0000000..13f20bf --- /dev/null +++ b/backups/footer-flag-20260322-045513/portal_dashboard.html @@ -0,0 +1,125 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% if row.payment_method_label %} +
+ {{ row.payment_method_label }} +
+ {% endif %} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} +
{{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + +
+
+ Billing base currency: CAD + + Crypto conversions use the OTB Oracle + + Methods: Square, e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/footer-flag-20260322-045513/portal_forgot_password.html b/backups/footer-flag-20260322-045513/portal_forgot_password.html new file mode 100644 index 0000000..da75c7d --- /dev/null +++ b/backups/footer-flag-20260322-045513/portal_forgot_password.html @@ -0,0 +1,21 @@ + + + Forgot Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Reset Portal Password

Enter your email address and a new single-use access code will be sent if your account exists.

{% if error %}
{{ error }}
{% endif %} {% if message %}
{{ message }}
{% endif %}
+
+
+
+ Billing base currency: CAD + + Crypto conversions use the OTB Oracle + + Methods: Square, e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/footer-flag-20260322-045513/portal_invoice_detail.html b/backups/footer-flag-20260322-045513/portal_invoice_detail.html new file mode 100644 index 0000000..d80fe44 --- /dev/null +++ b/backups/footer-flag-20260322-045513/portal_invoice_detail.html @@ -0,0 +1,31 @@ + + + Invoice Detail - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Invoice Detail

{{ client.company_name or client.contact_name or client.email }}

{% if (invoice.status or "")|lower == "paid" %}
βœ“ This invoice has been paid. Thank you!
{% endif %} {% if crypto_error %}
{{ crypto_error }}
{% endif %}

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Status

{% set s = (invoice.status or "")|lower %} {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} processing {% elif s == "paid" %}{{ invoice.status }} {% elif s == "pending" %}{{ invoice.status }} {% elif s == "overdue" %}{{ invoice.status }} {% else %}{{ invoice.status }}{% endif %}

Created

{{ invoice.created_at }}

Total

{{ invoice.total_amount }}

Paid

{{ invoice.amount_paid }}

Outstanding

{{ invoice.outstanding }}

Invoice Items

{% for item in items %} {% else %} {% endfor %}
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
{% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %}

Pay Now

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Credit Card (Square)

Pay with Credit Card
{% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %}

Crypto Quote Snapshot

Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
{% if pending_crypto_payment %}
Your quote is protected after acceptance.
{% else %}
Select a crypto asset to accept the quote.
{% endif %}
{% if pending_crypto_payment and pending_crypto_payment.txid %}
--:--
Watching transaction / waiting for confirmation
{% elif pending_crypto_payment %}
--:--
Quote protected while you open wallet
{% else %}
--:--
This price times out:
{% endif %}
{% if pending_crypto_payment and selected_crypto_option %}

{{ selected_crypto_option.label }} Payment Instructions

Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
Destination wallet:
{{ pending_crypto_payment.wallet_address }}
Reference / Invoice:
{{ pending_crypto_payment.reference }} {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %}
Open in MetaMask Mobile

Fastest way to pay

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

2. If that does not open your wallet, click Open in MetaMask Mobile.

3. If needed, use Copy Payment Details and send manually.

You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet.
{% elif pending_crypto_payment.txid %}
Transaction Hash:
{{ pending_crypto_payment.txid }}
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
{% elif pending_crypto_payment.lock_expired %}
price has expired - please refresh your quote to update
{% endif %}
{% else %}
{% for q in crypto_options %} {% endfor %}
AssetQuoted AmountCAD PriceStatusAction
{{ q.label }} {% if q.recommended %}recommended{% endif %} {% if q.wallet_capable %}wallet{% endif %} {{ q.display_amount or "β€”" }} {% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %} {% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
{% endif %}
{% else %}

No crypto quote snapshot is available for this invoice yet.

{% endif %}
{% endif %} {% if invoice_payments %}

Payments Applied

{% for p in invoice_payments %} {% endfor %}
Method Amount Status Received Reference / TXID
{{ p.payment_method_label }} {{ p.payment_amount_display }} {{ p.payment_currency }} {{ p.payment_status }} {{ p.received_at_local }} {% if p.txid %} {{ p.txid }} {% elif p.reference %} {{ p.reference }} {% else %} - {% endif %} {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %}
{% endif %} {% if pdf_url %} {% endif %} +
+
+
+ Billing base currency: CAD + + Crypto conversions use the OTB Oracle + + Methods: Square, e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/footer-flag-20260322-045513/portal_login.html b/backups/footer-flag-20260322-045513/portal_login.html new file mode 100644 index 0000000..822b680 --- /dev/null +++ b/backups/footer-flag-20260322-045513/portal_login.html @@ -0,0 +1,64 @@ + + + + + + Client Portal - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Customer Support +
+
+ + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ + +
+
+ Billing base currency: CAD + + Crypto conversions use the OTB Oracle + + Methods: Square, e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/footer-flag-20260322-045513/portal_set_password.html b/backups/footer-flag-20260322-045513/portal_set_password.html new file mode 100644 index 0000000..7360653 --- /dev/null +++ b/backups/footer-flag-20260322-045513/portal_set_password.html @@ -0,0 +1,21 @@ + + + Set Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Create Your Portal Password

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

{% if portal_message %}
{{ portal_message }}
{% endif %}
+
+
+
+ Billing base currency: CAD + + Crypto conversions use the OTB Oracle + + Methods: Square, e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/footer-toggle-cleanup-20260322-221548/footer.html b/backups/footer-toggle-cleanup-20260322-221548/footer.html new file mode 100644 index 0000000..ba209b4 --- /dev/null +++ b/backups/footer-toggle-cleanup-20260322-221548/footer.html @@ -0,0 +1,346 @@ + +
+ + + diff --git a/backups/footer-toggle-removal-20260322-220351/footer.html b/backups/footer-toggle-removal-20260322-220351/footer.html new file mode 100644 index 0000000..1d67be7 --- /dev/null +++ b/backups/footer-toggle-removal-20260322-220351/footer.html @@ -0,0 +1,376 @@ + + +
+ Theme + +
+ +
+ + + diff --git a/backups/payment-method-fix-20260322-040838/app.py.before_fix b/backups/payment-method-fix-20260322-040838/app.py.before_fix new file mode 100644 index 0000000..a9d7ed6 --- /dev/null +++ b/backups/payment-method-fix-20260322-040838/app.py.before_fix @@ -0,0 +1,6344 @@ +import os +from flask import Flask, render_template, request, redirect, send_file, make_response, jsonify, session, Response +from db import get_db_connection +from utils import generate_client_code, generate_service_code +from datetime import datetime, timezone, date, timedelta +from zoneinfo import ZoneInfo +from decimal import Decimal, InvalidOperation +from pathlib import Path +from email.message import EmailMessage +from dateutil.relativedelta import relativedelta + +from io import BytesIO, StringIO +import csv +import json +import hmac +import hashlib +import base64 +import urllib.request +import urllib.error +import urllib.parse +import uuid +import re +import math +import zipfile +import smtplib +import secrets +import threading +import time +from reportlab.lib.pagesizes import letter +from reportlab.pdfgen import canvas +from reportlab.lib.utils import ImageReader +from werkzeug.security import generate_password_hash, check_password_hash +from health import register_health_routes + +app = Flask( + __name__, + template_folder="../templates", + static_folder="../static", +) +app.config["OTB_HEALTH_DB_CONNECTOR"] = get_db_connection + +LOCAL_TZ = ZoneInfo("America/Toronto") + +BASE_DIR = Path(__file__).resolve().parent.parent + +app.secret_key = os.getenv("OTB_BILLING_SECRET_KEY", "otb-billing-dev-secret-change-me") +SQUARE_ACCESS_TOKEN = os.getenv("SQUARE_ACCESS_TOKEN", "") +SQUARE_WEBHOOK_SIGNATURE_KEY = os.getenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "") +SQUARE_WEBHOOK_NOTIFICATION_URL = os.getenv("SQUARE_WEBHOOK_NOTIFICATION_URL", "") +SQUARE_API_BASE = "https://connect.squareup.com" +SQUARE_API_VERSION = "2026-01-22" +SQUARE_WEBHOOK_LOG = str(BASE_DIR / "logs" / "square_webhook_events.log") +ORACLE_BASE_URL = os.getenv("ORACLE_BASE_URL", "https://monitor.outsidethebox.top") +CRYPTO_EVM_PAYMENT_ADDRESS = os.getenv("OTB_BILLING_CRYPTO_EVM_ADDRESS", "0x44f6c44C42e6ae0392E7289F032384C0d37F56D5") +RPC_ETHEREUM_URL = os.getenv("OTB_BILLING_RPC_ETHEREUM", "https://ethereum-rpc.publicnode.com") +RPC_ETHEREUM_URL_2 = os.getenv("OTB_BILLING_RPC_ETHEREUM_2", "https://rpc.ankr.com/eth") +RPC_ETHEREUM_URL_3 = os.getenv("OTB_BILLING_RPC_ETHEREUM_3", "https://eth.drpc.org") + +RPC_ARBITRUM_URL = os.getenv("OTB_BILLING_RPC_ARBITRUM", "https://arbitrum-one-rpc.publicnode.com") +RPC_ARBITRUM_URL_2 = os.getenv("OTB_BILLING_RPC_ARBITRUM_2", "https://rpc.ankr.com/arbitrum") +RPC_ARBITRUM_URL_3 = os.getenv("OTB_BILLING_RPC_ARBITRUM_3", "https://arb1.arbitrum.io/rpc") + +RPC_ETICA_URL = os.getenv("OTB_BILLING_RPC_ETICA", "https://rpc.etica-stats.org") +RPC_ETICA_URL_2 = os.getenv("OTB_BILLING_RPC_ETICA_2", "https://eticamainnet.eticaprotocol.org") +RPC_ETHO_URL = os.getenv("OTB_BILLING_RPC_ETHO", "https://rpc.ethoprotocol.com") +RPC_ETHO_URL_2 = os.getenv("OTB_BILLING_RPC_ETHO_2", "https://rpc4.ethoprotocol.com") + +CRYPTO_PROCESSING_TIMEOUT_SECONDS = int(os.getenv("OTB_BILLING_CRYPTO_PROCESSING_TIMEOUT_SECONDS", "180")) +CRYPTO_WATCH_INTERVAL_SECONDS = int(os.getenv("OTB_BILLING_CRYPTO_WATCH_INTERVAL_SECONDS", "30")) +CRYPTO_WATCHER_STARTED = False + + + + +def load_version(): + try: + with open(BASE_DIR / "VERSION", "r") as f: + return f.read().strip() + except Exception: + return "unknown" + +APP_VERSION = load_version() + +@app.context_processor +def inject_version(): + return {"app_version": APP_VERSION} + +@app.context_processor +def inject_app_settings(): + return {"app_settings": get_app_settings()} + +def fmt_local(dt_value): + if not dt_value: + return "" + if isinstance(dt_value, str): + try: + dt_value = datetime.fromisoformat(dt_value) + except ValueError: + return str(dt_value) + if dt_value.tzinfo is None: + dt_value = dt_value.replace(tzinfo=timezone.utc) + return dt_value.astimezone(LOCAL_TZ).strftime("%Y-%m-%d %I:%M:%S %p") + +def to_decimal(value): + if value is None or value == "": + return Decimal("0") + try: + return Decimal(str(value)) + except (InvalidOperation, ValueError): + return Decimal("0") + +def fmt_money(value, currency_code="CAD"): + amount = to_decimal(value) + if currency_code == "CAD": + return f"{amount:.2f}" + return f"{amount:.8f}" + +def payment_method_label(method, currency=None): + method_key = str(method or "").strip().lower() + currency_key = str(currency or "").strip().upper() + + if method_key == "square": + return "Square" + if method_key == "etransfer": + return "e-Transfer" + if method_key == "cash": + return "Cash" + if method_key == "other": + if currency_key in {"ETH", "ETHO", "ETI", "USDC", "EGAZ", "ALT", "CAD"}: + return currency_key + return "Other" + if method_key == "crypto_etho": + return "ETHO" + if method_key == "crypto_egaz": + return "EGAZ" + if method_key == "crypto_alt": + return "ALT" + + if currency_key in {"ETH", "ETHO", "ETI", "USDC", "EGAZ", "ALT"}: + return currency_key + + return method or "Unknown" + +def get_invoice_payments(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + confirmations, + confirmation_required, + received_at, + created_at, + notes + FROM payments + WHERE invoice_id = %s + ORDER BY COALESCE(received_at, created_at) ASC, id ASC + """, (invoice_id,)) + rows = cursor.fetchall() + conn.close() + + out = [] + for row in rows: + item = dict(row) + item["payment_method_label"] = payment_method_label( + item.get("payment_method"), + item.get("payment_currency"), + ) + item["payment_amount_display"] = fmt_money( + item.get("payment_amount"), + item.get("payment_currency") or "CAD", + ) + item["cad_value_display"] = fmt_money(item.get("cad_value_at_payment"), "CAD") + item["received_at_local"] = fmt_local(item.get("received_at") or item.get("created_at")) + out.append(item) + return out + +def normalize_oracle_datetime(value): + if not value: + return None + try: + text = str(value).replace("Z", "+00:00") + dt = datetime.fromisoformat(text) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + return None + +def ensure_invoice_quote_columns(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT COLUMN_NAME + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'invoices' + """) + existing = {row["COLUMN_NAME"] for row in cursor.fetchall()} + + wanted = { + "quote_fiat_amount": "ALTER TABLE invoices ADD COLUMN quote_fiat_amount DECIMAL(18,8) DEFAULT NULL AFTER status", + "quote_fiat_currency": "ALTER TABLE invoices ADD COLUMN quote_fiat_currency VARCHAR(16) DEFAULT NULL AFTER quote_fiat_amount", + "quote_expires_at": "ALTER TABLE invoices ADD COLUMN quote_expires_at DATETIME DEFAULT NULL AFTER quote_fiat_currency", + "oracle_snapshot": "ALTER TABLE invoices ADD COLUMN oracle_snapshot LONGTEXT DEFAULT NULL AFTER quote_expires_at" + } + + exec_cursor = conn.cursor() + changed = False + for column_name, ddl in wanted.items(): + if column_name not in existing: + exec_cursor.execute(ddl) + changed = True + + if changed: + conn.commit() + conn.close() + +def fetch_oracle_quote_snapshot(currency_code, total_amount): + if str(currency_code or "").upper() != "CAD": + return None + + try: + amount_value = Decimal(str(total_amount)) + if amount_value <= 0: + return None + except (InvalidOperation, ValueError): + return None + + try: + qs = urllib.parse.urlencode({ + "fiat": "CAD", + "amount": format(amount_value, "f"), + }) + req = urllib.request.Request( + f"{ORACLE_BASE_URL.rstrip('/')}/api/oracle/quote?{qs}", + headers={ + "Accept": "application/json", + "User-Agent": "otb-billing-oracle/0.1" + }, + method="GET" + ) + with urllib.request.urlopen(req, timeout=15) as resp: + data = json.loads(resp.read().decode("utf-8")) + + if not isinstance(data, dict) or not isinstance(data.get("quotes"), list): + return None + + return { + "oracle_url": ORACLE_BASE_URL.rstrip("/"), + "quoted_at": data.get("quoted_at"), + "expires_at": data.get("expires_at"), + "ttl_seconds": data.get("ttl_seconds"), + "source_status": data.get("source_status"), + "fiat": data.get("fiat") or "CAD", + "amount": format(amount_value, "f"), + "quotes": data.get("quotes", []), + } + except Exception: + return None + +def get_invoice_crypto_options(invoice): + oracle_quote = invoice.get("oracle_quote") or {} + raw_quotes = oracle_quote.get("quotes") or [] + + option_map = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "label": "USDC (Arbitrum)", + "payment_currency": "USDC", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "token", + "chain_id": 42161, + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "label": "ETH (Ethereum)", + "payment_currency": "ETH", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "native", + "chain_id": 1, + "decimals": 18, + "token_contract": None, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "label": "ETHO (Etho)", + "payment_currency": "ETHO", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "native", + "chain_id": 1313114, + "decimals": 18, + "token_contract": None, + "rpc_urls": [RPC_ETHO_URL, RPC_ETHO_URL_2], + "chain_add_params": { + "chainId": "0x14095a", + "chainName": "Etho Protocol", + "nativeCurrency": { + "name": "Etho Protocol", + "symbol": "ETHO", + "decimals": 18 + }, + "rpcUrls": [RPC_ETHO_URL, RPC_ETHO_URL_2], + "blockExplorerUrls": ["https://explorer.ethoprotocol.com"] + }, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "label": "ETI (Etica)", + "payment_currency": "ETI", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "token", + "chain_id": 61803, + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "rpc_urls": [RPC_ETICA_URL, RPC_ETICA_URL_2], + "chain_add_params": { + "chainId": "0xf16b", + "chainName": "Etica", + "nativeCurrency": { + "name": "Etica Gas", + "symbol": "EGAZ", + "decimals": 18 + }, + "rpcUrls": [RPC_ETICA_URL, RPC_ETICA_URL_2], + "blockExplorerUrls": ["https://explorer.etica-stats.org"] + }, + }, + } + + options = [] + for q in raw_quotes: + symbol = str(q.get("symbol") or "").upper() + if symbol not in option_map: + continue + if not q.get("display_amount"): + continue + + opt = dict(option_map[symbol]) + opt["display_amount"] = q.get("display_amount") + opt["crypto_amount"] = q.get("crypto_amount") + opt["price_cad"] = q.get("price_cad") + opt["recommended"] = bool(q.get("recommended")) + opt["available"] = bool(q.get("available")) + opt["reason"] = q.get("reason") + options.append(opt) + + options.sort(key=lambda x: (0 if x.get("recommended") else 1, x.get("symbol"))) + return options + +def get_rpc_urls_for_chain(chain_name): + chain = str(chain_name or "").lower() + if chain == "ethereum": + return [u for u in [RPC_ETHEREUM_URL, RPC_ETHEREUM_URL_2, RPC_ETHEREUM_URL_3] if u] + if chain == "arbitrum": + return [u for u in [RPC_ARBITRUM_URL, RPC_ARBITRUM_URL_2, RPC_ARBITRUM_URL_3] if u] + if chain == "etica": + return [u for u in [RPC_ETICA_URL, RPC_ETICA_URL_2] if u] + if chain == "etho": + return [u for u in [RPC_ETHO_URL, RPC_ETHO_URL_2] if u] + return [] + +def rpc_call_any(rpc_urls, method, params): + last_error = None + + for rpc_url in rpc_urls: + try: + payload = json.dumps({ + "jsonrpc": "2.0", + "id": 1, + "method": method, + "params": params, + }).encode("utf-8") + + req = urllib.request.Request( + rpc_url, + data=payload, + headers={ + "Content-Type": "application/json", + "Accept": "application/json", + "User-Agent": "otb-billing-rpc/0.1", + }, + method="POST" + ) + + with urllib.request.urlopen(req, timeout=20) as resp: + data = json.loads(resp.read().decode("utf-8")) + + if isinstance(data, dict) and data.get("error"): + raise RuntimeError(str(data["error"])) + + return { + "rpc_url": rpc_url, + "result": (data or {}).get("result"), + } + except Exception as err: + last_error = err + + if last_error: + raise last_error + raise RuntimeError("No RPC URLs configured") + + +def append_payment_note(existing_notes, extra_line): + base = (existing_notes or "").rstrip() + if not base: + return extra_line.strip() + return base + "\n" + extra_line.strip() + +def _hex_to_int(value): + if value is None: + return 0 + text = str(value).strip() + if not text: + return 0 + if text.startswith("0x"): + return int(text, 16) + return int(text) + +def fetch_rpc_balance(chain_name, wallet_address): + rpc_urls = get_rpc_urls_for_chain(chain_name) + if not rpc_urls or not wallet_address: + return None + try: + resp = rpc_call_any(rpc_urls, "eth_getBalance", [wallet_address, "latest"]) + result = (resp or {}).get("result") + if result is None: + return None + return { + "rpc_url": resp.get("rpc_url"), + "balance_wei": _hex_to_int(result), + } + except Exception: + return None + +def verify_expected_tx_for_payment(option, tx): + if not option or not tx: + raise RuntimeError("missing transaction data") + + wallet_to = str(option.get("wallet_address") or "").lower() + expected_units = _to_base_units(option.get("display_amount"), option.get("decimals") or 18) + + if option.get("asset_type") == "native": + tx_to = str(tx.get("to") or "").lower() + tx_value = _hex_to_int(tx.get("value") or "0x0") + + if tx_to != wallet_to: + raise RuntimeError("transaction destination does not match payment wallet") + if tx_value != expected_units: + raise RuntimeError("transaction value does not match frozen quote amount") + + return True + + tx_to = str(tx.get("to") or "").lower() + contract = str(option.get("token_contract") or "").lower() + if tx_to != contract: + raise RuntimeError("token contract does not match expected asset contract") + + parsed = parse_erc20_transfer_input(tx.get("input") or "") + if not parsed: + raise RuntimeError("transaction input is not a supported ERC20 transfer") + + if str(parsed["to"]).lower() != wallet_to: + raise RuntimeError("token transfer recipient does not match payment wallet") + + if int(parsed["amount"]) != expected_units: + raise RuntimeError("token transfer amount does not match frozen quote amount") + + return True + +def get_processing_crypto_option(payment_row): + currency = str(payment_row.get("payment_currency") or "").upper() + amount_text = str(payment_row.get("payment_amount") or "0") + wallet_address = payment_row.get("wallet_address") or CRYPTO_EVM_PAYMENT_ADDRESS + + mapping = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + "display_amount": amount_text, + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "display_amount": amount_text, + }, + } + return mapping.get(currency) + +def reconcile_pending_crypto_payment(payment_row): + tx_hash = str(payment_row.get("txid") or "").strip() + if not tx_hash or not tx_hash.startswith("0x"): + return {"state": "no_tx_hash"} + + option = get_processing_crypto_option(payment_row) + if not option: + return {"state": "unsupported_currency"} + + created_dt = payment_row.get("updated_at") or payment_row.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + if not created_dt: + created_dt = datetime.now(timezone.utc) + + age_seconds = max(0, int((datetime.now(timezone.utc) - created_dt).total_seconds())) + rpc_urls = get_rpc_urls_for_chain(option.get("chain")) + if not rpc_urls: + return {"state": "no_rpc"} + + tx_hit = None + receipt_hit = None + tx_rpc = None + receipt_rpc = None + + for rpc_url in rpc_urls: + try: + tx_resp = rpc_call_any([rpc_url], "eth_getTransactionByHash", [tx_hash]) + tx_obj = tx_resp.get("result") + if tx_obj: + verify_expected_tx_for_payment(option, tx_obj) + tx_hit = tx_obj + tx_rpc = tx_resp.get("rpc_url") + break + except Exception: + continue + + if tx_hit: + for rpc_url in rpc_urls: + try: + receipt_resp = rpc_call_any([rpc_url], "eth_getTransactionReceipt", [tx_hash]) + receipt_obj = receipt_resp.get("result") + if receipt_obj: + receipt_hit = receipt_obj + receipt_rpc = receipt_resp.get("rpc_url") + break + except Exception: + continue + + balance_info = fetch_rpc_balance(option.get("chain"), option.get("wallet_address")) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, invoice_id, notes, payment_status + FROM payments + WHERE id = %s + LIMIT 1 + """, (payment_row["id"],)) + live_payment = cursor.fetchone() + + if not live_payment: + conn.close() + return {"state": "payment_missing"} + + notes = live_payment.get("notes") or "" + + if tx_hit and receipt_hit: + receipt_status = _hex_to_int(receipt_hit.get("status") or "0x0") + confirmations = 0 + block_number = receipt_hit.get("blockNumber") + if block_number: + try: + bn = _hex_to_int(block_number) + latest_resp = rpc_call_any(rpc_urls, "eth_blockNumber", []) + latest_bn = _hex_to_int((latest_resp or {}).get("result") or "0x0") + if latest_bn >= bn: + confirmations = (latest_bn - bn) + 1 + except Exception: + confirmations = 1 + + if receipt_status == 1: + notes = append_payment_note(notes, f"[reconcile] confirmed tx {tx_hash} via {receipt_rpc or tx_rpc or 'rpc'}") + if balance_info: + notes = append_payment_note(notes, f"[reconcile] wallet balance seen on {balance_info.get('rpc_url')}: {balance_info.get('balance_wei')} wei") + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'confirmed', + confirmations = %s, + confirmation_required = 1, + received_at = COALESCE(received_at, UTC_TIMESTAMP()), + notes = %s + WHERE id = %s + """, ( + confirmations or 1, + notes, + payment_row["id"] + )) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "confirmed", "confirmations": confirmations or 1} + + notes = append_payment_note(notes, f"[reconcile] receipt status failed for tx {tx_hash}") + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "failed_receipt"} + + if age_seconds <= CRYPTO_PROCESSING_TIMEOUT_SECONDS: + notes_line = f"[reconcile] waiting for tx/receipt age={age_seconds}s" + if balance_info: + notes_line += f" wallet_balance_wei={balance_info.get('balance_wei')}" + if notes_line not in notes: + notes = append_payment_note(notes, notes_line) + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + return {"state": "processing", "age_seconds": age_seconds} + + fail_line = f"[reconcile] timeout after {age_seconds}s without confirmed receipt for tx {tx_hash}" + if balance_info: + fail_line += f" wallet_balance_wei={balance_info.get('balance_wei')}" + notes = append_payment_note(notes, fail_line) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "timeout", "age_seconds": age_seconds} + +def _to_base_units(amount_text, decimals): + amount_dec = Decimal(str(amount_text)) + scale = Decimal(10) ** int(decimals) + return int((amount_dec * scale).quantize(Decimal("1"))) + +def _strip_0x(value): + return str(value or "").lower().replace("0x", "") + +def parse_erc20_transfer_input(input_data): + data = _strip_0x(input_data) + if not data.startswith("a9059cbb"): + return None + if len(data) < 8 + 64 + 64: + return None + to_chunk = data[8:72] + amount_chunk = data[72:136] + to_addr = "0x" + to_chunk[-40:] + amount_int = int(amount_chunk, 16) + return { + "to": to_addr, + "amount": amount_int, + } + +def verify_wallet_transaction(option, tx_hash): + rpc_urls = get_rpc_urls_for_chain(option.get("chain")) + if not rpc_urls: + raise RuntimeError("No RPC configured for chain") + + seen_result = None + last_not_found = False + + for rpc_url in rpc_urls: + try: + rpc_resp = rpc_call_any([rpc_url], "eth_getTransactionByHash", [tx_hash]) + tx = rpc_resp.get("result") + if not tx: + last_not_found = True + continue + + wallet_to = str(option.get("wallet_address") or "").lower() + expected_units = _to_base_units(option.get("display_amount"), option.get("decimals") or 18) + + if option.get("asset_type") == "native": + tx_to = str(tx.get("to") or "").lower() + tx_value = int(tx.get("value") or "0x0", 16) + if tx_to != wallet_to: + raise RuntimeError("Transaction destination does not match payment wallet") + if tx_value != expected_units: + raise RuntimeError("Transaction value does not match frozen quote amount") + else: + tx_to = str(tx.get("to") or "").lower() + contract = str(option.get("token_contract") or "").lower() + if tx_to != contract: + raise RuntimeError("Token contract does not match expected asset contract") + parsed = parse_erc20_transfer_input(tx.get("input") or "") + if not parsed: + raise RuntimeError("Transaction input is not a supported ERC20 transfer") + if str(parsed["to"]).lower() != wallet_to: + raise RuntimeError("Token transfer recipient does not match payment wallet") + if int(parsed["amount"]) != expected_units: + raise RuntimeError("Token transfer amount does not match frozen quote amount") + + seen_result = { + "rpc_url": rpc_url, + "tx": tx, + } + break + except Exception: + continue + + if not seen_result: + if last_not_found: + raise RuntimeError("Transaction hash not found on any configured RPC") + raise RuntimeError("Unable to verify transaction on configured RPC pool") + + return seen_result + + +def get_processing_crypto_option(payment_row): + currency = str(payment_row.get("payment_currency") or "").upper() + amount_text = str(payment_row.get("payment_amount") or "0") + wallet_address = payment_row.get("wallet_address") or CRYPTO_EVM_PAYMENT_ADDRESS + + mapping = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + "display_amount": amount_text, + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "display_amount": amount_text, + }, + } + + return mapping.get(currency) + +def append_payment_note(existing_notes, extra_line): + base = (existing_notes or "").rstrip() + if not base: + return extra_line.strip() + return base + "\n" + extra_line.strip() + +def mark_crypto_payment_failed(payment_id, reason): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT invoice_id, notes + FROM payments + WHERE id = %s + LIMIT 1 + """, (payment_id,)) + row = cursor.fetchone() + + if not row: + conn.close() + return + + new_notes = append_payment_note( + row.get("notes"), + f"[crypto watcher] failed: {reason}" + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (new_notes, payment_id)) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(row["invoice_id"]) + except Exception: + pass + +def mark_crypto_payment_confirmed(payment_id, invoice_id, rpc_url): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT p.*, i.client_id AS invoice_client_id, i.invoice_number, + i.total_amount, i.amount_paid, i.status AS invoice_status, + c.email AS client_email, c.company_name, c.contact_name + FROM payments p + JOIN invoices i ON i.id = p.invoice_id + LEFT JOIN clients c ON c.id = i.client_id + WHERE p.id = %s + LIMIT 1 + """, (payment_id,)) + row = cursor.fetchone() + + if not row: + conn.close() + return + + if str(row.get("payment_status") or "").lower() == "confirmed": + conn.close() + return + + new_notes = append_payment_note( + row.get("notes"), + "[crypto watcher] confirmed via %s txid=%s" % (rpc_url, row.get("txid") or "") + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'confirmed', + confirmations = COALESCE(confirmations, 1), + confirmation_required = COALESCE(confirmation_required, 1), + received_at = COALESCE(received_at, UTC_TIMESTAMP()), + notes = %s + WHERE id = %s + """, (new_notes, payment_id)) + conn.commit() + + try: + recalc_invoice_totals(invoice_id) + except Exception: + pass + + refresh_cursor = conn.cursor(dictionary=True) + refresh_cursor.execute(""" + SELECT id, client_id, invoice_number, total_amount, amount_paid, status + FROM invoices + WHERE id = %s + LIMIT 1 + """, (invoice_id,)) + invoice = refresh_cursor.fetchone() or {} + + try: + from decimal import Decimal + total_dec = Decimal(str(invoice.get("total_amount") or "0")) + paid_dec = Decimal(str(invoice.get("amount_paid") or "0")) + + overpayment_dec = paid_dec - total_dec + if overpayment_dec > Decimal("0"): + credit_note = "Overpayment from invoice %s (crypto payment_id=%s)" % ( + invoice.get("invoice_number") or invoice_id, + payment_id + ) + + check_cursor = conn.cursor(dictionary=True) + check_cursor.execute(""" + SELECT id FROM credit_ledger + WHERE client_id = %s AND notes = %s + LIMIT 1 + """, (invoice.get("client_id"), credit_note)) + + if not check_cursor.fetchone(): + credit_cursor = conn.cursor() + credit_cursor.execute(""" + INSERT INTO credit_ledger + (client_id, entry_type, amount, currency_code, notes) + VALUES (%s, %s, %s, %s, %s) + """, ( + invoice.get("client_id"), + "credit", + str(overpayment_dec), + "CAD", + credit_note + )) + conn.commit() + except Exception: + pass + + try: + if str(invoice.get("status") or "").lower() == "paid": + recipient = (row.get("client_email") or "").strip() + if recipient: + subject = "Invoice %s Paid (Crypto)" % (invoice.get("invoice_number") or invoice_id) + + body = "Your payment has been received and confirmed.\n\n" + body += "Invoice: %s\n" % (invoice.get("invoice_number") or invoice_id) + body += "Amount: %s %s\n" % (row.get("payment_amount"), row.get("payment_currency")) + body += "TXID: %s\n\n" % (row.get("txid") or "") + body += "Thank you for your business.\n" + + send_configured_email( + to_email=recipient, + subject=subject, + body=body, + attachments=None, + email_type="invoice_paid_crypto", + invoice_id=invoice_id + ) + except Exception: + pass + + conn.close() +def watch_pending_crypto_payments_once(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + invoice_id, + client_id, + payment_currency, + payment_amount, + cad_value_at_payment, + wallet_address, + txid, + payment_status, + created_at, + updated_at, + notes + FROM payments + WHERE payment_status = 'pending' + AND txid IS NOT NULL + AND txid <> '' + AND notes LIKE '%%portal_crypto_intent:%%' + ORDER BY id ASC + """) + pending_rows = cursor.fetchall() + conn.close() + + now_utc = datetime.now(timezone.utc) + + for row in pending_rows: + option = get_processing_crypto_option(row) + if not option: + continue + + submitted_at = row.get("updated_at") or row.get("created_at") + if submitted_at and submitted_at.tzinfo is None: + submitted_at = submitted_at.replace(tzinfo=timezone.utc) + + if not submitted_at: + submitted_at = now_utc + + age_seconds = (now_utc - submitted_at).total_seconds() + + if age_seconds > CRYPTO_PROCESSING_TIMEOUT_SECONDS: + mark_crypto_payment_failed(row["id"], "processing timeout exceeded") + continue + + try: + verified = verify_wallet_transaction(option, str(row.get("txid") or "").strip()) + mark_crypto_payment_confirmed(row["id"], row["invoice_id"], verified.get("rpc_url") or "rpc") + except Exception as err: + msg = str(err or "") + lower = msg.lower() + retryable = ( + "not found on any configured rpc" in lower + or "not found on rpc" in lower + or "unable to verify transaction on configured rpc pool" in lower + ) + if retryable: + continue + # non-retryable verification problems get marked failed immediately + mark_crypto_payment_failed(row["id"], msg) + +def crypto_payment_watcher_loop(): + while True: + try: + watch_pending_crypto_payments_once() + except Exception as err: + try: + print(f"[crypto-watcher] {err}") + except Exception: + pass + time.sleep(max(5, CRYPTO_WATCH_INTERVAL_SECONDS)) + +def start_crypto_payment_watcher(): + global CRYPTO_WATCHER_STARTED + if CRYPTO_WATCHER_STARTED: + return + + t = threading.Thread( + target=crypto_payment_watcher_loop, + name="crypto-payment-watcher", + daemon=True, + ) + t.start() + CRYPTO_WATCHER_STARTED = True + +def square_amount_to_cents(value): + return int((to_decimal(value) * 100).quantize(Decimal("1"))) + +def create_square_payment_link_for_invoice(invoice_row, buyer_email=""): + if not SQUARE_ACCESS_TOKEN: + raise RuntimeError("Square access token is not configured") + + invoice_number = invoice_row.get("invoice_number") or f"INV-{invoice_row.get('id')}" + currency_code = invoice_row.get("currency_code") or "CAD" + amount_cents = square_amount_to_cents(invoice_row.get("total_amount") or "0") + location_id = "1TSPHT78106WX" + + payload = { + "idempotency_key": str(uuid.uuid4()), + "description": f"OTB Billing invoice {invoice_number}", + "quick_pay": { + "name": f"Invoice {invoice_number}", + "price_money": { + "amount": amount_cents, + "currency": currency_code + }, + "location_id": location_id + }, + "payment_note": f"Invoice {invoice_number}", + "checkout_options": { + "redirect_url": "https://portal.outsidethebox.top/portal" + } + } + + if buyer_email: + payload["pre_populated_data"] = { + "buyer_email": buyer_email + } + + req = urllib.request.Request( + f"{SQUARE_API_BASE}/v2/online-checkout/payment-links", + data=json.dumps(payload).encode("utf-8"), + headers={ + "Authorization": f"Bearer {SQUARE_ACCESS_TOKEN}", + "Square-Version": SQUARE_API_VERSION, + "Content-Type": "application/json" + }, + method="POST" + ) + + try: + with urllib.request.urlopen(req, timeout=30) as resp: + data = json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + raise RuntimeError(f"Square payment link creation failed: {e.code} {body}") + + payment_link = (data or {}).get("payment_link") or {} + url = payment_link.get("url") + if not url: + raise RuntimeError(f"Square payment link response missing URL: {data}") + + return url + + +def square_signature_is_valid(signature_header, raw_body, notification_url): + if not SQUARE_WEBHOOK_SIGNATURE_KEY or not signature_header: + return False + message = notification_url.encode("utf-8") + raw_body + digest = hmac.new( + SQUARE_WEBHOOK_SIGNATURE_KEY.encode("utf-8"), + message, + hashlib.sha256 + ).digest() + computed_signature = base64.b64encode(digest).decode("utf-8") + return hmac.compare_digest(computed_signature, signature_header) + +def append_square_webhook_log(entry): + try: + log_path = Path(SQUARE_WEBHOOK_LOG) + log_path.parent.mkdir(parents=True, exist_ok=True) + with log_path.open("a", encoding="utf-8") as f: + f.write(json.dumps(entry, ensure_ascii=False) + "\n") + except Exception: + pass + +def generate_portal_access_code(): + alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" + groups = [] + for _ in range(3): + groups.append("".join(secrets.choice(alphabet) for _ in range(4))) + return "-".join(groups) + +def refresh_overdue_invoices(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE invoices + SET status = 'overdue' + WHERE due_at IS NOT NULL + AND due_at < UTC_TIMESTAMP() + AND status IN ('pending', 'partial') + """) + conn.commit() + conn.close() + +def recalc_invoice_totals(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, total_amount, due_at, status + FROM invoices + WHERE id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return + + invoice_currency = str(invoice.get("currency_code") or "CAD").upper() + + if invoice_currency == "CAD": + cursor.execute(""" + SELECT COALESCE(SUM( + CASE + WHEN UPPER(COALESCE(payment_currency, '')) = 'CAD' + THEN payment_amount + ELSE COALESCE(cad_value_at_payment, 0) + END + ), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_id,)) + else: + cursor.execute(""" + SELECT COALESCE(SUM( + CASE + WHEN UPPER(COALESCE(payment_currency, '')) = %s + THEN payment_amount + ELSE 0 + END + ), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_currency, invoice_id)) + + row = cursor.fetchone() + + total_paid = to_decimal(row["total_paid"]) + total_amount = to_decimal(invoice["total_amount"]) + + if invoice["status"] == "cancelled": + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET amount_paid = %s, + paid_at = NULL + WHERE id = %s + """, ( + str(total_paid), + invoice_id + )) + conn.commit() + conn.close() + return + + if total_paid >= total_amount and total_amount > 0: + new_status = "paid" + paid_at_value = "UTC_TIMESTAMP()" + elif total_paid > 0: + new_status = "partial" + paid_at_value = "NULL" + else: + if invoice["due_at"] and invoice["due_at"] < datetime.utcnow(): + new_status = "overdue" + else: + new_status = "pending" + paid_at_value = "NULL" + + update_cursor = conn.cursor() + update_cursor.execute(f""" + UPDATE invoices + SET amount_paid = %s, + status = %s, + paid_at = {paid_at_value} + WHERE id = %s + """, ( + str(total_paid), + new_status, + invoice_id + )) + + conn.commit() + conn.close() + +def get_client_credit_balance(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT COALESCE(SUM(amount), 0) AS balance + FROM credit_ledger + WHERE client_id = %s + """, (client_id,)) + row = cursor.fetchone() + conn.close() + return to_decimal(row["balance"]) + + +def generate_invoice_number(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT invoice_number + FROM invoices + WHERE invoice_number IS NOT NULL + AND invoice_number LIKE 'INV-%' + ORDER BY id DESC + LIMIT 1 + """) + row = cursor.fetchone() + conn.close() + + if not row or not row.get("invoice_number"): + return "INV-0001" + + invoice_number = str(row["invoice_number"]).strip() + + try: + number = int(invoice_number.split("-")[1]) + except (IndexError, ValueError): + return "INV-0001" + + return f"INV-{number + 1:04d}" + + +def ensure_subscriptions_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS subscriptions ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + client_id INT UNSIGNED NOT NULL, + service_id INT UNSIGNED NULL, + subscription_name VARCHAR(255) NOT NULL, + billing_interval ENUM('monthly','quarterly','yearly') NOT NULL DEFAULT 'monthly', + price DECIMAL(18,8) NOT NULL DEFAULT 0.00000000, + currency_code VARCHAR(16) NOT NULL DEFAULT 'CAD', + start_date DATE NOT NULL, + next_invoice_date DATE NOT NULL, + status ENUM('active','paused','cancelled') NOT NULL DEFAULT 'active', + notes TEXT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + KEY idx_subscriptions_client_id (client_id), + KEY idx_subscriptions_service_id (service_id), + KEY idx_subscriptions_status (status), + KEY idx_subscriptions_next_invoice_date (next_invoice_date) + ) + """) + conn.commit() + conn.close() + + +def get_next_subscription_date(current_date, billing_interval): + if isinstance(current_date, str): + current_date = datetime.strptime(current_date, "%Y-%m-%d").date() + + if billing_interval == "yearly": + return current_date + relativedelta(years=1) + if billing_interval == "quarterly": + return current_date + relativedelta(months=3) + return current_date + relativedelta(months=1) + + +def generate_due_subscription_invoices(run_date=None): + ensure_subscriptions_table() + + today = run_date or date.today() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + s.*, + c.client_code, + c.company_name, + srv.service_code, + srv.service_name + FROM subscriptions s + JOIN clients c ON s.client_id = c.id + LEFT JOIN services srv ON s.service_id = srv.id + WHERE s.status = 'active' + AND s.next_invoice_date <= %s + ORDER BY s.next_invoice_date ASC, s.id ASC + """, (today,)) + due_subscriptions = cursor.fetchall() + + created_count = 0 + created_invoice_numbers = [] + + for sub in due_subscriptions: + invoice_number = generate_invoice_number() + due_dt = datetime.combine(today + timedelta(days=14), datetime.min.time()) + + note_parts = [f"Recurring subscription: {sub['subscription_name']}"] + if sub.get("service_code"): + note_parts.append(f"Service: {sub['service_code']}") + if sub.get("service_name"): + note_parts.append(f"({sub['service_name']})") + if sub.get("notes"): + note_parts.append(f"Notes: {sub['notes']}") + + note_text = " ".join(note_parts) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO invoices + ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + subtotal_amount, + tax_amount, + issued_at, + due_at, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, 0, UTC_TIMESTAMP(), %s, 'pending', %s) + """, ( + sub["client_id"], + sub["service_id"], + invoice_number, + sub["currency_code"], + str(sub["price"]), + str(sub["price"]), + due_dt, + note_text, + )) + + next_date = get_next_subscription_date(sub["next_invoice_date"], sub["billing_interval"]) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE subscriptions + SET next_invoice_date = %s + WHERE id = %s + """, (next_date, sub["id"])) + + created_count += 1 + created_invoice_numbers.append(invoice_number) + + conn.commit() + conn.close() + + return { + "created_count": created_count, + "invoice_numbers": created_invoice_numbers, + "run_date": str(today), + } + + +APP_SETTINGS_DEFAULTS = { + "business_name": "OTB Billing", + "business_tagline": "By a contractor, for contractors", + "business_logo_url": "", + "business_email": "", + "business_phone": "", + "business_address": "", + "business_website": "", + "tax_label": "HST", + "tax_rate": "13.00", + "tax_number": "", + "business_number": "", + "default_currency": "CAD", + "report_frequency": "monthly", + "invoice_footer": "", + "payment_terms": "", + "local_country": "Canada", + "apply_local_tax_only": "1", + "smtp_host": "", + "smtp_port": "587", + "smtp_user": "", + "smtp_pass": "", + "smtp_from_email": "", + "smtp_from_name": "", + "smtp_use_tls": "1", + "smtp_use_ssl": "0", + "report_delivery_email": "", +} + +def ensure_app_settings_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS app_settings ( + setting_key VARCHAR(100) NOT NULL PRIMARY KEY, + setting_value TEXT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + ) + """) + conn.commit() + conn.close() + +def get_app_settings(): + ensure_app_settings_table() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT setting_key, setting_value + FROM app_settings + """) + rows = cursor.fetchall() + conn.close() + + settings = dict(APP_SETTINGS_DEFAULTS) + for row in rows: + settings[row["setting_key"]] = row["setting_value"] if row["setting_value"] is not None else "" + + return settings + +def save_app_settings(form_data): + ensure_app_settings_table() + conn = get_db_connection() + cursor = conn.cursor() + + for key in APP_SETTINGS_DEFAULTS.keys(): + if key in {"apply_local_tax_only", "smtp_use_tls", "smtp_use_ssl"}: + value = "1" if form_data.get(key) else "0" + else: + value = (form_data.get(key) or "").strip() + + cursor.execute(""" + INSERT INTO app_settings (setting_key, setting_value) + VALUES (%s, %s) + ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value) + """, (key, value)) + + conn.commit() + conn.close() + + +@app.template_filter("localtime") +def localtime_filter(value): + return fmt_local(value) + +@app.template_filter("money") +def money_filter(value, currency_code="CAD"): + return fmt_money(value, currency_code) + + + + +def get_report_period_bounds(frequency): + now_local = datetime.now(LOCAL_TZ) + + if frequency == "yearly": + start_local = now_local.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) + label = f"{now_local.year}" + elif frequency == "quarterly": + quarter = ((now_local.month - 1) // 3) + 1 + start_month = (quarter - 1) * 3 + 1 + start_local = now_local.replace(month=start_month, day=1, hour=0, minute=0, second=0, microsecond=0) + label = f"Q{quarter} {now_local.year}" + else: + start_local = now_local.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + label = now_local.strftime("%B %Y") + + start_utc = start_local.astimezone(timezone.utc).replace(tzinfo=None) + end_utc = now_local.astimezone(timezone.utc).replace(tzinfo=None) + + return start_utc, end_utc, label + + + +def build_accounting_package_bytes(): + import json + import zipfile + from io import BytesIO + + report = get_revenue_report_data() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.created_at, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + ORDER BY i.created_at DESC + """) + invoices = cursor.fetchall() + + conn.close() + + payload = { + "report": report, + "invoices": invoices + } + + json_bytes = json.dumps(payload, indent=2, default=str).encode() + + zip_buffer = BytesIO() + + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("revenue_report.json", json.dumps(report, indent=2)) + z.writestr("invoices.json", json.dumps(invoices, indent=2, default=str)) + + zip_buffer.seek(0) + + filename = f"accounting_package_{report.get('period_label','report')}.zip" + + return zip_buffer.read(), filename + + + +def get_revenue_report_data(): + settings = get_app_settings() + frequency = (settings.get("report_frequency") or "monthly").strip().lower() + if frequency not in {"monthly", "quarterly", "yearly"}: + frequency = "monthly" + + start_utc, end_utc, label = get_report_period_bounds(frequency) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT COALESCE(SUM(cad_value_at_payment), 0) AS collected + FROM payments + WHERE payment_status = 'confirmed' + AND received_at >= %s + AND received_at <= %s + """, (start_utc, end_utc)) + collected_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS invoice_count, + COALESCE(SUM(total_amount), 0) AS invoiced + FROM invoices + WHERE issued_at >= %s + AND issued_at <= %s + """, (start_utc, end_utc)) + invoiced_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS overdue_count, + COALESCE(SUM(total_amount - amount_paid), 0) AS overdue_balance + FROM invoices + WHERE status = 'overdue' + """) + overdue_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS outstanding_count, + COALESCE(SUM(total_amount - amount_paid), 0) AS outstanding_balance + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + """) + outstanding_row = cursor.fetchone() + + conn.close() + + return { + "frequency": frequency, + "period_label": label, + "period_start": start_utc.isoformat(sep=" "), + "period_end": end_utc.isoformat(sep=" "), + "collected_cad": str(to_decimal(collected_row["collected"])), + "invoice_count": int(invoiced_row["invoice_count"] or 0), + "invoiced_total": str(to_decimal(invoiced_row["invoiced"])), + "overdue_count": int(overdue_row["overdue_count"] or 0), + "overdue_balance": str(to_decimal(overdue_row["overdue_balance"])), + "outstanding_count": int(outstanding_row["outstanding_count"] or 0), + "outstanding_balance": str(to_decimal(outstanding_row["outstanding_balance"])), + } + + +def ensure_email_log_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS email_log ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + email_type VARCHAR(50) NOT NULL, + invoice_id INT UNSIGNED NULL, + recipient_email VARCHAR(255) NOT NULL, + subject VARCHAR(255) NOT NULL, + status VARCHAR(20) NOT NULL, + error_message TEXT NULL, + sent_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + KEY idx_email_log_invoice_id (invoice_id), + KEY idx_email_log_type (email_type), + KEY idx_email_log_sent_at (sent_at) + ) + """) + conn.commit() + conn.close() + + +def log_email_event(email_type, recipient_email, subject, status, invoice_id=None, error_message=None): + ensure_email_log_table() + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + INSERT INTO email_log + (email_type, invoice_id, recipient_email, subject, status, error_message) + VALUES (%s, %s, %s, %s, %s, %s) + """, ( + email_type, + invoice_id, + recipient_email, + subject, + status, + error_message + )) + conn.commit() + conn.close() + + + +def send_configured_email(to_email, subject, body, attachments=None, email_type="system_email", invoice_id=None): + settings = get_app_settings() + + smtp_host = (settings.get("smtp_host") or "").strip() + smtp_port = int((settings.get("smtp_port") or "587").strip() or "587") + smtp_user = (settings.get("smtp_user") or "").strip() + smtp_pass = (settings.get("smtp_pass") or "").strip() + from_email = (settings.get("smtp_from_email") or settings.get("business_email") or "").strip() + from_name = (settings.get("smtp_from_name") or settings.get("business_name") or "").strip() + use_tls = (settings.get("smtp_use_tls") or "0") == "1" + use_ssl = (settings.get("smtp_use_ssl") or "0") == "1" + + if not smtp_host: + raise ValueError("SMTP host is not configured.") + if not from_email: + raise ValueError("From email is not configured.") + if not to_email: + raise ValueError("Recipient email is missing.") + + msg = EmailMessage() + msg["Subject"] = subject + msg["From"] = f"{from_name} <{from_email}>" if from_name else from_email + msg["To"] = to_email + msg.set_content(body) + + for attachment in attachments or []: + filename = attachment["filename"] + mime_type = attachment["mime_type"] + data = attachment["data"] + maintype, subtype = mime_type.split("/", 1) + msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=filename) + + try: + if use_ssl: + with smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=30) as server: + if smtp_user: + server.login(smtp_user, smtp_pass) + server.send_message(msg) + else: + with smtplib.SMTP(smtp_host, smtp_port, timeout=30) as server: + server.ehlo() + if use_tls: + server.starttls() + server.ehlo() + if smtp_user: + server.login(smtp_user, smtp_pass) + server.send_message(msg) + + log_email_event(email_type, to_email, subject, "sent", invoice_id=invoice_id, error_message=None) + except Exception as e: + log_email_event(email_type, to_email, subject, "failed", invoice_id=invoice_id, error_message=str(e)) + raise + +@app.route("/settings", methods=["GET", "POST"]) +def settings(): + ensure_app_settings_table() + + if request.method == "POST": + save_app_settings(request.form) + return redirect("/settings") + + settings = get_app_settings() + return render_template("settings.html", settings=settings) + + + + +@app.route("/reports/accounting-package.zip") +def accounting_package_zip(): + package_bytes, filename = build_accounting_package_bytes() + return send_file( + BytesIO(package_bytes), + mimetype="application/zip", + as_attachment=True, + download_name=filename + ) + +@app.route("/reports/revenue") +def revenue_report(): + report = get_revenue_report_data() + return render_template("reports/revenue.html", report=report) + +@app.route("/reports/revenue.json") +def revenue_report_json(): + report = get_revenue_report_data() + return jsonify(report) + +@app.route("/reports/revenue/print") +def revenue_report_print(): + report = get_revenue_report_data() + return render_template("reports/revenue_print.html", report=report) + + + +@app.route("/invoices/email/", methods=["POST"]) +def email_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return "Invoice not found", 404 + + recipient = (invoice.get("email") or "").strip() + if not recipient: + return "Client email is missing for this invoice.", 400 + + settings = get_app_settings() + + with app.test_client() as client: + pdf_response = client.get(f"/invoices/pdf/{invoice_id}") + if pdf_response.status_code != 200: + return "Could not generate invoice PDF for email.", 500 + + pdf_bytes = pdf_response.data + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + subject = f"Invoice {invoice['invoice_number']} from {settings.get('business_name') or 'OTB Billing'}" + body = ( + f"Hello {invoice.get('contact_name') or invoice.get('company_name') or ''},\n\n" + f"Please find attached invoice {invoice['invoice_number']}.\n" + f"Total: {to_decimal(invoice.get('total_amount')):.2f} {invoice.get('currency_code', 'CAD')}\n" + f"Remaining: {remaining:.2f} {invoice.get('currency_code', 'CAD')}\n" + f"Due: {fmt_local(invoice.get('due_at'))}\n\n" + f"Thank you,\n" + f"{settings.get('business_name') or 'OTB Billing'}" + ) + + try: + send_configured_email( + recipient, + subject, + body, + email_type="invoice", + invoice_id=invoice_id, + attachments=[{ + "filename": f"{invoice['invoice_number']}.pdf", + "mime_type": "application/pdf", + "data": pdf_bytes, + }] + ) + return redirect(f"/invoices/view/{invoice_id}?email_sent=1") + except Exception: + return redirect(f"/invoices/view/{invoice_id}?email_failed=1") + + +@app.route("/reports/revenue/email", methods=["POST"]) +def email_revenue_report_json(): + settings = get_app_settings() + recipient = (settings.get("report_delivery_email") or settings.get("business_email") or "").strip() + if not recipient: + return "Report delivery email is not configured.", 400 + + with app.test_client() as client: + json_response = client.get("/reports/revenue.json") + if json_response.status_code != 200: + return "Could not generate revenue report JSON.", 500 + + report = get_revenue_report_data() + subject = f"Revenue Report {report.get('period_label', '')} from {settings.get('business_name') or 'OTB Billing'}" + body = ( + f"Attached is the revenue report JSON for {report.get('period_label', '')}.\n\n" + f"Frequency: {report.get('frequency', '')}\n" + f"Collected CAD: {report.get('collected_cad', '')}\n" + f"Invoices Issued: {report.get('invoice_count', '')}\n" + ) + + try: + send_configured_email( + recipient, + subject, + body, + email_type="revenue_report", + attachments=[{ + "filename": "revenue_report.json", + "mime_type": "application/json", + "data": json_response.data, + }] + ) + return redirect("/reports/revenue?email_sent=1") + except Exception: + return redirect("/reports/revenue?email_failed=1") + + +@app.route("/reports/accounting-package/email", methods=["POST"]) +def email_accounting_package(): + settings = get_app_settings() + recipient = (settings.get("report_delivery_email") or settings.get("business_email") or "").strip() + if not recipient: + return "Report delivery email is not configured.", 400 + + with app.test_client() as client: + zip_response = client.get("/reports/accounting-package.zip") + if zip_response.status_code != 200: + return "Could not generate accounting package ZIP.", 500 + + subject = f"Accounting Package from {settings.get('business_name') or 'OTB Billing'}" + body = "Attached is the latest accounting package export." + + try: + send_configured_email( + recipient, + subject, + body, + email_type="accounting_package", + attachments=[{ + "filename": "accounting_package.zip", + "mime_type": "application/zip", + "data": zip_response.data, + }] + ) + return redirect("/?pkg_email=1") + except Exception: + return redirect("/?pkg_email_failed=1") + + + +@app.route("/subscriptions") +def subscriptions(): + ensure_subscriptions_table() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + s.*, + c.client_code, + c.company_name, + srv.service_code, + srv.service_name + FROM subscriptions s + JOIN clients c ON s.client_id = c.id + LEFT JOIN services srv ON s.service_id = srv.id + ORDER BY s.id DESC + """) + subscriptions = cursor.fetchall() + conn.close() + + return render_template("subscriptions/list.html", subscriptions=subscriptions) + + +@app.route("/subscriptions/new", methods=["GET", "POST"]) +def new_subscription(): + ensure_subscriptions_table() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + subscription_name = request.form.get("subscription_name", "").strip() + billing_interval = request.form.get("billing_interval", "").strip() + price = request.form.get("price", "").strip() + currency_code = request.form.get("currency_code", "").strip() + start_date_value = request.form.get("start_date", "").strip() + next_invoice_date = request.form.get("next_invoice_date", "").strip() + status = request.form.get("status", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not subscription_name: + errors.append("Subscription name is required.") + if billing_interval not in {"monthly", "quarterly", "yearly"}: + errors.append("Billing interval is required.") + if not price: + errors.append("Price is required.") + if not currency_code: + errors.append("Currency is required.") + if not start_date_value: + errors.append("Start date is required.") + if not next_invoice_date: + errors.append("Next invoice date is required.") + if status not in {"active", "paused", "cancelled"}: + errors.append("Status is required.") + + if not errors: + try: + price_value = Decimal(str(price)) + if price_value <= Decimal("0"): + errors.append("Price must be greater than zero.") + except Exception: + errors.append("Price must be a valid number.") + + if errors: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + conn.close() + + return render_template( + "subscriptions/new.html", + clients=clients, + services=services, + errors=errors, + form_data={ + "client_id": client_id, + "service_id": service_id, + "subscription_name": subscription_name, + "billing_interval": billing_interval, + "price": price, + "currency_code": currency_code, + "start_date": start_date_value, + "next_invoice_date": next_invoice_date, + "status": status, + "notes": notes, + }, + ) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO subscriptions + ( + client_id, + service_id, + subscription_name, + billing_interval, + price, + currency_code, + start_date, + next_invoice_date, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, ( + client_id, + service_id or None, + subscription_name, + billing_interval, + str(price_value), + currency_code, + start_date_value, + next_invoice_date, + status, + notes or None, + )) + + conn.commit() + conn.close() + return redirect("/subscriptions") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + conn.close() + + today_str = date.today().isoformat() + + return render_template( + "subscriptions/new.html", + clients=clients, + services=services, + errors=[], + form_data={ + "billing_interval": "monthly", + "currency_code": "CAD", + "start_date": today_str, + "next_invoice_date": today_str, + "status": "active", + }, + ) + + +@app.route("/subscriptions/run", methods=["POST"]) +def run_subscriptions_now(): + result = generate_due_subscription_invoices() + return redirect(f"/subscriptions?run_count={result['created_count']}") + + + +@app.route("/reports/aging") +def report_aging(): + refresh_overdue_invoices() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + c.id AS client_id, + c.client_code, + c.company_name, + i.invoice_number, + i.due_at, + i.total_amount, + i.amount_paid, + (i.total_amount - i.amount_paid) AS remaining + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY c.company_name, i.due_at + """) + rows = cursor.fetchall() + conn.close() + + today = datetime.utcnow().date() + grouped = {} + totals = { + "current": Decimal("0"), + "d30": Decimal("0"), + "d60": Decimal("0"), + "d90": Decimal("0"), + "d90p": Decimal("0"), + "total": Decimal("0"), + } + + for row in rows: + client_id = row["client_id"] + client_label = f"{row['client_code']} - {row['company_name']}" + + if client_id not in grouped: + grouped[client_id] = { + "client": client_label, + "current": Decimal("0"), + "d30": Decimal("0"), + "d60": Decimal("0"), + "d90": Decimal("0"), + "d90p": Decimal("0"), + "total": Decimal("0"), + } + + remaining = to_decimal(row["remaining"]) + + if row["due_at"]: + due_date = row["due_at"].date() + age_days = (today - due_date).days + else: + age_days = 0 + + if age_days <= 0: + bucket = "current" + elif age_days <= 30: + bucket = "d30" + elif age_days <= 60: + bucket = "d60" + elif age_days <= 90: + bucket = "d90" + else: + bucket = "d90p" + + grouped[client_id][bucket] += remaining + grouped[client_id]["total"] += remaining + + totals[bucket] += remaining + totals["total"] += remaining + + aging_rows = list(grouped.values()) + + return render_template( + "reports/aging.html", + aging_rows=aging_rows, + totals=totals + ) + + +@app.route("/") +def index(): + refresh_overdue_invoices() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute("SELECT COUNT(*) AS total_clients FROM clients") + total_clients = cursor.fetchone()["total_clients"] + + cursor.execute("SELECT COUNT(*) AS active_services FROM services WHERE status = 'active'") + active_services = cursor.fetchone()["active_services"] + + cursor.execute(""" + SELECT COUNT(*) AS outstanding_invoices + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + AND (total_amount - amount_paid) > 0 + """) + outstanding_invoices = cursor.fetchone()["outstanding_invoices"] + + cursor.execute(""" + SELECT COALESCE(SUM(cad_value_at_payment), 0) AS revenue_received + FROM payments + WHERE payment_status = 'confirmed' + """) + revenue_received = to_decimal(cursor.fetchone()["revenue_received"]) + + cursor.execute(""" + SELECT COALESCE(SUM(total_amount - amount_paid), 0) AS outstanding_balance + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + AND (total_amount - amount_paid) > 0 + """) + outstanding_balance = to_decimal(cursor.fetchone()["outstanding_balance"]) + + conn.close() + + app_settings = get_app_settings() + + return render_template( + "dashboard.html", + total_clients=total_clients, + active_services=active_services, + outstanding_invoices=outstanding_invoices, + outstanding_balance=outstanding_balance, + revenue_received=revenue_received, + app_settings=app_settings, + ) + +@app.route("/clients") +def clients(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + c.*, + COALESCE(( + SELECT SUM(i.total_amount - i.amount_paid) + FROM invoices i + WHERE i.client_id = c.id + AND i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ), 0) AS outstanding_balance + FROM clients c + ORDER BY c.company_name + """) + clients = cursor.fetchall() + + conn.close() + return render_template("clients/list.html", clients=clients) + +@app.route("/clients/new", methods=["GET", "POST"]) +def new_client(): + if request.method == "POST": + company_name = request.form["company_name"] + contact_name = request.form["contact_name"] + email = request.form["email"] + phone = request.form["phone"] + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute("SELECT MAX(id) AS last_id FROM clients") + result = cursor.fetchone() + last_number = result["last_id"] if result["last_id"] else 0 + + client_code = generate_client_code(company_name, last_number) + + insert_cursor = conn.cursor() + insert_cursor.execute( + """ + INSERT INTO clients + (client_code, company_name, contact_name, email, phone) + VALUES (%s, %s, %s, %s, %s) + """, + (client_code, company_name, contact_name, email, phone) + ) + conn.commit() + conn.close() + + return redirect("/clients") + + return render_template("clients/new.html") + +@app.route("/clients/edit/", methods=["GET", "POST"]) +def edit_client(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + company_name = request.form.get("company_name", "").strip() + contact_name = request.form.get("contact_name", "").strip() + email = request.form.get("email", "").strip() + phone = request.form.get("phone", "").strip() + status = request.form.get("status", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not company_name: + errors.append("Company name is required.") + if not status: + errors.append("Status is required.") + + if errors: + cursor.execute("SELECT * FROM clients WHERE id = %s", (client_id,)) + client = cursor.fetchone() + client["credit_balance"] = get_client_credit_balance(client_id) + conn.close() + return render_template("clients/edit.html", client=client, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET company_name = %s, + contact_name = %s, + email = %s, + phone = %s, + status = %s, + notes = %s + WHERE id = %s + """, ( + company_name, + contact_name or None, + email or None, + phone or None, + status, + notes or None, + client_id + )) + conn.commit() + conn.close() + return redirect("/clients") + + cursor.execute("SELECT * FROM clients WHERE id = %s", (client_id,)) + client = cursor.fetchone() + conn.close() + + if not client: + return "Client not found", 404 + + client["credit_balance"] = get_client_credit_balance(client_id) + + return render_template("clients/edit.html", client=client, errors=[]) + +@app.route("/credits/") +def client_credits(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + WHERE id = %s + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return "Client not found", 404 + + cursor.execute(""" + SELECT * + FROM credit_ledger + WHERE client_id = %s + ORDER BY id DESC + """, (client_id,)) + entries = cursor.fetchall() + + conn.close() + + balance = get_client_credit_balance(client_id) + + return render_template( + "credits/list.html", + client=client, + entries=entries, + balance=balance, + ) + +@app.route("/credits/add/", methods=["GET", "POST"]) +def add_credit(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + WHERE id = %s + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return "Client not found", 404 + + if request.method == "POST": + entry_type = request.form.get("entry_type", "").strip() + amount = request.form.get("amount", "").strip() + currency_code = request.form.get("currency_code", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not entry_type: + errors.append("Entry type is required.") + if not amount: + errors.append("Amount is required.") + if not currency_code: + errors.append("Currency code is required.") + + if not errors: + try: + amount_value = Decimal(str(amount)) + if amount_value == 0: + errors.append("Amount cannot be zero.") + except Exception: + errors.append("Amount must be a valid number.") + + if errors: + conn.close() + return render_template("credits/add.html", client=client, errors=errors) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO credit_ledger + ( + client_id, + entry_type, + amount, + currency_code, + notes + ) + VALUES (%s, %s, %s, %s, %s) + """, ( + client_id, + entry_type, + amount, + currency_code, + notes or None + )) + conn.commit() + conn.close() + + return redirect(f"/credits/{client_id}") + + conn.close() + return render_template("credits/add.html", client=client, errors=[]) + +@app.route("/services") +def services(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT s.*, c.client_code, c.company_name + FROM services s + JOIN clients c ON s.client_id = c.id + ORDER BY s.id DESC + """) + services = cursor.fetchall() + conn.close() + return render_template("services/list.html", services=services) + +@app.route("/services/new", methods=["GET", "POST"]) +def new_service(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form["client_id"] + service_name = request.form["service_name"] + service_type = request.form["service_type"] + billing_cycle = request.form["billing_cycle"] + currency_code = request.form["currency_code"] + recurring_amount = request.form["recurring_amount"] + status = request.form["status"] + start_date = request.form["start_date"] or None + description = request.form["description"] + + cursor.execute("SELECT MAX(id) AS last_id FROM services") + result = cursor.fetchone() + last_number = result["last_id"] if result["last_id"] else 0 + service_code = generate_service_code(service_name, last_number) + + insert_cursor = conn.cursor() + insert_cursor.execute( + """ + INSERT INTO services + ( + client_id, + service_code, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date, + description + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, + ( + client_id, + service_code, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date, + description + ) + ) + conn.commit() + conn.close() + + return redirect("/services") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + conn.close() + return render_template("services/new.html", clients=clients) + +@app.route("/services/edit/", methods=["GET", "POST"]) +def edit_service(service_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_name = request.form.get("service_name", "").strip() + service_type = request.form.get("service_type", "").strip() + billing_cycle = request.form.get("billing_cycle", "").strip() + currency_code = request.form.get("currency_code", "").strip() + recurring_amount = request.form.get("recurring_amount", "").strip() + status = request.form.get("status", "").strip() + start_date = request.form.get("start_date", "").strip() + description = request.form.get("description", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_name: + errors.append("Service name is required.") + if not service_type: + errors.append("Service type is required.") + if not billing_cycle: + errors.append("Billing cycle is required.") + if not currency_code: + errors.append("Currency code is required.") + if not recurring_amount: + errors.append("Recurring amount is required.") + if not status: + errors.append("Status is required.") + + if not errors: + try: + recurring_amount_value = float(recurring_amount) + if recurring_amount_value < 0: + errors.append("Recurring amount cannot be negative.") + except ValueError: + errors.append("Recurring amount must be a valid number.") + + if errors: + cursor.execute(""" + SELECT s.*, c.company_name + FROM services s + LEFT JOIN clients c ON s.client_id = c.id + WHERE s.id = %s + """, (service_id,)) + service = cursor.fetchone() + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + + conn.close() + return render_template("services/edit.html", service=service, clients=clients, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE services + SET client_id = %s, + service_name = %s, + service_type = %s, + billing_cycle = %s, + status = %s, + currency_code = %s, + recurring_amount = %s, + start_date = %s, + description = %s + WHERE id = %s + """, ( + client_id, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date or None, + description or None, + service_id + )) + conn.commit() + conn.close() + return redirect("/services") + + cursor.execute(""" + SELECT s.*, c.company_name + FROM services s + LEFT JOIN clients c ON s.client_id = c.id + WHERE s.id = %s + """, (service_id,)) + service = cursor.fetchone() + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + conn.close() + + if not service: + return "Service not found", 404 + + return render_template("services/edit.html", service=service, clients=clients, errors=[]) + + + + + + +@app.route("/invoices/export.csv") +def export_invoices_csv(): + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.id, + i.invoice_number, + i.client_id, + c.client_code, + c.company_name, + i.service_id, + i.currency_code, + i.subtotal_amount, + i.tax_amount, + i.total_amount, + i.amount_paid, + i.status, + i.issued_at, + i.due_at, + i.paid_at, + i.notes, + i.created_at, + i.updated_at + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + rows = cursor.fetchall() + conn.close() + + output = StringIO() + writer = csv.writer(output) + writer.writerow([ + "id", + "invoice_number", + "client_id", + "client_code", + "company_name", + "service_id", + "currency_code", + "subtotal_amount", + "tax_amount", + "total_amount", + "amount_paid", + "status", + "issued_at", + "due_at", + "paid_at", + "notes", + "created_at", + "updated_at", + ]) + + for r in rows: + writer.writerow([ + r.get("id", ""), + r.get("invoice_number", ""), + r.get("client_id", ""), + r.get("client_code", ""), + r.get("company_name", ""), + r.get("service_id", ""), + r.get("currency_code", ""), + r.get("subtotal_amount", ""), + r.get("tax_amount", ""), + r.get("total_amount", ""), + r.get("amount_paid", ""), + r.get("status", ""), + r.get("issued_at", ""), + r.get("due_at", ""), + r.get("paid_at", ""), + r.get("notes", ""), + r.get("created_at", ""), + r.get("updated_at", ""), + ]) + + filename = "invoices" + if start_date or end_date or status or client_id or limit_count: + filename += "_filtered" + filename += ".csv" + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = f"attachment; filename={filename}" + return response + + +@app.route("/invoices/export-pdf.zip") +def export_invoices_pdf_zip(): + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + conn.close() + + settings = get_app_settings() + + def build_invoice_pdf_bytes(invoice, settings): + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + terms = settings.get("payment_terms", "") + for chunk_start in range(0, len(terms), 90): + line_text = terms[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + footer = settings.get("invoice_footer", "") + for chunk_start in range(0, len(footer), 90): + line_text = footer[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + return buffer.getvalue() + + zip_buffer = BytesIO() + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf: + for invoice in invoices: + pdf_bytes = build_invoice_pdf_bytes(invoice, settings) + zipf.writestr(f"{invoice['invoice_number']}.pdf", pdf_bytes) + + zip_buffer.seek(0) + + filename = "invoices_export" + if start_date: + filename += f"_{start_date}" + if end_date: + filename += f"_to_{end_date}" + if status: + filename += f"_{status}" + if client_id: + filename += f"_client_{client_id}" + if limit_count: + filename += f"_limit_{limit_count}" + filename += ".zip" + + return send_file( + zip_buffer, + mimetype="application/zip", + as_attachment=True, + download_name=filename + ) + + +@app.route("/invoices/print") +def print_invoices(): + refresh_overdue_invoices() + + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + conn.close() + + settings = get_app_settings() + + filters = { + "start_date": start_date, + "end_date": end_date, + "status": status, + "client_id": client_id, + "limit": limit_count, + } + + return render_template("invoices/print_batch.html", invoices=invoices, settings=settings, filters=filters) + +@app.route("/invoices") +def invoices(): + refresh_overdue_invoices() + + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + COALESCE((SELECT COUNT(*) FROM payments p WHERE p.invoice_id = i.id AND p.payment_status = 'confirmed'), 0) AS payment_count + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id DESC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + ORDER BY company_name ASC + """) + clients = cursor.fetchall() + + conn.close() + + filters = { + "start_date": start_date, + "end_date": end_date, + "status": status, + "client_id": client_id, + "limit": limit_count, + } + for inv in invoices: + inv["paid_via"] = "-" + + if str(inv.get("status") or "").lower() not in {"paid", "partial"}: + continue + + pay_conn = get_db_connection() + pay_cursor = pay_conn.cursor(dictionary=True) + pay_cursor.execute(""" + SELECT payment_method, payment_currency + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + ORDER BY COALESCE(received_at, created_at) DESC, id DESC + LIMIT 1 + """, (inv["id"],)) + last_payment = pay_cursor.fetchone() + pay_conn.close() + + if last_payment: + inv["paid_via"] = payment_method_label( + last_payment.get("payment_method"), + last_payment.get("payment_currency"), + ) + + + + return render_template("invoices/list.html", invoices=invoices, filters=filters, clients=clients) + +@app.route("/invoices/new", methods=["GET", "POST"]) +def new_invoice(): + ensure_invoice_quote_columns() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + currency_code = request.form.get("currency_code", "").strip() + total_amount = request.form.get("total_amount", "").strip() + due_at = request.form.get("due_at", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_id: + errors.append("Service is required.") + if not currency_code: + errors.append("Currency is required.") + if not total_amount: + errors.append("Total amount is required.") + if not due_at: + errors.append("Due date is required.") + + if not errors: + try: + amount_value = float(total_amount) + if amount_value <= 0: + errors.append("Total amount must be greater than zero.") + except ValueError: + errors.append("Total amount must be a valid number.") + + if errors: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + + form_data = { + "client_id": client_id, + "service_id": service_id, + "currency_code": currency_code, + "total_amount": total_amount, + "due_at": due_at, + "notes": notes, + } + + return render_template( + "invoices/new.html", + clients=clients, + services=services, + errors=errors, + form_data=form_data, + ) + + invoice_number = generate_invoice_number() + + cursor.execute("SELECT service_name FROM services WHERE id = %s", (service_id,)) + service_row = cursor.fetchone() + service_name = (service_row or {}).get("service_name") or "Service" + + line_description = service_name + if notes: + line_description = f"{service_name} - {notes}" + + oracle_snapshot = fetch_oracle_quote_snapshot(currency_code, total_amount) + oracle_snapshot_json = json.dumps(oracle_snapshot, ensure_ascii=False) if oracle_snapshot else None + quote_expires_at = normalize_oracle_datetime((oracle_snapshot or {}).get("expires_at")) + quote_fiat_amount = total_amount if oracle_snapshot else None + quote_fiat_currency = currency_code if oracle_snapshot else None + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO invoices + ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + subtotal_amount, + issued_at, + due_at, + status, + notes, + quote_fiat_amount, + quote_fiat_currency, + quote_expires_at, + oracle_snapshot + ) + VALUES (%s, %s, %s, %s, %s, %s, UTC_TIMESTAMP(), %s, 'pending', %s, %s, %s, %s, %s) + """, ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + total_amount, + due_at, + notes, + quote_fiat_amount, + quote_fiat_currency, + quote_expires_at, + oracle_snapshot_json + )) + + invoice_id = insert_cursor.lastrowid + + insert_cursor.execute(""" + INSERT INTO invoice_items + ( + invoice_id, + line_number, + item_type, + description, + quantity, + unit_amount, + line_total, + currency_code, + service_id + ) + VALUES (%s, 1, 'service', %s, 1.0000, %s, %s, %s, %s) + """, ( + invoice_id, + line_description, + total_amount, + total_amount, + currency_code, + service_id + )) + + conn.commit() + conn.close() + + return redirect("/invoices") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + + return render_template( + "invoices/new.html", + clients=clients, + services=services, + errors=[], + form_data={}, + ) + + + + + +@app.route("/invoices/pdf/") +def invoice_pdf(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + conn.close() + + settings = get_app_settings() + + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def draw_line(txt, x=left, font="Helvetica", size=11): + nonlocal y + pdf.setFont(font, size) + pdf.drawString(x, y, str(txt) if txt is not None else "") + y -= 16 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("payment_terms", "")), 90): + line_text = settings.get("payment_terms", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if invoice_payments: + y -= 8 + if y < 170: + pdf.showPage() + y = height - 50 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payments Applied") + y -= 16 + + for p in invoice_payments: + if y < 110: + pdf.showPage() + y = height - 50 + + pdf.setFont("Helvetica-Bold", 10) + pdf.drawString( + left, + y, + f"{p.get('payment_method_label', 'Unknown')} | {p.get('payment_amount_display', '')} {p.get('payment_currency', '')} | {str(p.get('payment_status') or '').upper()}" + ) + y -= 13 + + details_parts = [] + if p.get("received_at_local"): + details_parts.append(f"At: {p.get('received_at_local')}") + if p.get("txid"): + details_parts.append(f"TXID: {p.get('txid')}") + elif p.get("reference"): + details_parts.append(f"Ref: {p.get('reference')}") + if p.get("wallet_address"): + details_parts.append(f"Wallet: {p.get('wallet_address')}") + + details = " | ".join(details_parts) + if details: + pdf.setFont("Helvetica", 9) + for chunk_start in range(0, len(details), 108): + if y < 95: + pdf.showPage() + y = height - 50 + pdf.setFont("Helvetica", 9) + pdf.drawString(left + 10, y, details[chunk_start:chunk_start+108]) + y -= 11 + + y -= 6 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("invoice_footer", "")), 90): + line_text = settings.get("invoice_footer", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + + return send_file( + buffer, + mimetype="application/pdf", + as_attachment=True, + download_name=f"{invoice['invoice_number']}.pdf" + ) + + +@app.route("/invoices/view/") +def view_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + conn.close() + settings = get_app_settings() + invoice_payments = get_invoice_payments(invoice_id) + return render_template( + "invoices/view.html", + invoice=invoice, + settings=settings, + invoice_payments=invoice_payments + ) + + +@app.route("/invoices/edit/", methods=["GET", "POST"]) +def edit_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT i.*, + COALESCE((SELECT COUNT(*) FROM payments p WHERE p.invoice_id = i.id), 0) AS payment_count + FROM invoices i + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + locked = invoice["payment_count"] > 0 or float(invoice["amount_paid"]) > 0 + + if request.method == "POST": + due_at = request.form.get("due_at", "").strip() + notes = request.form.get("notes", "").strip() + + if locked: + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET due_at = %s, + notes = %s + WHERE id = %s + """, ( + due_at or None, + notes or None, + invoice_id + )) + conn.commit() + conn.close() + return redirect("/invoices") + + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + currency_code = request.form.get("currency_code", "").strip() + total_amount = request.form.get("total_amount", "").strip() + status = request.form.get("status", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_id: + errors.append("Service is required.") + if not currency_code: + errors.append("Currency is required.") + if not total_amount: + errors.append("Total amount is required.") + if not due_at: + errors.append("Due date is required.") + if not status: + errors.append("Status is required.") + + manual_statuses = {"draft", "pending", "cancelled"} + if status and status not in manual_statuses: + errors.append("Manual invoice status must be draft, pending, or cancelled.") + + if not errors: + try: + amount_value = float(total_amount) + if amount_value < 0: + errors.append("Total amount cannot be negative.") + except ValueError: + errors.append("Total amount must be a valid number.") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + if errors: + invoice["client_id"] = int(client_id) if client_id else invoice["client_id"] + invoice["service_id"] = int(service_id) if service_id else invoice["service_id"] + invoice["currency_code"] = currency_code or invoice["currency_code"] + invoice["total_amount"] = total_amount or invoice["total_amount"] + invoice["due_at"] = due_at or invoice["due_at"] + invoice["status"] = status or invoice["status"] + invoice["notes"] = notes + conn.close() + return render_template("invoices/edit.html", invoice=invoice, clients=clients, services=services, errors=errors, locked=locked) + + cursor.execute("SELECT service_name FROM services WHERE id = %s", (service_id,)) + service_row = cursor.fetchone() + service_name = (service_row or {}).get("service_name") or "Service" + + line_description = service_name + if notes: + line_description = f"{service_name} - {notes}" + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET client_id = %s, + service_id = %s, + currency_code = %s, + total_amount = %s, + subtotal_amount = %s, + due_at = %s, + status = %s, + notes = %s + WHERE id = %s + """, ( + client_id, + service_id, + currency_code, + total_amount, + total_amount, + due_at, + status, + notes or None, + invoice_id + )) + + update_cursor.execute("DELETE FROM invoice_items WHERE invoice_id = %s", (invoice_id,)) + update_cursor.execute(""" + INSERT INTO invoice_items + ( + invoice_id, + line_number, + item_type, + description, + quantity, + unit_amount, + line_total, + currency_code, + service_id + ) + VALUES (%s, 1, 'service', %s, 1.0000, %s, %s, %s, %s) + """, ( + invoice_id, + line_description, + total_amount, + total_amount, + currency_code, + service_id + )) + + conn.commit() + conn.close() + return redirect("/invoices") + + clients = [] + services = [] + + if not locked: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + return render_template("invoices/edit.html", invoice=invoice, clients=clients, services=services, errors=[], locked=locked) + + + +@app.route("/payments/export.csv") +def export_payments_csv(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + p.id, + p.invoice_id, + i.invoice_number, + p.client_id, + c.client_code, + c.company_name, + p.payment_method, + p.payment_currency, + p.payment_amount, + p.cad_value_at_payment, + p.reference, + p.sender_name, + p.txid, + p.wallet_address, + p.payment_status, + p.received_at, + p.notes + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + ORDER BY p.id ASC + """) + rows = cursor.fetchall() + conn.close() + + output = StringIO() + writer = csv.writer(output) + writer.writerow([ + "id", + "invoice_id", + "invoice_number", + "client_id", + "client_code", + "company_name", + "payment_method", + "payment_currency", + "payment_amount", + "cad_value_at_payment", + "reference", + "sender_name", + "txid", + "wallet_address", + "payment_status", + "received_at", + "notes", + ]) + + for r in rows: + writer.writerow([ + r.get("id", ""), + r.get("invoice_id", ""), + r.get("invoice_number", ""), + r.get("client_id", ""), + r.get("client_code", ""), + r.get("company_name", ""), + r.get("payment_method", ""), + r.get("payment_currency", ""), + r.get("payment_amount", ""), + r.get("cad_value_at_payment", ""), + r.get("reference", ""), + r.get("sender_name", ""), + r.get("txid", ""), + r.get("wallet_address", ""), + r.get("payment_status", ""), + r.get("received_at", ""), + r.get("notes", ""), + ]) + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = "attachment; filename=payments.csv" + return response + +@app.route("/payments") +def payments(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + p.*, + i.invoice_number, + i.status AS invoice_status, + i.total_amount, + i.amount_paid, + i.currency_code AS invoice_currency_code, + c.client_code, + c.company_name + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + ORDER BY p.id DESC + """) + payments = cursor.fetchall() + + conn.close() + return render_template("payments/list.html", payments=payments) + +@app.route("/payments/new", methods=["GET", "POST"]) +def new_payment(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + invoice_id = request.form.get("invoice_id", "").strip() + payment_method = request.form.get("payment_method", "").strip() + payment_currency = request.form.get("payment_currency", "").strip() + payment_amount = request.form.get("payment_amount", "").strip() + cad_value_at_payment = request.form.get("cad_value_at_payment", "").strip() + reference = request.form.get("reference", "").strip() + sender_name = request.form.get("sender_name", "").strip() + txid = request.form.get("txid", "").strip() + wallet_address = request.form.get("wallet_address", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not invoice_id: + errors.append("Invoice is required.") + if not payment_method: + errors.append("Payment method is required.") + if not payment_currency: + errors.append("Payment currency is required.") + if not payment_amount: + errors.append("Payment amount is required.") + if not cad_value_at_payment: + errors.append("CAD value at payment is required.") + + if not errors: + try: + payment_amount_value = Decimal(str(payment_amount)) + if payment_amount_value <= Decimal("0"): + errors.append("Payment amount must be greater than zero.") + except Exception: + errors.append("Payment amount must be a valid number.") + + if not errors: + try: + cad_value_value = Decimal(str(cad_value_at_payment)) + if cad_value_value < Decimal("0"): + errors.append("CAD value at payment cannot be negative.") + except Exception: + errors.append("CAD value at payment must be a valid number.") + + invoice_row = None + + if not errors: + cursor.execute(""" + SELECT + i.id, + i.client_id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + """, (invoice_id,)) + invoice_row = cursor.fetchone() + + if not invoice_row: + errors.append("Selected invoice was not found.") + else: + allowed_statuses = {"pending", "partial", "overdue"} + if invoice_row["status"] not in allowed_statuses: + errors.append("Payments can only be recorded against pending, partial, or overdue invoices.") + else: + remaining_balance = to_decimal(invoice_row["total_amount"]) - to_decimal(invoice_row["amount_paid"]) + entered_amount = to_decimal(payment_amount) + + if remaining_balance <= Decimal("0"): + errors.append("This invoice has no remaining balance.") + elif entered_amount > remaining_balance: + errors.append( + f"Payment amount exceeds remaining balance. Remaining balance is {fmt_money(remaining_balance, invoice_row['currency_code'])} {invoice_row['currency_code']}." + ) + + if errors: + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY i.id DESC + """) + invoices = cursor.fetchall() + conn.close() + + form_data = { + "invoice_id": invoice_id, + "payment_method": payment_method, + "payment_currency": payment_currency, + "payment_amount": payment_amount, + "cad_value_at_payment": cad_value_at_payment, + "reference": reference, + "sender_name": sender_name, + "txid": txid, + "wallet_address": wallet_address, + "notes": notes, + } + + return render_template( + "payments/new.html", + invoices=invoices, + errors=errors, + form_data=form_data, + ) + + client_id = invoice_row["client_id"] + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'confirmed', UTC_TIMESTAMP(), %s) + """, ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference or None, + sender_name or None, + txid or None, + wallet_address or None, + notes or None + )) + + conn.commit() + conn.close() + + recalc_invoice_totals(invoice_id) + + try: + notify_conn = get_db_connection() + notify_cursor = notify_conn.cursor(dictionary=True) + notify_cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.currency_code, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice_id,)) + invoice_email_row = notify_cursor.fetchone() + notify_conn.close() + + if invoice_email_row and invoice_email_row.get("email"): + client_name = ( + invoice_email_row.get("contact_name") + or invoice_email_row.get("company_name") + or invoice_email_row.get("email") + ) + payment_amount_display = f"{to_decimal(cad_value_at_payment):.2f} CAD" + invoice_total_display = f"{to_decimal(invoice_email_row.get('total_amount')):.2f} {invoice_email_row.get('currency_code') or 'CAD'}" + + subject = f"Payment Received for Invoice {invoice_email_row.get('invoice_number')}" + body = f"""Hello {client_name}, + +We have received your payment for invoice {invoice_email_row.get('invoice_number')}. + +Amount Received: +{payment_amount_display} + +Invoice Total: +{invoice_total_display} + +Current Invoice Status: +{invoice_email_row.get('status')} + +You can view your invoice anytime in the client portal: +https://portal.outsidethebox.top/portal + +Thank you, +OutsideTheBox +support@outsidethebox.top +""" + + send_configured_email( + to_email=invoice_email_row.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="payment_received", + invoice_id=invoice_id + ) + except Exception: + pass + + return redirect("/payments") + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY i.id DESC + """) + invoices = cursor.fetchall() + conn.close() + + return render_template( + "payments/new.html", + invoices=invoices, + errors=[], + form_data={}, + ) + + + +@app.route("/payments/void/", methods=["POST"]) +def void_payment(payment_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, invoice_id, payment_status + FROM payments + WHERE id = %s + """, (payment_id,)) + payment = cursor.fetchone() + + if not payment: + conn.close() + return "Payment not found", 404 + + if payment["payment_status"] != "confirmed": + conn.close() + return redirect("/payments") + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'reversed' + WHERE id = %s + """, (payment_id,)) + + conn.commit() + conn.close() + + recalc_invoice_totals(payment["invoice_id"]) + + return redirect("/payments") + + recalc_invoice_totals(payment["invoice_id"]) + + return redirect("/payments") + +@app.route("/payments/edit/", methods=["GET", "POST"]) +def edit_payment(payment_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + p.*, + i.invoice_number, + c.client_code, + c.company_name + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + WHERE p.id = %s + """, (payment_id,)) + payment = cursor.fetchone() + + if not payment: + conn.close() + return "Payment not found", 404 + + if request.method == "POST": + payment_method = request.form.get("payment_method", "").strip() + payment_currency = request.form.get("payment_currency", "").strip() + payment_amount = request.form.get("payment_amount", "").strip() + cad_value_at_payment = request.form.get("cad_value_at_payment", "").strip() + reference = request.form.get("reference", "").strip() + sender_name = request.form.get("sender_name", "").strip() + txid = request.form.get("txid", "").strip() + wallet_address = request.form.get("wallet_address", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not payment_method: + errors.append("Payment method is required.") + if not payment_currency: + errors.append("Payment currency is required.") + if not payment_amount: + errors.append("Payment amount is required.") + if not cad_value_at_payment: + errors.append("CAD value at payment is required.") + + if not errors: + try: + amount_value = float(payment_amount) + if amount_value <= 0: + errors.append("Payment amount must be greater than zero.") + except ValueError: + errors.append("Payment amount must be a valid number.") + + try: + cad_value = float(cad_value_at_payment) + if cad_value < 0: + errors.append("CAD value at payment cannot be negative.") + except ValueError: + errors.append("CAD value at payment must be a valid number.") + + if errors: + payment["payment_method"] = payment_method or payment["payment_method"] + payment["payment_currency"] = payment_currency or payment["payment_currency"] + payment["payment_amount"] = payment_amount or payment["payment_amount"] + payment["cad_value_at_payment"] = cad_value_at_payment or payment["cad_value_at_payment"] + payment["reference"] = reference + payment["sender_name"] = sender_name + payment["txid"] = txid + payment["wallet_address"] = wallet_address + payment["notes"] = notes + conn.close() + return render_template("payments/edit.html", payment=payment, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_method = %s, + payment_currency = %s, + payment_amount = %s, + cad_value_at_payment = %s, + reference = %s, + sender_name = %s, + txid = %s, + wallet_address = %s, + notes = %s + WHERE id = %s + """, ( + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference or None, + sender_name or None, + txid or None, + wallet_address or None, + notes or None, + payment_id + )) + conn.commit() + invoice_id = payment["invoice_id"] + conn.close() + + recalc_invoice_totals(invoice_id) + + return redirect("/payments") + + conn.close() + return render_template("payments/edit.html", payment=payment, errors=[]) + + +def _portal_current_client(): + client_id = session.get("portal_client_id") + if not client_id: + return None + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, company_name, contact_name, email, portal_enabled, portal_force_password_change + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + conn.close() + return client + +@app.route("/portal", methods=["GET"]) +def portal_index(): + if session.get("portal_client_id"): + return redirect("/portal/dashboard") + return render_template("portal_login.html") + +@app.route("/portal/login", methods=["POST"]) +def portal_login(): + email = (request.form.get("email") or "").strip().lower() + credential = (request.form.get("credential") or "").strip() + + if not email or not credential: + return render_template("portal_login.html", portal_message="Email and access code or password are required.", portal_email=email) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, company_name, contact_name, email, portal_enabled, portal_access_code, + portal_password_hash, portal_force_password_change + FROM clients + WHERE LOWER(email) = %s + LIMIT 1 + """, (email,)) + client = cursor.fetchone() + + if not client or not client.get("portal_enabled"): + conn.close() + return render_template("portal_login.html", portal_message="Portal access is not enabled for that email address.", portal_email=email) + + password_hash = client.get("portal_password_hash") + access_code = client.get("portal_access_code") or "" + + ok = False + first_login = False + + if password_hash: + ok = check_password_hash(password_hash, credential) + else: + ok = (credential == access_code) + first_login = ok + + if not ok and access_code and credential == access_code: + ok = True + first_login = True + + if not ok: + conn.close() + return render_template("portal_login.html", portal_message="Invalid credentials.", portal_email=email) + + session["portal_client_id"] = client["id"] + session["portal_email"] = client["email"] + + cursor.execute(""" + UPDATE clients + SET portal_last_login_at = UTC_TIMESTAMP() + WHERE id = %s + """, (client["id"],)) + conn.commit() + conn.close() + + if first_login or client.get("portal_force_password_change"): + return redirect("/portal/set-password") + + return redirect("/portal/dashboard") + +@app.route("/portal/set-password", methods=["GET", "POST"]) +def portal_set_password(): + client = _portal_current_client() + if not client: + return redirect("/portal") + + client_name = client.get("company_name") or client.get("contact_name") or client.get("email") + + if request.method == "GET": + return render_template("portal_set_password.html", client_name=client_name) + + password = (request.form.get("password") or "") + password2 = (request.form.get("password2") or "") + + if len(password) < 10: + return render_template("portal_set_password.html", client_name=client_name, portal_message="Password must be at least 10 characters long.") + if password != password2: + return render_template("portal_set_password.html", client_name=client_name, portal_message="Passwords do not match.") + + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_password_hash = %s, + portal_password_set_at = UTC_TIMESTAMP(), + portal_force_password_change = 0, + portal_access_code = NULL + WHERE id = %s + """, (generate_password_hash(password), client["id"])) + conn.commit() + conn.close() + + return redirect("/portal/dashboard") + + + +@app.route("/portal/invoices/download-all") +def portal_download_all_invoices(): + import io + import zipfile + + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, invoice_number + FROM invoices + WHERE client_id = %s + ORDER BY id + """, (client["id"],)) + invoices = cursor.fetchall() + conn.close() + + memory_file = io.BytesIO() + + with zipfile.ZipFile(memory_file, "w", zipfile.ZIP_DEFLATED) as zf: + for inv in invoices: + response = invoice_pdf(inv["id"]) + response.direct_passthrough = False + pdf_bytes = response.get_data() + + filename = f"{inv.get('invoice_number') or ('invoice_' + str(inv['id']))}.pdf" + zf.writestr(filename, pdf_bytes) + + memory_file.seek(0) + + return send_file( + memory_file, + download_name="all_invoices.zip", + as_attachment=True, + mimetype="application/zip", + ) + +@app.route("/portal/dashboard", methods=["GET"]) +def portal_dashboard(): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT i.id, i.invoice_number, i.status, i.created_at, i.total_amount, i.amount_paid, + p.payment_currency, p.notes, p.reference + FROM invoices i + LEFT JOIN payments p ON p.id = ( + SELECT id FROM payments + WHERE invoice_id = i.id + ORDER BY id DESC + LIMIT 1 + ) + WHERE client_id = %s + ORDER BY created_at DESC + """, (client["id"],)) + invoices = cursor.fetchall() + + def _fmt_money(value): + return f"{to_decimal(value):.2f}" + + for row in invoices: + # Determine payment method + method = "" + currency = (row.get("payment_currency") or "").upper() + notes = (row.get("notes") or "").lower() + ref = (row.get("reference") or "").lower() + + if currency: + method = currency + elif "square" in ref: + method = "Square" + elif "etransfer" in ref or "e-transfer" in ref: + method = "e-Transfer" + + row["payment_method"] = method + # Determine payment method + method = "" + currency = (row.get("payment_currency") or "").upper() + notes = (row.get("notes") or "").lower() + ref = (row.get("reference") or "").lower() + + if currency: + method = currency + elif "square" in ref: + method = "Square" + elif "etransfer" in ref or "e-transfer" in ref: + method = "e-Transfer" + + row["payment_method"] = method + outstanding = to_decimal(row.get("total_amount")) - to_decimal(row.get("amount_paid")) + row["outstanding"] = _fmt_money(outstanding) + row["total_amount"] = _fmt_money(row.get("total_amount")) + row["amount_paid"] = _fmt_money(row.get("amount_paid")) + row["created_at"] = fmt_local(row.get("created_at")) + + total_outstanding = sum((to_decimal(r["outstanding"]) for r in invoices), to_decimal("0")) + total_paid = sum((to_decimal(r["amount_paid"]) for r in invoices), to_decimal("0")) + + conn.close() + + return render_template( + "portal_dashboard.html", + client=client, + invoices=invoices, + invoice_count=len(invoices), + total_outstanding=f"{total_outstanding:.2f}", + total_paid=f"{total_paid:.2f}", + ) + + + +@app.route("/portal/invoice//pdf", methods=["GET"]) +def portal_invoice_pdf(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s AND i.client_id = %s + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + conn.close() + + settings = get_app_settings() + + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def draw_line(txt, x=left, font="Helvetica", size=11): + nonlocal y + pdf.setFont(font, size) + pdf.drawString(x, y, str(txt) if txt is not None else "") + y -= 16 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("payment_terms", "")), 90): + line_text = settings.get("payment_terms", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("invoice_footer", "")), 90): + line_text = settings.get("invoice_footer", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + + return send_file( + buffer, + mimetype="application/pdf", + as_attachment=True, + download_name=f"{invoice['invoice_number']}.pdf" + ) + + +@app.route("/portal/invoice/", methods=["GET"]) +def portal_invoice_detail(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + ensure_invoice_quote_columns() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_id, invoice_number, status, created_at, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + cursor.execute(""" + SELECT description, quantity, unit_amount AS unit_price, line_total + FROM invoice_items + WHERE invoice_id = %s + ORDER BY id ASC + """, (invoice_id,)) + items = cursor.fetchall() + + def _fmt_money(value): + return f"{to_decimal(value):.2f}" + + outstanding = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + invoice["outstanding"] = _fmt_money(outstanding) + invoice["total_amount"] = _fmt_money(invoice.get("total_amount")) + invoice["amount_paid"] = _fmt_money(invoice.get("amount_paid")) + invoice["created_at"] = fmt_local(invoice.get("created_at")) + invoice["quote_expires_at_local"] = fmt_local(invoice.get("quote_expires_at")) + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + for item in items: + item["quantity"] = _fmt_money(item.get("quantity")) + item["unit_price"] = _fmt_money(item.get("unit_price")) + item["line_total"] = _fmt_money(item.get("line_total")) + + pay_mode = (request.args.get("pay") or "").strip().lower() + crypto_error = (request.args.get("crypto_error") or "").strip() + + crypto_options = get_invoice_crypto_options(invoice) + selected_crypto_option = None + pending_crypto_payment = None + crypto_quote_window_expires_iso = None + crypto_quote_window_expires_local = None + + if (invoice.get("status") or "").lower() != "paid": + if pay_mode != "crypto": + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, updated_at, txid, confirmations, + confirmation_required, notes + FROM payments + WHERE invoice_id = %s + AND client_id = %s + AND payment_status = 'pending' + AND notes LIKE '%%portal_crypto_intent:%%' + ORDER BY id DESC + LIMIT 1 + """, (invoice_id, client["id"])) + auto_pending_payment = cursor.fetchone() + if auto_pending_payment: + pending_crypto_payment = auto_pending_payment + pay_mode = "crypto" + if not request.args.get("payment_id"): + selected_crypto_option = next( + (o for o in crypto_options if o["payment_currency"] == str(auto_pending_payment.get("payment_currency") or "").upper()), + None + ) + + if pay_mode == "crypto" and crypto_options and (invoice.get("status") or "").lower() != "paid": + quote_key = f"portal_crypto_quote_window_{invoice_id}_{client['id']}" + now_utc = datetime.now(timezone.utc) + + stored_start = session.get(quote_key) + quote_start_dt = None + if stored_start: + try: + quote_start_dt = datetime.fromisoformat(str(stored_start).replace("Z", "+00:00")) + if quote_start_dt.tzinfo is None: + quote_start_dt = quote_start_dt.replace(tzinfo=timezone.utc) + except Exception: + quote_start_dt = None + + if request.args.get("refresh_quote") == "1" or not quote_start_dt or (now_utc - quote_start_dt).total_seconds() > 90: + quote_start_dt = now_utc + session[quote_key] = quote_start_dt.isoformat() + + quote_expires_dt = quote_start_dt + timedelta(seconds=90) + crypto_quote_window_expires_iso = quote_expires_dt.astimezone(timezone.utc).isoformat() + crypto_quote_window_expires_local = fmt_local(quote_expires_dt) + + selected_asset = (request.args.get("asset") or "").strip().upper() + if selected_asset: + selected_crypto_option = next((o for o in crypto_options if o["symbol"] == selected_asset), None) + + payment_id = (request.args.get("payment_id") or "").strip() + if not payment_id and pending_crypto_payment: + payment_id = str(pending_crypto_payment.get("id") or "").strip() + + if payment_id.isdigit(): + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, received_at, txid, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (payment_id, invoice_id, client["id"])) + pending_crypto_payment = cursor.fetchone() + + if pending_crypto_payment: + created_dt = pending_crypto_payment.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + + if created_dt: + lock_expires_dt = created_dt + timedelta(minutes=2) + pending_crypto_payment["created_at_local"] = fmt_local(created_dt) + pending_crypto_payment["lock_expires_at_local"] = fmt_local(lock_expires_dt) + pending_crypto_payment["lock_expires_at_iso"] = lock_expires_dt.astimezone(timezone.utc).isoformat() + pending_crypto_payment["lock_expired"] = datetime.now(timezone.utc) >= lock_expires_dt + else: + pending_crypto_payment["created_at_local"] = "" + pending_crypto_payment["lock_expires_at_local"] = "" + pending_crypto_payment["lock_expires_at_iso"] = "" + pending_crypto_payment["lock_expired"] = True + + received_dt = pending_crypto_payment.get("received_at") + if received_dt and received_dt.tzinfo is None: + received_dt = received_dt.replace(tzinfo=timezone.utc) + + if received_dt: + processing_expires_dt = received_dt + timedelta(minutes=15) + pending_crypto_payment["received_at_local"] = fmt_local(received_dt) + pending_crypto_payment["processing_expires_at_local"] = fmt_local(processing_expires_dt) + pending_crypto_payment["processing_expires_at_iso"] = processing_expires_dt.astimezone(timezone.utc).isoformat() + pending_crypto_payment["processing_expired"] = datetime.now(timezone.utc) >= processing_expires_dt + else: + pending_crypto_payment["received_at_local"] = "" + pending_crypto_payment["processing_expires_at_local"] = "" + pending_crypto_payment["processing_expires_at_iso"] = "" + pending_crypto_payment["processing_expired"] = False + + if not selected_crypto_option: + selected_crypto_option = next( + (o for o in crypto_options if o["payment_currency"] == str(pending_crypto_payment.get("payment_currency") or "").upper()), + None + ) + + if pending_crypto_payment.get("txid") and str(pending_crypto_payment.get("payment_status") or "").lower() == "pending": + reconcile_result = reconcile_pending_crypto_payment(pending_crypto_payment) + + cursor.execute(""" + SELECT id, client_id, invoice_number, status, created_at, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + refreshed_invoice = cursor.fetchone() + if refreshed_invoice: + invoice.update(refreshed_invoice) + + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, updated_at, txid, confirmations, + confirmation_required, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (payment_id, invoice_id, client["id"])) + refreshed_payment = cursor.fetchone() + if refreshed_payment: + pending_crypto_payment = refreshed_payment + + if reconcile_result.get("state") == "confirmed": + outstanding = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + invoice["outstanding"] = _fmt_money(outstanding) + invoice["total_amount"] = _fmt_money(invoice.get("total_amount")) + invoice["amount_paid"] = _fmt_money(invoice.get("amount_paid")) + elif reconcile_result.get("state") in {"timeout", "failed_receipt"}: + crypto_error = "Transaction was not confirmed in time. Please refresh your quote and try again." + + pdf_url = f"/invoices/pdf/{invoice_id}" + invoice_payments = get_invoice_payments(invoice_id) + + conn.close() + + return render_template( + "portal_invoice_detail.html", + client=client, + invoice=invoice, + items=items, + pdf_url=pdf_url, + pay_mode=pay_mode, + crypto_error=crypto_error, + crypto_options=crypto_options, + selected_crypto_option=selected_crypto_option, + pending_crypto_payment=pending_crypto_payment, + crypto_quote_window_expires_iso=crypto_quote_window_expires_iso, + crypto_quote_window_expires_local=crypto_quote_window_expires_local, + invoice_payments=invoice_payments, + ) + + +@app.route("/portal/logout", methods=["GET"]) +def portal_logout(): + session.pop("portal_client_id", None) + session.pop("portal_email", None) + return redirect("/portal") + + + +@app.route("/clients/portal/enable/", methods=["POST"]) +def client_portal_enable(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, portal_enabled, portal_access_code, portal_password_hash + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("portal_access_code") and not client.get("portal_password_hash"): + new_code = generate_portal_access_code() + cursor2 = conn.cursor() + cursor2.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + else: + cursor2 = conn.cursor() + cursor2.execute(""" + UPDATE clients + SET portal_enabled = 1 + WHERE id = %s + """, (client_id,)) + + conn.commit() + conn.close() + return redirect(f"/clients/edit/{client_id}") + +@app.route("/clients/portal/disable/", methods=["POST"]) +def client_portal_disable(client_id): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_enabled = 0 + WHERE id = %s + """, (client_id,)) + conn.commit() + conn.close() + return redirect(f"/clients/edit/{client_id}") + +@app.route("/clients/portal/reset-code/", methods=["POST"]) +def client_portal_reset_code(client_id): + new_code = generate_portal_access_code() + + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + conn.commit() + conn.close() + + return redirect(f"/clients/edit/{client_id}") + + +@app.route("/clients/portal/send-invite/", methods=["POST"]) +def client_portal_send_invite(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled, + portal_access_code, + portal_password_hash, + portal_password_set_at + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("email"): + conn.close() + return redirect(f"/clients/edit/{client_id}?portal_email_status=missing_email") + + access_code = client.get("portal_access_code") + + # If no active one-time code exists, generate a fresh one and require password setup again. + if not access_code: + access_code = generate_portal_access_code() + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (access_code, client_id)) + conn.commit() + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled, + portal_access_code, + portal_password_hash, + portal_password_set_at + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + elif not client.get("portal_enabled"): + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1 + WHERE id = %s + """, (client_id,)) + conn.commit() + + conn.close() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_email = client.get("email") or "" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Client Portal Access" + body = f"""Hello {contact_name}, + +Your OutsideTheBox client portal access is now ready. + +Portal URL: +{portal_url} + +Login email: +{portal_email} + +Single-use access code: +{client.get("portal_access_code")} + +Important: +- This access code is single-use. +- After your first successful login, you will be asked to create your password. +- Once your password is created, this access code is cleared and future logins will use your email address and password. + +If you have any trouble signing in, contact support: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=portal_email, + subject=subject, + body=body, + attachments=None, + email_type="portal_invite", + invoice_id=None + ) + return redirect(f"/clients/edit/{client_id}?portal_email_status=sent") + except Exception: + return redirect(f"/clients/edit/{client_id}?portal_email_status=error") + + +@app.route("/clients/portal/send-password-reset/", methods=["POST"]) +def client_portal_send_password_reset(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("email"): + conn.close() + return redirect(f"/clients/edit/{client_id}?portal_reset_status=missing_email") + + new_code = generate_portal_access_code() + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + conn.commit() + conn.close() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_email = client.get("email") or "" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Portal Password Reset" + body = f"""Hello {contact_name}, + +A password reset has been issued for your OutsideTheBox client portal access. + +Portal URL: +{portal_url} + +Login email: +{portal_email} + +New single-use access code: +{new_code} + +Important: +- This access code is single-use. +- It replaces your previous portal password. +- After you sign in, you will be asked to create a new password. +- Once your new password is created, this access code is cleared and future logins will use your email address and password. + +If you did not expect this reset, contact support immediately: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=portal_email, + subject=subject, + body=body, + attachments=None, + email_type="portal_password_reset", + invoice_id=None + ) + return redirect(f"/clients/edit/{client_id}?portal_reset_status=sent") + except Exception: + return redirect(f"/clients/edit/{client_id}?portal_reset_status=error") + +@app.route("/portal/forgot-password", methods=["GET", "POST"]) +def portal_forgot_password(): + if request.method == "GET": + return render_template("portal_forgot_password.html", error=None, message=None, form_email="") + + email = (request.form.get("email") or "").strip().lower() + + if not email: + return render_template( + "portal_forgot_password.html", + error="Email address is required.", + message=None, + form_email="" + ) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, company_name, contact_name, email + FROM clients + WHERE LOWER(email) = %s + LIMIT 1 + """, (email,)) + client = cursor.fetchone() + + if client: + new_code = generate_portal_access_code() + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1, + portal_enabled = 1 + WHERE id = %s + """, (new_code, client["id"])) + conn.commit() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Portal Password Reset" + + body = f"""Hello {contact_name}, + +A password reset was requested for your OutsideTheBox client portal. + +Portal URL: +{portal_url} + +Login email: +{client.get("email")} + +Single-use access code: +{new_code} + +Important: +- This access code is single-use. +- It replaces your previous portal password. +- After you sign in, you will be asked to create a new password. +- Once your new password is created, this access code is cleared and future logins will use your email address and password. + +If you did not request this reset, contact support immediately: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=client.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="portal_forgot_password", + invoice_id=None + ) + except Exception: + pass + + conn.close() + + return render_template( + "portal_forgot_password.html", + error=None, + message="If that email exists in our system, a reset message has been sent.", + form_email=email + ) + + + + +@app.route("/portal/invoice//pay-crypto", methods=["POST"]) +def portal_invoice_pay_crypto(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + ensure_invoice_quote_columns() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, client_id, invoice_number, status, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot, + created_at + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + status = (invoice.get("status") or "").lower() + if status == "paid": + conn.close() + return redirect(f"/portal/invoice/{invoice_id}") + + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + options = get_invoice_crypto_options(invoice) + chosen_symbol = (request.form.get("asset") or "").strip().upper() + selected_option = next((o for o in options if o["symbol"] == chosen_symbol), None) + + quote_key = f"portal_crypto_quote_window_{invoice_id}_{client['id']}" + now_utc = datetime.now(timezone.utc) + stored_start = session.get(quote_key) + quote_start_dt = None + if stored_start: + try: + quote_start_dt = datetime.fromisoformat(str(stored_start).replace("Z", "+00:00")) + if quote_start_dt.tzinfo is None: + quote_start_dt = quote_start_dt.replace(tzinfo=timezone.utc) + except Exception: + quote_start_dt = None + + if not quote_start_dt or (now_utc - quote_start_dt).total_seconds() > 90: + session.pop(quote_key, None) + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error=price+has+expired+-+please+refresh+your+view+to+update&refresh_quote=1") + + if not selected_option: + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error=Please+choose+a+valid+crypto+asset") + + if not selected_option.get("available"): + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error={selected_option['symbol']}+is+not+currently+available") + + cursor.execute(""" + SELECT id, payment_currency, payment_amount, wallet_address, reference, payment_status, created_at, notes + FROM payments + WHERE invoice_id = %s + AND client_id = %s + AND payment_status = 'pending' + AND payment_currency = %s + ORDER BY id DESC + LIMIT 1 + """, (invoice_id, client["id"], selected_option["payment_currency"])) + existing = cursor.fetchone() + + pending_payment_id = None + + if existing: + created_dt = existing.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + + if created_dt and (now_utc - created_dt).total_seconds() <= 120: + pending_payment_id = existing["id"] + + if not pending_payment_id: + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, 'other', %s, %s, %s, %s, %s, NULL, %s, 'pending', NULL, %s) + """, ( + invoice["id"], + invoice["client_id"], + selected_option["payment_currency"], + str(selected_option["display_amount"]), + str(invoice.get("quote_fiat_amount") or invoice.get("total_amount") or "0"), + invoice["invoice_number"], + client.get("email") or client.get("company_name") or "Portal Client", + selected_option["wallet_address"], + f"portal_crypto_intent:{selected_option['symbol']}:{selected_option['chain']}|invoice:{invoice['invoice_number']}|frozen_quote" + )) + conn.commit() + pending_payment_id = insert_cursor.lastrowid + + session.pop(quote_key, None) + conn.close() + + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&asset={selected_option['symbol']}&payment_id={pending_payment_id}") + +@app.route("/portal/invoice//submit-crypto-tx", methods=["POST"]) +def portal_submit_crypto_tx(invoice_id): + client = _portal_current_client() + if not client: + return jsonify({"ok": False, "error": "not_authenticated"}), 401 + + ensure_invoice_quote_columns() + + try: + payload = request.get_json(force=True) or {} + except Exception: + payload = {} + + payment_id = str(payload.get("payment_id") or "").strip() + asset = str(payload.get("asset") or "").strip().upper() + tx_hash = str(payload.get("tx_hash") or "").strip() + + if not payment_id.isdigit(): + return jsonify({"ok": False, "error": "invalid_payment_id"}), 400 + if not asset: + return jsonify({"ok": False, "error": "missing_asset"}), 400 + if not tx_hash or not tx_hash.startswith("0x"): + return jsonify({"ok": False, "error": "missing_tx_hash"}), 400 + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_id, invoice_number, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return jsonify({"ok": False, "error": "invoice_not_found"}), 404 + + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + crypto_options = get_invoice_crypto_options(invoice) + selected_option = next((o for o in crypto_options if o["symbol"] == asset), None) + + if not selected_option: + conn.close() + return jsonify({"ok": False, "error": "invalid_asset"}), 400 + + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_status, txid, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (int(payment_id), invoice_id, client["id"])) + payment = cursor.fetchone() + + if not payment: + conn.close() + return jsonify({"ok": False, "error": "payment_not_found"}), 404 + + if str(payment.get("payment_currency") or "").upper() != selected_option["payment_currency"]: + conn.close() + return jsonify({"ok": False, "error": "payment_currency_mismatch"}), 400 + + if str(payment.get("payment_status") or "").lower() != "pending": + conn.close() + return jsonify({"ok": False, "error": "payment_not_pending"}), 400 + + new_notes = append_payment_note( + payment.get("notes"), + f"[portal wallet submit] tx hash accepted: {tx_hash}" + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET txid = %s, + payment_status = 'pending', + notes = %s + WHERE id = %s + """, ( + tx_hash, + new_notes, + payment["id"] + )) + conn.commit() + conn.close() + + return jsonify({ + "ok": True, + "redirect_url": f"/portal/invoice/{invoice_id}?pay=crypto&asset={asset}&payment_id={payment['id']}" + }) + + +@app.route("/portal/invoice//pay-square", methods=["GET"]) +def portal_invoice_pay_square(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + i.*, + c.email AS client_email, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s AND i.client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return redirect("/portal/dashboard") + + status = (invoice.get("status") or "").lower() + if status == "paid": + return redirect(f"/portal/invoice/{invoice_id}") + + square_url = create_square_payment_link_for_invoice(invoice, invoice.get("client_email") or "") + return redirect(square_url) + +@app.route("/invoices/pay-square/", methods=["GET"]) +def admin_invoice_pay_square(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + i.*, + c.email AS client_email, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice_id,)) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return "Invoice not found", 404 + + status = (invoice.get("status") or "").lower() + if status == "paid": + return redirect(f"/invoices/view/{invoice_id}") + + square_url = create_square_payment_link_for_invoice(invoice, invoice.get("client_email") or "") + return redirect(square_url) + + + +def auto_apply_square_payment(parsed_event): + try: + data_obj = (((parsed_event.get("data") or {}).get("object")) or {}) + payment = data_obj.get("payment") or {} + + payment_id = payment.get("id") or "" + payment_status = (payment.get("status") or "").upper() + note = (payment.get("note") or "").strip() + buyer_email = (payment.get("buyer_email_address") or "").strip() + amount_money = (payment.get("amount_money") or {}).get("amount") + currency = (payment.get("amount_money") or {}).get("currency") or "CAD" + + if not payment_id or payment_status != "COMPLETED": + return {"processed": False, "reason": "not_completed_or_missing_id"} + + m = re.search(r'Invoice\s+([A-Za-z0-9\-]+)', note, re.IGNORECASE) + if not m: + return {"processed": False, "reason": "invoice_note_not_found", "note": note} + + invoice_number = m.group(1).strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + # Deduplicate by Square payment ID + cursor.execute(""" + SELECT id + FROM payments + WHERE txid = %s + LIMIT 1 + """, (payment_id,)) + existing = cursor.fetchone() + if existing: + conn.close() + return {"processed": False, "reason": "duplicate_payment_id", "payment_id": payment_id} + + cursor.execute(""" + SELECT + i.id, + i.client_id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.invoice_number = %s + LIMIT 1 + """, (invoice_number,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return {"processed": False, "reason": "invoice_not_found", "invoice_number": invoice_number} + + payment_amount = to_decimal(amount_money) / to_decimal("100") + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, UTC_TIMESTAMP(), %s) + """, ( + invoice["id"], + invoice["client_id"], + "square", + currency, + payment_amount, + payment_amount if currency == "CAD" else payment_amount, + invoice_number, + buyer_email or "Square Customer", + payment_id, + "", + "confirmed", + f"Auto-recorded from Square webhook. Note: {note or ''}".strip() + )) + conn.commit() + conn.close() + + recalc_invoice_totals(invoice["id"]) + + try: + notify_conn = get_db_connection() + notify_cursor = notify_conn.cursor(dictionary=True) + notify_cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.currency_code, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice["id"],)) + invoice_email_row = notify_cursor.fetchone() + notify_conn.close() + + if invoice_email_row and invoice_email_row.get("email"): + client_name = ( + invoice_email_row.get("contact_name") + or invoice_email_row.get("company_name") + or invoice_email_row.get("email") + ) + payment_amount_display = f"{to_decimal(payment_amount):.2f} {currency}" + invoice_total_display = f"{to_decimal(invoice_email_row.get('total_amount')):.2f} {invoice_email_row.get('currency_code') or 'CAD'}" + + subject = f"Payment Received for Invoice {invoice_email_row.get('invoice_number')}" + body = f"""Hello {client_name}, + +We have received your payment for invoice {invoice_email_row.get('invoice_number')}. + +Amount Received: +{payment_amount_display} + +Invoice Total: +{invoice_total_display} + +Current Invoice Status: +{invoice_email_row.get('status')} + +You can view your invoice anytime in the client portal: +https://portal.outsidethebox.top/portal + +Thank you, +OutsideTheBox +support@outsidethebox.top +""" + + send_configured_email( + to_email=invoice_email_row.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="payment_received", + invoice_id=invoice["id"] + ) + except Exception: + pass + + return { + "processed": True, + "invoice_number": invoice_number, + "payment_id": payment_id, + "amount": str(payment_amount), + "currency": currency, + } + + except Exception as e: + return {"processed": False, "reason": "exception", "error": str(e)} + + + + +@app.route("/accountbook/export.csv") +def accountbook_export_csv(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + payment_status, + received_at + FROM payments + WHERE payment_status = 'confirmed' + ORDER BY received_at DESC + """) + payments = cursor.fetchall() + conn.close() + + now_local = datetime.now(LOCAL_TZ) + today_str = now_local.strftime("%Y-%m-%d") + month_prefix = now_local.strftime("%Y-%m") + year_prefix = now_local.strftime("%Y") + + categories = [ + ("cash", "Cash"), + ("etransfer", "eTransfer"), + ("square", "Square"), + ("etho", "ETHO"), + ("eti", "ETI"), + ("egaz", "EGAZ"), + ("eth", "ETH"), + ("other", "Other"), + ] + + periods = { + "today": {"label": "Today", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "month": {"label": "This Month", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "ytd": {"label": "Year to Date", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + } + + def norm_method(method): + m = (method or "").strip().lower() + if m in ("cash",): + return "cash" + if m in ("etransfer", "e-transfer", "interac", "interac e-transfer", "email money transfer"): + return "etransfer" + if m in ("square",): + return "square" + if m in ("etho",): + return "etho" + if m in ("eti",): + return "eti" + if m in ("egaz",): + return "egaz" + if m in ("eth", "ethereum"): + return "eth" + return "other" + + for pay in payments: + received = pay.get("received_at") + if not received: + continue + + if isinstance(received, str): + received_local_str = received[:10] + received_month = received[:7] + received_year = received[:4] + else: + if received.tzinfo is None: + received = received.replace(tzinfo=timezone.utc) + received_local = received.astimezone(LOCAL_TZ) + received_local_str = received_local.strftime("%Y-%m-%d") + received_month = received_local.strftime("%Y-%m") + received_year = received_local.strftime("%Y") + + bucket = norm_method(pay.get("payment_method")) + amount = to_decimal(pay.get("cad_value_at_payment") or pay.get("payment_amount") or "0") + + if received_year == year_prefix: + periods["ytd"]["totals"][bucket] += amount + periods["ytd"]["grand"] += amount + + if received_month == month_prefix: + periods["month"]["totals"][bucket] += amount + periods["month"]["grand"] += amount + + if received_local_str == today_str: + periods["today"]["totals"][bucket] += amount + periods["today"]["grand"] += amount + + output = StringIO() + writer = csv.writer(output) + writer.writerow(["Period", "Category", "Total CAD"]) + + for period_key in ("today", "month", "ytd"): + period = periods[period_key] + for cat_key, cat_label in categories: + writer.writerow([period["label"], cat_label, f"{period['totals'][cat_key]:.2f}"]) + writer.writerow([period["label"], "Grand Total", f"{period['grand']:.2f}"]) + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = "attachment; filename=accountbook_summary.csv" + return response + + +@app.route("/accountbook") +def accountbook(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + payment_status, + received_at + FROM payments + WHERE payment_status = 'confirmed' + ORDER BY received_at DESC + """) + payments = cursor.fetchall() + conn.close() + + now_local = datetime.now(LOCAL_TZ) + today_str = now_local.strftime("%Y-%m-%d") + month_prefix = now_local.strftime("%Y-%m") + year_prefix = now_local.strftime("%Y") + + categories = [ + ("cash", "Cash"), + ("etransfer", "eTransfer"), + ("square", "Square"), + ("etho", "ETHO"), + ("eti", "ETI"), + ("egaz", "EGAZ"), + ("eth", "ETH"), + ("other", "Other"), + ] + + periods = { + "today": {"label": "Today", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "month": {"label": "This Month", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "ytd": {"label": "Year to Date", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + } + + def norm_method(method): + m = (method or "").strip().lower() + if m in ("cash",): + return "cash" + if m in ("etransfer", "e-transfer", "interac", "interac e-transfer", "email money transfer"): + return "etransfer" + if m in ("square",): + return "square" + if m in ("etho",): + return "etho" + if m in ("eti",): + return "eti" + if m in ("egaz",): + return "egaz" + if m in ("eth", "ethereum"): + return "eth" + return "other" + + for p in payments: + received = p.get("received_at") + if not received: + continue + + if isinstance(received, str): + received_local_str = received[:10] + received_month = received[:7] + received_year = received[:4] + else: + if received.tzinfo is None: + received = received.replace(tzinfo=timezone.utc) + received_local = received.astimezone(LOCAL_TZ) + received_local_str = received_local.strftime("%Y-%m-%d") + received_month = received_local.strftime("%Y-%m") + received_year = received_local.strftime("%Y") + + bucket = norm_method(p.get("payment_method")) + amount = to_decimal(p.get("cad_value_at_payment") or p.get("payment_amount") or "0") + + if received_year == year_prefix: + periods["ytd"]["totals"][bucket] += amount + periods["ytd"]["grand"] += amount + + if received_month == month_prefix: + periods["month"]["totals"][bucket] += amount + periods["month"]["grand"] += amount + + if received_local_str == today_str: + periods["today"]["totals"][bucket] += amount + periods["today"]["grand"] += amount + + period_cards = [] + for key in ("today", "month", "ytd"): + block = periods[key] + lines = [] + for cat_key, cat_label in categories: + lines.append(f"{cat_label}{block['totals'][cat_key]:.2f}") + period_cards.append(f""" +
+

{block['label']}

+
{block['grand']:.2f}
+ + + {''.join(lines)} + +
+
+ """) + + html = f""" + + + + + Accountbook - OTB Billing + + + + + +
+
+
+

Accountbook

+

Confirmed payment totals by period and payment type.

+
+ +
+ +
+ {''.join(period_cards)} +
+
+ +""" + return Response(html, mimetype="text/html") + + +@app.route("/square/reconciliation") +def square_reconciliation(): + log_path = Path(SQUARE_WEBHOOK_LOG) + events = [] + + if log_path.exists(): + lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines() + for line in reversed(lines[-400:]): + try: + row = json.loads(line) + events.append(row) + except Exception: + continue + + summary_cards = { + "processed_true": 0, + "duplicates": 0, + "failures": 0, + "sig_invalid": 0, + } + + for row in events[:150]: + if row.get("signature_valid") is False: + summary_cards["sig_invalid"] += 1 + auto_apply_result = row.get("auto_apply_result") + if isinstance(auto_apply_result, dict): + if auto_apply_result.get("processed") is True: + summary_cards["processed_true"] += 1 + elif auto_apply_result.get("reason") == "duplicate_payment_id": + summary_cards["duplicates"] += 1 + else: + summary_cards["failures"] += 1 + + summary_html = f""" + + """ + + filter_mode = (request.args.get("filter") or "").strip().lower() + + filtered_events = [] + for row in events[:150]: + auto_apply_result = row.get("auto_apply_result") + sig_valid = row.get("signature_valid") + + include = True + if filter_mode == "processed": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("processed") is True + elif filter_mode == "duplicates": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("reason") == "duplicate_payment_id" + elif filter_mode == "failures": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("processed") is False and auto_apply_result.get("reason") != "duplicate_payment_id" + elif filter_mode == "invalid": + include = (sig_valid is False) + + if include: + filtered_events.append(row) + + rows_html = [] + for row in filtered_events: + logged_at = row.get("logged_at_utc", "") + event_type = row.get("event_type", row.get("source", "")) + payment_id = row.get("payment_id", "") + note = row.get("note", "") + amount_money = row.get("amount_money", "") + signature_valid = row.get("signature_valid", "") + auto_apply_result = row.get("auto_apply_result") + + if isinstance(auto_apply_result, dict): + if auto_apply_result.get("processed") is True: + result_text = f"processed: true / invoice {auto_apply_result.get('invoice_number','')}" + result_class = "ok" + else: + result_text = f"processed: false / {auto_apply_result.get('reason','')}" + if auto_apply_result.get("error"): + result_text += f" / {auto_apply_result.get('error')}" + result_class = "warn" + else: + result_text = "" + result_class = "" + + signature_text = "true" if signature_valid is True else ("false" if signature_valid is False else "") + + rows_html.append(f""" + + {logged_at} + {event_type} + {payment_id} + {amount_money} + {note} + {signature_text} + {result_text} + + """) + + html = f""" + + + + + Square Reconciliation - OTB Billing + + + + + +
+
+
+

Square Reconciliation

+

Recent Square webhook events and auto-apply outcomes.

+
+ +
+ +

Log file: {SQUARE_WEBHOOK_LOG}

+

Current Filter: {filter_mode or "all"}

+ + {summary_html} + + + + + + + + + + + + + + + {''.join(rows_html) if rows_html else ''} + +
Logged At (UTC)EventPayment IDAmount (cents)NoteSig ValidAuto Apply Result
No webhook events found.
+
+ +""" + return Response(html, mimetype="text/html") + + +@app.route("/square/webhook", methods=["POST"]) +def square_webhook(): + raw_body = request.get_data() + signature_header = request.headers.get("x-square-hmacsha256-signature", "") + notification_url = SQUARE_WEBHOOK_NOTIFICATION_URL or request.url + + valid = square_signature_is_valid(signature_header, raw_body, notification_url) + + parsed = None + try: + parsed = json.loads(raw_body.decode("utf-8")) + except Exception: + parsed = None + + event_id = None + event_type = None + payment_id = None + payment_status = None + amount_money = None + reference_id = None + note = None + order_id = None + customer_id = None + receipt_number = None + source_type = None + + try: + if isinstance(parsed, dict): + event_id = parsed.get("event_id") + event_type = parsed.get("type") + data_obj = (((parsed.get("data") or {}).get("object")) or {}) + payment = data_obj.get("payment") or {} + payment_id = payment.get("id") + payment_status = payment.get("status") + amount_money = (((payment.get("amount_money") or {}).get("amount"))) + reference_id = payment.get("reference_id") + note = payment.get("note") + order_id = payment.get("order_id") + customer_id = payment.get("customer_id") + receipt_number = payment.get("receipt_number") + source_type = ((payment.get("source_type")) or "") + except Exception: + pass + + append_square_webhook_log({ + "logged_at_utc": datetime.utcnow().isoformat() + "Z", + "signature_valid": valid, + "event_id": event_id, + "event_type": event_type, + "payment_id": payment_id, + "payment_status": payment_status, + "amount_money": amount_money, + "reference_id": reference_id, + "note": note, + "order_id": order_id, + "customer_id": customer_id, + "receipt_number": receipt_number, + "source_type": source_type, + "headers": { + "x-square-hmacsha256-signature": bool(signature_header), + "content-type": request.headers.get("content-type", ""), + "user-agent": request.headers.get("user-agent", ""), + }, + "raw_json": parsed, + }) + + if not valid: + return jsonify({"ok": False, "error": "invalid signature"}), 403 + + result = auto_apply_square_payment(parsed or {}) + append_square_webhook_log({ + "logged_at_utc": datetime.utcnow().isoformat() + "Z", + "auto_apply_result": result, + "source": "square_webhook_postprocess" + }) + + return jsonify({"ok": True, "result": result}), 200 + +register_health_routes(app) +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5050, debug=False, use_reloader=False) \ No newline at end of file diff --git a/backups/payment-method-fix-20260322-040838/portal_dashboard.html.before_fix b/backups/payment-method-fix-20260322-040838/portal_dashboard.html.before_fix new file mode 100644 index 0000000..f154632 --- /dev/null +++ b/backups/payment-method-fix-20260322-040838/portal_dashboard.html.before_fix @@ -0,0 +1,107 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} + {{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + {% include "footer.html" %} + + diff --git a/backups/payment-method-fix2-20260322-041036/app.py.before_fix b/backups/payment-method-fix2-20260322-041036/app.py.before_fix new file mode 100644 index 0000000..a9d7ed6 --- /dev/null +++ b/backups/payment-method-fix2-20260322-041036/app.py.before_fix @@ -0,0 +1,6344 @@ +import os +from flask import Flask, render_template, request, redirect, send_file, make_response, jsonify, session, Response +from db import get_db_connection +from utils import generate_client_code, generate_service_code +from datetime import datetime, timezone, date, timedelta +from zoneinfo import ZoneInfo +from decimal import Decimal, InvalidOperation +from pathlib import Path +from email.message import EmailMessage +from dateutil.relativedelta import relativedelta + +from io import BytesIO, StringIO +import csv +import json +import hmac +import hashlib +import base64 +import urllib.request +import urllib.error +import urllib.parse +import uuid +import re +import math +import zipfile +import smtplib +import secrets +import threading +import time +from reportlab.lib.pagesizes import letter +from reportlab.pdfgen import canvas +from reportlab.lib.utils import ImageReader +from werkzeug.security import generate_password_hash, check_password_hash +from health import register_health_routes + +app = Flask( + __name__, + template_folder="../templates", + static_folder="../static", +) +app.config["OTB_HEALTH_DB_CONNECTOR"] = get_db_connection + +LOCAL_TZ = ZoneInfo("America/Toronto") + +BASE_DIR = Path(__file__).resolve().parent.parent + +app.secret_key = os.getenv("OTB_BILLING_SECRET_KEY", "otb-billing-dev-secret-change-me") +SQUARE_ACCESS_TOKEN = os.getenv("SQUARE_ACCESS_TOKEN", "") +SQUARE_WEBHOOK_SIGNATURE_KEY = os.getenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "") +SQUARE_WEBHOOK_NOTIFICATION_URL = os.getenv("SQUARE_WEBHOOK_NOTIFICATION_URL", "") +SQUARE_API_BASE = "https://connect.squareup.com" +SQUARE_API_VERSION = "2026-01-22" +SQUARE_WEBHOOK_LOG = str(BASE_DIR / "logs" / "square_webhook_events.log") +ORACLE_BASE_URL = os.getenv("ORACLE_BASE_URL", "https://monitor.outsidethebox.top") +CRYPTO_EVM_PAYMENT_ADDRESS = os.getenv("OTB_BILLING_CRYPTO_EVM_ADDRESS", "0x44f6c44C42e6ae0392E7289F032384C0d37F56D5") +RPC_ETHEREUM_URL = os.getenv("OTB_BILLING_RPC_ETHEREUM", "https://ethereum-rpc.publicnode.com") +RPC_ETHEREUM_URL_2 = os.getenv("OTB_BILLING_RPC_ETHEREUM_2", "https://rpc.ankr.com/eth") +RPC_ETHEREUM_URL_3 = os.getenv("OTB_BILLING_RPC_ETHEREUM_3", "https://eth.drpc.org") + +RPC_ARBITRUM_URL = os.getenv("OTB_BILLING_RPC_ARBITRUM", "https://arbitrum-one-rpc.publicnode.com") +RPC_ARBITRUM_URL_2 = os.getenv("OTB_BILLING_RPC_ARBITRUM_2", "https://rpc.ankr.com/arbitrum") +RPC_ARBITRUM_URL_3 = os.getenv("OTB_BILLING_RPC_ARBITRUM_3", "https://arb1.arbitrum.io/rpc") + +RPC_ETICA_URL = os.getenv("OTB_BILLING_RPC_ETICA", "https://rpc.etica-stats.org") +RPC_ETICA_URL_2 = os.getenv("OTB_BILLING_RPC_ETICA_2", "https://eticamainnet.eticaprotocol.org") +RPC_ETHO_URL = os.getenv("OTB_BILLING_RPC_ETHO", "https://rpc.ethoprotocol.com") +RPC_ETHO_URL_2 = os.getenv("OTB_BILLING_RPC_ETHO_2", "https://rpc4.ethoprotocol.com") + +CRYPTO_PROCESSING_TIMEOUT_SECONDS = int(os.getenv("OTB_BILLING_CRYPTO_PROCESSING_TIMEOUT_SECONDS", "180")) +CRYPTO_WATCH_INTERVAL_SECONDS = int(os.getenv("OTB_BILLING_CRYPTO_WATCH_INTERVAL_SECONDS", "30")) +CRYPTO_WATCHER_STARTED = False + + + + +def load_version(): + try: + with open(BASE_DIR / "VERSION", "r") as f: + return f.read().strip() + except Exception: + return "unknown" + +APP_VERSION = load_version() + +@app.context_processor +def inject_version(): + return {"app_version": APP_VERSION} + +@app.context_processor +def inject_app_settings(): + return {"app_settings": get_app_settings()} + +def fmt_local(dt_value): + if not dt_value: + return "" + if isinstance(dt_value, str): + try: + dt_value = datetime.fromisoformat(dt_value) + except ValueError: + return str(dt_value) + if dt_value.tzinfo is None: + dt_value = dt_value.replace(tzinfo=timezone.utc) + return dt_value.astimezone(LOCAL_TZ).strftime("%Y-%m-%d %I:%M:%S %p") + +def to_decimal(value): + if value is None or value == "": + return Decimal("0") + try: + return Decimal(str(value)) + except (InvalidOperation, ValueError): + return Decimal("0") + +def fmt_money(value, currency_code="CAD"): + amount = to_decimal(value) + if currency_code == "CAD": + return f"{amount:.2f}" + return f"{amount:.8f}" + +def payment_method_label(method, currency=None): + method_key = str(method or "").strip().lower() + currency_key = str(currency or "").strip().upper() + + if method_key == "square": + return "Square" + if method_key == "etransfer": + return "e-Transfer" + if method_key == "cash": + return "Cash" + if method_key == "other": + if currency_key in {"ETH", "ETHO", "ETI", "USDC", "EGAZ", "ALT", "CAD"}: + return currency_key + return "Other" + if method_key == "crypto_etho": + return "ETHO" + if method_key == "crypto_egaz": + return "EGAZ" + if method_key == "crypto_alt": + return "ALT" + + if currency_key in {"ETH", "ETHO", "ETI", "USDC", "EGAZ", "ALT"}: + return currency_key + + return method or "Unknown" + +def get_invoice_payments(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + confirmations, + confirmation_required, + received_at, + created_at, + notes + FROM payments + WHERE invoice_id = %s + ORDER BY COALESCE(received_at, created_at) ASC, id ASC + """, (invoice_id,)) + rows = cursor.fetchall() + conn.close() + + out = [] + for row in rows: + item = dict(row) + item["payment_method_label"] = payment_method_label( + item.get("payment_method"), + item.get("payment_currency"), + ) + item["payment_amount_display"] = fmt_money( + item.get("payment_amount"), + item.get("payment_currency") or "CAD", + ) + item["cad_value_display"] = fmt_money(item.get("cad_value_at_payment"), "CAD") + item["received_at_local"] = fmt_local(item.get("received_at") or item.get("created_at")) + out.append(item) + return out + +def normalize_oracle_datetime(value): + if not value: + return None + try: + text = str(value).replace("Z", "+00:00") + dt = datetime.fromisoformat(text) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + return None + +def ensure_invoice_quote_columns(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT COLUMN_NAME + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'invoices' + """) + existing = {row["COLUMN_NAME"] for row in cursor.fetchall()} + + wanted = { + "quote_fiat_amount": "ALTER TABLE invoices ADD COLUMN quote_fiat_amount DECIMAL(18,8) DEFAULT NULL AFTER status", + "quote_fiat_currency": "ALTER TABLE invoices ADD COLUMN quote_fiat_currency VARCHAR(16) DEFAULT NULL AFTER quote_fiat_amount", + "quote_expires_at": "ALTER TABLE invoices ADD COLUMN quote_expires_at DATETIME DEFAULT NULL AFTER quote_fiat_currency", + "oracle_snapshot": "ALTER TABLE invoices ADD COLUMN oracle_snapshot LONGTEXT DEFAULT NULL AFTER quote_expires_at" + } + + exec_cursor = conn.cursor() + changed = False + for column_name, ddl in wanted.items(): + if column_name not in existing: + exec_cursor.execute(ddl) + changed = True + + if changed: + conn.commit() + conn.close() + +def fetch_oracle_quote_snapshot(currency_code, total_amount): + if str(currency_code or "").upper() != "CAD": + return None + + try: + amount_value = Decimal(str(total_amount)) + if amount_value <= 0: + return None + except (InvalidOperation, ValueError): + return None + + try: + qs = urllib.parse.urlencode({ + "fiat": "CAD", + "amount": format(amount_value, "f"), + }) + req = urllib.request.Request( + f"{ORACLE_BASE_URL.rstrip('/')}/api/oracle/quote?{qs}", + headers={ + "Accept": "application/json", + "User-Agent": "otb-billing-oracle/0.1" + }, + method="GET" + ) + with urllib.request.urlopen(req, timeout=15) as resp: + data = json.loads(resp.read().decode("utf-8")) + + if not isinstance(data, dict) or not isinstance(data.get("quotes"), list): + return None + + return { + "oracle_url": ORACLE_BASE_URL.rstrip("/"), + "quoted_at": data.get("quoted_at"), + "expires_at": data.get("expires_at"), + "ttl_seconds": data.get("ttl_seconds"), + "source_status": data.get("source_status"), + "fiat": data.get("fiat") or "CAD", + "amount": format(amount_value, "f"), + "quotes": data.get("quotes", []), + } + except Exception: + return None + +def get_invoice_crypto_options(invoice): + oracle_quote = invoice.get("oracle_quote") or {} + raw_quotes = oracle_quote.get("quotes") or [] + + option_map = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "label": "USDC (Arbitrum)", + "payment_currency": "USDC", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "token", + "chain_id": 42161, + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "label": "ETH (Ethereum)", + "payment_currency": "ETH", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "native", + "chain_id": 1, + "decimals": 18, + "token_contract": None, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "label": "ETHO (Etho)", + "payment_currency": "ETHO", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "native", + "chain_id": 1313114, + "decimals": 18, + "token_contract": None, + "rpc_urls": [RPC_ETHO_URL, RPC_ETHO_URL_2], + "chain_add_params": { + "chainId": "0x14095a", + "chainName": "Etho Protocol", + "nativeCurrency": { + "name": "Etho Protocol", + "symbol": "ETHO", + "decimals": 18 + }, + "rpcUrls": [RPC_ETHO_URL, RPC_ETHO_URL_2], + "blockExplorerUrls": ["https://explorer.ethoprotocol.com"] + }, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "label": "ETI (Etica)", + "payment_currency": "ETI", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "token", + "chain_id": 61803, + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "rpc_urls": [RPC_ETICA_URL, RPC_ETICA_URL_2], + "chain_add_params": { + "chainId": "0xf16b", + "chainName": "Etica", + "nativeCurrency": { + "name": "Etica Gas", + "symbol": "EGAZ", + "decimals": 18 + }, + "rpcUrls": [RPC_ETICA_URL, RPC_ETICA_URL_2], + "blockExplorerUrls": ["https://explorer.etica-stats.org"] + }, + }, + } + + options = [] + for q in raw_quotes: + symbol = str(q.get("symbol") or "").upper() + if symbol not in option_map: + continue + if not q.get("display_amount"): + continue + + opt = dict(option_map[symbol]) + opt["display_amount"] = q.get("display_amount") + opt["crypto_amount"] = q.get("crypto_amount") + opt["price_cad"] = q.get("price_cad") + opt["recommended"] = bool(q.get("recommended")) + opt["available"] = bool(q.get("available")) + opt["reason"] = q.get("reason") + options.append(opt) + + options.sort(key=lambda x: (0 if x.get("recommended") else 1, x.get("symbol"))) + return options + +def get_rpc_urls_for_chain(chain_name): + chain = str(chain_name or "").lower() + if chain == "ethereum": + return [u for u in [RPC_ETHEREUM_URL, RPC_ETHEREUM_URL_2, RPC_ETHEREUM_URL_3] if u] + if chain == "arbitrum": + return [u for u in [RPC_ARBITRUM_URL, RPC_ARBITRUM_URL_2, RPC_ARBITRUM_URL_3] if u] + if chain == "etica": + return [u for u in [RPC_ETICA_URL, RPC_ETICA_URL_2] if u] + if chain == "etho": + return [u for u in [RPC_ETHO_URL, RPC_ETHO_URL_2] if u] + return [] + +def rpc_call_any(rpc_urls, method, params): + last_error = None + + for rpc_url in rpc_urls: + try: + payload = json.dumps({ + "jsonrpc": "2.0", + "id": 1, + "method": method, + "params": params, + }).encode("utf-8") + + req = urllib.request.Request( + rpc_url, + data=payload, + headers={ + "Content-Type": "application/json", + "Accept": "application/json", + "User-Agent": "otb-billing-rpc/0.1", + }, + method="POST" + ) + + with urllib.request.urlopen(req, timeout=20) as resp: + data = json.loads(resp.read().decode("utf-8")) + + if isinstance(data, dict) and data.get("error"): + raise RuntimeError(str(data["error"])) + + return { + "rpc_url": rpc_url, + "result": (data or {}).get("result"), + } + except Exception as err: + last_error = err + + if last_error: + raise last_error + raise RuntimeError("No RPC URLs configured") + + +def append_payment_note(existing_notes, extra_line): + base = (existing_notes or "").rstrip() + if not base: + return extra_line.strip() + return base + "\n" + extra_line.strip() + +def _hex_to_int(value): + if value is None: + return 0 + text = str(value).strip() + if not text: + return 0 + if text.startswith("0x"): + return int(text, 16) + return int(text) + +def fetch_rpc_balance(chain_name, wallet_address): + rpc_urls = get_rpc_urls_for_chain(chain_name) + if not rpc_urls or not wallet_address: + return None + try: + resp = rpc_call_any(rpc_urls, "eth_getBalance", [wallet_address, "latest"]) + result = (resp or {}).get("result") + if result is None: + return None + return { + "rpc_url": resp.get("rpc_url"), + "balance_wei": _hex_to_int(result), + } + except Exception: + return None + +def verify_expected_tx_for_payment(option, tx): + if not option or not tx: + raise RuntimeError("missing transaction data") + + wallet_to = str(option.get("wallet_address") or "").lower() + expected_units = _to_base_units(option.get("display_amount"), option.get("decimals") or 18) + + if option.get("asset_type") == "native": + tx_to = str(tx.get("to") or "").lower() + tx_value = _hex_to_int(tx.get("value") or "0x0") + + if tx_to != wallet_to: + raise RuntimeError("transaction destination does not match payment wallet") + if tx_value != expected_units: + raise RuntimeError("transaction value does not match frozen quote amount") + + return True + + tx_to = str(tx.get("to") or "").lower() + contract = str(option.get("token_contract") or "").lower() + if tx_to != contract: + raise RuntimeError("token contract does not match expected asset contract") + + parsed = parse_erc20_transfer_input(tx.get("input") or "") + if not parsed: + raise RuntimeError("transaction input is not a supported ERC20 transfer") + + if str(parsed["to"]).lower() != wallet_to: + raise RuntimeError("token transfer recipient does not match payment wallet") + + if int(parsed["amount"]) != expected_units: + raise RuntimeError("token transfer amount does not match frozen quote amount") + + return True + +def get_processing_crypto_option(payment_row): + currency = str(payment_row.get("payment_currency") or "").upper() + amount_text = str(payment_row.get("payment_amount") or "0") + wallet_address = payment_row.get("wallet_address") or CRYPTO_EVM_PAYMENT_ADDRESS + + mapping = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + "display_amount": amount_text, + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "display_amount": amount_text, + }, + } + return mapping.get(currency) + +def reconcile_pending_crypto_payment(payment_row): + tx_hash = str(payment_row.get("txid") or "").strip() + if not tx_hash or not tx_hash.startswith("0x"): + return {"state": "no_tx_hash"} + + option = get_processing_crypto_option(payment_row) + if not option: + return {"state": "unsupported_currency"} + + created_dt = payment_row.get("updated_at") or payment_row.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + if not created_dt: + created_dt = datetime.now(timezone.utc) + + age_seconds = max(0, int((datetime.now(timezone.utc) - created_dt).total_seconds())) + rpc_urls = get_rpc_urls_for_chain(option.get("chain")) + if not rpc_urls: + return {"state": "no_rpc"} + + tx_hit = None + receipt_hit = None + tx_rpc = None + receipt_rpc = None + + for rpc_url in rpc_urls: + try: + tx_resp = rpc_call_any([rpc_url], "eth_getTransactionByHash", [tx_hash]) + tx_obj = tx_resp.get("result") + if tx_obj: + verify_expected_tx_for_payment(option, tx_obj) + tx_hit = tx_obj + tx_rpc = tx_resp.get("rpc_url") + break + except Exception: + continue + + if tx_hit: + for rpc_url in rpc_urls: + try: + receipt_resp = rpc_call_any([rpc_url], "eth_getTransactionReceipt", [tx_hash]) + receipt_obj = receipt_resp.get("result") + if receipt_obj: + receipt_hit = receipt_obj + receipt_rpc = receipt_resp.get("rpc_url") + break + except Exception: + continue + + balance_info = fetch_rpc_balance(option.get("chain"), option.get("wallet_address")) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, invoice_id, notes, payment_status + FROM payments + WHERE id = %s + LIMIT 1 + """, (payment_row["id"],)) + live_payment = cursor.fetchone() + + if not live_payment: + conn.close() + return {"state": "payment_missing"} + + notes = live_payment.get("notes") or "" + + if tx_hit and receipt_hit: + receipt_status = _hex_to_int(receipt_hit.get("status") or "0x0") + confirmations = 0 + block_number = receipt_hit.get("blockNumber") + if block_number: + try: + bn = _hex_to_int(block_number) + latest_resp = rpc_call_any(rpc_urls, "eth_blockNumber", []) + latest_bn = _hex_to_int((latest_resp or {}).get("result") or "0x0") + if latest_bn >= bn: + confirmations = (latest_bn - bn) + 1 + except Exception: + confirmations = 1 + + if receipt_status == 1: + notes = append_payment_note(notes, f"[reconcile] confirmed tx {tx_hash} via {receipt_rpc or tx_rpc or 'rpc'}") + if balance_info: + notes = append_payment_note(notes, f"[reconcile] wallet balance seen on {balance_info.get('rpc_url')}: {balance_info.get('balance_wei')} wei") + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'confirmed', + confirmations = %s, + confirmation_required = 1, + received_at = COALESCE(received_at, UTC_TIMESTAMP()), + notes = %s + WHERE id = %s + """, ( + confirmations or 1, + notes, + payment_row["id"] + )) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "confirmed", "confirmations": confirmations or 1} + + notes = append_payment_note(notes, f"[reconcile] receipt status failed for tx {tx_hash}") + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "failed_receipt"} + + if age_seconds <= CRYPTO_PROCESSING_TIMEOUT_SECONDS: + notes_line = f"[reconcile] waiting for tx/receipt age={age_seconds}s" + if balance_info: + notes_line += f" wallet_balance_wei={balance_info.get('balance_wei')}" + if notes_line not in notes: + notes = append_payment_note(notes, notes_line) + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + return {"state": "processing", "age_seconds": age_seconds} + + fail_line = f"[reconcile] timeout after {age_seconds}s without confirmed receipt for tx {tx_hash}" + if balance_info: + fail_line += f" wallet_balance_wei={balance_info.get('balance_wei')}" + notes = append_payment_note(notes, fail_line) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "timeout", "age_seconds": age_seconds} + +def _to_base_units(amount_text, decimals): + amount_dec = Decimal(str(amount_text)) + scale = Decimal(10) ** int(decimals) + return int((amount_dec * scale).quantize(Decimal("1"))) + +def _strip_0x(value): + return str(value or "").lower().replace("0x", "") + +def parse_erc20_transfer_input(input_data): + data = _strip_0x(input_data) + if not data.startswith("a9059cbb"): + return None + if len(data) < 8 + 64 + 64: + return None + to_chunk = data[8:72] + amount_chunk = data[72:136] + to_addr = "0x" + to_chunk[-40:] + amount_int = int(amount_chunk, 16) + return { + "to": to_addr, + "amount": amount_int, + } + +def verify_wallet_transaction(option, tx_hash): + rpc_urls = get_rpc_urls_for_chain(option.get("chain")) + if not rpc_urls: + raise RuntimeError("No RPC configured for chain") + + seen_result = None + last_not_found = False + + for rpc_url in rpc_urls: + try: + rpc_resp = rpc_call_any([rpc_url], "eth_getTransactionByHash", [tx_hash]) + tx = rpc_resp.get("result") + if not tx: + last_not_found = True + continue + + wallet_to = str(option.get("wallet_address") or "").lower() + expected_units = _to_base_units(option.get("display_amount"), option.get("decimals") or 18) + + if option.get("asset_type") == "native": + tx_to = str(tx.get("to") or "").lower() + tx_value = int(tx.get("value") or "0x0", 16) + if tx_to != wallet_to: + raise RuntimeError("Transaction destination does not match payment wallet") + if tx_value != expected_units: + raise RuntimeError("Transaction value does not match frozen quote amount") + else: + tx_to = str(tx.get("to") or "").lower() + contract = str(option.get("token_contract") or "").lower() + if tx_to != contract: + raise RuntimeError("Token contract does not match expected asset contract") + parsed = parse_erc20_transfer_input(tx.get("input") or "") + if not parsed: + raise RuntimeError("Transaction input is not a supported ERC20 transfer") + if str(parsed["to"]).lower() != wallet_to: + raise RuntimeError("Token transfer recipient does not match payment wallet") + if int(parsed["amount"]) != expected_units: + raise RuntimeError("Token transfer amount does not match frozen quote amount") + + seen_result = { + "rpc_url": rpc_url, + "tx": tx, + } + break + except Exception: + continue + + if not seen_result: + if last_not_found: + raise RuntimeError("Transaction hash not found on any configured RPC") + raise RuntimeError("Unable to verify transaction on configured RPC pool") + + return seen_result + + +def get_processing_crypto_option(payment_row): + currency = str(payment_row.get("payment_currency") or "").upper() + amount_text = str(payment_row.get("payment_amount") or "0") + wallet_address = payment_row.get("wallet_address") or CRYPTO_EVM_PAYMENT_ADDRESS + + mapping = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + "display_amount": amount_text, + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "display_amount": amount_text, + }, + } + + return mapping.get(currency) + +def append_payment_note(existing_notes, extra_line): + base = (existing_notes or "").rstrip() + if not base: + return extra_line.strip() + return base + "\n" + extra_line.strip() + +def mark_crypto_payment_failed(payment_id, reason): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT invoice_id, notes + FROM payments + WHERE id = %s + LIMIT 1 + """, (payment_id,)) + row = cursor.fetchone() + + if not row: + conn.close() + return + + new_notes = append_payment_note( + row.get("notes"), + f"[crypto watcher] failed: {reason}" + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (new_notes, payment_id)) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(row["invoice_id"]) + except Exception: + pass + +def mark_crypto_payment_confirmed(payment_id, invoice_id, rpc_url): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT p.*, i.client_id AS invoice_client_id, i.invoice_number, + i.total_amount, i.amount_paid, i.status AS invoice_status, + c.email AS client_email, c.company_name, c.contact_name + FROM payments p + JOIN invoices i ON i.id = p.invoice_id + LEFT JOIN clients c ON c.id = i.client_id + WHERE p.id = %s + LIMIT 1 + """, (payment_id,)) + row = cursor.fetchone() + + if not row: + conn.close() + return + + if str(row.get("payment_status") or "").lower() == "confirmed": + conn.close() + return + + new_notes = append_payment_note( + row.get("notes"), + "[crypto watcher] confirmed via %s txid=%s" % (rpc_url, row.get("txid") or "") + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'confirmed', + confirmations = COALESCE(confirmations, 1), + confirmation_required = COALESCE(confirmation_required, 1), + received_at = COALESCE(received_at, UTC_TIMESTAMP()), + notes = %s + WHERE id = %s + """, (new_notes, payment_id)) + conn.commit() + + try: + recalc_invoice_totals(invoice_id) + except Exception: + pass + + refresh_cursor = conn.cursor(dictionary=True) + refresh_cursor.execute(""" + SELECT id, client_id, invoice_number, total_amount, amount_paid, status + FROM invoices + WHERE id = %s + LIMIT 1 + """, (invoice_id,)) + invoice = refresh_cursor.fetchone() or {} + + try: + from decimal import Decimal + total_dec = Decimal(str(invoice.get("total_amount") or "0")) + paid_dec = Decimal(str(invoice.get("amount_paid") or "0")) + + overpayment_dec = paid_dec - total_dec + if overpayment_dec > Decimal("0"): + credit_note = "Overpayment from invoice %s (crypto payment_id=%s)" % ( + invoice.get("invoice_number") or invoice_id, + payment_id + ) + + check_cursor = conn.cursor(dictionary=True) + check_cursor.execute(""" + SELECT id FROM credit_ledger + WHERE client_id = %s AND notes = %s + LIMIT 1 + """, (invoice.get("client_id"), credit_note)) + + if not check_cursor.fetchone(): + credit_cursor = conn.cursor() + credit_cursor.execute(""" + INSERT INTO credit_ledger + (client_id, entry_type, amount, currency_code, notes) + VALUES (%s, %s, %s, %s, %s) + """, ( + invoice.get("client_id"), + "credit", + str(overpayment_dec), + "CAD", + credit_note + )) + conn.commit() + except Exception: + pass + + try: + if str(invoice.get("status") or "").lower() == "paid": + recipient = (row.get("client_email") or "").strip() + if recipient: + subject = "Invoice %s Paid (Crypto)" % (invoice.get("invoice_number") or invoice_id) + + body = "Your payment has been received and confirmed.\n\n" + body += "Invoice: %s\n" % (invoice.get("invoice_number") or invoice_id) + body += "Amount: %s %s\n" % (row.get("payment_amount"), row.get("payment_currency")) + body += "TXID: %s\n\n" % (row.get("txid") or "") + body += "Thank you for your business.\n" + + send_configured_email( + to_email=recipient, + subject=subject, + body=body, + attachments=None, + email_type="invoice_paid_crypto", + invoice_id=invoice_id + ) + except Exception: + pass + + conn.close() +def watch_pending_crypto_payments_once(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + invoice_id, + client_id, + payment_currency, + payment_amount, + cad_value_at_payment, + wallet_address, + txid, + payment_status, + created_at, + updated_at, + notes + FROM payments + WHERE payment_status = 'pending' + AND txid IS NOT NULL + AND txid <> '' + AND notes LIKE '%%portal_crypto_intent:%%' + ORDER BY id ASC + """) + pending_rows = cursor.fetchall() + conn.close() + + now_utc = datetime.now(timezone.utc) + + for row in pending_rows: + option = get_processing_crypto_option(row) + if not option: + continue + + submitted_at = row.get("updated_at") or row.get("created_at") + if submitted_at and submitted_at.tzinfo is None: + submitted_at = submitted_at.replace(tzinfo=timezone.utc) + + if not submitted_at: + submitted_at = now_utc + + age_seconds = (now_utc - submitted_at).total_seconds() + + if age_seconds > CRYPTO_PROCESSING_TIMEOUT_SECONDS: + mark_crypto_payment_failed(row["id"], "processing timeout exceeded") + continue + + try: + verified = verify_wallet_transaction(option, str(row.get("txid") or "").strip()) + mark_crypto_payment_confirmed(row["id"], row["invoice_id"], verified.get("rpc_url") or "rpc") + except Exception as err: + msg = str(err or "") + lower = msg.lower() + retryable = ( + "not found on any configured rpc" in lower + or "not found on rpc" in lower + or "unable to verify transaction on configured rpc pool" in lower + ) + if retryable: + continue + # non-retryable verification problems get marked failed immediately + mark_crypto_payment_failed(row["id"], msg) + +def crypto_payment_watcher_loop(): + while True: + try: + watch_pending_crypto_payments_once() + except Exception as err: + try: + print(f"[crypto-watcher] {err}") + except Exception: + pass + time.sleep(max(5, CRYPTO_WATCH_INTERVAL_SECONDS)) + +def start_crypto_payment_watcher(): + global CRYPTO_WATCHER_STARTED + if CRYPTO_WATCHER_STARTED: + return + + t = threading.Thread( + target=crypto_payment_watcher_loop, + name="crypto-payment-watcher", + daemon=True, + ) + t.start() + CRYPTO_WATCHER_STARTED = True + +def square_amount_to_cents(value): + return int((to_decimal(value) * 100).quantize(Decimal("1"))) + +def create_square_payment_link_for_invoice(invoice_row, buyer_email=""): + if not SQUARE_ACCESS_TOKEN: + raise RuntimeError("Square access token is not configured") + + invoice_number = invoice_row.get("invoice_number") or f"INV-{invoice_row.get('id')}" + currency_code = invoice_row.get("currency_code") or "CAD" + amount_cents = square_amount_to_cents(invoice_row.get("total_amount") or "0") + location_id = "1TSPHT78106WX" + + payload = { + "idempotency_key": str(uuid.uuid4()), + "description": f"OTB Billing invoice {invoice_number}", + "quick_pay": { + "name": f"Invoice {invoice_number}", + "price_money": { + "amount": amount_cents, + "currency": currency_code + }, + "location_id": location_id + }, + "payment_note": f"Invoice {invoice_number}", + "checkout_options": { + "redirect_url": "https://portal.outsidethebox.top/portal" + } + } + + if buyer_email: + payload["pre_populated_data"] = { + "buyer_email": buyer_email + } + + req = urllib.request.Request( + f"{SQUARE_API_BASE}/v2/online-checkout/payment-links", + data=json.dumps(payload).encode("utf-8"), + headers={ + "Authorization": f"Bearer {SQUARE_ACCESS_TOKEN}", + "Square-Version": SQUARE_API_VERSION, + "Content-Type": "application/json" + }, + method="POST" + ) + + try: + with urllib.request.urlopen(req, timeout=30) as resp: + data = json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + raise RuntimeError(f"Square payment link creation failed: {e.code} {body}") + + payment_link = (data or {}).get("payment_link") or {} + url = payment_link.get("url") + if not url: + raise RuntimeError(f"Square payment link response missing URL: {data}") + + return url + + +def square_signature_is_valid(signature_header, raw_body, notification_url): + if not SQUARE_WEBHOOK_SIGNATURE_KEY or not signature_header: + return False + message = notification_url.encode("utf-8") + raw_body + digest = hmac.new( + SQUARE_WEBHOOK_SIGNATURE_KEY.encode("utf-8"), + message, + hashlib.sha256 + ).digest() + computed_signature = base64.b64encode(digest).decode("utf-8") + return hmac.compare_digest(computed_signature, signature_header) + +def append_square_webhook_log(entry): + try: + log_path = Path(SQUARE_WEBHOOK_LOG) + log_path.parent.mkdir(parents=True, exist_ok=True) + with log_path.open("a", encoding="utf-8") as f: + f.write(json.dumps(entry, ensure_ascii=False) + "\n") + except Exception: + pass + +def generate_portal_access_code(): + alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" + groups = [] + for _ in range(3): + groups.append("".join(secrets.choice(alphabet) for _ in range(4))) + return "-".join(groups) + +def refresh_overdue_invoices(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE invoices + SET status = 'overdue' + WHERE due_at IS NOT NULL + AND due_at < UTC_TIMESTAMP() + AND status IN ('pending', 'partial') + """) + conn.commit() + conn.close() + +def recalc_invoice_totals(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, total_amount, due_at, status + FROM invoices + WHERE id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return + + invoice_currency = str(invoice.get("currency_code") or "CAD").upper() + + if invoice_currency == "CAD": + cursor.execute(""" + SELECT COALESCE(SUM( + CASE + WHEN UPPER(COALESCE(payment_currency, '')) = 'CAD' + THEN payment_amount + ELSE COALESCE(cad_value_at_payment, 0) + END + ), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_id,)) + else: + cursor.execute(""" + SELECT COALESCE(SUM( + CASE + WHEN UPPER(COALESCE(payment_currency, '')) = %s + THEN payment_amount + ELSE 0 + END + ), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_currency, invoice_id)) + + row = cursor.fetchone() + + total_paid = to_decimal(row["total_paid"]) + total_amount = to_decimal(invoice["total_amount"]) + + if invoice["status"] == "cancelled": + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET amount_paid = %s, + paid_at = NULL + WHERE id = %s + """, ( + str(total_paid), + invoice_id + )) + conn.commit() + conn.close() + return + + if total_paid >= total_amount and total_amount > 0: + new_status = "paid" + paid_at_value = "UTC_TIMESTAMP()" + elif total_paid > 0: + new_status = "partial" + paid_at_value = "NULL" + else: + if invoice["due_at"] and invoice["due_at"] < datetime.utcnow(): + new_status = "overdue" + else: + new_status = "pending" + paid_at_value = "NULL" + + update_cursor = conn.cursor() + update_cursor.execute(f""" + UPDATE invoices + SET amount_paid = %s, + status = %s, + paid_at = {paid_at_value} + WHERE id = %s + """, ( + str(total_paid), + new_status, + invoice_id + )) + + conn.commit() + conn.close() + +def get_client_credit_balance(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT COALESCE(SUM(amount), 0) AS balance + FROM credit_ledger + WHERE client_id = %s + """, (client_id,)) + row = cursor.fetchone() + conn.close() + return to_decimal(row["balance"]) + + +def generate_invoice_number(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT invoice_number + FROM invoices + WHERE invoice_number IS NOT NULL + AND invoice_number LIKE 'INV-%' + ORDER BY id DESC + LIMIT 1 + """) + row = cursor.fetchone() + conn.close() + + if not row or not row.get("invoice_number"): + return "INV-0001" + + invoice_number = str(row["invoice_number"]).strip() + + try: + number = int(invoice_number.split("-")[1]) + except (IndexError, ValueError): + return "INV-0001" + + return f"INV-{number + 1:04d}" + + +def ensure_subscriptions_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS subscriptions ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + client_id INT UNSIGNED NOT NULL, + service_id INT UNSIGNED NULL, + subscription_name VARCHAR(255) NOT NULL, + billing_interval ENUM('monthly','quarterly','yearly') NOT NULL DEFAULT 'monthly', + price DECIMAL(18,8) NOT NULL DEFAULT 0.00000000, + currency_code VARCHAR(16) NOT NULL DEFAULT 'CAD', + start_date DATE NOT NULL, + next_invoice_date DATE NOT NULL, + status ENUM('active','paused','cancelled') NOT NULL DEFAULT 'active', + notes TEXT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + KEY idx_subscriptions_client_id (client_id), + KEY idx_subscriptions_service_id (service_id), + KEY idx_subscriptions_status (status), + KEY idx_subscriptions_next_invoice_date (next_invoice_date) + ) + """) + conn.commit() + conn.close() + + +def get_next_subscription_date(current_date, billing_interval): + if isinstance(current_date, str): + current_date = datetime.strptime(current_date, "%Y-%m-%d").date() + + if billing_interval == "yearly": + return current_date + relativedelta(years=1) + if billing_interval == "quarterly": + return current_date + relativedelta(months=3) + return current_date + relativedelta(months=1) + + +def generate_due_subscription_invoices(run_date=None): + ensure_subscriptions_table() + + today = run_date or date.today() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + s.*, + c.client_code, + c.company_name, + srv.service_code, + srv.service_name + FROM subscriptions s + JOIN clients c ON s.client_id = c.id + LEFT JOIN services srv ON s.service_id = srv.id + WHERE s.status = 'active' + AND s.next_invoice_date <= %s + ORDER BY s.next_invoice_date ASC, s.id ASC + """, (today,)) + due_subscriptions = cursor.fetchall() + + created_count = 0 + created_invoice_numbers = [] + + for sub in due_subscriptions: + invoice_number = generate_invoice_number() + due_dt = datetime.combine(today + timedelta(days=14), datetime.min.time()) + + note_parts = [f"Recurring subscription: {sub['subscription_name']}"] + if sub.get("service_code"): + note_parts.append(f"Service: {sub['service_code']}") + if sub.get("service_name"): + note_parts.append(f"({sub['service_name']})") + if sub.get("notes"): + note_parts.append(f"Notes: {sub['notes']}") + + note_text = " ".join(note_parts) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO invoices + ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + subtotal_amount, + tax_amount, + issued_at, + due_at, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, 0, UTC_TIMESTAMP(), %s, 'pending', %s) + """, ( + sub["client_id"], + sub["service_id"], + invoice_number, + sub["currency_code"], + str(sub["price"]), + str(sub["price"]), + due_dt, + note_text, + )) + + next_date = get_next_subscription_date(sub["next_invoice_date"], sub["billing_interval"]) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE subscriptions + SET next_invoice_date = %s + WHERE id = %s + """, (next_date, sub["id"])) + + created_count += 1 + created_invoice_numbers.append(invoice_number) + + conn.commit() + conn.close() + + return { + "created_count": created_count, + "invoice_numbers": created_invoice_numbers, + "run_date": str(today), + } + + +APP_SETTINGS_DEFAULTS = { + "business_name": "OTB Billing", + "business_tagline": "By a contractor, for contractors", + "business_logo_url": "", + "business_email": "", + "business_phone": "", + "business_address": "", + "business_website": "", + "tax_label": "HST", + "tax_rate": "13.00", + "tax_number": "", + "business_number": "", + "default_currency": "CAD", + "report_frequency": "monthly", + "invoice_footer": "", + "payment_terms": "", + "local_country": "Canada", + "apply_local_tax_only": "1", + "smtp_host": "", + "smtp_port": "587", + "smtp_user": "", + "smtp_pass": "", + "smtp_from_email": "", + "smtp_from_name": "", + "smtp_use_tls": "1", + "smtp_use_ssl": "0", + "report_delivery_email": "", +} + +def ensure_app_settings_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS app_settings ( + setting_key VARCHAR(100) NOT NULL PRIMARY KEY, + setting_value TEXT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + ) + """) + conn.commit() + conn.close() + +def get_app_settings(): + ensure_app_settings_table() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT setting_key, setting_value + FROM app_settings + """) + rows = cursor.fetchall() + conn.close() + + settings = dict(APP_SETTINGS_DEFAULTS) + for row in rows: + settings[row["setting_key"]] = row["setting_value"] if row["setting_value"] is not None else "" + + return settings + +def save_app_settings(form_data): + ensure_app_settings_table() + conn = get_db_connection() + cursor = conn.cursor() + + for key in APP_SETTINGS_DEFAULTS.keys(): + if key in {"apply_local_tax_only", "smtp_use_tls", "smtp_use_ssl"}: + value = "1" if form_data.get(key) else "0" + else: + value = (form_data.get(key) or "").strip() + + cursor.execute(""" + INSERT INTO app_settings (setting_key, setting_value) + VALUES (%s, %s) + ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value) + """, (key, value)) + + conn.commit() + conn.close() + + +@app.template_filter("localtime") +def localtime_filter(value): + return fmt_local(value) + +@app.template_filter("money") +def money_filter(value, currency_code="CAD"): + return fmt_money(value, currency_code) + + + + +def get_report_period_bounds(frequency): + now_local = datetime.now(LOCAL_TZ) + + if frequency == "yearly": + start_local = now_local.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) + label = f"{now_local.year}" + elif frequency == "quarterly": + quarter = ((now_local.month - 1) // 3) + 1 + start_month = (quarter - 1) * 3 + 1 + start_local = now_local.replace(month=start_month, day=1, hour=0, minute=0, second=0, microsecond=0) + label = f"Q{quarter} {now_local.year}" + else: + start_local = now_local.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + label = now_local.strftime("%B %Y") + + start_utc = start_local.astimezone(timezone.utc).replace(tzinfo=None) + end_utc = now_local.astimezone(timezone.utc).replace(tzinfo=None) + + return start_utc, end_utc, label + + + +def build_accounting_package_bytes(): + import json + import zipfile + from io import BytesIO + + report = get_revenue_report_data() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.created_at, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + ORDER BY i.created_at DESC + """) + invoices = cursor.fetchall() + + conn.close() + + payload = { + "report": report, + "invoices": invoices + } + + json_bytes = json.dumps(payload, indent=2, default=str).encode() + + zip_buffer = BytesIO() + + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("revenue_report.json", json.dumps(report, indent=2)) + z.writestr("invoices.json", json.dumps(invoices, indent=2, default=str)) + + zip_buffer.seek(0) + + filename = f"accounting_package_{report.get('period_label','report')}.zip" + + return zip_buffer.read(), filename + + + +def get_revenue_report_data(): + settings = get_app_settings() + frequency = (settings.get("report_frequency") or "monthly").strip().lower() + if frequency not in {"monthly", "quarterly", "yearly"}: + frequency = "monthly" + + start_utc, end_utc, label = get_report_period_bounds(frequency) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT COALESCE(SUM(cad_value_at_payment), 0) AS collected + FROM payments + WHERE payment_status = 'confirmed' + AND received_at >= %s + AND received_at <= %s + """, (start_utc, end_utc)) + collected_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS invoice_count, + COALESCE(SUM(total_amount), 0) AS invoiced + FROM invoices + WHERE issued_at >= %s + AND issued_at <= %s + """, (start_utc, end_utc)) + invoiced_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS overdue_count, + COALESCE(SUM(total_amount - amount_paid), 0) AS overdue_balance + FROM invoices + WHERE status = 'overdue' + """) + overdue_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS outstanding_count, + COALESCE(SUM(total_amount - amount_paid), 0) AS outstanding_balance + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + """) + outstanding_row = cursor.fetchone() + + conn.close() + + return { + "frequency": frequency, + "period_label": label, + "period_start": start_utc.isoformat(sep=" "), + "period_end": end_utc.isoformat(sep=" "), + "collected_cad": str(to_decimal(collected_row["collected"])), + "invoice_count": int(invoiced_row["invoice_count"] or 0), + "invoiced_total": str(to_decimal(invoiced_row["invoiced"])), + "overdue_count": int(overdue_row["overdue_count"] or 0), + "overdue_balance": str(to_decimal(overdue_row["overdue_balance"])), + "outstanding_count": int(outstanding_row["outstanding_count"] or 0), + "outstanding_balance": str(to_decimal(outstanding_row["outstanding_balance"])), + } + + +def ensure_email_log_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS email_log ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + email_type VARCHAR(50) NOT NULL, + invoice_id INT UNSIGNED NULL, + recipient_email VARCHAR(255) NOT NULL, + subject VARCHAR(255) NOT NULL, + status VARCHAR(20) NOT NULL, + error_message TEXT NULL, + sent_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + KEY idx_email_log_invoice_id (invoice_id), + KEY idx_email_log_type (email_type), + KEY idx_email_log_sent_at (sent_at) + ) + """) + conn.commit() + conn.close() + + +def log_email_event(email_type, recipient_email, subject, status, invoice_id=None, error_message=None): + ensure_email_log_table() + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + INSERT INTO email_log + (email_type, invoice_id, recipient_email, subject, status, error_message) + VALUES (%s, %s, %s, %s, %s, %s) + """, ( + email_type, + invoice_id, + recipient_email, + subject, + status, + error_message + )) + conn.commit() + conn.close() + + + +def send_configured_email(to_email, subject, body, attachments=None, email_type="system_email", invoice_id=None): + settings = get_app_settings() + + smtp_host = (settings.get("smtp_host") or "").strip() + smtp_port = int((settings.get("smtp_port") or "587").strip() or "587") + smtp_user = (settings.get("smtp_user") or "").strip() + smtp_pass = (settings.get("smtp_pass") or "").strip() + from_email = (settings.get("smtp_from_email") or settings.get("business_email") or "").strip() + from_name = (settings.get("smtp_from_name") or settings.get("business_name") or "").strip() + use_tls = (settings.get("smtp_use_tls") or "0") == "1" + use_ssl = (settings.get("smtp_use_ssl") or "0") == "1" + + if not smtp_host: + raise ValueError("SMTP host is not configured.") + if not from_email: + raise ValueError("From email is not configured.") + if not to_email: + raise ValueError("Recipient email is missing.") + + msg = EmailMessage() + msg["Subject"] = subject + msg["From"] = f"{from_name} <{from_email}>" if from_name else from_email + msg["To"] = to_email + msg.set_content(body) + + for attachment in attachments or []: + filename = attachment["filename"] + mime_type = attachment["mime_type"] + data = attachment["data"] + maintype, subtype = mime_type.split("/", 1) + msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=filename) + + try: + if use_ssl: + with smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=30) as server: + if smtp_user: + server.login(smtp_user, smtp_pass) + server.send_message(msg) + else: + with smtplib.SMTP(smtp_host, smtp_port, timeout=30) as server: + server.ehlo() + if use_tls: + server.starttls() + server.ehlo() + if smtp_user: + server.login(smtp_user, smtp_pass) + server.send_message(msg) + + log_email_event(email_type, to_email, subject, "sent", invoice_id=invoice_id, error_message=None) + except Exception as e: + log_email_event(email_type, to_email, subject, "failed", invoice_id=invoice_id, error_message=str(e)) + raise + +@app.route("/settings", methods=["GET", "POST"]) +def settings(): + ensure_app_settings_table() + + if request.method == "POST": + save_app_settings(request.form) + return redirect("/settings") + + settings = get_app_settings() + return render_template("settings.html", settings=settings) + + + + +@app.route("/reports/accounting-package.zip") +def accounting_package_zip(): + package_bytes, filename = build_accounting_package_bytes() + return send_file( + BytesIO(package_bytes), + mimetype="application/zip", + as_attachment=True, + download_name=filename + ) + +@app.route("/reports/revenue") +def revenue_report(): + report = get_revenue_report_data() + return render_template("reports/revenue.html", report=report) + +@app.route("/reports/revenue.json") +def revenue_report_json(): + report = get_revenue_report_data() + return jsonify(report) + +@app.route("/reports/revenue/print") +def revenue_report_print(): + report = get_revenue_report_data() + return render_template("reports/revenue_print.html", report=report) + + + +@app.route("/invoices/email/", methods=["POST"]) +def email_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return "Invoice not found", 404 + + recipient = (invoice.get("email") or "").strip() + if not recipient: + return "Client email is missing for this invoice.", 400 + + settings = get_app_settings() + + with app.test_client() as client: + pdf_response = client.get(f"/invoices/pdf/{invoice_id}") + if pdf_response.status_code != 200: + return "Could not generate invoice PDF for email.", 500 + + pdf_bytes = pdf_response.data + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + subject = f"Invoice {invoice['invoice_number']} from {settings.get('business_name') or 'OTB Billing'}" + body = ( + f"Hello {invoice.get('contact_name') or invoice.get('company_name') or ''},\n\n" + f"Please find attached invoice {invoice['invoice_number']}.\n" + f"Total: {to_decimal(invoice.get('total_amount')):.2f} {invoice.get('currency_code', 'CAD')}\n" + f"Remaining: {remaining:.2f} {invoice.get('currency_code', 'CAD')}\n" + f"Due: {fmt_local(invoice.get('due_at'))}\n\n" + f"Thank you,\n" + f"{settings.get('business_name') or 'OTB Billing'}" + ) + + try: + send_configured_email( + recipient, + subject, + body, + email_type="invoice", + invoice_id=invoice_id, + attachments=[{ + "filename": f"{invoice['invoice_number']}.pdf", + "mime_type": "application/pdf", + "data": pdf_bytes, + }] + ) + return redirect(f"/invoices/view/{invoice_id}?email_sent=1") + except Exception: + return redirect(f"/invoices/view/{invoice_id}?email_failed=1") + + +@app.route("/reports/revenue/email", methods=["POST"]) +def email_revenue_report_json(): + settings = get_app_settings() + recipient = (settings.get("report_delivery_email") or settings.get("business_email") or "").strip() + if not recipient: + return "Report delivery email is not configured.", 400 + + with app.test_client() as client: + json_response = client.get("/reports/revenue.json") + if json_response.status_code != 200: + return "Could not generate revenue report JSON.", 500 + + report = get_revenue_report_data() + subject = f"Revenue Report {report.get('period_label', '')} from {settings.get('business_name') or 'OTB Billing'}" + body = ( + f"Attached is the revenue report JSON for {report.get('period_label', '')}.\n\n" + f"Frequency: {report.get('frequency', '')}\n" + f"Collected CAD: {report.get('collected_cad', '')}\n" + f"Invoices Issued: {report.get('invoice_count', '')}\n" + ) + + try: + send_configured_email( + recipient, + subject, + body, + email_type="revenue_report", + attachments=[{ + "filename": "revenue_report.json", + "mime_type": "application/json", + "data": json_response.data, + }] + ) + return redirect("/reports/revenue?email_sent=1") + except Exception: + return redirect("/reports/revenue?email_failed=1") + + +@app.route("/reports/accounting-package/email", methods=["POST"]) +def email_accounting_package(): + settings = get_app_settings() + recipient = (settings.get("report_delivery_email") or settings.get("business_email") or "").strip() + if not recipient: + return "Report delivery email is not configured.", 400 + + with app.test_client() as client: + zip_response = client.get("/reports/accounting-package.zip") + if zip_response.status_code != 200: + return "Could not generate accounting package ZIP.", 500 + + subject = f"Accounting Package from {settings.get('business_name') or 'OTB Billing'}" + body = "Attached is the latest accounting package export." + + try: + send_configured_email( + recipient, + subject, + body, + email_type="accounting_package", + attachments=[{ + "filename": "accounting_package.zip", + "mime_type": "application/zip", + "data": zip_response.data, + }] + ) + return redirect("/?pkg_email=1") + except Exception: + return redirect("/?pkg_email_failed=1") + + + +@app.route("/subscriptions") +def subscriptions(): + ensure_subscriptions_table() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + s.*, + c.client_code, + c.company_name, + srv.service_code, + srv.service_name + FROM subscriptions s + JOIN clients c ON s.client_id = c.id + LEFT JOIN services srv ON s.service_id = srv.id + ORDER BY s.id DESC + """) + subscriptions = cursor.fetchall() + conn.close() + + return render_template("subscriptions/list.html", subscriptions=subscriptions) + + +@app.route("/subscriptions/new", methods=["GET", "POST"]) +def new_subscription(): + ensure_subscriptions_table() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + subscription_name = request.form.get("subscription_name", "").strip() + billing_interval = request.form.get("billing_interval", "").strip() + price = request.form.get("price", "").strip() + currency_code = request.form.get("currency_code", "").strip() + start_date_value = request.form.get("start_date", "").strip() + next_invoice_date = request.form.get("next_invoice_date", "").strip() + status = request.form.get("status", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not subscription_name: + errors.append("Subscription name is required.") + if billing_interval not in {"monthly", "quarterly", "yearly"}: + errors.append("Billing interval is required.") + if not price: + errors.append("Price is required.") + if not currency_code: + errors.append("Currency is required.") + if not start_date_value: + errors.append("Start date is required.") + if not next_invoice_date: + errors.append("Next invoice date is required.") + if status not in {"active", "paused", "cancelled"}: + errors.append("Status is required.") + + if not errors: + try: + price_value = Decimal(str(price)) + if price_value <= Decimal("0"): + errors.append("Price must be greater than zero.") + except Exception: + errors.append("Price must be a valid number.") + + if errors: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + conn.close() + + return render_template( + "subscriptions/new.html", + clients=clients, + services=services, + errors=errors, + form_data={ + "client_id": client_id, + "service_id": service_id, + "subscription_name": subscription_name, + "billing_interval": billing_interval, + "price": price, + "currency_code": currency_code, + "start_date": start_date_value, + "next_invoice_date": next_invoice_date, + "status": status, + "notes": notes, + }, + ) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO subscriptions + ( + client_id, + service_id, + subscription_name, + billing_interval, + price, + currency_code, + start_date, + next_invoice_date, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, ( + client_id, + service_id or None, + subscription_name, + billing_interval, + str(price_value), + currency_code, + start_date_value, + next_invoice_date, + status, + notes or None, + )) + + conn.commit() + conn.close() + return redirect("/subscriptions") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + conn.close() + + today_str = date.today().isoformat() + + return render_template( + "subscriptions/new.html", + clients=clients, + services=services, + errors=[], + form_data={ + "billing_interval": "monthly", + "currency_code": "CAD", + "start_date": today_str, + "next_invoice_date": today_str, + "status": "active", + }, + ) + + +@app.route("/subscriptions/run", methods=["POST"]) +def run_subscriptions_now(): + result = generate_due_subscription_invoices() + return redirect(f"/subscriptions?run_count={result['created_count']}") + + + +@app.route("/reports/aging") +def report_aging(): + refresh_overdue_invoices() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + c.id AS client_id, + c.client_code, + c.company_name, + i.invoice_number, + i.due_at, + i.total_amount, + i.amount_paid, + (i.total_amount - i.amount_paid) AS remaining + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY c.company_name, i.due_at + """) + rows = cursor.fetchall() + conn.close() + + today = datetime.utcnow().date() + grouped = {} + totals = { + "current": Decimal("0"), + "d30": Decimal("0"), + "d60": Decimal("0"), + "d90": Decimal("0"), + "d90p": Decimal("0"), + "total": Decimal("0"), + } + + for row in rows: + client_id = row["client_id"] + client_label = f"{row['client_code']} - {row['company_name']}" + + if client_id not in grouped: + grouped[client_id] = { + "client": client_label, + "current": Decimal("0"), + "d30": Decimal("0"), + "d60": Decimal("0"), + "d90": Decimal("0"), + "d90p": Decimal("0"), + "total": Decimal("0"), + } + + remaining = to_decimal(row["remaining"]) + + if row["due_at"]: + due_date = row["due_at"].date() + age_days = (today - due_date).days + else: + age_days = 0 + + if age_days <= 0: + bucket = "current" + elif age_days <= 30: + bucket = "d30" + elif age_days <= 60: + bucket = "d60" + elif age_days <= 90: + bucket = "d90" + else: + bucket = "d90p" + + grouped[client_id][bucket] += remaining + grouped[client_id]["total"] += remaining + + totals[bucket] += remaining + totals["total"] += remaining + + aging_rows = list(grouped.values()) + + return render_template( + "reports/aging.html", + aging_rows=aging_rows, + totals=totals + ) + + +@app.route("/") +def index(): + refresh_overdue_invoices() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute("SELECT COUNT(*) AS total_clients FROM clients") + total_clients = cursor.fetchone()["total_clients"] + + cursor.execute("SELECT COUNT(*) AS active_services FROM services WHERE status = 'active'") + active_services = cursor.fetchone()["active_services"] + + cursor.execute(""" + SELECT COUNT(*) AS outstanding_invoices + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + AND (total_amount - amount_paid) > 0 + """) + outstanding_invoices = cursor.fetchone()["outstanding_invoices"] + + cursor.execute(""" + SELECT COALESCE(SUM(cad_value_at_payment), 0) AS revenue_received + FROM payments + WHERE payment_status = 'confirmed' + """) + revenue_received = to_decimal(cursor.fetchone()["revenue_received"]) + + cursor.execute(""" + SELECT COALESCE(SUM(total_amount - amount_paid), 0) AS outstanding_balance + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + AND (total_amount - amount_paid) > 0 + """) + outstanding_balance = to_decimal(cursor.fetchone()["outstanding_balance"]) + + conn.close() + + app_settings = get_app_settings() + + return render_template( + "dashboard.html", + total_clients=total_clients, + active_services=active_services, + outstanding_invoices=outstanding_invoices, + outstanding_balance=outstanding_balance, + revenue_received=revenue_received, + app_settings=app_settings, + ) + +@app.route("/clients") +def clients(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + c.*, + COALESCE(( + SELECT SUM(i.total_amount - i.amount_paid) + FROM invoices i + WHERE i.client_id = c.id + AND i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ), 0) AS outstanding_balance + FROM clients c + ORDER BY c.company_name + """) + clients = cursor.fetchall() + + conn.close() + return render_template("clients/list.html", clients=clients) + +@app.route("/clients/new", methods=["GET", "POST"]) +def new_client(): + if request.method == "POST": + company_name = request.form["company_name"] + contact_name = request.form["contact_name"] + email = request.form["email"] + phone = request.form["phone"] + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute("SELECT MAX(id) AS last_id FROM clients") + result = cursor.fetchone() + last_number = result["last_id"] if result["last_id"] else 0 + + client_code = generate_client_code(company_name, last_number) + + insert_cursor = conn.cursor() + insert_cursor.execute( + """ + INSERT INTO clients + (client_code, company_name, contact_name, email, phone) + VALUES (%s, %s, %s, %s, %s) + """, + (client_code, company_name, contact_name, email, phone) + ) + conn.commit() + conn.close() + + return redirect("/clients") + + return render_template("clients/new.html") + +@app.route("/clients/edit/", methods=["GET", "POST"]) +def edit_client(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + company_name = request.form.get("company_name", "").strip() + contact_name = request.form.get("contact_name", "").strip() + email = request.form.get("email", "").strip() + phone = request.form.get("phone", "").strip() + status = request.form.get("status", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not company_name: + errors.append("Company name is required.") + if not status: + errors.append("Status is required.") + + if errors: + cursor.execute("SELECT * FROM clients WHERE id = %s", (client_id,)) + client = cursor.fetchone() + client["credit_balance"] = get_client_credit_balance(client_id) + conn.close() + return render_template("clients/edit.html", client=client, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET company_name = %s, + contact_name = %s, + email = %s, + phone = %s, + status = %s, + notes = %s + WHERE id = %s + """, ( + company_name, + contact_name or None, + email or None, + phone or None, + status, + notes or None, + client_id + )) + conn.commit() + conn.close() + return redirect("/clients") + + cursor.execute("SELECT * FROM clients WHERE id = %s", (client_id,)) + client = cursor.fetchone() + conn.close() + + if not client: + return "Client not found", 404 + + client["credit_balance"] = get_client_credit_balance(client_id) + + return render_template("clients/edit.html", client=client, errors=[]) + +@app.route("/credits/") +def client_credits(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + WHERE id = %s + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return "Client not found", 404 + + cursor.execute(""" + SELECT * + FROM credit_ledger + WHERE client_id = %s + ORDER BY id DESC + """, (client_id,)) + entries = cursor.fetchall() + + conn.close() + + balance = get_client_credit_balance(client_id) + + return render_template( + "credits/list.html", + client=client, + entries=entries, + balance=balance, + ) + +@app.route("/credits/add/", methods=["GET", "POST"]) +def add_credit(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + WHERE id = %s + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return "Client not found", 404 + + if request.method == "POST": + entry_type = request.form.get("entry_type", "").strip() + amount = request.form.get("amount", "").strip() + currency_code = request.form.get("currency_code", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not entry_type: + errors.append("Entry type is required.") + if not amount: + errors.append("Amount is required.") + if not currency_code: + errors.append("Currency code is required.") + + if not errors: + try: + amount_value = Decimal(str(amount)) + if amount_value == 0: + errors.append("Amount cannot be zero.") + except Exception: + errors.append("Amount must be a valid number.") + + if errors: + conn.close() + return render_template("credits/add.html", client=client, errors=errors) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO credit_ledger + ( + client_id, + entry_type, + amount, + currency_code, + notes + ) + VALUES (%s, %s, %s, %s, %s) + """, ( + client_id, + entry_type, + amount, + currency_code, + notes or None + )) + conn.commit() + conn.close() + + return redirect(f"/credits/{client_id}") + + conn.close() + return render_template("credits/add.html", client=client, errors=[]) + +@app.route("/services") +def services(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT s.*, c.client_code, c.company_name + FROM services s + JOIN clients c ON s.client_id = c.id + ORDER BY s.id DESC + """) + services = cursor.fetchall() + conn.close() + return render_template("services/list.html", services=services) + +@app.route("/services/new", methods=["GET", "POST"]) +def new_service(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form["client_id"] + service_name = request.form["service_name"] + service_type = request.form["service_type"] + billing_cycle = request.form["billing_cycle"] + currency_code = request.form["currency_code"] + recurring_amount = request.form["recurring_amount"] + status = request.form["status"] + start_date = request.form["start_date"] or None + description = request.form["description"] + + cursor.execute("SELECT MAX(id) AS last_id FROM services") + result = cursor.fetchone() + last_number = result["last_id"] if result["last_id"] else 0 + service_code = generate_service_code(service_name, last_number) + + insert_cursor = conn.cursor() + insert_cursor.execute( + """ + INSERT INTO services + ( + client_id, + service_code, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date, + description + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, + ( + client_id, + service_code, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date, + description + ) + ) + conn.commit() + conn.close() + + return redirect("/services") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + conn.close() + return render_template("services/new.html", clients=clients) + +@app.route("/services/edit/", methods=["GET", "POST"]) +def edit_service(service_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_name = request.form.get("service_name", "").strip() + service_type = request.form.get("service_type", "").strip() + billing_cycle = request.form.get("billing_cycle", "").strip() + currency_code = request.form.get("currency_code", "").strip() + recurring_amount = request.form.get("recurring_amount", "").strip() + status = request.form.get("status", "").strip() + start_date = request.form.get("start_date", "").strip() + description = request.form.get("description", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_name: + errors.append("Service name is required.") + if not service_type: + errors.append("Service type is required.") + if not billing_cycle: + errors.append("Billing cycle is required.") + if not currency_code: + errors.append("Currency code is required.") + if not recurring_amount: + errors.append("Recurring amount is required.") + if not status: + errors.append("Status is required.") + + if not errors: + try: + recurring_amount_value = float(recurring_amount) + if recurring_amount_value < 0: + errors.append("Recurring amount cannot be negative.") + except ValueError: + errors.append("Recurring amount must be a valid number.") + + if errors: + cursor.execute(""" + SELECT s.*, c.company_name + FROM services s + LEFT JOIN clients c ON s.client_id = c.id + WHERE s.id = %s + """, (service_id,)) + service = cursor.fetchone() + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + + conn.close() + return render_template("services/edit.html", service=service, clients=clients, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE services + SET client_id = %s, + service_name = %s, + service_type = %s, + billing_cycle = %s, + status = %s, + currency_code = %s, + recurring_amount = %s, + start_date = %s, + description = %s + WHERE id = %s + """, ( + client_id, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date or None, + description or None, + service_id + )) + conn.commit() + conn.close() + return redirect("/services") + + cursor.execute(""" + SELECT s.*, c.company_name + FROM services s + LEFT JOIN clients c ON s.client_id = c.id + WHERE s.id = %s + """, (service_id,)) + service = cursor.fetchone() + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + conn.close() + + if not service: + return "Service not found", 404 + + return render_template("services/edit.html", service=service, clients=clients, errors=[]) + + + + + + +@app.route("/invoices/export.csv") +def export_invoices_csv(): + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.id, + i.invoice_number, + i.client_id, + c.client_code, + c.company_name, + i.service_id, + i.currency_code, + i.subtotal_amount, + i.tax_amount, + i.total_amount, + i.amount_paid, + i.status, + i.issued_at, + i.due_at, + i.paid_at, + i.notes, + i.created_at, + i.updated_at + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + rows = cursor.fetchall() + conn.close() + + output = StringIO() + writer = csv.writer(output) + writer.writerow([ + "id", + "invoice_number", + "client_id", + "client_code", + "company_name", + "service_id", + "currency_code", + "subtotal_amount", + "tax_amount", + "total_amount", + "amount_paid", + "status", + "issued_at", + "due_at", + "paid_at", + "notes", + "created_at", + "updated_at", + ]) + + for r in rows: + writer.writerow([ + r.get("id", ""), + r.get("invoice_number", ""), + r.get("client_id", ""), + r.get("client_code", ""), + r.get("company_name", ""), + r.get("service_id", ""), + r.get("currency_code", ""), + r.get("subtotal_amount", ""), + r.get("tax_amount", ""), + r.get("total_amount", ""), + r.get("amount_paid", ""), + r.get("status", ""), + r.get("issued_at", ""), + r.get("due_at", ""), + r.get("paid_at", ""), + r.get("notes", ""), + r.get("created_at", ""), + r.get("updated_at", ""), + ]) + + filename = "invoices" + if start_date or end_date or status or client_id or limit_count: + filename += "_filtered" + filename += ".csv" + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = f"attachment; filename={filename}" + return response + + +@app.route("/invoices/export-pdf.zip") +def export_invoices_pdf_zip(): + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + conn.close() + + settings = get_app_settings() + + def build_invoice_pdf_bytes(invoice, settings): + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + terms = settings.get("payment_terms", "") + for chunk_start in range(0, len(terms), 90): + line_text = terms[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + footer = settings.get("invoice_footer", "") + for chunk_start in range(0, len(footer), 90): + line_text = footer[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + return buffer.getvalue() + + zip_buffer = BytesIO() + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf: + for invoice in invoices: + pdf_bytes = build_invoice_pdf_bytes(invoice, settings) + zipf.writestr(f"{invoice['invoice_number']}.pdf", pdf_bytes) + + zip_buffer.seek(0) + + filename = "invoices_export" + if start_date: + filename += f"_{start_date}" + if end_date: + filename += f"_to_{end_date}" + if status: + filename += f"_{status}" + if client_id: + filename += f"_client_{client_id}" + if limit_count: + filename += f"_limit_{limit_count}" + filename += ".zip" + + return send_file( + zip_buffer, + mimetype="application/zip", + as_attachment=True, + download_name=filename + ) + + +@app.route("/invoices/print") +def print_invoices(): + refresh_overdue_invoices() + + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + conn.close() + + settings = get_app_settings() + + filters = { + "start_date": start_date, + "end_date": end_date, + "status": status, + "client_id": client_id, + "limit": limit_count, + } + + return render_template("invoices/print_batch.html", invoices=invoices, settings=settings, filters=filters) + +@app.route("/invoices") +def invoices(): + refresh_overdue_invoices() + + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + COALESCE((SELECT COUNT(*) FROM payments p WHERE p.invoice_id = i.id AND p.payment_status = 'confirmed'), 0) AS payment_count + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id DESC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + ORDER BY company_name ASC + """) + clients = cursor.fetchall() + + conn.close() + + filters = { + "start_date": start_date, + "end_date": end_date, + "status": status, + "client_id": client_id, + "limit": limit_count, + } + for inv in invoices: + inv["paid_via"] = "-" + + if str(inv.get("status") or "").lower() not in {"paid", "partial"}: + continue + + pay_conn = get_db_connection() + pay_cursor = pay_conn.cursor(dictionary=True) + pay_cursor.execute(""" + SELECT payment_method, payment_currency + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + ORDER BY COALESCE(received_at, created_at) DESC, id DESC + LIMIT 1 + """, (inv["id"],)) + last_payment = pay_cursor.fetchone() + pay_conn.close() + + if last_payment: + inv["paid_via"] = payment_method_label( + last_payment.get("payment_method"), + last_payment.get("payment_currency"), + ) + + + + return render_template("invoices/list.html", invoices=invoices, filters=filters, clients=clients) + +@app.route("/invoices/new", methods=["GET", "POST"]) +def new_invoice(): + ensure_invoice_quote_columns() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + currency_code = request.form.get("currency_code", "").strip() + total_amount = request.form.get("total_amount", "").strip() + due_at = request.form.get("due_at", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_id: + errors.append("Service is required.") + if not currency_code: + errors.append("Currency is required.") + if not total_amount: + errors.append("Total amount is required.") + if not due_at: + errors.append("Due date is required.") + + if not errors: + try: + amount_value = float(total_amount) + if amount_value <= 0: + errors.append("Total amount must be greater than zero.") + except ValueError: + errors.append("Total amount must be a valid number.") + + if errors: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + + form_data = { + "client_id": client_id, + "service_id": service_id, + "currency_code": currency_code, + "total_amount": total_amount, + "due_at": due_at, + "notes": notes, + } + + return render_template( + "invoices/new.html", + clients=clients, + services=services, + errors=errors, + form_data=form_data, + ) + + invoice_number = generate_invoice_number() + + cursor.execute("SELECT service_name FROM services WHERE id = %s", (service_id,)) + service_row = cursor.fetchone() + service_name = (service_row or {}).get("service_name") or "Service" + + line_description = service_name + if notes: + line_description = f"{service_name} - {notes}" + + oracle_snapshot = fetch_oracle_quote_snapshot(currency_code, total_amount) + oracle_snapshot_json = json.dumps(oracle_snapshot, ensure_ascii=False) if oracle_snapshot else None + quote_expires_at = normalize_oracle_datetime((oracle_snapshot or {}).get("expires_at")) + quote_fiat_amount = total_amount if oracle_snapshot else None + quote_fiat_currency = currency_code if oracle_snapshot else None + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO invoices + ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + subtotal_amount, + issued_at, + due_at, + status, + notes, + quote_fiat_amount, + quote_fiat_currency, + quote_expires_at, + oracle_snapshot + ) + VALUES (%s, %s, %s, %s, %s, %s, UTC_TIMESTAMP(), %s, 'pending', %s, %s, %s, %s, %s) + """, ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + total_amount, + due_at, + notes, + quote_fiat_amount, + quote_fiat_currency, + quote_expires_at, + oracle_snapshot_json + )) + + invoice_id = insert_cursor.lastrowid + + insert_cursor.execute(""" + INSERT INTO invoice_items + ( + invoice_id, + line_number, + item_type, + description, + quantity, + unit_amount, + line_total, + currency_code, + service_id + ) + VALUES (%s, 1, 'service', %s, 1.0000, %s, %s, %s, %s) + """, ( + invoice_id, + line_description, + total_amount, + total_amount, + currency_code, + service_id + )) + + conn.commit() + conn.close() + + return redirect("/invoices") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + + return render_template( + "invoices/new.html", + clients=clients, + services=services, + errors=[], + form_data={}, + ) + + + + + +@app.route("/invoices/pdf/") +def invoice_pdf(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + conn.close() + + settings = get_app_settings() + + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def draw_line(txt, x=left, font="Helvetica", size=11): + nonlocal y + pdf.setFont(font, size) + pdf.drawString(x, y, str(txt) if txt is not None else "") + y -= 16 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("payment_terms", "")), 90): + line_text = settings.get("payment_terms", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if invoice_payments: + y -= 8 + if y < 170: + pdf.showPage() + y = height - 50 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payments Applied") + y -= 16 + + for p in invoice_payments: + if y < 110: + pdf.showPage() + y = height - 50 + + pdf.setFont("Helvetica-Bold", 10) + pdf.drawString( + left, + y, + f"{p.get('payment_method_label', 'Unknown')} | {p.get('payment_amount_display', '')} {p.get('payment_currency', '')} | {str(p.get('payment_status') or '').upper()}" + ) + y -= 13 + + details_parts = [] + if p.get("received_at_local"): + details_parts.append(f"At: {p.get('received_at_local')}") + if p.get("txid"): + details_parts.append(f"TXID: {p.get('txid')}") + elif p.get("reference"): + details_parts.append(f"Ref: {p.get('reference')}") + if p.get("wallet_address"): + details_parts.append(f"Wallet: {p.get('wallet_address')}") + + details = " | ".join(details_parts) + if details: + pdf.setFont("Helvetica", 9) + for chunk_start in range(0, len(details), 108): + if y < 95: + pdf.showPage() + y = height - 50 + pdf.setFont("Helvetica", 9) + pdf.drawString(left + 10, y, details[chunk_start:chunk_start+108]) + y -= 11 + + y -= 6 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("invoice_footer", "")), 90): + line_text = settings.get("invoice_footer", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + + return send_file( + buffer, + mimetype="application/pdf", + as_attachment=True, + download_name=f"{invoice['invoice_number']}.pdf" + ) + + +@app.route("/invoices/view/") +def view_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + conn.close() + settings = get_app_settings() + invoice_payments = get_invoice_payments(invoice_id) + return render_template( + "invoices/view.html", + invoice=invoice, + settings=settings, + invoice_payments=invoice_payments + ) + + +@app.route("/invoices/edit/", methods=["GET", "POST"]) +def edit_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT i.*, + COALESCE((SELECT COUNT(*) FROM payments p WHERE p.invoice_id = i.id), 0) AS payment_count + FROM invoices i + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + locked = invoice["payment_count"] > 0 or float(invoice["amount_paid"]) > 0 + + if request.method == "POST": + due_at = request.form.get("due_at", "").strip() + notes = request.form.get("notes", "").strip() + + if locked: + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET due_at = %s, + notes = %s + WHERE id = %s + """, ( + due_at or None, + notes or None, + invoice_id + )) + conn.commit() + conn.close() + return redirect("/invoices") + + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + currency_code = request.form.get("currency_code", "").strip() + total_amount = request.form.get("total_amount", "").strip() + status = request.form.get("status", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_id: + errors.append("Service is required.") + if not currency_code: + errors.append("Currency is required.") + if not total_amount: + errors.append("Total amount is required.") + if not due_at: + errors.append("Due date is required.") + if not status: + errors.append("Status is required.") + + manual_statuses = {"draft", "pending", "cancelled"} + if status and status not in manual_statuses: + errors.append("Manual invoice status must be draft, pending, or cancelled.") + + if not errors: + try: + amount_value = float(total_amount) + if amount_value < 0: + errors.append("Total amount cannot be negative.") + except ValueError: + errors.append("Total amount must be a valid number.") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + if errors: + invoice["client_id"] = int(client_id) if client_id else invoice["client_id"] + invoice["service_id"] = int(service_id) if service_id else invoice["service_id"] + invoice["currency_code"] = currency_code or invoice["currency_code"] + invoice["total_amount"] = total_amount or invoice["total_amount"] + invoice["due_at"] = due_at or invoice["due_at"] + invoice["status"] = status or invoice["status"] + invoice["notes"] = notes + conn.close() + return render_template("invoices/edit.html", invoice=invoice, clients=clients, services=services, errors=errors, locked=locked) + + cursor.execute("SELECT service_name FROM services WHERE id = %s", (service_id,)) + service_row = cursor.fetchone() + service_name = (service_row or {}).get("service_name") or "Service" + + line_description = service_name + if notes: + line_description = f"{service_name} - {notes}" + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET client_id = %s, + service_id = %s, + currency_code = %s, + total_amount = %s, + subtotal_amount = %s, + due_at = %s, + status = %s, + notes = %s + WHERE id = %s + """, ( + client_id, + service_id, + currency_code, + total_amount, + total_amount, + due_at, + status, + notes or None, + invoice_id + )) + + update_cursor.execute("DELETE FROM invoice_items WHERE invoice_id = %s", (invoice_id,)) + update_cursor.execute(""" + INSERT INTO invoice_items + ( + invoice_id, + line_number, + item_type, + description, + quantity, + unit_amount, + line_total, + currency_code, + service_id + ) + VALUES (%s, 1, 'service', %s, 1.0000, %s, %s, %s, %s) + """, ( + invoice_id, + line_description, + total_amount, + total_amount, + currency_code, + service_id + )) + + conn.commit() + conn.close() + return redirect("/invoices") + + clients = [] + services = [] + + if not locked: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + return render_template("invoices/edit.html", invoice=invoice, clients=clients, services=services, errors=[], locked=locked) + + + +@app.route("/payments/export.csv") +def export_payments_csv(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + p.id, + p.invoice_id, + i.invoice_number, + p.client_id, + c.client_code, + c.company_name, + p.payment_method, + p.payment_currency, + p.payment_amount, + p.cad_value_at_payment, + p.reference, + p.sender_name, + p.txid, + p.wallet_address, + p.payment_status, + p.received_at, + p.notes + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + ORDER BY p.id ASC + """) + rows = cursor.fetchall() + conn.close() + + output = StringIO() + writer = csv.writer(output) + writer.writerow([ + "id", + "invoice_id", + "invoice_number", + "client_id", + "client_code", + "company_name", + "payment_method", + "payment_currency", + "payment_amount", + "cad_value_at_payment", + "reference", + "sender_name", + "txid", + "wallet_address", + "payment_status", + "received_at", + "notes", + ]) + + for r in rows: + writer.writerow([ + r.get("id", ""), + r.get("invoice_id", ""), + r.get("invoice_number", ""), + r.get("client_id", ""), + r.get("client_code", ""), + r.get("company_name", ""), + r.get("payment_method", ""), + r.get("payment_currency", ""), + r.get("payment_amount", ""), + r.get("cad_value_at_payment", ""), + r.get("reference", ""), + r.get("sender_name", ""), + r.get("txid", ""), + r.get("wallet_address", ""), + r.get("payment_status", ""), + r.get("received_at", ""), + r.get("notes", ""), + ]) + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = "attachment; filename=payments.csv" + return response + +@app.route("/payments") +def payments(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + p.*, + i.invoice_number, + i.status AS invoice_status, + i.total_amount, + i.amount_paid, + i.currency_code AS invoice_currency_code, + c.client_code, + c.company_name + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + ORDER BY p.id DESC + """) + payments = cursor.fetchall() + + conn.close() + return render_template("payments/list.html", payments=payments) + +@app.route("/payments/new", methods=["GET", "POST"]) +def new_payment(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + invoice_id = request.form.get("invoice_id", "").strip() + payment_method = request.form.get("payment_method", "").strip() + payment_currency = request.form.get("payment_currency", "").strip() + payment_amount = request.form.get("payment_amount", "").strip() + cad_value_at_payment = request.form.get("cad_value_at_payment", "").strip() + reference = request.form.get("reference", "").strip() + sender_name = request.form.get("sender_name", "").strip() + txid = request.form.get("txid", "").strip() + wallet_address = request.form.get("wallet_address", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not invoice_id: + errors.append("Invoice is required.") + if not payment_method: + errors.append("Payment method is required.") + if not payment_currency: + errors.append("Payment currency is required.") + if not payment_amount: + errors.append("Payment amount is required.") + if not cad_value_at_payment: + errors.append("CAD value at payment is required.") + + if not errors: + try: + payment_amount_value = Decimal(str(payment_amount)) + if payment_amount_value <= Decimal("0"): + errors.append("Payment amount must be greater than zero.") + except Exception: + errors.append("Payment amount must be a valid number.") + + if not errors: + try: + cad_value_value = Decimal(str(cad_value_at_payment)) + if cad_value_value < Decimal("0"): + errors.append("CAD value at payment cannot be negative.") + except Exception: + errors.append("CAD value at payment must be a valid number.") + + invoice_row = None + + if not errors: + cursor.execute(""" + SELECT + i.id, + i.client_id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + """, (invoice_id,)) + invoice_row = cursor.fetchone() + + if not invoice_row: + errors.append("Selected invoice was not found.") + else: + allowed_statuses = {"pending", "partial", "overdue"} + if invoice_row["status"] not in allowed_statuses: + errors.append("Payments can only be recorded against pending, partial, or overdue invoices.") + else: + remaining_balance = to_decimal(invoice_row["total_amount"]) - to_decimal(invoice_row["amount_paid"]) + entered_amount = to_decimal(payment_amount) + + if remaining_balance <= Decimal("0"): + errors.append("This invoice has no remaining balance.") + elif entered_amount > remaining_balance: + errors.append( + f"Payment amount exceeds remaining balance. Remaining balance is {fmt_money(remaining_balance, invoice_row['currency_code'])} {invoice_row['currency_code']}." + ) + + if errors: + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY i.id DESC + """) + invoices = cursor.fetchall() + conn.close() + + form_data = { + "invoice_id": invoice_id, + "payment_method": payment_method, + "payment_currency": payment_currency, + "payment_amount": payment_amount, + "cad_value_at_payment": cad_value_at_payment, + "reference": reference, + "sender_name": sender_name, + "txid": txid, + "wallet_address": wallet_address, + "notes": notes, + } + + return render_template( + "payments/new.html", + invoices=invoices, + errors=errors, + form_data=form_data, + ) + + client_id = invoice_row["client_id"] + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'confirmed', UTC_TIMESTAMP(), %s) + """, ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference or None, + sender_name or None, + txid or None, + wallet_address or None, + notes or None + )) + + conn.commit() + conn.close() + + recalc_invoice_totals(invoice_id) + + try: + notify_conn = get_db_connection() + notify_cursor = notify_conn.cursor(dictionary=True) + notify_cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.currency_code, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice_id,)) + invoice_email_row = notify_cursor.fetchone() + notify_conn.close() + + if invoice_email_row and invoice_email_row.get("email"): + client_name = ( + invoice_email_row.get("contact_name") + or invoice_email_row.get("company_name") + or invoice_email_row.get("email") + ) + payment_amount_display = f"{to_decimal(cad_value_at_payment):.2f} CAD" + invoice_total_display = f"{to_decimal(invoice_email_row.get('total_amount')):.2f} {invoice_email_row.get('currency_code') or 'CAD'}" + + subject = f"Payment Received for Invoice {invoice_email_row.get('invoice_number')}" + body = f"""Hello {client_name}, + +We have received your payment for invoice {invoice_email_row.get('invoice_number')}. + +Amount Received: +{payment_amount_display} + +Invoice Total: +{invoice_total_display} + +Current Invoice Status: +{invoice_email_row.get('status')} + +You can view your invoice anytime in the client portal: +https://portal.outsidethebox.top/portal + +Thank you, +OutsideTheBox +support@outsidethebox.top +""" + + send_configured_email( + to_email=invoice_email_row.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="payment_received", + invoice_id=invoice_id + ) + except Exception: + pass + + return redirect("/payments") + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY i.id DESC + """) + invoices = cursor.fetchall() + conn.close() + + return render_template( + "payments/new.html", + invoices=invoices, + errors=[], + form_data={}, + ) + + + +@app.route("/payments/void/", methods=["POST"]) +def void_payment(payment_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, invoice_id, payment_status + FROM payments + WHERE id = %s + """, (payment_id,)) + payment = cursor.fetchone() + + if not payment: + conn.close() + return "Payment not found", 404 + + if payment["payment_status"] != "confirmed": + conn.close() + return redirect("/payments") + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'reversed' + WHERE id = %s + """, (payment_id,)) + + conn.commit() + conn.close() + + recalc_invoice_totals(payment["invoice_id"]) + + return redirect("/payments") + + recalc_invoice_totals(payment["invoice_id"]) + + return redirect("/payments") + +@app.route("/payments/edit/", methods=["GET", "POST"]) +def edit_payment(payment_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + p.*, + i.invoice_number, + c.client_code, + c.company_name + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + WHERE p.id = %s + """, (payment_id,)) + payment = cursor.fetchone() + + if not payment: + conn.close() + return "Payment not found", 404 + + if request.method == "POST": + payment_method = request.form.get("payment_method", "").strip() + payment_currency = request.form.get("payment_currency", "").strip() + payment_amount = request.form.get("payment_amount", "").strip() + cad_value_at_payment = request.form.get("cad_value_at_payment", "").strip() + reference = request.form.get("reference", "").strip() + sender_name = request.form.get("sender_name", "").strip() + txid = request.form.get("txid", "").strip() + wallet_address = request.form.get("wallet_address", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not payment_method: + errors.append("Payment method is required.") + if not payment_currency: + errors.append("Payment currency is required.") + if not payment_amount: + errors.append("Payment amount is required.") + if not cad_value_at_payment: + errors.append("CAD value at payment is required.") + + if not errors: + try: + amount_value = float(payment_amount) + if amount_value <= 0: + errors.append("Payment amount must be greater than zero.") + except ValueError: + errors.append("Payment amount must be a valid number.") + + try: + cad_value = float(cad_value_at_payment) + if cad_value < 0: + errors.append("CAD value at payment cannot be negative.") + except ValueError: + errors.append("CAD value at payment must be a valid number.") + + if errors: + payment["payment_method"] = payment_method or payment["payment_method"] + payment["payment_currency"] = payment_currency or payment["payment_currency"] + payment["payment_amount"] = payment_amount or payment["payment_amount"] + payment["cad_value_at_payment"] = cad_value_at_payment or payment["cad_value_at_payment"] + payment["reference"] = reference + payment["sender_name"] = sender_name + payment["txid"] = txid + payment["wallet_address"] = wallet_address + payment["notes"] = notes + conn.close() + return render_template("payments/edit.html", payment=payment, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_method = %s, + payment_currency = %s, + payment_amount = %s, + cad_value_at_payment = %s, + reference = %s, + sender_name = %s, + txid = %s, + wallet_address = %s, + notes = %s + WHERE id = %s + """, ( + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference or None, + sender_name or None, + txid or None, + wallet_address or None, + notes or None, + payment_id + )) + conn.commit() + invoice_id = payment["invoice_id"] + conn.close() + + recalc_invoice_totals(invoice_id) + + return redirect("/payments") + + conn.close() + return render_template("payments/edit.html", payment=payment, errors=[]) + + +def _portal_current_client(): + client_id = session.get("portal_client_id") + if not client_id: + return None + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, company_name, contact_name, email, portal_enabled, portal_force_password_change + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + conn.close() + return client + +@app.route("/portal", methods=["GET"]) +def portal_index(): + if session.get("portal_client_id"): + return redirect("/portal/dashboard") + return render_template("portal_login.html") + +@app.route("/portal/login", methods=["POST"]) +def portal_login(): + email = (request.form.get("email") or "").strip().lower() + credential = (request.form.get("credential") or "").strip() + + if not email or not credential: + return render_template("portal_login.html", portal_message="Email and access code or password are required.", portal_email=email) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, company_name, contact_name, email, portal_enabled, portal_access_code, + portal_password_hash, portal_force_password_change + FROM clients + WHERE LOWER(email) = %s + LIMIT 1 + """, (email,)) + client = cursor.fetchone() + + if not client or not client.get("portal_enabled"): + conn.close() + return render_template("portal_login.html", portal_message="Portal access is not enabled for that email address.", portal_email=email) + + password_hash = client.get("portal_password_hash") + access_code = client.get("portal_access_code") or "" + + ok = False + first_login = False + + if password_hash: + ok = check_password_hash(password_hash, credential) + else: + ok = (credential == access_code) + first_login = ok + + if not ok and access_code and credential == access_code: + ok = True + first_login = True + + if not ok: + conn.close() + return render_template("portal_login.html", portal_message="Invalid credentials.", portal_email=email) + + session["portal_client_id"] = client["id"] + session["portal_email"] = client["email"] + + cursor.execute(""" + UPDATE clients + SET portal_last_login_at = UTC_TIMESTAMP() + WHERE id = %s + """, (client["id"],)) + conn.commit() + conn.close() + + if first_login or client.get("portal_force_password_change"): + return redirect("/portal/set-password") + + return redirect("/portal/dashboard") + +@app.route("/portal/set-password", methods=["GET", "POST"]) +def portal_set_password(): + client = _portal_current_client() + if not client: + return redirect("/portal") + + client_name = client.get("company_name") or client.get("contact_name") or client.get("email") + + if request.method == "GET": + return render_template("portal_set_password.html", client_name=client_name) + + password = (request.form.get("password") or "") + password2 = (request.form.get("password2") or "") + + if len(password) < 10: + return render_template("portal_set_password.html", client_name=client_name, portal_message="Password must be at least 10 characters long.") + if password != password2: + return render_template("portal_set_password.html", client_name=client_name, portal_message="Passwords do not match.") + + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_password_hash = %s, + portal_password_set_at = UTC_TIMESTAMP(), + portal_force_password_change = 0, + portal_access_code = NULL + WHERE id = %s + """, (generate_password_hash(password), client["id"])) + conn.commit() + conn.close() + + return redirect("/portal/dashboard") + + + +@app.route("/portal/invoices/download-all") +def portal_download_all_invoices(): + import io + import zipfile + + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, invoice_number + FROM invoices + WHERE client_id = %s + ORDER BY id + """, (client["id"],)) + invoices = cursor.fetchall() + conn.close() + + memory_file = io.BytesIO() + + with zipfile.ZipFile(memory_file, "w", zipfile.ZIP_DEFLATED) as zf: + for inv in invoices: + response = invoice_pdf(inv["id"]) + response.direct_passthrough = False + pdf_bytes = response.get_data() + + filename = f"{inv.get('invoice_number') or ('invoice_' + str(inv['id']))}.pdf" + zf.writestr(filename, pdf_bytes) + + memory_file.seek(0) + + return send_file( + memory_file, + download_name="all_invoices.zip", + as_attachment=True, + mimetype="application/zip", + ) + +@app.route("/portal/dashboard", methods=["GET"]) +def portal_dashboard(): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT i.id, i.invoice_number, i.status, i.created_at, i.total_amount, i.amount_paid, + p.payment_currency, p.notes, p.reference + FROM invoices i + LEFT JOIN payments p ON p.id = ( + SELECT id FROM payments + WHERE invoice_id = i.id + ORDER BY id DESC + LIMIT 1 + ) + WHERE client_id = %s + ORDER BY created_at DESC + """, (client["id"],)) + invoices = cursor.fetchall() + + def _fmt_money(value): + return f"{to_decimal(value):.2f}" + + for row in invoices: + # Determine payment method + method = "" + currency = (row.get("payment_currency") or "").upper() + notes = (row.get("notes") or "").lower() + ref = (row.get("reference") or "").lower() + + if currency: + method = currency + elif "square" in ref: + method = "Square" + elif "etransfer" in ref or "e-transfer" in ref: + method = "e-Transfer" + + row["payment_method"] = method + # Determine payment method + method = "" + currency = (row.get("payment_currency") or "").upper() + notes = (row.get("notes") or "").lower() + ref = (row.get("reference") or "").lower() + + if currency: + method = currency + elif "square" in ref: + method = "Square" + elif "etransfer" in ref or "e-transfer" in ref: + method = "e-Transfer" + + row["payment_method"] = method + outstanding = to_decimal(row.get("total_amount")) - to_decimal(row.get("amount_paid")) + row["outstanding"] = _fmt_money(outstanding) + row["total_amount"] = _fmt_money(row.get("total_amount")) + row["amount_paid"] = _fmt_money(row.get("amount_paid")) + row["created_at"] = fmt_local(row.get("created_at")) + + total_outstanding = sum((to_decimal(r["outstanding"]) for r in invoices), to_decimal("0")) + total_paid = sum((to_decimal(r["amount_paid"]) for r in invoices), to_decimal("0")) + + conn.close() + + return render_template( + "portal_dashboard.html", + client=client, + invoices=invoices, + invoice_count=len(invoices), + total_outstanding=f"{total_outstanding:.2f}", + total_paid=f"{total_paid:.2f}", + ) + + + +@app.route("/portal/invoice//pdf", methods=["GET"]) +def portal_invoice_pdf(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s AND i.client_id = %s + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + conn.close() + + settings = get_app_settings() + + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def draw_line(txt, x=left, font="Helvetica", size=11): + nonlocal y + pdf.setFont(font, size) + pdf.drawString(x, y, str(txt) if txt is not None else "") + y -= 16 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("payment_terms", "")), 90): + line_text = settings.get("payment_terms", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("invoice_footer", "")), 90): + line_text = settings.get("invoice_footer", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + + return send_file( + buffer, + mimetype="application/pdf", + as_attachment=True, + download_name=f"{invoice['invoice_number']}.pdf" + ) + + +@app.route("/portal/invoice/", methods=["GET"]) +def portal_invoice_detail(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + ensure_invoice_quote_columns() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_id, invoice_number, status, created_at, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + cursor.execute(""" + SELECT description, quantity, unit_amount AS unit_price, line_total + FROM invoice_items + WHERE invoice_id = %s + ORDER BY id ASC + """, (invoice_id,)) + items = cursor.fetchall() + + def _fmt_money(value): + return f"{to_decimal(value):.2f}" + + outstanding = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + invoice["outstanding"] = _fmt_money(outstanding) + invoice["total_amount"] = _fmt_money(invoice.get("total_amount")) + invoice["amount_paid"] = _fmt_money(invoice.get("amount_paid")) + invoice["created_at"] = fmt_local(invoice.get("created_at")) + invoice["quote_expires_at_local"] = fmt_local(invoice.get("quote_expires_at")) + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + for item in items: + item["quantity"] = _fmt_money(item.get("quantity")) + item["unit_price"] = _fmt_money(item.get("unit_price")) + item["line_total"] = _fmt_money(item.get("line_total")) + + pay_mode = (request.args.get("pay") or "").strip().lower() + crypto_error = (request.args.get("crypto_error") or "").strip() + + crypto_options = get_invoice_crypto_options(invoice) + selected_crypto_option = None + pending_crypto_payment = None + crypto_quote_window_expires_iso = None + crypto_quote_window_expires_local = None + + if (invoice.get("status") or "").lower() != "paid": + if pay_mode != "crypto": + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, updated_at, txid, confirmations, + confirmation_required, notes + FROM payments + WHERE invoice_id = %s + AND client_id = %s + AND payment_status = 'pending' + AND notes LIKE '%%portal_crypto_intent:%%' + ORDER BY id DESC + LIMIT 1 + """, (invoice_id, client["id"])) + auto_pending_payment = cursor.fetchone() + if auto_pending_payment: + pending_crypto_payment = auto_pending_payment + pay_mode = "crypto" + if not request.args.get("payment_id"): + selected_crypto_option = next( + (o for o in crypto_options if o["payment_currency"] == str(auto_pending_payment.get("payment_currency") or "").upper()), + None + ) + + if pay_mode == "crypto" and crypto_options and (invoice.get("status") or "").lower() != "paid": + quote_key = f"portal_crypto_quote_window_{invoice_id}_{client['id']}" + now_utc = datetime.now(timezone.utc) + + stored_start = session.get(quote_key) + quote_start_dt = None + if stored_start: + try: + quote_start_dt = datetime.fromisoformat(str(stored_start).replace("Z", "+00:00")) + if quote_start_dt.tzinfo is None: + quote_start_dt = quote_start_dt.replace(tzinfo=timezone.utc) + except Exception: + quote_start_dt = None + + if request.args.get("refresh_quote") == "1" or not quote_start_dt or (now_utc - quote_start_dt).total_seconds() > 90: + quote_start_dt = now_utc + session[quote_key] = quote_start_dt.isoformat() + + quote_expires_dt = quote_start_dt + timedelta(seconds=90) + crypto_quote_window_expires_iso = quote_expires_dt.astimezone(timezone.utc).isoformat() + crypto_quote_window_expires_local = fmt_local(quote_expires_dt) + + selected_asset = (request.args.get("asset") or "").strip().upper() + if selected_asset: + selected_crypto_option = next((o for o in crypto_options if o["symbol"] == selected_asset), None) + + payment_id = (request.args.get("payment_id") or "").strip() + if not payment_id and pending_crypto_payment: + payment_id = str(pending_crypto_payment.get("id") or "").strip() + + if payment_id.isdigit(): + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, received_at, txid, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (payment_id, invoice_id, client["id"])) + pending_crypto_payment = cursor.fetchone() + + if pending_crypto_payment: + created_dt = pending_crypto_payment.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + + if created_dt: + lock_expires_dt = created_dt + timedelta(minutes=2) + pending_crypto_payment["created_at_local"] = fmt_local(created_dt) + pending_crypto_payment["lock_expires_at_local"] = fmt_local(lock_expires_dt) + pending_crypto_payment["lock_expires_at_iso"] = lock_expires_dt.astimezone(timezone.utc).isoformat() + pending_crypto_payment["lock_expired"] = datetime.now(timezone.utc) >= lock_expires_dt + else: + pending_crypto_payment["created_at_local"] = "" + pending_crypto_payment["lock_expires_at_local"] = "" + pending_crypto_payment["lock_expires_at_iso"] = "" + pending_crypto_payment["lock_expired"] = True + + received_dt = pending_crypto_payment.get("received_at") + if received_dt and received_dt.tzinfo is None: + received_dt = received_dt.replace(tzinfo=timezone.utc) + + if received_dt: + processing_expires_dt = received_dt + timedelta(minutes=15) + pending_crypto_payment["received_at_local"] = fmt_local(received_dt) + pending_crypto_payment["processing_expires_at_local"] = fmt_local(processing_expires_dt) + pending_crypto_payment["processing_expires_at_iso"] = processing_expires_dt.astimezone(timezone.utc).isoformat() + pending_crypto_payment["processing_expired"] = datetime.now(timezone.utc) >= processing_expires_dt + else: + pending_crypto_payment["received_at_local"] = "" + pending_crypto_payment["processing_expires_at_local"] = "" + pending_crypto_payment["processing_expires_at_iso"] = "" + pending_crypto_payment["processing_expired"] = False + + if not selected_crypto_option: + selected_crypto_option = next( + (o for o in crypto_options if o["payment_currency"] == str(pending_crypto_payment.get("payment_currency") or "").upper()), + None + ) + + if pending_crypto_payment.get("txid") and str(pending_crypto_payment.get("payment_status") or "").lower() == "pending": + reconcile_result = reconcile_pending_crypto_payment(pending_crypto_payment) + + cursor.execute(""" + SELECT id, client_id, invoice_number, status, created_at, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + refreshed_invoice = cursor.fetchone() + if refreshed_invoice: + invoice.update(refreshed_invoice) + + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, updated_at, txid, confirmations, + confirmation_required, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (payment_id, invoice_id, client["id"])) + refreshed_payment = cursor.fetchone() + if refreshed_payment: + pending_crypto_payment = refreshed_payment + + if reconcile_result.get("state") == "confirmed": + outstanding = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + invoice["outstanding"] = _fmt_money(outstanding) + invoice["total_amount"] = _fmt_money(invoice.get("total_amount")) + invoice["amount_paid"] = _fmt_money(invoice.get("amount_paid")) + elif reconcile_result.get("state") in {"timeout", "failed_receipt"}: + crypto_error = "Transaction was not confirmed in time. Please refresh your quote and try again." + + pdf_url = f"/invoices/pdf/{invoice_id}" + invoice_payments = get_invoice_payments(invoice_id) + + conn.close() + + return render_template( + "portal_invoice_detail.html", + client=client, + invoice=invoice, + items=items, + pdf_url=pdf_url, + pay_mode=pay_mode, + crypto_error=crypto_error, + crypto_options=crypto_options, + selected_crypto_option=selected_crypto_option, + pending_crypto_payment=pending_crypto_payment, + crypto_quote_window_expires_iso=crypto_quote_window_expires_iso, + crypto_quote_window_expires_local=crypto_quote_window_expires_local, + invoice_payments=invoice_payments, + ) + + +@app.route("/portal/logout", methods=["GET"]) +def portal_logout(): + session.pop("portal_client_id", None) + session.pop("portal_email", None) + return redirect("/portal") + + + +@app.route("/clients/portal/enable/", methods=["POST"]) +def client_portal_enable(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, portal_enabled, portal_access_code, portal_password_hash + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("portal_access_code") and not client.get("portal_password_hash"): + new_code = generate_portal_access_code() + cursor2 = conn.cursor() + cursor2.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + else: + cursor2 = conn.cursor() + cursor2.execute(""" + UPDATE clients + SET portal_enabled = 1 + WHERE id = %s + """, (client_id,)) + + conn.commit() + conn.close() + return redirect(f"/clients/edit/{client_id}") + +@app.route("/clients/portal/disable/", methods=["POST"]) +def client_portal_disable(client_id): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_enabled = 0 + WHERE id = %s + """, (client_id,)) + conn.commit() + conn.close() + return redirect(f"/clients/edit/{client_id}") + +@app.route("/clients/portal/reset-code/", methods=["POST"]) +def client_portal_reset_code(client_id): + new_code = generate_portal_access_code() + + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + conn.commit() + conn.close() + + return redirect(f"/clients/edit/{client_id}") + + +@app.route("/clients/portal/send-invite/", methods=["POST"]) +def client_portal_send_invite(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled, + portal_access_code, + portal_password_hash, + portal_password_set_at + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("email"): + conn.close() + return redirect(f"/clients/edit/{client_id}?portal_email_status=missing_email") + + access_code = client.get("portal_access_code") + + # If no active one-time code exists, generate a fresh one and require password setup again. + if not access_code: + access_code = generate_portal_access_code() + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (access_code, client_id)) + conn.commit() + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled, + portal_access_code, + portal_password_hash, + portal_password_set_at + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + elif not client.get("portal_enabled"): + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1 + WHERE id = %s + """, (client_id,)) + conn.commit() + + conn.close() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_email = client.get("email") or "" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Client Portal Access" + body = f"""Hello {contact_name}, + +Your OutsideTheBox client portal access is now ready. + +Portal URL: +{portal_url} + +Login email: +{portal_email} + +Single-use access code: +{client.get("portal_access_code")} + +Important: +- This access code is single-use. +- After your first successful login, you will be asked to create your password. +- Once your password is created, this access code is cleared and future logins will use your email address and password. + +If you have any trouble signing in, contact support: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=portal_email, + subject=subject, + body=body, + attachments=None, + email_type="portal_invite", + invoice_id=None + ) + return redirect(f"/clients/edit/{client_id}?portal_email_status=sent") + except Exception: + return redirect(f"/clients/edit/{client_id}?portal_email_status=error") + + +@app.route("/clients/portal/send-password-reset/", methods=["POST"]) +def client_portal_send_password_reset(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("email"): + conn.close() + return redirect(f"/clients/edit/{client_id}?portal_reset_status=missing_email") + + new_code = generate_portal_access_code() + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + conn.commit() + conn.close() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_email = client.get("email") or "" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Portal Password Reset" + body = f"""Hello {contact_name}, + +A password reset has been issued for your OutsideTheBox client portal access. + +Portal URL: +{portal_url} + +Login email: +{portal_email} + +New single-use access code: +{new_code} + +Important: +- This access code is single-use. +- It replaces your previous portal password. +- After you sign in, you will be asked to create a new password. +- Once your new password is created, this access code is cleared and future logins will use your email address and password. + +If you did not expect this reset, contact support immediately: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=portal_email, + subject=subject, + body=body, + attachments=None, + email_type="portal_password_reset", + invoice_id=None + ) + return redirect(f"/clients/edit/{client_id}?portal_reset_status=sent") + except Exception: + return redirect(f"/clients/edit/{client_id}?portal_reset_status=error") + +@app.route("/portal/forgot-password", methods=["GET", "POST"]) +def portal_forgot_password(): + if request.method == "GET": + return render_template("portal_forgot_password.html", error=None, message=None, form_email="") + + email = (request.form.get("email") or "").strip().lower() + + if not email: + return render_template( + "portal_forgot_password.html", + error="Email address is required.", + message=None, + form_email="" + ) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, company_name, contact_name, email + FROM clients + WHERE LOWER(email) = %s + LIMIT 1 + """, (email,)) + client = cursor.fetchone() + + if client: + new_code = generate_portal_access_code() + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1, + portal_enabled = 1 + WHERE id = %s + """, (new_code, client["id"])) + conn.commit() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Portal Password Reset" + + body = f"""Hello {contact_name}, + +A password reset was requested for your OutsideTheBox client portal. + +Portal URL: +{portal_url} + +Login email: +{client.get("email")} + +Single-use access code: +{new_code} + +Important: +- This access code is single-use. +- It replaces your previous portal password. +- After you sign in, you will be asked to create a new password. +- Once your new password is created, this access code is cleared and future logins will use your email address and password. + +If you did not request this reset, contact support immediately: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=client.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="portal_forgot_password", + invoice_id=None + ) + except Exception: + pass + + conn.close() + + return render_template( + "portal_forgot_password.html", + error=None, + message="If that email exists in our system, a reset message has been sent.", + form_email=email + ) + + + + +@app.route("/portal/invoice//pay-crypto", methods=["POST"]) +def portal_invoice_pay_crypto(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + ensure_invoice_quote_columns() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, client_id, invoice_number, status, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot, + created_at + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + status = (invoice.get("status") or "").lower() + if status == "paid": + conn.close() + return redirect(f"/portal/invoice/{invoice_id}") + + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + options = get_invoice_crypto_options(invoice) + chosen_symbol = (request.form.get("asset") or "").strip().upper() + selected_option = next((o for o in options if o["symbol"] == chosen_symbol), None) + + quote_key = f"portal_crypto_quote_window_{invoice_id}_{client['id']}" + now_utc = datetime.now(timezone.utc) + stored_start = session.get(quote_key) + quote_start_dt = None + if stored_start: + try: + quote_start_dt = datetime.fromisoformat(str(stored_start).replace("Z", "+00:00")) + if quote_start_dt.tzinfo is None: + quote_start_dt = quote_start_dt.replace(tzinfo=timezone.utc) + except Exception: + quote_start_dt = None + + if not quote_start_dt or (now_utc - quote_start_dt).total_seconds() > 90: + session.pop(quote_key, None) + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error=price+has+expired+-+please+refresh+your+view+to+update&refresh_quote=1") + + if not selected_option: + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error=Please+choose+a+valid+crypto+asset") + + if not selected_option.get("available"): + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error={selected_option['symbol']}+is+not+currently+available") + + cursor.execute(""" + SELECT id, payment_currency, payment_amount, wallet_address, reference, payment_status, created_at, notes + FROM payments + WHERE invoice_id = %s + AND client_id = %s + AND payment_status = 'pending' + AND payment_currency = %s + ORDER BY id DESC + LIMIT 1 + """, (invoice_id, client["id"], selected_option["payment_currency"])) + existing = cursor.fetchone() + + pending_payment_id = None + + if existing: + created_dt = existing.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + + if created_dt and (now_utc - created_dt).total_seconds() <= 120: + pending_payment_id = existing["id"] + + if not pending_payment_id: + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, 'other', %s, %s, %s, %s, %s, NULL, %s, 'pending', NULL, %s) + """, ( + invoice["id"], + invoice["client_id"], + selected_option["payment_currency"], + str(selected_option["display_amount"]), + str(invoice.get("quote_fiat_amount") or invoice.get("total_amount") or "0"), + invoice["invoice_number"], + client.get("email") or client.get("company_name") or "Portal Client", + selected_option["wallet_address"], + f"portal_crypto_intent:{selected_option['symbol']}:{selected_option['chain']}|invoice:{invoice['invoice_number']}|frozen_quote" + )) + conn.commit() + pending_payment_id = insert_cursor.lastrowid + + session.pop(quote_key, None) + conn.close() + + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&asset={selected_option['symbol']}&payment_id={pending_payment_id}") + +@app.route("/portal/invoice//submit-crypto-tx", methods=["POST"]) +def portal_submit_crypto_tx(invoice_id): + client = _portal_current_client() + if not client: + return jsonify({"ok": False, "error": "not_authenticated"}), 401 + + ensure_invoice_quote_columns() + + try: + payload = request.get_json(force=True) or {} + except Exception: + payload = {} + + payment_id = str(payload.get("payment_id") or "").strip() + asset = str(payload.get("asset") or "").strip().upper() + tx_hash = str(payload.get("tx_hash") or "").strip() + + if not payment_id.isdigit(): + return jsonify({"ok": False, "error": "invalid_payment_id"}), 400 + if not asset: + return jsonify({"ok": False, "error": "missing_asset"}), 400 + if not tx_hash or not tx_hash.startswith("0x"): + return jsonify({"ok": False, "error": "missing_tx_hash"}), 400 + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_id, invoice_number, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return jsonify({"ok": False, "error": "invoice_not_found"}), 404 + + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + crypto_options = get_invoice_crypto_options(invoice) + selected_option = next((o for o in crypto_options if o["symbol"] == asset), None) + + if not selected_option: + conn.close() + return jsonify({"ok": False, "error": "invalid_asset"}), 400 + + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_status, txid, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (int(payment_id), invoice_id, client["id"])) + payment = cursor.fetchone() + + if not payment: + conn.close() + return jsonify({"ok": False, "error": "payment_not_found"}), 404 + + if str(payment.get("payment_currency") or "").upper() != selected_option["payment_currency"]: + conn.close() + return jsonify({"ok": False, "error": "payment_currency_mismatch"}), 400 + + if str(payment.get("payment_status") or "").lower() != "pending": + conn.close() + return jsonify({"ok": False, "error": "payment_not_pending"}), 400 + + new_notes = append_payment_note( + payment.get("notes"), + f"[portal wallet submit] tx hash accepted: {tx_hash}" + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET txid = %s, + payment_status = 'pending', + notes = %s + WHERE id = %s + """, ( + tx_hash, + new_notes, + payment["id"] + )) + conn.commit() + conn.close() + + return jsonify({ + "ok": True, + "redirect_url": f"/portal/invoice/{invoice_id}?pay=crypto&asset={asset}&payment_id={payment['id']}" + }) + + +@app.route("/portal/invoice//pay-square", methods=["GET"]) +def portal_invoice_pay_square(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + i.*, + c.email AS client_email, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s AND i.client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return redirect("/portal/dashboard") + + status = (invoice.get("status") or "").lower() + if status == "paid": + return redirect(f"/portal/invoice/{invoice_id}") + + square_url = create_square_payment_link_for_invoice(invoice, invoice.get("client_email") or "") + return redirect(square_url) + +@app.route("/invoices/pay-square/", methods=["GET"]) +def admin_invoice_pay_square(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + i.*, + c.email AS client_email, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice_id,)) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return "Invoice not found", 404 + + status = (invoice.get("status") or "").lower() + if status == "paid": + return redirect(f"/invoices/view/{invoice_id}") + + square_url = create_square_payment_link_for_invoice(invoice, invoice.get("client_email") or "") + return redirect(square_url) + + + +def auto_apply_square_payment(parsed_event): + try: + data_obj = (((parsed_event.get("data") or {}).get("object")) or {}) + payment = data_obj.get("payment") or {} + + payment_id = payment.get("id") or "" + payment_status = (payment.get("status") or "").upper() + note = (payment.get("note") or "").strip() + buyer_email = (payment.get("buyer_email_address") or "").strip() + amount_money = (payment.get("amount_money") or {}).get("amount") + currency = (payment.get("amount_money") or {}).get("currency") or "CAD" + + if not payment_id or payment_status != "COMPLETED": + return {"processed": False, "reason": "not_completed_or_missing_id"} + + m = re.search(r'Invoice\s+([A-Za-z0-9\-]+)', note, re.IGNORECASE) + if not m: + return {"processed": False, "reason": "invoice_note_not_found", "note": note} + + invoice_number = m.group(1).strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + # Deduplicate by Square payment ID + cursor.execute(""" + SELECT id + FROM payments + WHERE txid = %s + LIMIT 1 + """, (payment_id,)) + existing = cursor.fetchone() + if existing: + conn.close() + return {"processed": False, "reason": "duplicate_payment_id", "payment_id": payment_id} + + cursor.execute(""" + SELECT + i.id, + i.client_id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.invoice_number = %s + LIMIT 1 + """, (invoice_number,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return {"processed": False, "reason": "invoice_not_found", "invoice_number": invoice_number} + + payment_amount = to_decimal(amount_money) / to_decimal("100") + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, UTC_TIMESTAMP(), %s) + """, ( + invoice["id"], + invoice["client_id"], + "square", + currency, + payment_amount, + payment_amount if currency == "CAD" else payment_amount, + invoice_number, + buyer_email or "Square Customer", + payment_id, + "", + "confirmed", + f"Auto-recorded from Square webhook. Note: {note or ''}".strip() + )) + conn.commit() + conn.close() + + recalc_invoice_totals(invoice["id"]) + + try: + notify_conn = get_db_connection() + notify_cursor = notify_conn.cursor(dictionary=True) + notify_cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.currency_code, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice["id"],)) + invoice_email_row = notify_cursor.fetchone() + notify_conn.close() + + if invoice_email_row and invoice_email_row.get("email"): + client_name = ( + invoice_email_row.get("contact_name") + or invoice_email_row.get("company_name") + or invoice_email_row.get("email") + ) + payment_amount_display = f"{to_decimal(payment_amount):.2f} {currency}" + invoice_total_display = f"{to_decimal(invoice_email_row.get('total_amount')):.2f} {invoice_email_row.get('currency_code') or 'CAD'}" + + subject = f"Payment Received for Invoice {invoice_email_row.get('invoice_number')}" + body = f"""Hello {client_name}, + +We have received your payment for invoice {invoice_email_row.get('invoice_number')}. + +Amount Received: +{payment_amount_display} + +Invoice Total: +{invoice_total_display} + +Current Invoice Status: +{invoice_email_row.get('status')} + +You can view your invoice anytime in the client portal: +https://portal.outsidethebox.top/portal + +Thank you, +OutsideTheBox +support@outsidethebox.top +""" + + send_configured_email( + to_email=invoice_email_row.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="payment_received", + invoice_id=invoice["id"] + ) + except Exception: + pass + + return { + "processed": True, + "invoice_number": invoice_number, + "payment_id": payment_id, + "amount": str(payment_amount), + "currency": currency, + } + + except Exception as e: + return {"processed": False, "reason": "exception", "error": str(e)} + + + + +@app.route("/accountbook/export.csv") +def accountbook_export_csv(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + payment_status, + received_at + FROM payments + WHERE payment_status = 'confirmed' + ORDER BY received_at DESC + """) + payments = cursor.fetchall() + conn.close() + + now_local = datetime.now(LOCAL_TZ) + today_str = now_local.strftime("%Y-%m-%d") + month_prefix = now_local.strftime("%Y-%m") + year_prefix = now_local.strftime("%Y") + + categories = [ + ("cash", "Cash"), + ("etransfer", "eTransfer"), + ("square", "Square"), + ("etho", "ETHO"), + ("eti", "ETI"), + ("egaz", "EGAZ"), + ("eth", "ETH"), + ("other", "Other"), + ] + + periods = { + "today": {"label": "Today", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "month": {"label": "This Month", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "ytd": {"label": "Year to Date", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + } + + def norm_method(method): + m = (method or "").strip().lower() + if m in ("cash",): + return "cash" + if m in ("etransfer", "e-transfer", "interac", "interac e-transfer", "email money transfer"): + return "etransfer" + if m in ("square",): + return "square" + if m in ("etho",): + return "etho" + if m in ("eti",): + return "eti" + if m in ("egaz",): + return "egaz" + if m in ("eth", "ethereum"): + return "eth" + return "other" + + for pay in payments: + received = pay.get("received_at") + if not received: + continue + + if isinstance(received, str): + received_local_str = received[:10] + received_month = received[:7] + received_year = received[:4] + else: + if received.tzinfo is None: + received = received.replace(tzinfo=timezone.utc) + received_local = received.astimezone(LOCAL_TZ) + received_local_str = received_local.strftime("%Y-%m-%d") + received_month = received_local.strftime("%Y-%m") + received_year = received_local.strftime("%Y") + + bucket = norm_method(pay.get("payment_method")) + amount = to_decimal(pay.get("cad_value_at_payment") or pay.get("payment_amount") or "0") + + if received_year == year_prefix: + periods["ytd"]["totals"][bucket] += amount + periods["ytd"]["grand"] += amount + + if received_month == month_prefix: + periods["month"]["totals"][bucket] += amount + periods["month"]["grand"] += amount + + if received_local_str == today_str: + periods["today"]["totals"][bucket] += amount + periods["today"]["grand"] += amount + + output = StringIO() + writer = csv.writer(output) + writer.writerow(["Period", "Category", "Total CAD"]) + + for period_key in ("today", "month", "ytd"): + period = periods[period_key] + for cat_key, cat_label in categories: + writer.writerow([period["label"], cat_label, f"{period['totals'][cat_key]:.2f}"]) + writer.writerow([period["label"], "Grand Total", f"{period['grand']:.2f}"]) + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = "attachment; filename=accountbook_summary.csv" + return response + + +@app.route("/accountbook") +def accountbook(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + payment_status, + received_at + FROM payments + WHERE payment_status = 'confirmed' + ORDER BY received_at DESC + """) + payments = cursor.fetchall() + conn.close() + + now_local = datetime.now(LOCAL_TZ) + today_str = now_local.strftime("%Y-%m-%d") + month_prefix = now_local.strftime("%Y-%m") + year_prefix = now_local.strftime("%Y") + + categories = [ + ("cash", "Cash"), + ("etransfer", "eTransfer"), + ("square", "Square"), + ("etho", "ETHO"), + ("eti", "ETI"), + ("egaz", "EGAZ"), + ("eth", "ETH"), + ("other", "Other"), + ] + + periods = { + "today": {"label": "Today", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "month": {"label": "This Month", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "ytd": {"label": "Year to Date", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + } + + def norm_method(method): + m = (method or "").strip().lower() + if m in ("cash",): + return "cash" + if m in ("etransfer", "e-transfer", "interac", "interac e-transfer", "email money transfer"): + return "etransfer" + if m in ("square",): + return "square" + if m in ("etho",): + return "etho" + if m in ("eti",): + return "eti" + if m in ("egaz",): + return "egaz" + if m in ("eth", "ethereum"): + return "eth" + return "other" + + for p in payments: + received = p.get("received_at") + if not received: + continue + + if isinstance(received, str): + received_local_str = received[:10] + received_month = received[:7] + received_year = received[:4] + else: + if received.tzinfo is None: + received = received.replace(tzinfo=timezone.utc) + received_local = received.astimezone(LOCAL_TZ) + received_local_str = received_local.strftime("%Y-%m-%d") + received_month = received_local.strftime("%Y-%m") + received_year = received_local.strftime("%Y") + + bucket = norm_method(p.get("payment_method")) + amount = to_decimal(p.get("cad_value_at_payment") or p.get("payment_amount") or "0") + + if received_year == year_prefix: + periods["ytd"]["totals"][bucket] += amount + periods["ytd"]["grand"] += amount + + if received_month == month_prefix: + periods["month"]["totals"][bucket] += amount + periods["month"]["grand"] += amount + + if received_local_str == today_str: + periods["today"]["totals"][bucket] += amount + periods["today"]["grand"] += amount + + period_cards = [] + for key in ("today", "month", "ytd"): + block = periods[key] + lines = [] + for cat_key, cat_label in categories: + lines.append(f"{cat_label}{block['totals'][cat_key]:.2f}") + period_cards.append(f""" +
+

{block['label']}

+
{block['grand']:.2f}
+ + + {''.join(lines)} + +
+
+ """) + + html = f""" + + + + + Accountbook - OTB Billing + + + + + +
+
+
+

Accountbook

+

Confirmed payment totals by period and payment type.

+
+ +
+ +
+ {''.join(period_cards)} +
+
+ +""" + return Response(html, mimetype="text/html") + + +@app.route("/square/reconciliation") +def square_reconciliation(): + log_path = Path(SQUARE_WEBHOOK_LOG) + events = [] + + if log_path.exists(): + lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines() + for line in reversed(lines[-400:]): + try: + row = json.loads(line) + events.append(row) + except Exception: + continue + + summary_cards = { + "processed_true": 0, + "duplicates": 0, + "failures": 0, + "sig_invalid": 0, + } + + for row in events[:150]: + if row.get("signature_valid") is False: + summary_cards["sig_invalid"] += 1 + auto_apply_result = row.get("auto_apply_result") + if isinstance(auto_apply_result, dict): + if auto_apply_result.get("processed") is True: + summary_cards["processed_true"] += 1 + elif auto_apply_result.get("reason") == "duplicate_payment_id": + summary_cards["duplicates"] += 1 + else: + summary_cards["failures"] += 1 + + summary_html = f""" + + """ + + filter_mode = (request.args.get("filter") or "").strip().lower() + + filtered_events = [] + for row in events[:150]: + auto_apply_result = row.get("auto_apply_result") + sig_valid = row.get("signature_valid") + + include = True + if filter_mode == "processed": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("processed") is True + elif filter_mode == "duplicates": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("reason") == "duplicate_payment_id" + elif filter_mode == "failures": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("processed") is False and auto_apply_result.get("reason") != "duplicate_payment_id" + elif filter_mode == "invalid": + include = (sig_valid is False) + + if include: + filtered_events.append(row) + + rows_html = [] + for row in filtered_events: + logged_at = row.get("logged_at_utc", "") + event_type = row.get("event_type", row.get("source", "")) + payment_id = row.get("payment_id", "") + note = row.get("note", "") + amount_money = row.get("amount_money", "") + signature_valid = row.get("signature_valid", "") + auto_apply_result = row.get("auto_apply_result") + + if isinstance(auto_apply_result, dict): + if auto_apply_result.get("processed") is True: + result_text = f"processed: true / invoice {auto_apply_result.get('invoice_number','')}" + result_class = "ok" + else: + result_text = f"processed: false / {auto_apply_result.get('reason','')}" + if auto_apply_result.get("error"): + result_text += f" / {auto_apply_result.get('error')}" + result_class = "warn" + else: + result_text = "" + result_class = "" + + signature_text = "true" if signature_valid is True else ("false" if signature_valid is False else "") + + rows_html.append(f""" + + {logged_at} + {event_type} + {payment_id} + {amount_money} + {note} + {signature_text} + {result_text} + + """) + + html = f""" + + + + + Square Reconciliation - OTB Billing + + + + + +
+
+
+

Square Reconciliation

+

Recent Square webhook events and auto-apply outcomes.

+
+ +
+ +

Log file: {SQUARE_WEBHOOK_LOG}

+

Current Filter: {filter_mode or "all"}

+ + {summary_html} + + + + + + + + + + + + + + + {''.join(rows_html) if rows_html else ''} + +
Logged At (UTC)EventPayment IDAmount (cents)NoteSig ValidAuto Apply Result
No webhook events found.
+
+ +""" + return Response(html, mimetype="text/html") + + +@app.route("/square/webhook", methods=["POST"]) +def square_webhook(): + raw_body = request.get_data() + signature_header = request.headers.get("x-square-hmacsha256-signature", "") + notification_url = SQUARE_WEBHOOK_NOTIFICATION_URL or request.url + + valid = square_signature_is_valid(signature_header, raw_body, notification_url) + + parsed = None + try: + parsed = json.loads(raw_body.decode("utf-8")) + except Exception: + parsed = None + + event_id = None + event_type = None + payment_id = None + payment_status = None + amount_money = None + reference_id = None + note = None + order_id = None + customer_id = None + receipt_number = None + source_type = None + + try: + if isinstance(parsed, dict): + event_id = parsed.get("event_id") + event_type = parsed.get("type") + data_obj = (((parsed.get("data") or {}).get("object")) or {}) + payment = data_obj.get("payment") or {} + payment_id = payment.get("id") + payment_status = payment.get("status") + amount_money = (((payment.get("amount_money") or {}).get("amount"))) + reference_id = payment.get("reference_id") + note = payment.get("note") + order_id = payment.get("order_id") + customer_id = payment.get("customer_id") + receipt_number = payment.get("receipt_number") + source_type = ((payment.get("source_type")) or "") + except Exception: + pass + + append_square_webhook_log({ + "logged_at_utc": datetime.utcnow().isoformat() + "Z", + "signature_valid": valid, + "event_id": event_id, + "event_type": event_type, + "payment_id": payment_id, + "payment_status": payment_status, + "amount_money": amount_money, + "reference_id": reference_id, + "note": note, + "order_id": order_id, + "customer_id": customer_id, + "receipt_number": receipt_number, + "source_type": source_type, + "headers": { + "x-square-hmacsha256-signature": bool(signature_header), + "content-type": request.headers.get("content-type", ""), + "user-agent": request.headers.get("user-agent", ""), + }, + "raw_json": parsed, + }) + + if not valid: + return jsonify({"ok": False, "error": "invalid signature"}), 403 + + result = auto_apply_square_payment(parsed or {}) + append_square_webhook_log({ + "logged_at_utc": datetime.utcnow().isoformat() + "Z", + "auto_apply_result": result, + "source": "square_webhook_postprocess" + }) + + return jsonify({"ok": True, "result": result}), 200 + +register_health_routes(app) +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5050, debug=False, use_reloader=False) \ No newline at end of file diff --git a/backups/payment-method-fix2-20260322-041036/portal_dashboard.html.before_fix b/backups/payment-method-fix2-20260322-041036/portal_dashboard.html.before_fix new file mode 100644 index 0000000..f154632 --- /dev/null +++ b/backups/payment-method-fix2-20260322-041036/portal_dashboard.html.before_fix @@ -0,0 +1,107 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} + {{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + {% include "footer.html" %} + + diff --git a/backups/portal-bottom-bar-20260322-044046/portal_dashboard.html b/backups/portal-bottom-bar-20260322-044046/portal_dashboard.html new file mode 100644 index 0000000..456d493 --- /dev/null +++ b/backups/portal-bottom-bar-20260322-044046/portal_dashboard.html @@ -0,0 +1,110 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% if row.payment_method_label %} +
via {{ row.payment_method_label }}
+ {% endif %} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} +
{{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + {% include "footer.html" %} + + diff --git a/backups/portal-bottom-bar-20260322-044046/portal_forgot_password.html b/backups/portal-bottom-bar-20260322-044046/portal_forgot_password.html new file mode 100644 index 0000000..43ac9a6 --- /dev/null +++ b/backups/portal-bottom-bar-20260322-044046/portal_forgot_password.html @@ -0,0 +1,9 @@ + + + Forgot Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Reset Portal Password

Enter your email address and a new single-use access code will be sent if your account exists.

{% if error %}
{{ error }}
{% endif %} {% if message %}
{{ message }}
{% endif %}
+
{% include "footer.html" %} + + diff --git a/backups/portal-bottom-bar-20260322-044046/portal_invoice_detail.html b/backups/portal-bottom-bar-20260322-044046/portal_invoice_detail.html new file mode 100644 index 0000000..672dfcb --- /dev/null +++ b/backups/portal-bottom-bar-20260322-044046/portal_invoice_detail.html @@ -0,0 +1,19 @@ + + + Invoice Detail - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Invoice Detail

{{ client.company_name or client.contact_name or client.email }}

{% if (invoice.status or "")|lower == "paid" %}
βœ“ This invoice has been paid. Thank you!
{% endif %} {% if crypto_error %}
{{ crypto_error }}
{% endif %}

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Status

{% set s = (invoice.status or "")|lower %} {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} processing {% elif s == "paid" %}{{ invoice.status }} {% elif s == "pending" %}{{ invoice.status }} {% elif s == "overdue" %}{{ invoice.status }} {% else %}{{ invoice.status }}{% endif %}

Created

{{ invoice.created_at }}

Total

{{ invoice.total_amount }}

Paid

{{ invoice.amount_paid }}

Outstanding

{{ invoice.outstanding }}

Invoice Items

{% for item in items %} {% else %} {% endfor %}
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
{% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %}

Pay Now

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Credit Card (Square)

Pay with Credit Card
{% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %}

Crypto Quote Snapshot

Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
{% if pending_crypto_payment %}
Your quote is protected after acceptance.
{% else %}
Select a crypto asset to accept the quote.
{% endif %}
{% if pending_crypto_payment and pending_crypto_payment.txid %}
--:--
Watching transaction / waiting for confirmation
{% elif pending_crypto_payment %}
--:--
Quote protected while you open wallet
{% else %}
--:--
This price times out:
{% endif %}
{% if pending_crypto_payment and selected_crypto_option %}

{{ selected_crypto_option.label }} Payment Instructions

Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
Destination wallet:
{{ pending_crypto_payment.wallet_address }}
Reference / Invoice:
{{ pending_crypto_payment.reference }} {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %}
Open in MetaMask Mobile

Fastest way to pay

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

2. If that does not open your wallet, click Open in MetaMask Mobile.

3. If needed, use Copy Payment Details and send manually.

You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet.
{% elif pending_crypto_payment.txid %}
Transaction Hash:
{{ pending_crypto_payment.txid }}
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
{% elif pending_crypto_payment.lock_expired %}
price has expired - please refresh your quote to update
{% endif %}
{% else %}
{% for q in crypto_options %} {% endfor %}
AssetQuoted AmountCAD PriceStatusAction
{{ q.label }} {% if q.recommended %}recommended{% endif %} {% if q.wallet_capable %}wallet{% endif %} {{ q.display_amount or "β€”" }} {% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %} {% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
{% endif %}
{% else %}

No crypto quote snapshot is available for this invoice yet.

{% endif %}
{% endif %} {% if invoice_payments %}

Payments Applied

{% for p in invoice_payments %} {% endfor %}
Method Amount Status Received Reference / TXID
{{ p.payment_method_label }} {{ p.payment_amount_display }} {{ p.payment_currency }} {{ p.payment_status }} {{ p.received_at_local }} {% if p.txid %} {{ p.txid }} {% elif p.reference %} {{ p.reference }} {% else %} - {% endif %} {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %}
{% endif %} {% if pdf_url %} {% endif %} +
{% include "footer.html" %} + + diff --git a/backups/portal-bottom-bar-20260322-044046/portal_login.html b/backups/portal-bottom-bar-20260322-044046/portal_login.html new file mode 100644 index 0000000..0d7233d --- /dev/null +++ b/backups/portal-bottom-bar-20260322-044046/portal_login.html @@ -0,0 +1,52 @@ + + + + + + Client Portal - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Customer Support +
+
+ + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ + {% include "footer.html" %} + + diff --git a/backups/portal-bottom-bar-20260322-044046/portal_set_password.html b/backups/portal-bottom-bar-20260322-044046/portal_set_password.html new file mode 100644 index 0000000..5d1491c --- /dev/null +++ b/backups/portal-bottom-bar-20260322-044046/portal_set_password.html @@ -0,0 +1,9 @@ + + + Set Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Create Your Portal Password

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

{% if portal_message %}
{{ portal_message }}
{% endif %}
+
{% include "footer.html" %} + + diff --git a/backups/portal-bottom-bar-20260322-044046/style.css b/backups/portal-bottom-bar-20260322-044046/style.css new file mode 100644 index 0000000..4658e7f --- /dev/null +++ b/backups/portal-bottom-bar-20260322-044046/style.css @@ -0,0 +1,587 @@ +:root{ + --bg:#0b0f14; + --card:#121825; + --card-soft:rgba(18,24,37,.78); + --text:#e8eefc; + --muted:#aab6d6; + --line:#24304a; + --accent:#7aa2ff; + --accent2:#62e6b7; + --success:#4ade80; + --warn:#fbbf24; + --danger:#f87171; + --radius:16px; + --shadow:0 16px 40px rgba(0,0,0,.35); +} + +*{box-sizing:border-box} +html,body{height:100%} + +body{ + margin:0; + font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, "Apple Color Emoji","Segoe UI Emoji"; + background: + radial-gradient(1200px 600px at 20% 0%, rgba(122,162,255,.22), transparent 60%), + radial-gradient(900px 500px at 90% 20%, rgba(98,230,183,.15), transparent 60%), + linear-gradient(180deg, #081225 0%, #09172d 100%); + color:var(--text); + line-height:1.45; +} + +a{color:inherit} + +/* ===== Shared container ===== */ +.container{ + max-width:1100px; + margin:0 auto; + padding:20px 18px; +} + +/* ===== Header / branded nav ===== */ +.header{width:100%} + +.nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + padding:12px 0 22px 0; +} + +.brand{ + display:flex; + align-items:center; + gap:14px; + text-decoration:none; +} + +.brand img{ + height:60px; + width:auto; + display:block; + object-fit:contain; + background: rgba(255,255,255,0.92); + padding: 6px 12px; + border-radius: 999px; + box-shadow: 0 8px 24px rgba(0,0,0,0.35); +} + +.title{ + display:flex; + flex-direction:column; + line-height:1.1; +} + +.title strong{letter-spacing:.2px} +.title span{ + color:var(--muted); + font-size:13px; + margin-top:2px; +} + +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; +} + +.navlinks a{ + text-decoration:none; + padding:8px 10px; + border-radius:12px; + color:var(--muted); + border:1px solid transparent; +} + +.navlinks a:hover{ + color:var(--text); + border-color:rgba(255,255,255,.08); + background:rgba(255,255,255,.03); +} + +.navlinks a.active{ + color:var(--text); + border-color:rgba(255,255,255,.10); + background:rgba(255,255,255,.04); +} + +/* ===== Generic portal shell ===== */ +.portal-shell{ + max-width:1100px; + margin:16px auto 28px auto; + padding:0 18px 20px 18px; +} + +.portal-card, +.detail-card, +.summary-card, +.pay-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); +} + +.portal-card{ + max-width:760px; + margin:24px auto 12px auto; + padding:22px; +} + +.portal-page-header{ + display:flex; + align-items:flex-start; + justify-content:space-between; + gap:16px; + flex-wrap:wrap; + margin:6px 0 18px 0; +} + +.portal-page-title{ + margin:0; + font-size:24px; + line-height:1.1; +} + +.portal-page-subtitle{ + margin:8px 0 0 0; + color:var(--muted); +} + +.portal-client-name{ + margin:8px 0 0 0; + color:var(--text); + font-size:15px; +} + +.portal-toolbar{ + display:flex; + gap:10px; + flex-wrap:wrap; + align-items:center; +} + +.portal-btn, +.btn, +.pay-btn, +.quote-pick-btn{ + display:inline-flex; + align-items:center; + justify-content:center; + gap:8px; + min-height:42px; + padding:10px 14px; + border-radius:12px; + text-decoration:none; + border:1px solid rgba(255,255,255,.10); + background: rgba(255,255,255,.05); + color:var(--text); + font-weight:600; + cursor:pointer; +} + +.portal-btn:hover, +.btn:hover, +.pay-btn:hover, +.quote-pick-btn:hover{ + border-color:rgba(122,162,255,.45); + box-shadow:0 0 0 4px rgba(122,162,255,.12); + text-decoration:none; +} + +.portal-btn.primary, +.btn.primary{ + background: linear-gradient(135deg, rgba(122,162,255,.95), rgba(98,230,183,.85)); + border-color: transparent; + color:#071017; + font-weight:700; +} + +.portal-btn.primary:hover, +.btn.primary:hover{ + box-shadow:0 0 0 4px rgba(98,230,183,.18); +} + +/* ===== Login / forms ===== */ +.portal-sub{ + color:var(--muted); + margin:0 0 16px 0; +} + +.portal-form{ + display:grid; + gap:14px; +} + +.portal-form label{ + display:block; + font-weight:600; + margin-bottom:6px; +} + +.portal-form input, +.portal-form select, +.pay-selector{ + width:100%; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.14); + background: rgba(255,255,255,.06); + color:var(--text); + box-sizing:border-box; + outline:none; +} + +.portal-form input:focus, +.portal-form select:focus, +.pay-selector:focus{ + border-color:rgba(122,162,255,.65); + box-shadow:0 0 0 4px rgba(122,162,255,.12); +} + +.portal-actions{ + display:flex; + gap:10px; + flex-wrap:wrap; + margin-top:4px; +} + +.portal-note{ + margin-top:16px; + color:var(--muted); + font-size:14px; + line-height:1.5; +} + +.portal-msg, +.error-box, +.success-box{ + margin-bottom:16px; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.16); + background: rgba(255,255,255,.04); +} + +.error-box{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); + color: #fecaca; +} + +.success-box{ + border-color: rgba(34, 197, 94, 0.55); + background: rgba(22, 101, 52, 0.18); + color: #dcfce7; +} + +/* ===== Dashboard ===== */ +.portal-wrap{ + max-width:1100px; + margin:0 auto; + padding:0; +} + +.summary-grid, +.detail-grid{ + display:grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap:14px; + margin: 0 0 18px 0; +} + +.summary-card, +.detail-card{ + padding:18px; +} + +.summary-card h3, +.detail-card h3{ + margin:0 0 8px 0; + font-size:14px; + color:var(--muted); +} + +.summary-card .summary-value, +.detail-card .detail-value{ + font-size:28px; + font-weight:800; + line-height:1.1; + color:var(--text); +} + +.summary-card .summary-sub{ + margin-top:6px; + font-size:12px; + color:var(--muted); +} + +.section-title{ + margin:18px 0 10px 0; + font-size:22px; +} + +.table-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); + overflow:hidden; +} + +/* ===== Tables ===== */ +table, +.portal-table, +.quote-table{ + width:100%; + border-collapse: collapse; +} + +table.portal-table th, +table.portal-table td, +.quote-table th, +.quote-table td{ + padding: 0.9rem 0.85rem; + border-bottom: 1px solid rgba(255,255,255,0.10); + text-align: left; + vertical-align: middle; +} + +table.portal-table th, +.quote-table th{ + background: rgba(255,255,255,.06); + color: var(--text); + font-size:13px; + letter-spacing:.02em; +} + +table.portal-table tr:hover td, +.quote-table tr:hover td{ + background: rgba(255,255,255,.02); +} + +.invoice-link{ + color: var(--text); + text-decoration: none; + font-weight: 700; +} + +.invoice-link:hover{ + color: var(--accent); + text-decoration: underline; +} + +/* ===== Badges ===== */ +.status-badge, +.quote-badge{ + display: inline-block; + padding: 0.22rem 0.62rem; + border-radius: 999px; + font-size: 0.82rem; + font-weight: 700; +} + +.status-paid{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.status-pending{ background: rgba(245, 158, 11, 0.20); color: var(--warn); } +.status-overdue{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } +.status-other{ background: rgba(148, 163, 184, 0.20); color: #cbd5e1; } + +.quote-live{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.quote-stale{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } + +/* ===== Payments / invoice detail ===== */ +.pay-card{ + padding:18px; + margin-top: 1.25rem; +} + +.pay-selector-row{ + display:flex; + gap:0.75rem; + align-items:center; + flex-wrap:wrap; + margin-top:0.75rem; +} + +.pay-panel{ + margin-top: 1rem; + padding: 1rem; + border: 1px solid rgba(255,255,255,0.12); + border-radius: 12px; + background: rgba(255,255,255,0.02); +} + +.pay-panel.hidden{ display:none; } + +.pay-btn-square { background:#16a34a; border-color:transparent; color:#fff; } +.pay-btn-wallet { background:#2563eb; border-color:transparent; color:#fff; } +.pay-btn-mobile { background:#7c3aed; border-color:transparent; color:#fff; } +.pay-btn-copy { background:#374151; border-color:transparent; color:#fff; } + +.snapshot-wrap{ + position: relative; + margin-top: 1rem; + border: 1px solid rgba(255,255,255,0.14); + border-radius: 14px; + padding: 1rem; + background: rgba(255,255,255,0.02); +} + +.snapshot-header{ + display:flex; + justify-content:space-between; + gap:1rem; + align-items:flex-start; +} + +.snapshot-meta{ + flex: 1 1 auto; + min-width: 0; + line-height: 1.65; +} + +.snapshot-timer-box{ + width: 220px; + min-height: 132px; + border: 1px solid rgba(255,255,255,0.16); + border-radius: 14px; + background: rgba(0,0,0,0.18); + display:flex; + flex-direction:column; + justify-content:center; + align-items:center; + text-align:center; + padding: 0.9rem; +} + +.snapshot-timer-value{ + font-size: 2rem; + font-weight: 800; + line-height: 1.1; +} + +.snapshot-timer-label{ + margin-top: 0.55rem; + font-size: 0.95rem; + opacity: 0.95; +} + +.snapshot-timer-expired{ color: var(--danger); } + +.lock-box{ + margin-top: 1rem; + border: 1px solid rgba(34, 197, 94, 0.28); + background: rgba(22, 101, 52, 0.16); + border-radius: 12px; + padding: 1rem; +} + +.lock-box.expired{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); +} + +.lock-grid{ + display:grid; + grid-template-columns: 1fr 220px; + gap:1rem; + align-items:start; +} + +.lock-code{ + display:block; + margin-top:0.35rem; + padding:0.65rem 0.8rem; + background: rgba(0,0,0,0.22); + border-radius: 8px; + overflow-wrap:anywhere; +} + +.wallet-actions{ + display:flex; + gap:0.75rem; + flex-wrap:wrap; + margin-top:0.9rem; + align-items:center; +} + +.wallet-help{ + margin-top: 0.85rem; + padding: 0.9rem 1rem; + border-radius: 10px; + background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.10); +} + +.wallet-help h4{ + margin: 0 0 0.55rem 0; + font-size: 1rem; +} + +.wallet-help p{ margin: 0.35rem 0; } +.wallet-note{ opacity:0.9; margin-top:0.65rem; } +.mono{ font-family: monospace; } + +.copy-row{ + display:flex; + gap:0.5rem; + flex-wrap:wrap; + align-items:center; + margin-top:0.65rem; +} + +.copy-target{ + flex: 1 1 420px; + min-width: 220px; +} + +.copy-status{ + display:inline-block; + margin-left: 0.5rem; + opacity: 0.9; +} + +/* ===== Footer ===== */ +footer{ + margin:28px auto 20px auto; + max-width:1100px; + padding:0 18px; + color:var(--muted); + font-size:13px; +} + +/* ===== Responsive ===== */ +@media (max-width: 900px){ + .summary-grid, + .detail-grid{ + grid-template-columns:1fr; + } + + .nav{ + align-items:flex-start; + flex-direction:column; + } + + .navlinks{ + justify-content:flex-start; + } + + .brand img{ + height:54px; + } +} + +@media (max-width: 820px){ + .snapshot-header, + .lock-grid{ + grid-template-columns: 1fr; + display:block; + } + + .snapshot-timer-box{ + width: 100%; + margin-top: 1rem; + min-height: 110px; + } +} diff --git a/backups/portal-cleanup-20260322-032010/portal_dashboard.html b/backups/portal-cleanup-20260322-032010/portal_dashboard.html new file mode 100644 index 0000000..41f9fcd --- /dev/null +++ b/backups/portal-cleanup-20260322-032010/portal_dashboard.html @@ -0,0 +1,170 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
+
+

Total Outstanding

+
{{ total_outstanding }}
+
+
+

Total Paid

+
{{ total_paid }}
+
+
+ +

Invoices

+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} + {{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+ + + + +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup-20260322-032010/portal_forgot_password.html b/backups/portal-cleanup-20260322-032010/portal_forgot_password.html new file mode 100644 index 0000000..49e3b4c --- /dev/null +++ b/backups/portal-cleanup-20260322-032010/portal_forgot_password.html @@ -0,0 +1,90 @@ + + + + + + Forgot Portal Password - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+

Reset Portal Password

+

Enter your email address and a new single-use access code will be sent if your account exists.

+ + {% if error %} +
{{ error }}
+ {% endif %} + + {% if message %} +
{{ message }}
+ {% endif %} + +
+
+ + +
+ +
+ + Back to Portal Login + Contact Support +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup-20260322-032010/portal_invoice_detail.html b/backups/portal-cleanup-20260322-032010/portal_invoice_detail.html new file mode 100644 index 0000000..fcabddf --- /dev/null +++ b/backups/portal-cleanup-20260322-032010/portal_invoice_detail.html @@ -0,0 +1,735 @@ + + + + + + Invoice Detail - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+
+

Invoice Detail

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ + {% if (invoice.status or "")|lower == "paid" %} +
βœ“ This invoice has been paid. Thank you!
+ {% endif %} + + {% if crypto_error %} +
{{ crypto_error }}
+ {% endif %} + +
+

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}
+
+

Status

+ {% set s = (invoice.status or "")|lower %} + {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} + processing + {% elif s == "paid" %}{{ invoice.status }} + {% elif s == "pending" %}{{ invoice.status }} + {% elif s == "overdue" %}{{ invoice.status }} + {% else %}{{ invoice.status }}{% endif %} +
+

Created

{{ invoice.created_at }}
+

Total

{{ invoice.total_amount }}
+

Paid

{{ invoice.amount_paid }}
+

Outstanding

{{ invoice.outstanding }}
+
+ +

Invoice Items

+ + + + {% for item in items %} + + {% else %} + + {% endfor %} + +
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
+ + {% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %} +
+

Pay Now

+
+ + +
+ +
+

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

+
+ +
+

Credit Card (Square)

+ Pay with Credit Card +
+ +
+ {% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %} +
+
+
+

Crypto Quote Snapshot

+
Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
+
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
+
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
+ {% if pending_crypto_payment %} +
Your quote is protected after acceptance.
+ {% else %} +
Select a crypto asset to accept the quote.
+ {% endif %} +
+ + {% if pending_crypto_payment and pending_crypto_payment.txid %} +
+
--:--
+
Watching transaction / waiting for confirmation
+
+ {% elif pending_crypto_payment %} +
+
--:--
+
Quote protected while you open wallet
+
+ {% else %} +
+
--:--
+
This price times out:
+
+ {% endif %} +
+ + {% if pending_crypto_payment and selected_crypto_option %} +
+
+
+

{{ selected_crypto_option.label }} Payment Instructions

+
Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
+
Destination wallet:
+ {{ pending_crypto_payment.wallet_address }} +
Reference / Invoice:
+ {{ pending_crypto_payment.reference }} + + {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %} +
+ + + + Open in MetaMask Mobile + + + +
+ +
+

Fastest way to pay

+

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

+

2. If that does not open your wallet, click Open in MetaMask Mobile.

+

3. If needed, use Copy Payment Details and send manually.

+
+ +
+ You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet. +
+ +
+ + +
+ + {% elif pending_crypto_payment.txid %} +
Transaction Hash:
+ {{ pending_crypto_payment.txid }} +
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
+ {% elif pending_crypto_payment.lock_expired %} +
price has expired - please refresh your quote to update
+ {% endif %} +
+ + +
+
+ {% else %} +
+ + + + {% for q in crypto_options %} + + + + + + + + {% endfor %} + +
AssetQuoted AmountCAD PriceStatusAction
+ {{ q.label }} + {% if q.recommended %}recommended{% endif %} + {% if q.wallet_capable %}wallet{% endif %} + {{ q.display_amount or "β€”" }}{% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %}{% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
+
+ {% endif %} +
+ {% else %} +

No crypto quote snapshot is available for this invoice yet.

+ {% endif %} +
+
+ {% endif %} + + {% if invoice_payments %} +
+

Payments Applied

+ + + + + + + + + + + + {% for p in invoice_payments %} + + + + + + + + {% endfor %} + +
MethodAmountStatusReceivedReference / TXID
{{ p.payment_method_label }}{{ p.payment_amount_display }} {{ p.payment_currency }}{{ p.payment_status }}{{ p.received_at_local }} + {% if p.txid %} + {{ p.txid }} + {% elif p.reference %} + {{ p.reference }} + {% else %} + - + {% endif %} + {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %} +
+
+ {% endif %} + + {% if pdf_url %} + + {% endif %} +
+ + + + + + +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup-20260322-032010/portal_login.html b/backups/portal-cleanup-20260322-032010/portal_login.html new file mode 100644 index 0000000..f0f534b --- /dev/null +++ b/backups/portal-cleanup-20260322-032010/portal_login.html @@ -0,0 +1,104 @@ + + + + + + Client Portal - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Home + Contact Support +
+
+ + + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup-20260322-032010/portal_set_password.html b/backups/portal-cleanup-20260322-032010/portal_set_password.html new file mode 100644 index 0000000..fb25ac6 --- /dev/null +++ b/backups/portal-cleanup-20260322-032010/portal_set_password.html @@ -0,0 +1,84 @@ + + + + + + Set Portal Password - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+

Create Your Portal Password

+

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup2-20260322-032316/portal_dashboard.html b/backups/portal-cleanup2-20260322-032316/portal_dashboard.html new file mode 100644 index 0000000..41f9fcd --- /dev/null +++ b/backups/portal-cleanup2-20260322-032316/portal_dashboard.html @@ -0,0 +1,170 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
+
+

Total Outstanding

+
{{ total_outstanding }}
+
+
+

Total Paid

+
{{ total_paid }}
+
+
+ +

Invoices

+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} + {{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+ + + + +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup2-20260322-032316/portal_forgot_password.html b/backups/portal-cleanup2-20260322-032316/portal_forgot_password.html new file mode 100644 index 0000000..49e3b4c --- /dev/null +++ b/backups/portal-cleanup2-20260322-032316/portal_forgot_password.html @@ -0,0 +1,90 @@ + + + + + + Forgot Portal Password - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+

Reset Portal Password

+

Enter your email address and a new single-use access code will be sent if your account exists.

+ + {% if error %} +
{{ error }}
+ {% endif %} + + {% if message %} +
{{ message }}
+ {% endif %} + +
+
+ + +
+ +
+ + Back to Portal Login + Contact Support +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup2-20260322-032316/portal_invoice_detail.html b/backups/portal-cleanup2-20260322-032316/portal_invoice_detail.html new file mode 100644 index 0000000..fcabddf --- /dev/null +++ b/backups/portal-cleanup2-20260322-032316/portal_invoice_detail.html @@ -0,0 +1,735 @@ + + + + + + Invoice Detail - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+
+

Invoice Detail

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ + {% if (invoice.status or "")|lower == "paid" %} +
βœ“ This invoice has been paid. Thank you!
+ {% endif %} + + {% if crypto_error %} +
{{ crypto_error }}
+ {% endif %} + +
+

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}
+
+

Status

+ {% set s = (invoice.status or "")|lower %} + {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} + processing + {% elif s == "paid" %}{{ invoice.status }} + {% elif s == "pending" %}{{ invoice.status }} + {% elif s == "overdue" %}{{ invoice.status }} + {% else %}{{ invoice.status }}{% endif %} +
+

Created

{{ invoice.created_at }}
+

Total

{{ invoice.total_amount }}
+

Paid

{{ invoice.amount_paid }}
+

Outstanding

{{ invoice.outstanding }}
+
+ +

Invoice Items

+ + + + {% for item in items %} + + {% else %} + + {% endfor %} + +
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
+ + {% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %} +
+

Pay Now

+
+ + +
+ +
+

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

+
+ +
+

Credit Card (Square)

+ Pay with Credit Card +
+ +
+ {% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %} +
+
+
+

Crypto Quote Snapshot

+
Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
+
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
+
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
+ {% if pending_crypto_payment %} +
Your quote is protected after acceptance.
+ {% else %} +
Select a crypto asset to accept the quote.
+ {% endif %} +
+ + {% if pending_crypto_payment and pending_crypto_payment.txid %} +
+
--:--
+
Watching transaction / waiting for confirmation
+
+ {% elif pending_crypto_payment %} +
+
--:--
+
Quote protected while you open wallet
+
+ {% else %} +
+
--:--
+
This price times out:
+
+ {% endif %} +
+ + {% if pending_crypto_payment and selected_crypto_option %} +
+
+
+

{{ selected_crypto_option.label }} Payment Instructions

+
Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
+
Destination wallet:
+ {{ pending_crypto_payment.wallet_address }} +
Reference / Invoice:
+ {{ pending_crypto_payment.reference }} + + {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %} +
+ + + + Open in MetaMask Mobile + + + +
+ +
+

Fastest way to pay

+

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

+

2. If that does not open your wallet, click Open in MetaMask Mobile.

+

3. If needed, use Copy Payment Details and send manually.

+
+ +
+ You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet. +
+ +
+ + +
+ + {% elif pending_crypto_payment.txid %} +
Transaction Hash:
+ {{ pending_crypto_payment.txid }} +
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
+ {% elif pending_crypto_payment.lock_expired %} +
price has expired - please refresh your quote to update
+ {% endif %} +
+ + +
+
+ {% else %} +
+ + + + {% for q in crypto_options %} + + + + + + + + {% endfor %} + +
AssetQuoted AmountCAD PriceStatusAction
+ {{ q.label }} + {% if q.recommended %}recommended{% endif %} + {% if q.wallet_capable %}wallet{% endif %} + {{ q.display_amount or "β€”" }}{% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %}{% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
+
+ {% endif %} +
+ {% else %} +

No crypto quote snapshot is available for this invoice yet.

+ {% endif %} +
+
+ {% endif %} + + {% if invoice_payments %} +
+

Payments Applied

+ + + + + + + + + + + + {% for p in invoice_payments %} + + + + + + + + {% endfor %} + +
MethodAmountStatusReceivedReference / TXID
{{ p.payment_method_label }}{{ p.payment_amount_display }} {{ p.payment_currency }}{{ p.payment_status }}{{ p.received_at_local }} + {% if p.txid %} + {{ p.txid }} + {% elif p.reference %} + {{ p.reference }} + {% else %} + - + {% endif %} + {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %} +
+
+ {% endif %} + + {% if pdf_url %} + + {% endif %} +
+ + + + + + +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup2-20260322-032316/portal_login.html b/backups/portal-cleanup2-20260322-032316/portal_login.html new file mode 100644 index 0000000..f0f534b --- /dev/null +++ b/backups/portal-cleanup2-20260322-032316/portal_login.html @@ -0,0 +1,104 @@ + + + + + + Client Portal - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Home + Contact Support +
+
+ + + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-cleanup2-20260322-032316/portal_set_password.html b/backups/portal-cleanup2-20260322-032316/portal_set_password.html new file mode 100644 index 0000000..fb25ac6 --- /dev/null +++ b/backups/portal-cleanup2-20260322-032316/portal_set_password.html @@ -0,0 +1,84 @@ + + + + + + Set Portal Password - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + + + +
+
+

Create Your Portal Password

+

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-dropdown-fix-20260322-182243/site_nav.html b/backups/portal-dropdown-fix-20260322-182243/site_nav.html new file mode 100644 index 0000000..3421246 --- /dev/null +++ b/backups/portal-dropdown-fix-20260322-182243/site_nav.html @@ -0,0 +1,21 @@ +
+ +
diff --git a/backups/portal-dropdown-fix-20260322-182243/style.css b/backups/portal-dropdown-fix-20260322-182243/style.css new file mode 100644 index 0000000..6fbb5ad --- /dev/null +++ b/backups/portal-dropdown-fix-20260322-182243/style.css @@ -0,0 +1,699 @@ +:root{ + --bg:#0b0f14; + --card:#121825; + --card-soft:rgba(18,24,37,.78); + --text:#e8eefc; + --muted:#aab6d6; + --line:#24304a; + --accent:#7aa2ff; + --accent2:#62e6b7; + --success:#4ade80; + --warn:#fbbf24; + --danger:#f87171; + --radius:16px; + --shadow:0 16px 40px rgba(0,0,0,.35); +} + +*{box-sizing:border-box} +html,body{height:100%} + +body{ + margin:0; + font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, "Apple Color Emoji","Segoe UI Emoji"; + background: + radial-gradient(1200px 600px at 20% 0%, rgba(122,162,255,.22), transparent 60%), + radial-gradient(900px 500px at 90% 20%, rgba(98,230,183,.15), transparent 60%), + linear-gradient(180deg, #081225 0%, #09172d 100%); + color:var(--text); + line-height:1.45; +} + +a{color:inherit} + +/* ===== Shared container ===== */ +.container{ + max-width:1100px; + margin:0 auto; + padding:20px 18px; +} + +/* ===== Header / branded nav ===== */ +.header{width:100%} + +.nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + padding:12px 0 22px 0; +} + +.brand{ + display:flex; + align-items:center; + gap:14px; + text-decoration:none; +} + +.brand img{ + height:60px; + width:auto; + display:block; + object-fit:contain; + background: rgba(255,255,255,0.92); + padding: 6px 12px; + border-radius: 999px; + box-shadow: 0 8px 24px rgba(0,0,0,0.35); +} + +.title{ + display:flex; + flex-direction:column; + line-height:1.1; +} + +.title strong{letter-spacing:.2px} +.title span{ + color:var(--muted); + font-size:13px; + margin-top:2px; +} + +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; +} + +.navlinks a{ + text-decoration:none; + padding:8px 10px; + border-radius:12px; + color:var(--muted); + border:1px solid transparent; +} + +.navlinks a:hover{ + color:var(--text); + border-color:rgba(255,255,255,.08); + background:rgba(255,255,255,.03); +} + +.navlinks a.active{ + color:var(--text); + border-color:rgba(255,255,255,.10); + background:rgba(255,255,255,.04); +} + +/* ===== Generic portal shell ===== */ +.portal-shell{ + max-width:1100px; + margin:16px auto 28px auto; + padding:0 18px 20px 18px; +} + +.portal-card, +.detail-card, +.summary-card, +.pay-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); +} + +.portal-card{ + max-width:760px; + margin:24px auto 12px auto; + padding:22px; +} + +.portal-page-header{ + display:flex; + align-items:flex-start; + justify-content:space-between; + gap:16px; + flex-wrap:wrap; + margin:6px 0 18px 0; +} + +.portal-page-title{ + margin:0; + font-size:24px; + line-height:1.1; +} + +.portal-page-subtitle{ + margin:8px 0 0 0; + color:var(--muted); +} + +.portal-client-name{ + margin:8px 0 0 0; + color:var(--text); + font-size:15px; +} + +.portal-toolbar{ + display:flex; + gap:10px; + flex-wrap:wrap; + align-items:center; +} + +.portal-btn, +.btn, +.pay-btn, +.quote-pick-btn{ + display:inline-flex; + align-items:center; + justify-content:center; + gap:8px; + min-height:42px; + padding:10px 14px; + border-radius:12px; + text-decoration:none; + border:1px solid rgba(255,255,255,.10); + background: rgba(255,255,255,.05); + color:var(--text); + font-weight:600; + cursor:pointer; +} + +.portal-btn:hover, +.btn:hover, +.pay-btn:hover, +.quote-pick-btn:hover{ + border-color:rgba(122,162,255,.45); + box-shadow:0 0 0 4px rgba(122,162,255,.12); + text-decoration:none; +} + +.portal-btn.primary, +.btn.primary{ + background: linear-gradient(135deg, rgba(122,162,255,.95), rgba(98,230,183,.85)); + border-color: transparent; + color:#071017; + font-weight:700; +} + +.portal-btn.primary:hover, +.btn.primary:hover{ + box-shadow:0 0 0 4px rgba(98,230,183,.18); +} + +/* ===== Login / forms ===== */ +.portal-sub{ + color:var(--muted); + margin:0 0 16px 0; +} + +.portal-form{ + display:grid; + gap:14px; +} + +.portal-form label{ + display:block; + font-weight:600; + margin-bottom:6px; +} + +.portal-form input, +.portal-form select, +.pay-selector{ + width:100%; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.14); + background: rgba(255,255,255,.06); + color:var(--text); + box-sizing:border-box; + outline:none; +} + +.portal-form input:focus, +.portal-form select:focus, +.pay-selector:focus{ + border-color:rgba(122,162,255,.65); + box-shadow:0 0 0 4px rgba(122,162,255,.12); +} + +.portal-actions{ + display:flex; + gap:10px; + flex-wrap:wrap; + margin-top:4px; +} + +.portal-note{ + margin-top:16px; + color:var(--muted); + font-size:14px; + line-height:1.5; +} + +.portal-msg, +.error-box, +.success-box{ + margin-bottom:16px; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.16); + background: rgba(255,255,255,.04); +} + +.error-box{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); + color: #fecaca; +} + +.success-box{ + border-color: rgba(34, 197, 94, 0.55); + background: rgba(22, 101, 52, 0.18); + color: #dcfce7; +} + +/* ===== Dashboard ===== */ +.portal-wrap{ + max-width:1100px; + margin:0 auto; + padding:0; +} + +.summary-grid, +.detail-grid{ + display:grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap:14px; + margin: 0 0 18px 0; +} + +.summary-card, +.detail-card{ + padding:18px; +} + +.summary-card h3, +.detail-card h3{ + margin:0 0 8px 0; + font-size:14px; + color:var(--muted); +} + +.summary-card .summary-value, +.detail-card .detail-value{ + font-size:28px; + font-weight:800; + line-height:1.1; + color:var(--text); +} + +.summary-card .summary-sub{ + margin-top:6px; + font-size:12px; + color:var(--muted); +} + +.section-title{ + margin:18px 0 10px 0; + font-size:22px; +} + +.table-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); + overflow:hidden; +} + +/* ===== Tables ===== */ +table, +.portal-table, +.quote-table{ + width:100%; + border-collapse: collapse; +} + +table.portal-table th, +table.portal-table td, +.quote-table th, +.quote-table td{ + padding: 0.9rem 0.85rem; + border-bottom: 1px solid rgba(255,255,255,0.10); + text-align: left; + vertical-align: middle; +} + +table.portal-table th, +.quote-table th{ + background: rgba(255,255,255,.06); + color: var(--text); + font-size:13px; + letter-spacing:.02em; +} + +table.portal-table tr:hover td, +.quote-table tr:hover td{ + background: rgba(255,255,255,.02); +} + +.invoice-link{ + color: var(--text); + text-decoration: none; + font-weight: 700; +} + +.invoice-link:hover{ + color: var(--accent); + text-decoration: underline; +} + +/* ===== Badges ===== */ +.status-badge, +.quote-badge{ + display: inline-block; + padding: 0.22rem 0.62rem; + border-radius: 999px; + font-size: 0.82rem; + font-weight: 700; +} + +.status-paid{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.status-pending{ background: rgba(245, 158, 11, 0.20); color: var(--warn); } +.status-overdue{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } +.status-other{ background: rgba(148, 163, 184, 0.20); color: #cbd5e1; } + +.quote-live{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.quote-stale{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } + +/* ===== Payments / invoice detail ===== */ +.pay-card{ + padding:18px; + margin-top: 1.25rem; +} + +.pay-selector-row{ + display:flex; + gap:0.75rem; + align-items:center; + flex-wrap:wrap; + margin-top:0.75rem; +} + +.pay-panel{ + margin-top: 1rem; + padding: 1rem; + border: 1px solid rgba(255,255,255,0.12); + border-radius: 12px; + background: rgba(255,255,255,0.02); +} + +.pay-panel.hidden{ display:none; } + +.pay-btn-square { background:#16a34a; border-color:transparent; color:#fff; } +.pay-btn-wallet { background:#2563eb; border-color:transparent; color:#fff; } +.pay-btn-mobile { background:#7c3aed; border-color:transparent; color:#fff; } +.pay-btn-copy { background:#374151; border-color:transparent; color:#fff; } + +.snapshot-wrap{ + position: relative; + margin-top: 1rem; + border: 1px solid rgba(255,255,255,0.14); + border-radius: 14px; + padding: 1rem; + background: rgba(255,255,255,0.02); +} + +.snapshot-header{ + display:flex; + justify-content:space-between; + gap:1rem; + align-items:flex-start; +} + +.snapshot-meta{ + flex: 1 1 auto; + min-width: 0; + line-height: 1.65; +} + +.snapshot-timer-box{ + width: 220px; + min-height: 132px; + border: 1px solid rgba(255,255,255,0.16); + border-radius: 14px; + background: rgba(0,0,0,0.18); + display:flex; + flex-direction:column; + justify-content:center; + align-items:center; + text-align:center; + padding: 0.9rem; +} + +.snapshot-timer-value{ + font-size: 2rem; + font-weight: 800; + line-height: 1.1; +} + +.snapshot-timer-label{ + margin-top: 0.55rem; + font-size: 0.95rem; + opacity: 0.95; +} + +.snapshot-timer-expired{ color: var(--danger); } + +.lock-box{ + margin-top: 1rem; + border: 1px solid rgba(34, 197, 94, 0.28); + background: rgba(22, 101, 52, 0.16); + border-radius: 12px; + padding: 1rem; +} + +.lock-box.expired{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); +} + +.lock-grid{ + display:grid; + grid-template-columns: 1fr 220px; + gap:1rem; + align-items:start; +} + +.lock-code{ + display:block; + margin-top:0.35rem; + padding:0.65rem 0.8rem; + background: rgba(0,0,0,0.22); + border-radius: 8px; + overflow-wrap:anywhere; +} + +.wallet-actions{ + display:flex; + gap:0.75rem; + flex-wrap:wrap; + margin-top:0.9rem; + align-items:center; +} + +.wallet-help{ + margin-top: 0.85rem; + padding: 0.9rem 1rem; + border-radius: 10px; + background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.10); +} + +.wallet-help h4{ + margin: 0 0 0.55rem 0; + font-size: 1rem; +} + +.wallet-help p{ margin: 0.35rem 0; } +.wallet-note{ opacity:0.9; margin-top:0.65rem; } +.mono{ font-family: monospace; } + +.copy-row{ + display:flex; + gap:0.5rem; + flex-wrap:wrap; + align-items:center; + margin-top:0.65rem; +} + +.copy-target{ + flex: 1 1 420px; + min-width: 220px; +} + +.copy-status{ + display:inline-block; + margin-left: 0.5rem; + opacity: 0.9; +} + +/* ===== Footer ===== */ +footer{ + margin:28px auto 20px auto; + max-width:1100px; + padding:0 18px; + color:var(--muted); + font-size:13px; +} + +/* ===== Responsive ===== */ +@media (max-width: 900px){ + .summary-grid, + .detail-grid{ + grid-template-columns:1fr; + } + + .nav{ + align-items:flex-start; + flex-direction:column; + } + + .navlinks{ + justify-content:flex-start; + } + + .brand img{ + height:54px; + } +} + +@media (max-width: 820px){ + .snapshot-header, + .lock-grid{ + grid-template-columns: 1fr; + display:block; + } + + .snapshot-timer-box{ + width: 100%; + margin-top: 1rem; + min-height: 110px; + } +} + + +/* ===== Fixed CAD / Oracle status bar ===== */ +body{ + padding-bottom: 56px; +} + +.otb-statusbar{ + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 9999; + display: flex; + align-items: center; + justify-content: center; + min-height: 42px; + padding: 8px 14px; + background: rgba(8, 16, 32, 0.94); + border-top: 1px solid rgba(255,255,255,.10); + backdrop-filter: blur(8px); + box-shadow: 0 -8px 24px rgba(0,0,0,.28); +} + +.otb-statusbar-inner{ + width: 100%; + max-width: 1100px; + display: flex; + gap: 10px; + align-items: center; + justify-content: center; + flex-wrap: wrap; + text-align: center; + color: var(--muted); + font-size: 12px; + line-height: 1.35; +} + +.otb-statusbar strong{ + color: var(--text); + font-weight: 700; +} + +.otb-statusbar a{ + color: var(--accent2); + text-decoration: none; + font-weight: 600; +} + +.otb-statusbar a:hover{ + text-decoration: underline; +} + +.otb-dot{ + width: 6px; + height: 6px; + border-radius: 999px; + display: inline-block; + background: rgba(255,255,255,.25); + flex: 0 0 auto; +} + +/* ===== Payment method chips ===== */ +.payment-method{ + display: inline-flex; + align-items: center; + gap: 7px; + margin-top: 7px; + padding: 4px 9px; + border-radius: 999px; + background: rgba(255,255,255,.05); + border: 1px solid rgba(255,255,255,.08); + color: var(--muted); + font-size: 11px; + font-weight: 700; + letter-spacing: .01em; +} + +.payment-method::before{ + content: ""; + width: 8px; + height: 8px; + border-radius: 999px; + display: inline-block; + background: #7aa2ff; + box-shadow: 0 0 0 3px rgba(255,255,255,.04); +} + +.payment-square::before{ background: #7dd3fc; } +.payment-etransfer::before{ background: #86efac; } +.payment-etho::before{ background: #b084ff; } +.payment-etica::before{ background: #4fd1c5; } +.payment-alt::before{ background: #fbbf24; } +.payment-cad::before{ background: #cbd5e1; } + +/* ===== Slightly stronger row hover ===== */ +table.portal-table tbody tr:hover td, +.quote-table tbody tr:hover td{ + background: rgba(255,255,255,.035); + transition: background .14s ease; +} + +@media (max-width: 700px){ + body{ + padding-bottom: 72px; + } + + .otb-statusbar-inner{ + font-size: 11px; + line-height: 1.25; + } +} diff --git a/backups/portal-dropdown-fix-20260322-182803/site_nav.html b/backups/portal-dropdown-fix-20260322-182803/site_nav.html new file mode 100644 index 0000000..33992fb --- /dev/null +++ b/backups/portal-dropdown-fix-20260322-182803/site_nav.html @@ -0,0 +1,28 @@ +
+ +
diff --git a/backups/portal-dropdown-fix-20260322-182803/style.css b/backups/portal-dropdown-fix-20260322-182803/style.css new file mode 100644 index 0000000..dc9c5f7 --- /dev/null +++ b/backups/portal-dropdown-fix-20260322-182803/style.css @@ -0,0 +1,775 @@ +:root{ + --bg:#0b0f14; + --card:#121825; + --card-soft:rgba(18,24,37,.78); + --text:#e8eefc; + --muted:#aab6d6; + --line:#24304a; + --accent:#7aa2ff; + --accent2:#62e6b7; + --success:#4ade80; + --warn:#fbbf24; + --danger:#f87171; + --radius:16px; + --shadow:0 16px 40px rgba(0,0,0,.35); +} + +*{box-sizing:border-box} +html,body{height:100%} + +body{ + margin:0; + font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, "Apple Color Emoji","Segoe UI Emoji"; + background: + radial-gradient(1200px 600px at 20% 0%, rgba(122,162,255,.22), transparent 60%), + radial-gradient(900px 500px at 90% 20%, rgba(98,230,183,.15), transparent 60%), + linear-gradient(180deg, #081225 0%, #09172d 100%); + color:var(--text); + line-height:1.45; +} + +a{color:inherit} + +/* ===== Shared container ===== */ +.container{ + max-width:1100px; + margin:0 auto; + padding:20px 18px; +} + +/* ===== Header / branded nav ===== */ +.header{width:100%} + +.nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + padding:12px 0 22px 0; +} + +.brand{ + display:flex; + align-items:center; + gap:14px; + text-decoration:none; +} + +.brand img{ + height:60px; + width:auto; + display:block; + object-fit:contain; + background: rgba(255,255,255,0.92); + padding: 6px 12px; + border-radius: 999px; + box-shadow: 0 8px 24px rgba(0,0,0,0.35); +} + +.title{ + display:flex; + flex-direction:column; + line-height:1.1; +} + +.title strong{letter-spacing:.2px} +.title span{ + color:var(--muted); + font-size:13px; + margin-top:2px; +} + +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; +} + +.navlinks a{ + text-decoration:none; + padding:8px 10px; + border-radius:12px; + color:var(--muted); + border:1px solid transparent; +} + +.navlinks a:hover{ + color:var(--text); + border-color:rgba(255,255,255,.08); + background:rgba(255,255,255,.03); +} + +.navlinks a.active{ + color:var(--text); + border-color:rgba(255,255,255,.10); + background:rgba(255,255,255,.04); +} + +/* ===== Generic portal shell ===== */ +.portal-shell{ + max-width:1100px; + margin:16px auto 28px auto; + padding:0 18px 20px 18px; +} + +.portal-card, +.detail-card, +.summary-card, +.pay-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); +} + +.portal-card{ + max-width:760px; + margin:24px auto 12px auto; + padding:22px; +} + +.portal-page-header{ + display:flex; + align-items:flex-start; + justify-content:space-between; + gap:16px; + flex-wrap:wrap; + margin:6px 0 18px 0; +} + +.portal-page-title{ + margin:0; + font-size:24px; + line-height:1.1; +} + +.portal-page-subtitle{ + margin:8px 0 0 0; + color:var(--muted); +} + +.portal-client-name{ + margin:8px 0 0 0; + color:var(--text); + font-size:15px; +} + +.portal-toolbar{ + display:flex; + gap:10px; + flex-wrap:wrap; + align-items:center; +} + +.portal-btn, +.btn, +.pay-btn, +.quote-pick-btn{ + display:inline-flex; + align-items:center; + justify-content:center; + gap:8px; + min-height:42px; + padding:10px 14px; + border-radius:12px; + text-decoration:none; + border:1px solid rgba(255,255,255,.10); + background: rgba(255,255,255,.05); + color:var(--text); + font-weight:600; + cursor:pointer; +} + +.portal-btn:hover, +.btn:hover, +.pay-btn:hover, +.quote-pick-btn:hover{ + border-color:rgba(122,162,255,.45); + box-shadow:0 0 0 4px rgba(122,162,255,.12); + text-decoration:none; +} + +.portal-btn.primary, +.btn.primary{ + background: linear-gradient(135deg, rgba(122,162,255,.95), rgba(98,230,183,.85)); + border-color: transparent; + color:#071017; + font-weight:700; +} + +.portal-btn.primary:hover, +.btn.primary:hover{ + box-shadow:0 0 0 4px rgba(98,230,183,.18); +} + +/* ===== Login / forms ===== */ +.portal-sub{ + color:var(--muted); + margin:0 0 16px 0; +} + +.portal-form{ + display:grid; + gap:14px; +} + +.portal-form label{ + display:block; + font-weight:600; + margin-bottom:6px; +} + +.portal-form input, +.portal-form select, +.pay-selector{ + width:100%; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.14); + background: rgba(255,255,255,.06); + color:var(--text); + box-sizing:border-box; + outline:none; +} + +.portal-form input:focus, +.portal-form select:focus, +.pay-selector:focus{ + border-color:rgba(122,162,255,.65); + box-shadow:0 0 0 4px rgba(122,162,255,.12); +} + +.portal-actions{ + display:flex; + gap:10px; + flex-wrap:wrap; + margin-top:4px; +} + +.portal-note{ + margin-top:16px; + color:var(--muted); + font-size:14px; + line-height:1.5; +} + +.portal-msg, +.error-box, +.success-box{ + margin-bottom:16px; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.16); + background: rgba(255,255,255,.04); +} + +.error-box{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); + color: #fecaca; +} + +.success-box{ + border-color: rgba(34, 197, 94, 0.55); + background: rgba(22, 101, 52, 0.18); + color: #dcfce7; +} + +/* ===== Dashboard ===== */ +.portal-wrap{ + max-width:1100px; + margin:0 auto; + padding:0; +} + +.summary-grid, +.detail-grid{ + display:grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap:14px; + margin: 0 0 18px 0; +} + +.summary-card, +.detail-card{ + padding:18px; +} + +.summary-card h3, +.detail-card h3{ + margin:0 0 8px 0; + font-size:14px; + color:var(--muted); +} + +.summary-card .summary-value, +.detail-card .detail-value{ + font-size:28px; + font-weight:800; + line-height:1.1; + color:var(--text); +} + +.summary-card .summary-sub{ + margin-top:6px; + font-size:12px; + color:var(--muted); +} + +.section-title{ + margin:18px 0 10px 0; + font-size:22px; +} + +.table-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); + overflow:hidden; +} + +/* ===== Tables ===== */ +table, +.portal-table, +.quote-table{ + width:100%; + border-collapse: collapse; +} + +table.portal-table th, +table.portal-table td, +.quote-table th, +.quote-table td{ + padding: 0.9rem 0.85rem; + border-bottom: 1px solid rgba(255,255,255,0.10); + text-align: left; + vertical-align: middle; +} + +table.portal-table th, +.quote-table th{ + background: rgba(255,255,255,.06); + color: var(--text); + font-size:13px; + letter-spacing:.02em; +} + +table.portal-table tr:hover td, +.quote-table tr:hover td{ + background: rgba(255,255,255,.02); +} + +.invoice-link{ + color: var(--text); + text-decoration: none; + font-weight: 700; +} + +.invoice-link:hover{ + color: var(--accent); + text-decoration: underline; +} + +/* ===== Badges ===== */ +.status-badge, +.quote-badge{ + display: inline-block; + padding: 0.22rem 0.62rem; + border-radius: 999px; + font-size: 0.82rem; + font-weight: 700; +} + +.status-paid{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.status-pending{ background: rgba(245, 158, 11, 0.20); color: var(--warn); } +.status-overdue{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } +.status-other{ background: rgba(148, 163, 184, 0.20); color: #cbd5e1; } + +.quote-live{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.quote-stale{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } + +/* ===== Payments / invoice detail ===== */ +.pay-card{ + padding:18px; + margin-top: 1.25rem; +} + +.pay-selector-row{ + display:flex; + gap:0.75rem; + align-items:center; + flex-wrap:wrap; + margin-top:0.75rem; +} + +.pay-panel{ + margin-top: 1rem; + padding: 1rem; + border: 1px solid rgba(255,255,255,0.12); + border-radius: 12px; + background: rgba(255,255,255,0.02); +} + +.pay-panel.hidden{ display:none; } + +.pay-btn-square { background:#16a34a; border-color:transparent; color:#fff; } +.pay-btn-wallet { background:#2563eb; border-color:transparent; color:#fff; } +.pay-btn-mobile { background:#7c3aed; border-color:transparent; color:#fff; } +.pay-btn-copy { background:#374151; border-color:transparent; color:#fff; } + +.snapshot-wrap{ + position: relative; + margin-top: 1rem; + border: 1px solid rgba(255,255,255,0.14); + border-radius: 14px; + padding: 1rem; + background: rgba(255,255,255,0.02); +} + +.snapshot-header{ + display:flex; + justify-content:space-between; + gap:1rem; + align-items:flex-start; +} + +.snapshot-meta{ + flex: 1 1 auto; + min-width: 0; + line-height: 1.65; +} + +.snapshot-timer-box{ + width: 220px; + min-height: 132px; + border: 1px solid rgba(255,255,255,0.16); + border-radius: 14px; + background: rgba(0,0,0,0.18); + display:flex; + flex-direction:column; + justify-content:center; + align-items:center; + text-align:center; + padding: 0.9rem; +} + +.snapshot-timer-value{ + font-size: 2rem; + font-weight: 800; + line-height: 1.1; +} + +.snapshot-timer-label{ + margin-top: 0.55rem; + font-size: 0.95rem; + opacity: 0.95; +} + +.snapshot-timer-expired{ color: var(--danger); } + +.lock-box{ + margin-top: 1rem; + border: 1px solid rgba(34, 197, 94, 0.28); + background: rgba(22, 101, 52, 0.16); + border-radius: 12px; + padding: 1rem; +} + +.lock-box.expired{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); +} + +.lock-grid{ + display:grid; + grid-template-columns: 1fr 220px; + gap:1rem; + align-items:start; +} + +.lock-code{ + display:block; + margin-top:0.35rem; + padding:0.65rem 0.8rem; + background: rgba(0,0,0,0.22); + border-radius: 8px; + overflow-wrap:anywhere; +} + +.wallet-actions{ + display:flex; + gap:0.75rem; + flex-wrap:wrap; + margin-top:0.9rem; + align-items:center; +} + +.wallet-help{ + margin-top: 0.85rem; + padding: 0.9rem 1rem; + border-radius: 10px; + background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.10); +} + +.wallet-help h4{ + margin: 0 0 0.55rem 0; + font-size: 1rem; +} + +.wallet-help p{ margin: 0.35rem 0; } +.wallet-note{ opacity:0.9; margin-top:0.65rem; } +.mono{ font-family: monospace; } + +.copy-row{ + display:flex; + gap:0.5rem; + flex-wrap:wrap; + align-items:center; + margin-top:0.65rem; +} + +.copy-target{ + flex: 1 1 420px; + min-width: 220px; +} + +.copy-status{ + display:inline-block; + margin-left: 0.5rem; + opacity: 0.9; +} + +/* ===== Footer ===== */ +footer{ + margin:28px auto 20px auto; + max-width:1100px; + padding:0 18px; + color:var(--muted); + font-size:13px; +} + +/* ===== Responsive ===== */ +@media (max-width: 900px){ + .summary-grid, + .detail-grid{ + grid-template-columns:1fr; + } + + .nav{ + align-items:flex-start; + flex-direction:column; + } + + .navlinks{ + justify-content:flex-start; + } + + .brand img{ + height:54px; + } +} + +@media (max-width: 820px){ + .snapshot-header, + .lock-grid{ + grid-template-columns: 1fr; + display:block; + } + + .snapshot-timer-box{ + width: 100%; + margin-top: 1rem; + min-height: 110px; + } +} + + +/* ===== Fixed CAD / Oracle status bar ===== */ +body{ + padding-bottom: 56px; +} + +.otb-statusbar{ + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 9999; + display: flex; + align-items: center; + justify-content: center; + min-height: 42px; + padding: 8px 14px; + background: rgba(8, 16, 32, 0.94); + border-top: 1px solid rgba(255,255,255,.10); + backdrop-filter: blur(8px); + box-shadow: 0 -8px 24px rgba(0,0,0,.28); +} + +.otb-statusbar-inner{ + width: 100%; + max-width: 1100px; + display: flex; + gap: 10px; + align-items: center; + justify-content: center; + flex-wrap: wrap; + text-align: center; + color: var(--muted); + font-size: 12px; + line-height: 1.35; +} + +.otb-statusbar strong{ + color: var(--text); + font-weight: 700; +} + +.otb-statusbar a{ + color: var(--accent2); + text-decoration: none; + font-weight: 600; +} + +.otb-statusbar a:hover{ + text-decoration: underline; +} + +.otb-dot{ + width: 6px; + height: 6px; + border-radius: 999px; + display: inline-block; + background: rgba(255,255,255,.25); + flex: 0 0 auto; +} + +/* ===== Payment method chips ===== */ +.payment-method{ + display: inline-flex; + align-items: center; + gap: 7px; + margin-top: 7px; + padding: 4px 9px; + border-radius: 999px; + background: rgba(255,255,255,.05); + border: 1px solid rgba(255,255,255,.08); + color: var(--muted); + font-size: 11px; + font-weight: 700; + letter-spacing: .01em; +} + +.payment-method::before{ + content: ""; + width: 8px; + height: 8px; + border-radius: 999px; + display: inline-block; + background: #7aa2ff; + box-shadow: 0 0 0 3px rgba(255,255,255,.04); +} + +.payment-square::before{ background: #7dd3fc; } +.payment-etransfer::before{ background: #86efac; } +.payment-etho::before{ background: #b084ff; } +.payment-etica::before{ background: #4fd1c5; } +.payment-alt::before{ background: #fbbf24; } +.payment-cad::before{ background: #cbd5e1; } + +/* ===== Slightly stronger row hover ===== */ +table.portal-table tbody tr:hover td, +.quote-table tbody tr:hover td{ + background: rgba(255,255,255,.035); + transition: background .14s ease; +} + +@media (max-width: 700px){ + body{ + padding-bottom: 72px; + } + + .otb-statusbar-inner{ + font-size: 11px; + line-height: 1.25; + } +} + + +/* ===== Shared services dropdown ===== */ +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; + align-items:center; +} + +.dropdown{ + position:relative; + display:inline-block; +} + +.dropdown-toggle{ + display:inline-block; + cursor:pointer; +} + +.dropdown-menu{ + position:absolute; + top:calc(100% + 8px); + right:0; + min-width:220px; + display:none; + padding:10px; + border-radius:14px; + background:rgba(18,24,37,.98); + border:1px solid rgba(255,255,255,.08); + box-shadow:0 16px 40px rgba(0,0,0,.35); + z-index:9999; +} + +.dropdown:hover .dropdown-menu, +.dropdown:focus-within .dropdown-menu{ + display:block; +} + +.dropdown-menu a{ + display:block; + padding:9px 10px; + border-radius:10px; + color:var(--muted); + text-decoration:none; + white-space:nowrap; + margin:0; +} + +.dropdown-menu a + a{ + margin-top:4px; +} + +.dropdown-menu a:hover{ + color:var(--text); + background:rgba(255,255,255,.04); +} + +@media (max-width: 900px){ + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } +} diff --git a/backups/portal-links-20260322-033024/portal_dashboard.html b/backups/portal-links-20260322-033024/portal_dashboard.html new file mode 100644 index 0000000..84bf0c3 --- /dev/null +++ b/backups/portal-links-20260322-033024/portal_dashboard.html @@ -0,0 +1,168 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + +
+ +
+ +
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
+
+

Total Outstanding

+
{{ total_outstanding }}
+
+
+

Total Paid

+
{{ total_paid }}
+
+
+ +

Invoices

+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} + {{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+ + + + +{% include "footer.html" %} + + diff --git a/backups/portal-links-20260322-033024/portal_forgot_password.html b/backups/portal-links-20260322-033024/portal_forgot_password.html new file mode 100644 index 0000000..dd96948 --- /dev/null +++ b/backups/portal-links-20260322-033024/portal_forgot_password.html @@ -0,0 +1,88 @@ + + + + + + Forgot Portal Password - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + +
+ +
+ +
+
+

Reset Portal Password

+

Enter your email address and a new single-use access code will be sent if your account exists.

+ + {% if error %} +
{{ error }}
+ {% endif %} + + {% if message %} +
{{ message }}
+ {% endif %} + +
+
+ + +
+ +
+ + Back to Portal Login + Contact Support +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-links-20260322-033024/portal_invoice_detail.html b/backups/portal-links-20260322-033024/portal_invoice_detail.html new file mode 100644 index 0000000..54b4dcf --- /dev/null +++ b/backups/portal-links-20260322-033024/portal_invoice_detail.html @@ -0,0 +1,733 @@ + + + + + + Invoice Detail - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + +
+ +
+ +
+
+
+

Invoice Detail

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ + {% if (invoice.status or "")|lower == "paid" %} +
βœ“ This invoice has been paid. Thank you!
+ {% endif %} + + {% if crypto_error %} +
{{ crypto_error }}
+ {% endif %} + +
+

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}
+
+

Status

+ {% set s = (invoice.status or "")|lower %} + {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} + processing + {% elif s == "paid" %}{{ invoice.status }} + {% elif s == "pending" %}{{ invoice.status }} + {% elif s == "overdue" %}{{ invoice.status }} + {% else %}{{ invoice.status }}{% endif %} +
+

Created

{{ invoice.created_at }}
+

Total

{{ invoice.total_amount }}
+

Paid

{{ invoice.amount_paid }}
+

Outstanding

{{ invoice.outstanding }}
+
+ +

Invoice Items

+ + + + {% for item in items %} + + {% else %} + + {% endfor %} + +
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
+ + {% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %} +
+

Pay Now

+
+ + +
+ +
+

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

+
+ +
+

Credit Card (Square)

+ Pay with Credit Card +
+ +
+ {% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %} +
+
+
+

Crypto Quote Snapshot

+
Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
+
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
+
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
+ {% if pending_crypto_payment %} +
Your quote is protected after acceptance.
+ {% else %} +
Select a crypto asset to accept the quote.
+ {% endif %} +
+ + {% if pending_crypto_payment and pending_crypto_payment.txid %} +
+
--:--
+
Watching transaction / waiting for confirmation
+
+ {% elif pending_crypto_payment %} +
+
--:--
+
Quote protected while you open wallet
+
+ {% else %} +
+
--:--
+
This price times out:
+
+ {% endif %} +
+ + {% if pending_crypto_payment and selected_crypto_option %} +
+
+
+

{{ selected_crypto_option.label }} Payment Instructions

+
Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
+
Destination wallet:
+ {{ pending_crypto_payment.wallet_address }} +
Reference / Invoice:
+ {{ pending_crypto_payment.reference }} + + {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %} +
+ + + + Open in MetaMask Mobile + + + +
+ +
+

Fastest way to pay

+

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

+

2. If that does not open your wallet, click Open in MetaMask Mobile.

+

3. If needed, use Copy Payment Details and send manually.

+
+ +
+ You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet. +
+ +
+ + +
+ + {% elif pending_crypto_payment.txid %} +
Transaction Hash:
+ {{ pending_crypto_payment.txid }} +
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
+ {% elif pending_crypto_payment.lock_expired %} +
price has expired - please refresh your quote to update
+ {% endif %} +
+ + +
+
+ {% else %} +
+ + + + {% for q in crypto_options %} + + + + + + + + {% endfor %} + +
AssetQuoted AmountCAD PriceStatusAction
+ {{ q.label }} + {% if q.recommended %}recommended{% endif %} + {% if q.wallet_capable %}wallet{% endif %} + {{ q.display_amount or "β€”" }}{% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %}{% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
+
+ {% endif %} +
+ {% else %} +

No crypto quote snapshot is available for this invoice yet.

+ {% endif %} +
+
+ {% endif %} + + {% if invoice_payments %} +
+

Payments Applied

+ + + + + + + + + + + + {% for p in invoice_payments %} + + + + + + + + {% endfor %} + +
MethodAmountStatusReceivedReference / TXID
{{ p.payment_method_label }}{{ p.payment_amount_display }} {{ p.payment_currency }}{{ p.payment_status }}{{ p.received_at_local }} + {% if p.txid %} + {{ p.txid }} + {% elif p.reference %} + {{ p.reference }} + {% else %} + - + {% endif %} + {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %} +
+
+ {% endif %} + + {% if pdf_url %} + + {% endif %} +
+ + + + + + +{% include "footer.html" %} + + diff --git a/backups/portal-links-20260322-033024/portal_login.html b/backups/portal-links-20260322-033024/portal_login.html new file mode 100644 index 0000000..5a01c40 --- /dev/null +++ b/backups/portal-links-20260322-033024/portal_login.html @@ -0,0 +1,102 @@ + + + + + + Client Portal - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + +
+ +
+ +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Home + Contact Support +
+
+ + + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-links-20260322-033024/portal_set_password.html b/backups/portal-links-20260322-033024/portal_set_password.html new file mode 100644 index 0000000..fac0ce3 --- /dev/null +++ b/backups/portal-links-20260322-033024/portal_set_password.html @@ -0,0 +1,82 @@ + + + + + + Set Portal Password - OutsideTheBox + + + + + +{% include "includes/site_nav.html" %} + +
+ +
+ +
+
+

Create Your Portal Password

+

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-nav-20260322-030029/portal_dashboard.html b/backups/portal-nav-20260322-030029/portal_dashboard.html new file mode 100644 index 0000000..a43083e --- /dev/null +++ b/backups/portal-nav-20260322-030029/portal_dashboard.html @@ -0,0 +1,162 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + +
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
+
+

Total Outstanding

+
{{ total_outstanding }}
+
+
+

Total Paid

+
{{ total_paid }}
+
+
+ +

Invoices

+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} + {{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+ + + + +{% include "footer.html" %} + + diff --git a/backups/portal-nav-20260322-030029/portal_forgot_password.html b/backups/portal-nav-20260322-030029/portal_forgot_password.html new file mode 100644 index 0000000..eaa5f11 --- /dev/null +++ b/backups/portal-nav-20260322-030029/portal_forgot_password.html @@ -0,0 +1,82 @@ + + + + + + Forgot Portal Password - OutsideTheBox + + + + + +
+
+

Reset Portal Password

+

Enter your email address and a new single-use access code will be sent if your account exists.

+ + {% if error %} +
{{ error }}
+ {% endif %} + + {% if message %} +
{{ message }}
+ {% endif %} + +
+
+ + +
+ +
+ + Back to Portal Login + Contact Support +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-nav-20260322-030029/portal_invoice_detail.html b/backups/portal-nav-20260322-030029/portal_invoice_detail.html new file mode 100644 index 0000000..811327a --- /dev/null +++ b/backups/portal-nav-20260322-030029/portal_invoice_detail.html @@ -0,0 +1,727 @@ + + + + + + Invoice Detail - OutsideTheBox + + + + + +
+
+
+

Invoice Detail

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ + {% if (invoice.status or "")|lower == "paid" %} +
βœ“ This invoice has been paid. Thank you!
+ {% endif %} + + {% if crypto_error %} +
{{ crypto_error }}
+ {% endif %} + +
+

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}
+
+

Status

+ {% set s = (invoice.status or "")|lower %} + {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} + processing + {% elif s == "paid" %}{{ invoice.status }} + {% elif s == "pending" %}{{ invoice.status }} + {% elif s == "overdue" %}{{ invoice.status }} + {% else %}{{ invoice.status }}{% endif %} +
+

Created

{{ invoice.created_at }}
+

Total

{{ invoice.total_amount }}
+

Paid

{{ invoice.amount_paid }}
+

Outstanding

{{ invoice.outstanding }}
+
+ +

Invoice Items

+ + + + {% for item in items %} + + {% else %} + + {% endfor %} + +
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
+ + {% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %} +
+

Pay Now

+
+ + +
+ +
+

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

+
+ +
+

Credit Card (Square)

+ Pay with Credit Card +
+ +
+ {% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %} +
+
+
+

Crypto Quote Snapshot

+
Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
+
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
+
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
+ {% if pending_crypto_payment %} +
Your quote is protected after acceptance.
+ {% else %} +
Select a crypto asset to accept the quote.
+ {% endif %} +
+ + {% if pending_crypto_payment and pending_crypto_payment.txid %} +
+
--:--
+
Watching transaction / waiting for confirmation
+
+ {% elif pending_crypto_payment %} +
+
--:--
+
Quote protected while you open wallet
+
+ {% else %} +
+
--:--
+
This price times out:
+
+ {% endif %} +
+ + {% if pending_crypto_payment and selected_crypto_option %} +
+
+
+

{{ selected_crypto_option.label }} Payment Instructions

+
Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
+
Destination wallet:
+ {{ pending_crypto_payment.wallet_address }} +
Reference / Invoice:
+ {{ pending_crypto_payment.reference }} + + {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %} +
+ + + + Open in MetaMask Mobile + + + +
+ +
+

Fastest way to pay

+

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

+

2. If that does not open your wallet, click Open in MetaMask Mobile.

+

3. If needed, use Copy Payment Details and send manually.

+
+ +
+ You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet. +
+ +
+ + +
+ + {% elif pending_crypto_payment.txid %} +
Transaction Hash:
+ {{ pending_crypto_payment.txid }} +
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
+ {% elif pending_crypto_payment.lock_expired %} +
price has expired - please refresh your quote to update
+ {% endif %} +
+ + +
+
+ {% else %} +
+ + + + {% for q in crypto_options %} + + + + + + + + {% endfor %} + +
AssetQuoted AmountCAD PriceStatusAction
+ {{ q.label }} + {% if q.recommended %}recommended{% endif %} + {% if q.wallet_capable %}wallet{% endif %} + {{ q.display_amount or "β€”" }}{% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %}{% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
+
+ {% endif %} +
+ {% else %} +

No crypto quote snapshot is available for this invoice yet.

+ {% endif %} +
+
+ {% endif %} + + {% if invoice_payments %} +
+

Payments Applied

+ + + + + + + + + + + + {% for p in invoice_payments %} + + + + + + + + {% endfor %} + +
MethodAmountStatusReceivedReference / TXID
{{ p.payment_method_label }}{{ p.payment_amount_display }} {{ p.payment_currency }}{{ p.payment_status }}{{ p.received_at_local }} + {% if p.txid %} + {{ p.txid }} + {% elif p.reference %} + {{ p.reference }} + {% else %} + - + {% endif %} + {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %} +
+
+ {% endif %} + + {% if pdf_url %} + + {% endif %} +
+ + + + + + +{% include "footer.html" %} + + diff --git a/backups/portal-nav-20260322-030029/portal_login.html b/backups/portal-nav-20260322-030029/portal_login.html new file mode 100644 index 0000000..b6a3e4b --- /dev/null +++ b/backups/portal-nav-20260322-030029/portal_login.html @@ -0,0 +1,96 @@ + + + + + + Client Portal - OutsideTheBox + + + + + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Home + Contact Support +
+
+ + + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-nav-20260322-030029/portal_set_password.html b/backups/portal-nav-20260322-030029/portal_set_password.html new file mode 100644 index 0000000..7d304db --- /dev/null +++ b/backups/portal-nav-20260322-030029/portal_set_password.html @@ -0,0 +1,76 @@ + + + + + + Set Portal Password - OutsideTheBox + + + + + +
+
+

Create Your Portal Password

+

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-navbar-20260322-031219/portal_dashboard.html b/backups/portal-navbar-20260322-031219/portal_dashboard.html new file mode 100644 index 0000000..4e8e2b7 --- /dev/null +++ b/backups/portal-navbar-20260322-031219/portal_dashboard.html @@ -0,0 +1,168 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + + + +
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
+
+

Total Outstanding

+
{{ total_outstanding }}
+
+
+

Total Paid

+
{{ total_paid }}
+
+
+ +

Invoices

+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} + {{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+ + + + +{% include "footer.html" %} + + diff --git a/backups/portal-navbar-20260322-031219/portal_forgot_password.html b/backups/portal-navbar-20260322-031219/portal_forgot_password.html new file mode 100644 index 0000000..8490ef5 --- /dev/null +++ b/backups/portal-navbar-20260322-031219/portal_forgot_password.html @@ -0,0 +1,88 @@ + + + + + + Forgot Portal Password - OutsideTheBox + + + + + + + +
+
+

Reset Portal Password

+

Enter your email address and a new single-use access code will be sent if your account exists.

+ + {% if error %} +
{{ error }}
+ {% endif %} + + {% if message %} +
{{ message }}
+ {% endif %} + +
+
+ + +
+ +
+ + Back to Portal Login + Contact Support +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-navbar-20260322-031219/portal_invoice_detail.html b/backups/portal-navbar-20260322-031219/portal_invoice_detail.html new file mode 100644 index 0000000..cd49918 --- /dev/null +++ b/backups/portal-navbar-20260322-031219/portal_invoice_detail.html @@ -0,0 +1,733 @@ + + + + + + Invoice Detail - OutsideTheBox + + + + + + + +
+
+
+

Invoice Detail

+

{{ client.company_name or client.contact_name or client.email }}

+
+ +
+ + {% if (invoice.status or "")|lower == "paid" %} +
βœ“ This invoice has been paid. Thank you!
+ {% endif %} + + {% if crypto_error %} +
{{ crypto_error }}
+ {% endif %} + +
+

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}
+
+

Status

+ {% set s = (invoice.status or "")|lower %} + {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} + processing + {% elif s == "paid" %}{{ invoice.status }} + {% elif s == "pending" %}{{ invoice.status }} + {% elif s == "overdue" %}{{ invoice.status }} + {% else %}{{ invoice.status }}{% endif %} +
+

Created

{{ invoice.created_at }}
+

Total

{{ invoice.total_amount }}
+

Paid

{{ invoice.amount_paid }}
+

Outstanding

{{ invoice.outstanding }}
+
+ +

Invoice Items

+ + + + {% for item in items %} + + {% else %} + + {% endfor %} + +
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
+ + {% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %} +
+

Pay Now

+
+ + +
+ +
+

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

+
+ +
+

Credit Card (Square)

+ Pay with Credit Card +
+ +
+ {% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %} +
+
+
+

Crypto Quote Snapshot

+
Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
+
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
+
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
+ {% if pending_crypto_payment %} +
Your quote is protected after acceptance.
+ {% else %} +
Select a crypto asset to accept the quote.
+ {% endif %} +
+ + {% if pending_crypto_payment and pending_crypto_payment.txid %} +
+
--:--
+
Watching transaction / waiting for confirmation
+
+ {% elif pending_crypto_payment %} +
+
--:--
+
Quote protected while you open wallet
+
+ {% else %} +
+
--:--
+
This price times out:
+
+ {% endif %} +
+ + {% if pending_crypto_payment and selected_crypto_option %} +
+
+
+

{{ selected_crypto_option.label }} Payment Instructions

+
Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
+
Destination wallet:
+ {{ pending_crypto_payment.wallet_address }} +
Reference / Invoice:
+ {{ pending_crypto_payment.reference }} + + {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %} +
+ + + + Open in MetaMask Mobile + + + +
+ +
+

Fastest way to pay

+

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

+

2. If that does not open your wallet, click Open in MetaMask Mobile.

+

3. If needed, use Copy Payment Details and send manually.

+
+ +
+ You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet. +
+ +
+ + +
+ + {% elif pending_crypto_payment.txid %} +
Transaction Hash:
+ {{ pending_crypto_payment.txid }} +
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
+ {% elif pending_crypto_payment.lock_expired %} +
price has expired - please refresh your quote to update
+ {% endif %} +
+ + +
+
+ {% else %} +
+ + + + {% for q in crypto_options %} + + + + + + + + {% endfor %} + +
AssetQuoted AmountCAD PriceStatusAction
+ {{ q.label }} + {% if q.recommended %}recommended{% endif %} + {% if q.wallet_capable %}wallet{% endif %} + {{ q.display_amount or "β€”" }}{% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %}{% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
+
+ {% endif %} +
+ {% else %} +

No crypto quote snapshot is available for this invoice yet.

+ {% endif %} +
+
+ {% endif %} + + {% if invoice_payments %} +
+

Payments Applied

+ + + + + + + + + + + + {% for p in invoice_payments %} + + + + + + + + {% endfor %} + +
MethodAmountStatusReceivedReference / TXID
{{ p.payment_method_label }}{{ p.payment_amount_display }} {{ p.payment_currency }}{{ p.payment_status }}{{ p.received_at_local }} + {% if p.txid %} + {{ p.txid }} + {% elif p.reference %} + {{ p.reference }} + {% else %} + - + {% endif %} + {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %} +
+
+ {% endif %} + + {% if pdf_url %} + + {% endif %} +
+ + + + + + +{% include "footer.html" %} + + diff --git a/backups/portal-navbar-20260322-031219/portal_login.html b/backups/portal-navbar-20260322-031219/portal_login.html new file mode 100644 index 0000000..9fd14ff --- /dev/null +++ b/backups/portal-navbar-20260322-031219/portal_login.html @@ -0,0 +1,102 @@ + + + + + + Client Portal - OutsideTheBox + + + + + + + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Home + Contact Support +
+
+ + + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-navbar-20260322-031219/portal_set_password.html b/backups/portal-navbar-20260322-031219/portal_set_password.html new file mode 100644 index 0000000..4968db8 --- /dev/null +++ b/backups/portal-navbar-20260322-031219/portal_set_password.html @@ -0,0 +1,82 @@ + + + + + + Set Portal Password - OutsideTheBox + + + + + + + +
+
+

Create Your Portal Password

+

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +{% include "footer.html" %} + + diff --git a/backups/portal-theme-cleanup-20260322-215133/app.py b/backups/portal-theme-cleanup-20260322-215133/app.py new file mode 100644 index 0000000..24b101f --- /dev/null +++ b/backups/portal-theme-cleanup-20260322-215133/app.py @@ -0,0 +1,6392 @@ +import os +from flask import Flask, render_template, request, redirect, send_file, make_response, jsonify, session, Response +from db import get_db_connection +from utils import generate_client_code, generate_service_code +from datetime import datetime, timezone, date, timedelta +from zoneinfo import ZoneInfo +from decimal import Decimal, InvalidOperation +from pathlib import Path +from email.message import EmailMessage +from dateutil.relativedelta import relativedelta + +from io import BytesIO, StringIO +import csv +import json +import hmac +import hashlib +import base64 +import urllib.request +import urllib.error +import urllib.parse +import uuid +import re +import math +import zipfile +import smtplib +import secrets +import threading +import time +from reportlab.lib.pagesizes import letter +from reportlab.pdfgen import canvas +from reportlab.lib.utils import ImageReader +from werkzeug.security import generate_password_hash, check_password_hash +from health import register_health_routes + +app = Flask( + __name__, + template_folder="../templates", + static_folder="../static", +) +app.config["OTB_HEALTH_DB_CONNECTOR"] = get_db_connection + +LOCAL_TZ = ZoneInfo("America/Toronto") + +BASE_DIR = Path(__file__).resolve().parent.parent + +app.secret_key = os.getenv("OTB_BILLING_SECRET_KEY", "otb-billing-dev-secret-change-me") +SQUARE_ACCESS_TOKEN = os.getenv("SQUARE_ACCESS_TOKEN", "") +SQUARE_WEBHOOK_SIGNATURE_KEY = os.getenv("SQUARE_WEBHOOK_SIGNATURE_KEY", "") +SQUARE_WEBHOOK_NOTIFICATION_URL = os.getenv("SQUARE_WEBHOOK_NOTIFICATION_URL", "") +SQUARE_API_BASE = "https://connect.squareup.com" +SQUARE_API_VERSION = "2026-01-22" +SQUARE_WEBHOOK_LOG = str(BASE_DIR / "logs" / "square_webhook_events.log") +ORACLE_BASE_URL = os.getenv("ORACLE_BASE_URL", "https://monitor.outsidethebox.top") +CRYPTO_EVM_PAYMENT_ADDRESS = os.getenv("OTB_BILLING_CRYPTO_EVM_ADDRESS", "0x44f6c44C42e6ae0392E7289F032384C0d37F56D5") +RPC_ETHEREUM_URL = os.getenv("OTB_BILLING_RPC_ETHEREUM", "https://ethereum-rpc.publicnode.com") +RPC_ETHEREUM_URL_2 = os.getenv("OTB_BILLING_RPC_ETHEREUM_2", "https://rpc.ankr.com/eth") +RPC_ETHEREUM_URL_3 = os.getenv("OTB_BILLING_RPC_ETHEREUM_3", "https://eth.drpc.org") + +RPC_ARBITRUM_URL = os.getenv("OTB_BILLING_RPC_ARBITRUM", "https://arbitrum-one-rpc.publicnode.com") +RPC_ARBITRUM_URL_2 = os.getenv("OTB_BILLING_RPC_ARBITRUM_2", "https://rpc.ankr.com/arbitrum") +RPC_ARBITRUM_URL_3 = os.getenv("OTB_BILLING_RPC_ARBITRUM_3", "https://arb1.arbitrum.io/rpc") + +RPC_ETICA_URL = os.getenv("OTB_BILLING_RPC_ETICA", "https://rpc.etica-stats.org") +RPC_ETICA_URL_2 = os.getenv("OTB_BILLING_RPC_ETICA_2", "https://eticamainnet.eticaprotocol.org") +RPC_ETHO_URL = os.getenv("OTB_BILLING_RPC_ETHO", "https://rpc.ethoprotocol.com") +RPC_ETHO_URL_2 = os.getenv("OTB_BILLING_RPC_ETHO_2", "https://rpc4.ethoprotocol.com") + +CRYPTO_PROCESSING_TIMEOUT_SECONDS = int(os.getenv("OTB_BILLING_CRYPTO_PROCESSING_TIMEOUT_SECONDS", "180")) +CRYPTO_WATCH_INTERVAL_SECONDS = int(os.getenv("OTB_BILLING_CRYPTO_WATCH_INTERVAL_SECONDS", "30")) +CRYPTO_WATCHER_STARTED = False + + + + +def load_version(): + try: + with open(BASE_DIR / "VERSION", "r") as f: + return f.read().strip() + except Exception: + return "unknown" + +APP_VERSION = load_version() + +@app.context_processor +def inject_version(): + return {"app_version": APP_VERSION} + +@app.context_processor +def inject_app_settings(): + return {"app_settings": get_app_settings()} + +def fmt_local(dt_value): + if not dt_value: + return "" + if isinstance(dt_value, str): + try: + dt_value = datetime.fromisoformat(dt_value) + except ValueError: + return str(dt_value) + if dt_value.tzinfo is None: + dt_value = dt_value.replace(tzinfo=timezone.utc) + return dt_value.astimezone(LOCAL_TZ).strftime("%Y-%m-%d %I:%M:%S %p") + +def to_decimal(value): + if value is None or value == "": + return Decimal("0") + try: + return Decimal(str(value)) + except (InvalidOperation, ValueError): + return Decimal("0") + +def fmt_money(value, currency_code="CAD"): + amount = to_decimal(value) + if currency_code == "CAD": + return f"{amount:.2f}" + return f"{amount:.8f}" + +def payment_method_label(method, currency=None): + method_key = str(method or "").strip().lower() + currency_key = str(currency or "").strip().upper() + + if method_key == "square": + return "Square" + if method_key == "etransfer": + return "e-Transfer" + if method_key == "cash": + return "Cash" + if method_key == "other": + if currency_key in {"ETH", "ETHO", "ETI", "USDC", "EGAZ", "ALT", "CAD"}: + return currency_key + return "Other" + if method_key == "crypto_etho": + return "ETHO" + if method_key == "crypto_egaz": + return "EGAZ" + if method_key == "crypto_alt": + return "ALT" + + if currency_key in {"ETH", "ETHO", "ETI", "USDC", "EGAZ", "ALT"}: + return currency_key + + return method or "Unknown" + +def get_invoice_payments(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + confirmations, + confirmation_required, + received_at, + created_at, + notes + FROM payments + WHERE invoice_id = %s + ORDER BY COALESCE(received_at, created_at) ASC, id ASC + """, (invoice_id,)) + rows = cursor.fetchall() + conn.close() + + out = [] + for row in rows: + item = dict(row) + item["payment_method_label"] = payment_method_label( + item.get("payment_method"), + item.get("payment_currency"), + ) + item["payment_amount_display"] = fmt_money( + item.get("payment_amount"), + item.get("payment_currency") or "CAD", + ) + item["cad_value_display"] = fmt_money(item.get("cad_value_at_payment"), "CAD") + item["received_at_local"] = fmt_local(item.get("received_at") or item.get("created_at")) + out.append(item) + return out + +def normalize_oracle_datetime(value): + if not value: + return None + try: + text = str(value).replace("Z", "+00:00") + dt = datetime.fromisoformat(text) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return dt.astimezone(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + except Exception: + return None + +def ensure_invoice_quote_columns(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT COLUMN_NAME + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'invoices' + """) + existing = {row["COLUMN_NAME"] for row in cursor.fetchall()} + + wanted = { + "quote_fiat_amount": "ALTER TABLE invoices ADD COLUMN quote_fiat_amount DECIMAL(18,8) DEFAULT NULL AFTER status", + "quote_fiat_currency": "ALTER TABLE invoices ADD COLUMN quote_fiat_currency VARCHAR(16) DEFAULT NULL AFTER quote_fiat_amount", + "quote_expires_at": "ALTER TABLE invoices ADD COLUMN quote_expires_at DATETIME DEFAULT NULL AFTER quote_fiat_currency", + "oracle_snapshot": "ALTER TABLE invoices ADD COLUMN oracle_snapshot LONGTEXT DEFAULT NULL AFTER quote_expires_at" + } + + exec_cursor = conn.cursor() + changed = False + for column_name, ddl in wanted.items(): + if column_name not in existing: + exec_cursor.execute(ddl) + changed = True + + if changed: + conn.commit() + conn.close() + +def fetch_oracle_quote_snapshot(currency_code, total_amount): + if str(currency_code or "").upper() != "CAD": + return None + + try: + amount_value = Decimal(str(total_amount)) + if amount_value <= 0: + return None + except (InvalidOperation, ValueError): + return None + + try: + qs = urllib.parse.urlencode({ + "fiat": "CAD", + "amount": format(amount_value, "f"), + }) + req = urllib.request.Request( + f"{ORACLE_BASE_URL.rstrip('/')}/api/oracle/quote?{qs}", + headers={ + "Accept": "application/json", + "User-Agent": "otb-billing-oracle/0.1" + }, + method="GET" + ) + with urllib.request.urlopen(req, timeout=15) as resp: + data = json.loads(resp.read().decode("utf-8")) + + if not isinstance(data, dict) or not isinstance(data.get("quotes"), list): + return None + + return { + "oracle_url": ORACLE_BASE_URL.rstrip("/"), + "quoted_at": data.get("quoted_at"), + "expires_at": data.get("expires_at"), + "ttl_seconds": data.get("ttl_seconds"), + "source_status": data.get("source_status"), + "fiat": data.get("fiat") or "CAD", + "amount": format(amount_value, "f"), + "quotes": data.get("quotes", []), + } + except Exception: + return None + +def get_invoice_crypto_options(invoice): + oracle_quote = invoice.get("oracle_quote") or {} + raw_quotes = oracle_quote.get("quotes") or [] + + option_map = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "label": "USDC (Arbitrum)", + "payment_currency": "USDC", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "token", + "chain_id": 42161, + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "label": "ETH (Ethereum)", + "payment_currency": "ETH", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "native", + "chain_id": 1, + "decimals": 18, + "token_contract": None, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "label": "ETHO (Etho)", + "payment_currency": "ETHO", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "native", + "chain_id": 1313114, + "decimals": 18, + "token_contract": None, + "rpc_urls": [RPC_ETHO_URL, RPC_ETHO_URL_2], + "chain_add_params": { + "chainId": "0x14095a", + "chainName": "Etho Protocol", + "nativeCurrency": { + "name": "Etho Protocol", + "symbol": "ETHO", + "decimals": 18 + }, + "rpcUrls": [RPC_ETHO_URL, RPC_ETHO_URL_2], + "blockExplorerUrls": ["https://explorer.ethoprotocol.com"] + }, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "label": "ETI (Etica)", + "payment_currency": "ETI", + "wallet_address": CRYPTO_EVM_PAYMENT_ADDRESS, + "wallet_capable": True, + "asset_type": "token", + "chain_id": 61803, + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "rpc_urls": [RPC_ETICA_URL, RPC_ETICA_URL_2], + "chain_add_params": { + "chainId": "0xf16b", + "chainName": "Etica", + "nativeCurrency": { + "name": "Etica Gas", + "symbol": "EGAZ", + "decimals": 18 + }, + "rpcUrls": [RPC_ETICA_URL, RPC_ETICA_URL_2], + "blockExplorerUrls": ["https://explorer.etica-stats.org"] + }, + }, + } + + options = [] + for q in raw_quotes: + symbol = str(q.get("symbol") or "").upper() + if symbol not in option_map: + continue + if not q.get("display_amount"): + continue + + opt = dict(option_map[symbol]) + opt["display_amount"] = q.get("display_amount") + opt["crypto_amount"] = q.get("crypto_amount") + opt["price_cad"] = q.get("price_cad") + opt["recommended"] = bool(q.get("recommended")) + opt["available"] = bool(q.get("available")) + opt["reason"] = q.get("reason") + options.append(opt) + + options.sort(key=lambda x: (0 if x.get("recommended") else 1, x.get("symbol"))) + return options + +def get_rpc_urls_for_chain(chain_name): + chain = str(chain_name or "").lower() + if chain == "ethereum": + return [u for u in [RPC_ETHEREUM_URL, RPC_ETHEREUM_URL_2, RPC_ETHEREUM_URL_3] if u] + if chain == "arbitrum": + return [u for u in [RPC_ARBITRUM_URL, RPC_ARBITRUM_URL_2, RPC_ARBITRUM_URL_3] if u] + if chain == "etica": + return [u for u in [RPC_ETICA_URL, RPC_ETICA_URL_2] if u] + if chain == "etho": + return [u for u in [RPC_ETHO_URL, RPC_ETHO_URL_2] if u] + return [] + +def rpc_call_any(rpc_urls, method, params): + last_error = None + + for rpc_url in rpc_urls: + try: + payload = json.dumps({ + "jsonrpc": "2.0", + "id": 1, + "method": method, + "params": params, + }).encode("utf-8") + + req = urllib.request.Request( + rpc_url, + data=payload, + headers={ + "Content-Type": "application/json", + "Accept": "application/json", + "User-Agent": "otb-billing-rpc/0.1", + }, + method="POST" + ) + + with urllib.request.urlopen(req, timeout=20) as resp: + data = json.loads(resp.read().decode("utf-8")) + + if isinstance(data, dict) and data.get("error"): + raise RuntimeError(str(data["error"])) + + return { + "rpc_url": rpc_url, + "result": (data or {}).get("result"), + } + except Exception as err: + last_error = err + + if last_error: + raise last_error + raise RuntimeError("No RPC URLs configured") + + +def append_payment_note(existing_notes, extra_line): + base = (existing_notes or "").rstrip() + if not base: + return extra_line.strip() + return base + "\n" + extra_line.strip() + +def _hex_to_int(value): + if value is None: + return 0 + text = str(value).strip() + if not text: + return 0 + if text.startswith("0x"): + return int(text, 16) + return int(text) + +def fetch_rpc_balance(chain_name, wallet_address): + rpc_urls = get_rpc_urls_for_chain(chain_name) + if not rpc_urls or not wallet_address: + return None + try: + resp = rpc_call_any(rpc_urls, "eth_getBalance", [wallet_address, "latest"]) + result = (resp or {}).get("result") + if result is None: + return None + return { + "rpc_url": resp.get("rpc_url"), + "balance_wei": _hex_to_int(result), + } + except Exception: + return None + +def verify_expected_tx_for_payment(option, tx): + if not option or not tx: + raise RuntimeError("missing transaction data") + + wallet_to = str(option.get("wallet_address") or "").lower() + expected_units = _to_base_units(option.get("display_amount"), option.get("decimals") or 18) + + if option.get("asset_type") == "native": + tx_to = str(tx.get("to") or "").lower() + tx_value = _hex_to_int(tx.get("value") or "0x0") + + if tx_to != wallet_to: + raise RuntimeError("transaction destination does not match payment wallet") + if tx_value != expected_units: + raise RuntimeError("transaction value does not match frozen quote amount") + + return True + + tx_to = str(tx.get("to") or "").lower() + contract = str(option.get("token_contract") or "").lower() + if tx_to != contract: + raise RuntimeError("token contract does not match expected asset contract") + + parsed = parse_erc20_transfer_input(tx.get("input") or "") + if not parsed: + raise RuntimeError("transaction input is not a supported ERC20 transfer") + + if str(parsed["to"]).lower() != wallet_to: + raise RuntimeError("token transfer recipient does not match payment wallet") + + if int(parsed["amount"]) != expected_units: + raise RuntimeError("token transfer amount does not match frozen quote amount") + + return True + +def get_processing_crypto_option(payment_row): + currency = str(payment_row.get("payment_currency") or "").upper() + amount_text = str(payment_row.get("payment_amount") or "0") + wallet_address = payment_row.get("wallet_address") or CRYPTO_EVM_PAYMENT_ADDRESS + + mapping = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + "display_amount": amount_text, + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "display_amount": amount_text, + }, + } + return mapping.get(currency) + +def reconcile_pending_crypto_payment(payment_row): + tx_hash = str(payment_row.get("txid") or "").strip() + if not tx_hash or not tx_hash.startswith("0x"): + return {"state": "no_tx_hash"} + + option = get_processing_crypto_option(payment_row) + if not option: + return {"state": "unsupported_currency"} + + created_dt = payment_row.get("updated_at") or payment_row.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + if not created_dt: + created_dt = datetime.now(timezone.utc) + + age_seconds = max(0, int((datetime.now(timezone.utc) - created_dt).total_seconds())) + rpc_urls = get_rpc_urls_for_chain(option.get("chain")) + if not rpc_urls: + return {"state": "no_rpc"} + + tx_hit = None + receipt_hit = None + tx_rpc = None + receipt_rpc = None + + for rpc_url in rpc_urls: + try: + tx_resp = rpc_call_any([rpc_url], "eth_getTransactionByHash", [tx_hash]) + tx_obj = tx_resp.get("result") + if tx_obj: + verify_expected_tx_for_payment(option, tx_obj) + tx_hit = tx_obj + tx_rpc = tx_resp.get("rpc_url") + break + except Exception: + continue + + if tx_hit: + for rpc_url in rpc_urls: + try: + receipt_resp = rpc_call_any([rpc_url], "eth_getTransactionReceipt", [tx_hash]) + receipt_obj = receipt_resp.get("result") + if receipt_obj: + receipt_hit = receipt_obj + receipt_rpc = receipt_resp.get("rpc_url") + break + except Exception: + continue + + balance_info = fetch_rpc_balance(option.get("chain"), option.get("wallet_address")) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, invoice_id, notes, payment_status + FROM payments + WHERE id = %s + LIMIT 1 + """, (payment_row["id"],)) + live_payment = cursor.fetchone() + + if not live_payment: + conn.close() + return {"state": "payment_missing"} + + notes = live_payment.get("notes") or "" + + if tx_hit and receipt_hit: + receipt_status = _hex_to_int(receipt_hit.get("status") or "0x0") + confirmations = 0 + block_number = receipt_hit.get("blockNumber") + if block_number: + try: + bn = _hex_to_int(block_number) + latest_resp = rpc_call_any(rpc_urls, "eth_blockNumber", []) + latest_bn = _hex_to_int((latest_resp or {}).get("result") or "0x0") + if latest_bn >= bn: + confirmations = (latest_bn - bn) + 1 + except Exception: + confirmations = 1 + + if receipt_status == 1: + notes = append_payment_note(notes, f"[reconcile] confirmed tx {tx_hash} via {receipt_rpc or tx_rpc or 'rpc'}") + if balance_info: + notes = append_payment_note(notes, f"[reconcile] wallet balance seen on {balance_info.get('rpc_url')}: {balance_info.get('balance_wei')} wei") + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'confirmed', + confirmations = %s, + confirmation_required = 1, + received_at = COALESCE(received_at, UTC_TIMESTAMP()), + notes = %s + WHERE id = %s + """, ( + confirmations or 1, + notes, + payment_row["id"] + )) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "confirmed", "confirmations": confirmations or 1} + + notes = append_payment_note(notes, f"[reconcile] receipt status failed for tx {tx_hash}") + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "failed_receipt"} + + if age_seconds <= CRYPTO_PROCESSING_TIMEOUT_SECONDS: + notes_line = f"[reconcile] waiting for tx/receipt age={age_seconds}s" + if balance_info: + notes_line += f" wallet_balance_wei={balance_info.get('balance_wei')}" + if notes_line not in notes: + notes = append_payment_note(notes, notes_line) + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + return {"state": "processing", "age_seconds": age_seconds} + + fail_line = f"[reconcile] timeout after {age_seconds}s without confirmed receipt for tx {tx_hash}" + if balance_info: + fail_line += f" wallet_balance_wei={balance_info.get('balance_wei')}" + notes = append_payment_note(notes, fail_line) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (notes, payment_row["id"])) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(payment_row["invoice_id"]) + except Exception: + pass + + return {"state": "timeout", "age_seconds": age_seconds} + +def _to_base_units(amount_text, decimals): + amount_dec = Decimal(str(amount_text)) + scale = Decimal(10) ** int(decimals) + return int((amount_dec * scale).quantize(Decimal("1"))) + +def _strip_0x(value): + return str(value or "").lower().replace("0x", "") + +def parse_erc20_transfer_input(input_data): + data = _strip_0x(input_data) + if not data.startswith("a9059cbb"): + return None + if len(data) < 8 + 64 + 64: + return None + to_chunk = data[8:72] + amount_chunk = data[72:136] + to_addr = "0x" + to_chunk[-40:] + amount_int = int(amount_chunk, 16) + return { + "to": to_addr, + "amount": amount_int, + } + +def verify_wallet_transaction(option, tx_hash): + rpc_urls = get_rpc_urls_for_chain(option.get("chain")) + if not rpc_urls: + raise RuntimeError("No RPC configured for chain") + + seen_result = None + last_not_found = False + + for rpc_url in rpc_urls: + try: + rpc_resp = rpc_call_any([rpc_url], "eth_getTransactionByHash", [tx_hash]) + tx = rpc_resp.get("result") + if not tx: + last_not_found = True + continue + + wallet_to = str(option.get("wallet_address") or "").lower() + expected_units = _to_base_units(option.get("display_amount"), option.get("decimals") or 18) + + if option.get("asset_type") == "native": + tx_to = str(tx.get("to") or "").lower() + tx_value = int(tx.get("value") or "0x0", 16) + if tx_to != wallet_to: + raise RuntimeError("Transaction destination does not match payment wallet") + if tx_value != expected_units: + raise RuntimeError("Transaction value does not match frozen quote amount") + else: + tx_to = str(tx.get("to") or "").lower() + contract = str(option.get("token_contract") or "").lower() + if tx_to != contract: + raise RuntimeError("Token contract does not match expected asset contract") + parsed = parse_erc20_transfer_input(tx.get("input") or "") + if not parsed: + raise RuntimeError("Transaction input is not a supported ERC20 transfer") + if str(parsed["to"]).lower() != wallet_to: + raise RuntimeError("Token transfer recipient does not match payment wallet") + if int(parsed["amount"]) != expected_units: + raise RuntimeError("Token transfer amount does not match frozen quote amount") + + seen_result = { + "rpc_url": rpc_url, + "tx": tx, + } + break + except Exception: + continue + + if not seen_result: + if last_not_found: + raise RuntimeError("Transaction hash not found on any configured RPC") + raise RuntimeError("Unable to verify transaction on configured RPC pool") + + return seen_result + + +def get_processing_crypto_option(payment_row): + currency = str(payment_row.get("payment_currency") or "").upper() + amount_text = str(payment_row.get("payment_amount") or "0") + wallet_address = payment_row.get("wallet_address") or CRYPTO_EVM_PAYMENT_ADDRESS + + mapping = { + "USDC": { + "symbol": "USDC", + "chain": "arbitrum", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 6, + "token_contract": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", + "display_amount": amount_text, + }, + "ETH": { + "symbol": "ETH", + "chain": "ethereum", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETHO": { + "symbol": "ETHO", + "chain": "etho", + "wallet_address": wallet_address, + "asset_type": "native", + "decimals": 18, + "token_contract": None, + "display_amount": amount_text, + }, + "ETI": { + "symbol": "ETI", + "chain": "etica", + "wallet_address": wallet_address, + "asset_type": "token", + "decimals": 18, + "token_contract": "0x34c61EA91bAcdA647269d4e310A86b875c09946f", + "display_amount": amount_text, + }, + } + + return mapping.get(currency) + +def append_payment_note(existing_notes, extra_line): + base = (existing_notes or "").rstrip() + if not base: + return extra_line.strip() + return base + "\n" + extra_line.strip() + +def mark_crypto_payment_failed(payment_id, reason): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT invoice_id, notes + FROM payments + WHERE id = %s + LIMIT 1 + """, (payment_id,)) + row = cursor.fetchone() + + if not row: + conn.close() + return + + new_notes = append_payment_note( + row.get("notes"), + f"[crypto watcher] failed: {reason}" + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'failed', + notes = %s + WHERE id = %s + """, (new_notes, payment_id)) + conn.commit() + conn.close() + + try: + recalc_invoice_totals(row["invoice_id"]) + except Exception: + pass + +def mark_crypto_payment_confirmed(payment_id, invoice_id, rpc_url): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT p.*, i.client_id AS invoice_client_id, i.invoice_number, + i.total_amount, i.amount_paid, i.status AS invoice_status, + c.email AS client_email, c.company_name, c.contact_name + FROM payments p + JOIN invoices i ON i.id = p.invoice_id + LEFT JOIN clients c ON c.id = i.client_id + WHERE p.id = %s + LIMIT 1 + """, (payment_id,)) + row = cursor.fetchone() + + if not row: + conn.close() + return + + if str(row.get("payment_status") or "").lower() == "confirmed": + conn.close() + return + + new_notes = append_payment_note( + row.get("notes"), + "[crypto watcher] confirmed via %s txid=%s" % (rpc_url, row.get("txid") or "") + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'confirmed', + confirmations = COALESCE(confirmation_required, 1), + confirmation_required = COALESCE(confirmations, 1), + received_at = COALESCE(received_at, UTC_TIMESTAMP()), + notes = %s + WHERE id = %s + """, (new_notes, payment_id)) + conn.commit() + + try: + paid_via_cursor = conn.cursor() + paid_via_cursor.execute(""" + UPDATE invoices + SET paid_via_method = %s, + paid_via_asset = %s, + paid_via_network = %s + WHERE id = %s + """, ( + "crypto", + str(row.get("payment_currency") or "").upper() or None, + { + "ETH": "ethereum", + "ETHO": "etho", + "ETI": "etica", + "USDC": "arbitrum", + }.get(str(row.get("payment_currency") or "").upper()), + invoice_id + )) + conn.commit() + except Exception: + pass + + try: + paid_via_cursor = conn.cursor() + paid_via_cursor.execute(""" + UPDATE invoices + SET paid_via_method = %s, + paid_via_asset = %s, + paid_via_network = %s + WHERE id = %s + """, ( + "crypto", + str(row.get("payment_currency") or "").upper() or None, + ({ + "ETH": "ethereum", + "ETHO": "etho", + "ETI": "etica", + "USDC": "arbitrum", + }.get(str(row.get("payment_currency") or "").upper())), + invoice_id + )) + conn.commit() + except Exception: + pass + + try: + recalc_invoice_totals(invoice_id) + except Exception: + pass + + refresh_cursor = conn.cursor(dictionary=True) + refresh_cursor.execute(""" + SELECT id, client_id, invoice_number, total_amount, amount_paid, status + FROM invoices + WHERE id = %s + LIMIT 1 + """, (invoice_id,)) + invoice = refresh_cursor.fetchone() or {} + + try: + from decimal import Decimal + total_dec = Decimal(str(invoice.get("total_amount") or "0")) + paid_dec = Decimal(str(invoice.get("amount_paid") or "0")) + + overpayment_dec = paid_dec - total_dec + if overpayment_dec > Decimal("0"): + credit_note = "Overpayment from invoice %s (crypto payment_id=%s)" % ( + invoice.get("invoice_number") or invoice_id, + payment_id + ) + + check_cursor = conn.cursor(dictionary=True) + check_cursor.execute(""" + SELECT id FROM credit_ledger + WHERE client_id = %s AND notes = %s + LIMIT 1 + """, (invoice.get("client_id"), credit_note)) + + if not check_cursor.fetchone(): + credit_cursor = conn.cursor() + credit_cursor.execute(""" + INSERT INTO credit_ledger + (client_id, entry_type, amount, currency_code, notes) + VALUES (%s, %s, %s, %s, %s) + """, ( + invoice.get("client_id"), + "credit", + str(overpayment_dec), + "CAD", + credit_note + )) + conn.commit() + except Exception: + pass + + try: + if str(invoice.get("status") or "").lower() == "paid": + recipient = (row.get("client_email") or "").strip() + if recipient: + subject = "Invoice %s Paid (Crypto)" % (invoice.get("invoice_number") or invoice_id) + + body = "Your payment has been received and confirmed.\n\n" + body += "Invoice: %s\n" % (invoice.get("invoice_number") or invoice_id) + body += "Amount: %s %s\n" % (row.get("payment_amount"), row.get("payment_currency")) + body += "TXID: %s\n\n" % (row.get("txid") or "") + body += "Thank you for your business.\n" + + send_configured_email( + to_email=recipient, + subject=subject, + body=body, + attachments=None, + email_type="invoice_paid_crypto", + invoice_id=invoice_id + ) + except Exception: + pass + + conn.close() +def watch_pending_crypto_payments_once(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + invoice_id, + client_id, + payment_currency, + payment_amount, + cad_value_at_payment, + wallet_address, + txid, + payment_status, + created_at, + updated_at, + notes + FROM payments + WHERE payment_status = 'pending' + AND txid IS NOT NULL + AND txid <> '' + AND notes LIKE '%%portal_crypto_intent:%%' + ORDER BY id ASC + """) + pending_rows = cursor.fetchall() + conn.close() + + now_utc = datetime.now(timezone.utc) + + for row in pending_rows: + option = get_processing_crypto_option(row) + if not option: + continue + + submitted_at = row.get("updated_at") or row.get("created_at") + if submitted_at and submitted_at.tzinfo is None: + submitted_at = submitted_at.replace(tzinfo=timezone.utc) + + if not submitted_at: + submitted_at = now_utc + + age_seconds = (now_utc - submitted_at).total_seconds() + + if age_seconds > CRYPTO_PROCESSING_TIMEOUT_SECONDS: + mark_crypto_payment_failed(row["id"], "processing timeout exceeded") + continue + + try: + verified = verify_wallet_transaction(option, str(row.get("txid") or "").strip()) + mark_crypto_payment_confirmed(row["id"], row["invoice_id"], verified.get("rpc_url") or "rpc") + except Exception as err: + msg = str(err or "") + lower = msg.lower() + retryable = ( + "not found on any configured rpc" in lower + or "not found on rpc" in lower + or "unable to verify transaction on configured rpc pool" in lower + ) + if retryable: + continue + # non-retryable verification problems get marked failed immediately + mark_crypto_payment_failed(row["id"], msg) + +def crypto_payment_watcher_loop(): + while True: + try: + watch_pending_crypto_payments_once() + except Exception as err: + try: + print(f"[crypto-watcher] {err}") + except Exception: + pass + time.sleep(max(5, CRYPTO_WATCH_INTERVAL_SECONDS)) + +def start_crypto_payment_watcher(): + # Disabled in favor of the systemd-managed crypto_reconciliation_worker.py + # This avoids duplicate payment checks / duplicate notifications. + return + +def square_amount_to_cents(value): + return int((to_decimal(value) * 100).quantize(Decimal("1"))) + +def create_square_payment_link_for_invoice(invoice_row, buyer_email=""): + if not SQUARE_ACCESS_TOKEN: + raise RuntimeError("Square access token is not configured") + + invoice_number = invoice_row.get("invoice_number") or f"INV-{invoice_row.get('id')}" + currency_code = invoice_row.get("currency_code") or "CAD" + amount_cents = square_amount_to_cents(invoice_row.get("total_amount") or "0") + location_id = "1TSPHT78106WX" + + payload = { + "idempotency_key": str(uuid.uuid4()), + "description": f"OTB Billing invoice {invoice_number}", + "quick_pay": { + "name": f"Invoice {invoice_number}", + "price_money": { + "amount": amount_cents, + "currency": currency_code + }, + "location_id": location_id + }, + "payment_note": f"Invoice {invoice_number}", + "checkout_options": { + "redirect_url": "https://portal.outsidethebox.top/portal" + } + } + + if buyer_email: + payload["pre_populated_data"] = { + "buyer_email": buyer_email + } + + req = urllib.request.Request( + f"{SQUARE_API_BASE}/v2/online-checkout/payment-links", + data=json.dumps(payload).encode("utf-8"), + headers={ + "Authorization": f"Bearer {SQUARE_ACCESS_TOKEN}", + "Square-Version": SQUARE_API_VERSION, + "Content-Type": "application/json" + }, + method="POST" + ) + + try: + with urllib.request.urlopen(req, timeout=30) as resp: + data = json.loads(resp.read().decode("utf-8")) + except urllib.error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + raise RuntimeError(f"Square payment link creation failed: {e.code} {body}") + + payment_link = (data or {}).get("payment_link") or {} + url = payment_link.get("url") + if not url: + raise RuntimeError(f"Square payment link response missing URL: {data}") + + return url + + +def square_signature_is_valid(signature_header, raw_body, notification_url): + if not SQUARE_WEBHOOK_SIGNATURE_KEY or not signature_header: + return False + message = notification_url.encode("utf-8") + raw_body + digest = hmac.new( + SQUARE_WEBHOOK_SIGNATURE_KEY.encode("utf-8"), + message, + hashlib.sha256 + ).digest() + computed_signature = base64.b64encode(digest).decode("utf-8") + return hmac.compare_digest(computed_signature, signature_header) + +def append_square_webhook_log(entry): + try: + log_path = Path(SQUARE_WEBHOOK_LOG) + log_path.parent.mkdir(parents=True, exist_ok=True) + with log_path.open("a", encoding="utf-8") as f: + f.write(json.dumps(entry, ensure_ascii=False) + "\n") + except Exception: + pass + +def generate_portal_access_code(): + alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" + groups = [] + for _ in range(3): + groups.append("".join(secrets.choice(alphabet) for _ in range(4))) + return "-".join(groups) + +def refresh_overdue_invoices(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE invoices + SET status = 'overdue' + WHERE due_at IS NOT NULL + AND due_at < UTC_TIMESTAMP() + AND status IN ('pending', 'partial') + """) + conn.commit() + conn.close() + +def recalc_invoice_totals(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, total_amount, due_at, status + FROM invoices + WHERE id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return + + invoice_currency = str(invoice.get("currency_code") or "CAD").upper() + + if invoice_currency == "CAD": + cursor.execute(""" + SELECT COALESCE(SUM( + CASE + WHEN UPPER(COALESCE(payment_currency, '')) = 'CAD' + THEN payment_amount + ELSE COALESCE(cad_value_at_payment, 0) + END + ), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_id,)) + else: + cursor.execute(""" + SELECT COALESCE(SUM( + CASE + WHEN UPPER(COALESCE(payment_currency, '')) = %s + THEN payment_amount + ELSE 0 + END + ), 0) AS total_paid + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + """, (invoice_currency, invoice_id)) + + row = cursor.fetchone() + + total_paid = to_decimal(row["total_paid"]) + total_amount = to_decimal(invoice["total_amount"]) + + if invoice["status"] == "cancelled": + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET amount_paid = %s, + paid_at = NULL + WHERE id = %s + """, ( + str(total_paid), + invoice_id + )) + conn.commit() + conn.close() + return + + if total_paid >= total_amount and total_amount > 0: + new_status = "paid" + paid_at_value = "UTC_TIMESTAMP()" + elif total_paid > 0: + new_status = "partial" + paid_at_value = "NULL" + else: + if invoice["due_at"] and invoice["due_at"] < datetime.utcnow(): + new_status = "overdue" + else: + new_status = "pending" + paid_at_value = "NULL" + + update_cursor = conn.cursor() + update_cursor.execute(f""" + UPDATE invoices + SET amount_paid = %s, + status = %s, + paid_at = {paid_at_value} + WHERE id = %s + """, ( + str(total_paid), + new_status, + invoice_id + )) + + conn.commit() + conn.close() + +def get_client_credit_balance(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT COALESCE(SUM(amount), 0) AS balance + FROM credit_ledger + WHERE client_id = %s + """, (client_id,)) + row = cursor.fetchone() + conn.close() + return to_decimal(row["balance"]) + + +def generate_invoice_number(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT invoice_number + FROM invoices + WHERE invoice_number IS NOT NULL + AND invoice_number LIKE 'INV-%' + ORDER BY id DESC + LIMIT 1 + """) + row = cursor.fetchone() + conn.close() + + if not row or not row.get("invoice_number"): + return "INV-0001" + + invoice_number = str(row["invoice_number"]).strip() + + try: + number = int(invoice_number.split("-")[1]) + except (IndexError, ValueError): + return "INV-0001" + + return f"INV-{number + 1:04d}" + + +def ensure_subscriptions_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS subscriptions ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + client_id INT UNSIGNED NOT NULL, + service_id INT UNSIGNED NULL, + subscription_name VARCHAR(255) NOT NULL, + billing_interval ENUM('monthly','quarterly','yearly') NOT NULL DEFAULT 'monthly', + price DECIMAL(18,8) NOT NULL DEFAULT 0.00000000, + currency_code VARCHAR(16) NOT NULL DEFAULT 'CAD', + start_date DATE NOT NULL, + next_invoice_date DATE NOT NULL, + status ENUM('active','paused','cancelled') NOT NULL DEFAULT 'active', + notes TEXT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + KEY idx_subscriptions_client_id (client_id), + KEY idx_subscriptions_service_id (service_id), + KEY idx_subscriptions_status (status), + KEY idx_subscriptions_next_invoice_date (next_invoice_date) + ) + """) + conn.commit() + conn.close() + + +def get_next_subscription_date(current_date, billing_interval): + if isinstance(current_date, str): + current_date = datetime.strptime(current_date, "%Y-%m-%d").date() + + if billing_interval == "yearly": + return current_date + relativedelta(years=1) + if billing_interval == "quarterly": + return current_date + relativedelta(months=3) + return current_date + relativedelta(months=1) + + +def generate_due_subscription_invoices(run_date=None): + ensure_subscriptions_table() + + today = run_date or date.today() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + s.*, + c.client_code, + c.company_name, + srv.service_code, + srv.service_name + FROM subscriptions s + JOIN clients c ON s.client_id = c.id + LEFT JOIN services srv ON s.service_id = srv.id + WHERE s.status = 'active' + AND s.next_invoice_date <= %s + ORDER BY s.next_invoice_date ASC, s.id ASC + """, (today,)) + due_subscriptions = cursor.fetchall() + + created_count = 0 + created_invoice_numbers = [] + + for sub in due_subscriptions: + invoice_number = generate_invoice_number() + due_dt = datetime.combine(today + timedelta(days=14), datetime.min.time()) + + note_parts = [f"Recurring subscription: {sub['subscription_name']}"] + if sub.get("service_code"): + note_parts.append(f"Service: {sub['service_code']}") + if sub.get("service_name"): + note_parts.append(f"({sub['service_name']})") + if sub.get("notes"): + note_parts.append(f"Notes: {sub['notes']}") + + note_text = " ".join(note_parts) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO invoices + ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + subtotal_amount, + tax_amount, + issued_at, + due_at, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, 0, UTC_TIMESTAMP(), %s, 'pending', %s) + """, ( + sub["client_id"], + sub["service_id"], + invoice_number, + sub["currency_code"], + str(sub["price"]), + str(sub["price"]), + due_dt, + note_text, + )) + + next_date = get_next_subscription_date(sub["next_invoice_date"], sub["billing_interval"]) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE subscriptions + SET next_invoice_date = %s + WHERE id = %s + """, (next_date, sub["id"])) + + created_count += 1 + created_invoice_numbers.append(invoice_number) + + conn.commit() + conn.close() + + return { + "created_count": created_count, + "invoice_numbers": created_invoice_numbers, + "run_date": str(today), + } + + +APP_SETTINGS_DEFAULTS = { + "business_name": "OTB Billing", + "business_tagline": "By a contractor, for contractors", + "business_logo_url": "", + "business_email": "", + "business_phone": "", + "business_address": "", + "business_website": "", + "tax_label": "HST", + "tax_rate": "13.00", + "tax_number": "", + "business_number": "", + "default_currency": "CAD", + "report_frequency": "monthly", + "invoice_footer": "", + "payment_terms": "", + "local_country": "Canada", + "apply_local_tax_only": "1", + "smtp_host": "", + "smtp_port": "587", + "smtp_user": "", + "smtp_pass": "", + "smtp_from_email": "", + "smtp_from_name": "", + "smtp_use_tls": "1", + "smtp_use_ssl": "0", + "report_delivery_email": "", +} + +def ensure_app_settings_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS app_settings ( + setting_key VARCHAR(100) NOT NULL PRIMARY KEY, + setting_value TEXT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + ) + """) + conn.commit() + conn.close() + +def get_app_settings(): + ensure_app_settings_table() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT setting_key, setting_value + FROM app_settings + """) + rows = cursor.fetchall() + conn.close() + + settings = dict(APP_SETTINGS_DEFAULTS) + for row in rows: + settings[row["setting_key"]] = row["setting_value"] if row["setting_value"] is not None else "" + + return settings + +def save_app_settings(form_data): + ensure_app_settings_table() + conn = get_db_connection() + cursor = conn.cursor() + + for key in APP_SETTINGS_DEFAULTS.keys(): + if key in {"apply_local_tax_only", "smtp_use_tls", "smtp_use_ssl"}: + value = "1" if form_data.get(key) else "0" + else: + value = (form_data.get(key) or "").strip() + + cursor.execute(""" + INSERT INTO app_settings (setting_key, setting_value) + VALUES (%s, %s) + ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value) + """, (key, value)) + + conn.commit() + conn.close() + + +@app.template_filter("localtime") +def localtime_filter(value): + return fmt_local(value) + +@app.template_filter("money") +def money_filter(value, currency_code="CAD"): + return fmt_money(value, currency_code) + + + + +def get_report_period_bounds(frequency): + now_local = datetime.now(LOCAL_TZ) + + if frequency == "yearly": + start_local = now_local.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) + label = f"{now_local.year}" + elif frequency == "quarterly": + quarter = ((now_local.month - 1) // 3) + 1 + start_month = (quarter - 1) * 3 + 1 + start_local = now_local.replace(month=start_month, day=1, hour=0, minute=0, second=0, microsecond=0) + label = f"Q{quarter} {now_local.year}" + else: + start_local = now_local.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + label = now_local.strftime("%B %Y") + + start_utc = start_local.astimezone(timezone.utc).replace(tzinfo=None) + end_utc = now_local.astimezone(timezone.utc).replace(tzinfo=None) + + return start_utc, end_utc, label + + + +def build_accounting_package_bytes(): + import json + import zipfile + from io import BytesIO + + report = get_revenue_report_data() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.created_at, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + ORDER BY i.created_at DESC + """) + invoices = cursor.fetchall() + + conn.close() + + payload = { + "report": report, + "invoices": invoices + } + + json_bytes = json.dumps(payload, indent=2, default=str).encode() + + zip_buffer = BytesIO() + + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("revenue_report.json", json.dumps(report, indent=2)) + z.writestr("invoices.json", json.dumps(invoices, indent=2, default=str)) + + zip_buffer.seek(0) + + filename = f"accounting_package_{report.get('period_label','report')}.zip" + + return zip_buffer.read(), filename + + + +def get_revenue_report_data(): + settings = get_app_settings() + frequency = (settings.get("report_frequency") or "monthly").strip().lower() + if frequency not in {"monthly", "quarterly", "yearly"}: + frequency = "monthly" + + start_utc, end_utc, label = get_report_period_bounds(frequency) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT COALESCE(SUM(cad_value_at_payment), 0) AS collected + FROM payments + WHERE payment_status = 'confirmed' + AND received_at >= %s + AND received_at <= %s + """, (start_utc, end_utc)) + collected_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS invoice_count, + COALESCE(SUM(total_amount), 0) AS invoiced + FROM invoices + WHERE issued_at >= %s + AND issued_at <= %s + """, (start_utc, end_utc)) + invoiced_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS overdue_count, + COALESCE(SUM(total_amount - amount_paid), 0) AS overdue_balance + FROM invoices + WHERE status = 'overdue' + """) + overdue_row = cursor.fetchone() + + cursor.execute(""" + SELECT COUNT(*) AS outstanding_count, + COALESCE(SUM(total_amount - amount_paid), 0) AS outstanding_balance + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + """) + outstanding_row = cursor.fetchone() + + conn.close() + + return { + "frequency": frequency, + "period_label": label, + "period_start": start_utc.isoformat(sep=" "), + "period_end": end_utc.isoformat(sep=" "), + "collected_cad": str(to_decimal(collected_row["collected"])), + "invoice_count": int(invoiced_row["invoice_count"] or 0), + "invoiced_total": str(to_decimal(invoiced_row["invoiced"])), + "overdue_count": int(overdue_row["overdue_count"] or 0), + "overdue_balance": str(to_decimal(overdue_row["overdue_balance"])), + "outstanding_count": int(outstanding_row["outstanding_count"] or 0), + "outstanding_balance": str(to_decimal(outstanding_row["outstanding_balance"])), + } + + +def ensure_email_log_table(): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS email_log ( + id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, + email_type VARCHAR(50) NOT NULL, + invoice_id INT UNSIGNED NULL, + recipient_email VARCHAR(255) NOT NULL, + subject VARCHAR(255) NOT NULL, + status VARCHAR(20) NOT NULL, + error_message TEXT NULL, + sent_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + KEY idx_email_log_invoice_id (invoice_id), + KEY idx_email_log_type (email_type), + KEY idx_email_log_sent_at (sent_at) + ) + """) + conn.commit() + conn.close() + + +def log_email_event(email_type, recipient_email, subject, status, invoice_id=None, error_message=None): + ensure_email_log_table() + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + INSERT INTO email_log + (email_type, invoice_id, recipient_email, subject, status, error_message) + VALUES (%s, %s, %s, %s, %s, %s) + """, ( + email_type, + invoice_id, + recipient_email, + subject, + status, + error_message + )) + conn.commit() + conn.close() + + + +def send_configured_email(to_email, subject, body, attachments=None, email_type="system_email", invoice_id=None): + settings = get_app_settings() + + smtp_host = (settings.get("smtp_host") or "").strip() + smtp_port = int((settings.get("smtp_port") or "587").strip() or "587") + smtp_user = (settings.get("smtp_user") or "").strip() + smtp_pass = (settings.get("smtp_pass") or "").strip() + from_email = (settings.get("smtp_from_email") or settings.get("business_email") or "").strip() + from_name = (settings.get("smtp_from_name") or settings.get("business_name") or "").strip() + use_tls = (settings.get("smtp_use_tls") or "0") == "1" + use_ssl = (settings.get("smtp_use_ssl") or "0") == "1" + + if not smtp_host: + raise ValueError("SMTP host is not configured.") + if not from_email: + raise ValueError("From email is not configured.") + if not to_email: + raise ValueError("Recipient email is missing.") + + msg = EmailMessage() + msg["Subject"] = subject + msg["From"] = f"{from_name} <{from_email}>" if from_name else from_email + msg["To"] = to_email + msg.set_content(body) + + for attachment in attachments or []: + filename = attachment["filename"] + mime_type = attachment["mime_type"] + data = attachment["data"] + maintype, subtype = mime_type.split("/", 1) + msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=filename) + + try: + if use_ssl: + with smtplib.SMTP_SSL(smtp_host, smtp_port, timeout=30) as server: + if smtp_user: + server.login(smtp_user, smtp_pass) + server.send_message(msg) + else: + with smtplib.SMTP(smtp_host, smtp_port, timeout=30) as server: + server.ehlo() + if use_tls: + server.starttls() + server.ehlo() + if smtp_user: + server.login(smtp_user, smtp_pass) + server.send_message(msg) + + log_email_event(email_type, to_email, subject, "sent", invoice_id=invoice_id, error_message=None) + except Exception as e: + log_email_event(email_type, to_email, subject, "failed", invoice_id=invoice_id, error_message=str(e)) + raise + +@app.route("/settings", methods=["GET", "POST"]) +def settings(): + ensure_app_settings_table() + + if request.method == "POST": + save_app_settings(request.form) + return redirect("/settings") + + settings = get_app_settings() + return render_template("settings.html", settings=settings) + + + + +@app.route("/reports/accounting-package.zip") +def accounting_package_zip(): + package_bytes, filename = build_accounting_package_bytes() + return send_file( + BytesIO(package_bytes), + mimetype="application/zip", + as_attachment=True, + download_name=filename + ) + +@app.route("/reports/revenue") +def revenue_report(): + report = get_revenue_report_data() + return render_template("reports/revenue.html", report=report) + +@app.route("/reports/revenue.json") +def revenue_report_json(): + report = get_revenue_report_data() + return jsonify(report) + +@app.route("/reports/revenue/print") +def revenue_report_print(): + report = get_revenue_report_data() + return render_template("reports/revenue_print.html", report=report) + + + +@app.route("/invoices/email/", methods=["POST"]) +def email_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return "Invoice not found", 404 + + recipient = (invoice.get("email") or "").strip() + if not recipient: + return "Client email is missing for this invoice.", 400 + + settings = get_app_settings() + + with app.test_client() as client: + pdf_response = client.get(f"/invoices/pdf/{invoice_id}") + if pdf_response.status_code != 200: + return "Could not generate invoice PDF for email.", 500 + + pdf_bytes = pdf_response.data + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + subject = f"Invoice {invoice['invoice_number']} from {settings.get('business_name') or 'OTB Billing'}" + body = ( + f"Hello {invoice.get('contact_name') or invoice.get('company_name') or ''},\n\n" + f"Please find attached invoice {invoice['invoice_number']}.\n" + f"Total: {to_decimal(invoice.get('total_amount')):.2f} {invoice.get('currency_code', 'CAD')}\n" + f"Remaining: {remaining:.2f} {invoice.get('currency_code', 'CAD')}\n" + f"Due: {fmt_local(invoice.get('due_at'))}\n\n" + f"Thank you,\n" + f"{settings.get('business_name') or 'OTB Billing'}" + ) + + try: + send_configured_email( + recipient, + subject, + body, + email_type="invoice", + invoice_id=invoice_id, + attachments=[{ + "filename": f"{invoice['invoice_number']}.pdf", + "mime_type": "application/pdf", + "data": pdf_bytes, + }] + ) + return redirect(f"/invoices/view/{invoice_id}?email_sent=1") + except Exception: + return redirect(f"/invoices/view/{invoice_id}?email_failed=1") + + +@app.route("/reports/revenue/email", methods=["POST"]) +def email_revenue_report_json(): + settings = get_app_settings() + recipient = (settings.get("report_delivery_email") or settings.get("business_email") or "").strip() + if not recipient: + return "Report delivery email is not configured.", 400 + + with app.test_client() as client: + json_response = client.get("/reports/revenue.json") + if json_response.status_code != 200: + return "Could not generate revenue report JSON.", 500 + + report = get_revenue_report_data() + subject = f"Revenue Report {report.get('period_label', '')} from {settings.get('business_name') or 'OTB Billing'}" + body = ( + f"Attached is the revenue report JSON for {report.get('period_label', '')}.\n\n" + f"Frequency: {report.get('frequency', '')}\n" + f"Collected CAD: {report.get('collected_cad', '')}\n" + f"Invoices Issued: {report.get('invoice_count', '')}\n" + ) + + try: + send_configured_email( + recipient, + subject, + body, + email_type="revenue_report", + attachments=[{ + "filename": "revenue_report.json", + "mime_type": "application/json", + "data": json_response.data, + }] + ) + return redirect("/reports/revenue?email_sent=1") + except Exception: + return redirect("/reports/revenue?email_failed=1") + + +@app.route("/reports/accounting-package/email", methods=["POST"]) +def email_accounting_package(): + settings = get_app_settings() + recipient = (settings.get("report_delivery_email") or settings.get("business_email") or "").strip() + if not recipient: + return "Report delivery email is not configured.", 400 + + with app.test_client() as client: + zip_response = client.get("/reports/accounting-package.zip") + if zip_response.status_code != 200: + return "Could not generate accounting package ZIP.", 500 + + subject = f"Accounting Package from {settings.get('business_name') or 'OTB Billing'}" + body = "Attached is the latest accounting package export." + + try: + send_configured_email( + recipient, + subject, + body, + email_type="accounting_package", + attachments=[{ + "filename": "accounting_package.zip", + "mime_type": "application/zip", + "data": zip_response.data, + }] + ) + return redirect("/?pkg_email=1") + except Exception: + return redirect("/?pkg_email_failed=1") + + + +@app.route("/subscriptions") +def subscriptions(): + ensure_subscriptions_table() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + s.*, + c.client_code, + c.company_name, + srv.service_code, + srv.service_name + FROM subscriptions s + JOIN clients c ON s.client_id = c.id + LEFT JOIN services srv ON s.service_id = srv.id + ORDER BY s.id DESC + """) + subscriptions = cursor.fetchall() + conn.close() + + return render_template("subscriptions/list.html", subscriptions=subscriptions) + + +@app.route("/subscriptions/new", methods=["GET", "POST"]) +def new_subscription(): + ensure_subscriptions_table() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + subscription_name = request.form.get("subscription_name", "").strip() + billing_interval = request.form.get("billing_interval", "").strip() + price = request.form.get("price", "").strip() + currency_code = request.form.get("currency_code", "").strip() + start_date_value = request.form.get("start_date", "").strip() + next_invoice_date = request.form.get("next_invoice_date", "").strip() + status = request.form.get("status", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not subscription_name: + errors.append("Subscription name is required.") + if billing_interval not in {"monthly", "quarterly", "yearly"}: + errors.append("Billing interval is required.") + if not price: + errors.append("Price is required.") + if not currency_code: + errors.append("Currency is required.") + if not start_date_value: + errors.append("Start date is required.") + if not next_invoice_date: + errors.append("Next invoice date is required.") + if status not in {"active", "paused", "cancelled"}: + errors.append("Status is required.") + + if not errors: + try: + price_value = Decimal(str(price)) + if price_value <= Decimal("0"): + errors.append("Price must be greater than zero.") + except Exception: + errors.append("Price must be a valid number.") + + if errors: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + conn.close() + + return render_template( + "subscriptions/new.html", + clients=clients, + services=services, + errors=errors, + form_data={ + "client_id": client_id, + "service_id": service_id, + "subscription_name": subscription_name, + "billing_interval": billing_interval, + "price": price, + "currency_code": currency_code, + "start_date": start_date_value, + "next_invoice_date": next_invoice_date, + "status": status, + "notes": notes, + }, + ) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO subscriptions + ( + client_id, + service_id, + subscription_name, + billing_interval, + price, + currency_code, + start_date, + next_invoice_date, + status, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, ( + client_id, + service_id or None, + subscription_name, + billing_interval, + str(price_value), + currency_code, + start_date_value, + next_invoice_date, + status, + notes or None, + )) + + conn.commit() + conn.close() + return redirect("/subscriptions") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + conn.close() + + today_str = date.today().isoformat() + + return render_template( + "subscriptions/new.html", + clients=clients, + services=services, + errors=[], + form_data={ + "billing_interval": "monthly", + "currency_code": "CAD", + "start_date": today_str, + "next_invoice_date": today_str, + "status": "active", + }, + ) + + +@app.route("/subscriptions/run", methods=["POST"]) +def run_subscriptions_now(): + result = generate_due_subscription_invoices() + return redirect(f"/subscriptions?run_count={result['created_count']}") + + + +@app.route("/reports/aging") +def report_aging(): + refresh_overdue_invoices() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + c.id AS client_id, + c.client_code, + c.company_name, + i.invoice_number, + i.due_at, + i.total_amount, + i.amount_paid, + (i.total_amount - i.amount_paid) AS remaining + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY c.company_name, i.due_at + """) + rows = cursor.fetchall() + conn.close() + + today = datetime.utcnow().date() + grouped = {} + totals = { + "current": Decimal("0"), + "d30": Decimal("0"), + "d60": Decimal("0"), + "d90": Decimal("0"), + "d90p": Decimal("0"), + "total": Decimal("0"), + } + + for row in rows: + client_id = row["client_id"] + client_label = f"{row['client_code']} - {row['company_name']}" + + if client_id not in grouped: + grouped[client_id] = { + "client": client_label, + "current": Decimal("0"), + "d30": Decimal("0"), + "d60": Decimal("0"), + "d90": Decimal("0"), + "d90p": Decimal("0"), + "total": Decimal("0"), + } + + remaining = to_decimal(row["remaining"]) + + if row["due_at"]: + due_date = row["due_at"].date() + age_days = (today - due_date).days + else: + age_days = 0 + + if age_days <= 0: + bucket = "current" + elif age_days <= 30: + bucket = "d30" + elif age_days <= 60: + bucket = "d60" + elif age_days <= 90: + bucket = "d90" + else: + bucket = "d90p" + + grouped[client_id][bucket] += remaining + grouped[client_id]["total"] += remaining + + totals[bucket] += remaining + totals["total"] += remaining + + aging_rows = list(grouped.values()) + + return render_template( + "reports/aging.html", + aging_rows=aging_rows, + totals=totals + ) + + +@app.route("/") +def index(): + refresh_overdue_invoices() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute("SELECT COUNT(*) AS total_clients FROM clients") + total_clients = cursor.fetchone()["total_clients"] + + cursor.execute("SELECT COUNT(*) AS active_services FROM services WHERE status = 'active'") + active_services = cursor.fetchone()["active_services"] + + cursor.execute(""" + SELECT COUNT(*) AS outstanding_invoices + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + AND (total_amount - amount_paid) > 0 + """) + outstanding_invoices = cursor.fetchone()["outstanding_invoices"] + + cursor.execute(""" + SELECT COALESCE(SUM(cad_value_at_payment), 0) AS revenue_received + FROM payments + WHERE payment_status = 'confirmed' + """) + revenue_received = to_decimal(cursor.fetchone()["revenue_received"]) + + cursor.execute(""" + SELECT COALESCE(SUM(total_amount - amount_paid), 0) AS outstanding_balance + FROM invoices + WHERE status IN ('pending', 'partial', 'overdue') + AND (total_amount - amount_paid) > 0 + """) + outstanding_balance = to_decimal(cursor.fetchone()["outstanding_balance"]) + + conn.close() + + app_settings = get_app_settings() + + return render_template( + "dashboard.html", + total_clients=total_clients, + active_services=active_services, + outstanding_invoices=outstanding_invoices, + outstanding_balance=outstanding_balance, + revenue_received=revenue_received, + app_settings=app_settings, + ) + +@app.route("/clients") +def clients(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + c.*, + COALESCE(( + SELECT SUM(i.total_amount - i.amount_paid) + FROM invoices i + WHERE i.client_id = c.id + AND i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ), 0) AS outstanding_balance + FROM clients c + ORDER BY c.company_name + """) + clients = cursor.fetchall() + + conn.close() + return render_template("clients/list.html", clients=clients) + +@app.route("/clients/new", methods=["GET", "POST"]) +def new_client(): + if request.method == "POST": + company_name = request.form["company_name"] + contact_name = request.form["contact_name"] + email = request.form["email"] + phone = request.form["phone"] + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute("SELECT MAX(id) AS last_id FROM clients") + result = cursor.fetchone() + last_number = result["last_id"] if result["last_id"] else 0 + + client_code = generate_client_code(company_name, last_number) + + insert_cursor = conn.cursor() + insert_cursor.execute( + """ + INSERT INTO clients + (client_code, company_name, contact_name, email, phone) + VALUES (%s, %s, %s, %s, %s) + """, + (client_code, company_name, contact_name, email, phone) + ) + conn.commit() + conn.close() + + return redirect("/clients") + + return render_template("clients/new.html") + +@app.route("/clients/edit/", methods=["GET", "POST"]) +def edit_client(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + company_name = request.form.get("company_name", "").strip() + contact_name = request.form.get("contact_name", "").strip() + email = request.form.get("email", "").strip() + phone = request.form.get("phone", "").strip() + status = request.form.get("status", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not company_name: + errors.append("Company name is required.") + if not status: + errors.append("Status is required.") + + if errors: + cursor.execute("SELECT * FROM clients WHERE id = %s", (client_id,)) + client = cursor.fetchone() + client["credit_balance"] = get_client_credit_balance(client_id) + conn.close() + return render_template("clients/edit.html", client=client, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET company_name = %s, + contact_name = %s, + email = %s, + phone = %s, + status = %s, + notes = %s + WHERE id = %s + """, ( + company_name, + contact_name or None, + email or None, + phone or None, + status, + notes or None, + client_id + )) + conn.commit() + conn.close() + return redirect("/clients") + + cursor.execute("SELECT * FROM clients WHERE id = %s", (client_id,)) + client = cursor.fetchone() + conn.close() + + if not client: + return "Client not found", 404 + + client["credit_balance"] = get_client_credit_balance(client_id) + + return render_template("clients/edit.html", client=client, errors=[]) + +@app.route("/credits/") +def client_credits(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + WHERE id = %s + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return "Client not found", 404 + + cursor.execute(""" + SELECT * + FROM credit_ledger + WHERE client_id = %s + ORDER BY id DESC + """, (client_id,)) + entries = cursor.fetchall() + + conn.close() + + balance = get_client_credit_balance(client_id) + + return render_template( + "credits/list.html", + client=client, + entries=entries, + balance=balance, + ) + +@app.route("/credits/add/", methods=["GET", "POST"]) +def add_credit(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + WHERE id = %s + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return "Client not found", 404 + + if request.method == "POST": + entry_type = request.form.get("entry_type", "").strip() + amount = request.form.get("amount", "").strip() + currency_code = request.form.get("currency_code", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not entry_type: + errors.append("Entry type is required.") + if not amount: + errors.append("Amount is required.") + if not currency_code: + errors.append("Currency code is required.") + + if not errors: + try: + amount_value = Decimal(str(amount)) + if amount_value == 0: + errors.append("Amount cannot be zero.") + except Exception: + errors.append("Amount must be a valid number.") + + if errors: + conn.close() + return render_template("credits/add.html", client=client, errors=errors) + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO credit_ledger + ( + client_id, + entry_type, + amount, + currency_code, + notes + ) + VALUES (%s, %s, %s, %s, %s) + """, ( + client_id, + entry_type, + amount, + currency_code, + notes or None + )) + conn.commit() + conn.close() + + return redirect(f"/credits/{client_id}") + + conn.close() + return render_template("credits/add.html", client=client, errors=[]) + +@app.route("/services") +def services(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT s.*, c.client_code, c.company_name + FROM services s + JOIN clients c ON s.client_id = c.id + ORDER BY s.id DESC + """) + services = cursor.fetchall() + conn.close() + return render_template("services/list.html", services=services) + +@app.route("/services/new", methods=["GET", "POST"]) +def new_service(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form["client_id"] + service_name = request.form["service_name"] + service_type = request.form["service_type"] + billing_cycle = request.form["billing_cycle"] + currency_code = request.form["currency_code"] + recurring_amount = request.form["recurring_amount"] + status = request.form["status"] + start_date = request.form["start_date"] or None + description = request.form["description"] + + cursor.execute("SELECT MAX(id) AS last_id FROM services") + result = cursor.fetchone() + last_number = result["last_id"] if result["last_id"] else 0 + service_code = generate_service_code(service_name, last_number) + + insert_cursor = conn.cursor() + insert_cursor.execute( + """ + INSERT INTO services + ( + client_id, + service_code, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date, + description + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, + ( + client_id, + service_code, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date, + description + ) + ) + conn.commit() + conn.close() + + return redirect("/services") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + conn.close() + return render_template("services/new.html", clients=clients) + +@app.route("/services/edit/", methods=["GET", "POST"]) +def edit_service(service_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_name = request.form.get("service_name", "").strip() + service_type = request.form.get("service_type", "").strip() + billing_cycle = request.form.get("billing_cycle", "").strip() + currency_code = request.form.get("currency_code", "").strip() + recurring_amount = request.form.get("recurring_amount", "").strip() + status = request.form.get("status", "").strip() + start_date = request.form.get("start_date", "").strip() + description = request.form.get("description", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_name: + errors.append("Service name is required.") + if not service_type: + errors.append("Service type is required.") + if not billing_cycle: + errors.append("Billing cycle is required.") + if not currency_code: + errors.append("Currency code is required.") + if not recurring_amount: + errors.append("Recurring amount is required.") + if not status: + errors.append("Status is required.") + + if not errors: + try: + recurring_amount_value = float(recurring_amount) + if recurring_amount_value < 0: + errors.append("Recurring amount cannot be negative.") + except ValueError: + errors.append("Recurring amount must be a valid number.") + + if errors: + cursor.execute(""" + SELECT s.*, c.company_name + FROM services s + LEFT JOIN clients c ON s.client_id = c.id + WHERE s.id = %s + """, (service_id,)) + service = cursor.fetchone() + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + + conn.close() + return render_template("services/edit.html", service=service, clients=clients, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE services + SET client_id = %s, + service_name = %s, + service_type = %s, + billing_cycle = %s, + status = %s, + currency_code = %s, + recurring_amount = %s, + start_date = %s, + description = %s + WHERE id = %s + """, ( + client_id, + service_name, + service_type, + billing_cycle, + status, + currency_code, + recurring_amount, + start_date or None, + description or None, + service_id + )) + conn.commit() + conn.close() + return redirect("/services") + + cursor.execute(""" + SELECT s.*, c.company_name + FROM services s + LEFT JOIN clients c ON s.client_id = c.id + WHERE s.id = %s + """, (service_id,)) + service = cursor.fetchone() + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name ASC") + clients = cursor.fetchall() + conn.close() + + if not service: + return "Service not found", 404 + + return render_template("services/edit.html", service=service, clients=clients, errors=[]) + + + + + + +@app.route("/invoices/export.csv") +def export_invoices_csv(): + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.id, + i.invoice_number, + i.client_id, + c.client_code, + c.company_name, + i.service_id, + i.currency_code, + i.subtotal_amount, + i.tax_amount, + i.total_amount, + i.amount_paid, + i.status, + i.issued_at, + i.due_at, + i.paid_at, + i.notes, + i.created_at, + i.updated_at + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + rows = cursor.fetchall() + conn.close() + + output = StringIO() + writer = csv.writer(output) + writer.writerow([ + "id", + "invoice_number", + "client_id", + "client_code", + "company_name", + "service_id", + "currency_code", + "subtotal_amount", + "tax_amount", + "total_amount", + "amount_paid", + "status", + "issued_at", + "due_at", + "paid_at", + "notes", + "created_at", + "updated_at", + ]) + + for r in rows: + writer.writerow([ + r.get("id", ""), + r.get("invoice_number", ""), + r.get("client_id", ""), + r.get("client_code", ""), + r.get("company_name", ""), + r.get("service_id", ""), + r.get("currency_code", ""), + r.get("subtotal_amount", ""), + r.get("tax_amount", ""), + r.get("total_amount", ""), + r.get("amount_paid", ""), + r.get("status", ""), + r.get("issued_at", ""), + r.get("due_at", ""), + r.get("paid_at", ""), + r.get("notes", ""), + r.get("created_at", ""), + r.get("updated_at", ""), + ]) + + filename = "invoices" + if start_date or end_date or status or client_id or limit_count: + filename += "_filtered" + filename += ".csv" + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = f"attachment; filename={filename}" + return response + + +@app.route("/invoices/export-pdf.zip") +def export_invoices_pdf_zip(): + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + conn.close() + + settings = get_app_settings() + + def build_invoice_pdf_bytes(invoice, settings): + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + terms = settings.get("payment_terms", "") + for chunk_start in range(0, len(terms), 90): + line_text = terms[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + footer = settings.get("invoice_footer", "") + for chunk_start in range(0, len(footer), 90): + line_text = footer[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + return buffer.getvalue() + + zip_buffer = BytesIO() + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zipf: + for invoice in invoices: + pdf_bytes = build_invoice_pdf_bytes(invoice, settings) + zipf.writestr(f"{invoice['invoice_number']}.pdf", pdf_bytes) + + zip_buffer.seek(0) + + filename = "invoices_export" + if start_date: + filename += f"_{start_date}" + if end_date: + filename += f"_to_{end_date}" + if status: + filename += f"_{status}" + if client_id: + filename += f"_client_{client_id}" + if limit_count: + filename += f"_limit_{limit_count}" + filename += ".zip" + + return send_file( + zip_buffer, + mimetype="application/zip", + as_attachment=True, + download_name=filename + ) + + +@app.route("/invoices/print") +def print_invoices(): + refresh_overdue_invoices() + + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id ASC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + conn.close() + + settings = get_app_settings() + + filters = { + "start_date": start_date, + "end_date": end_date, + "status": status, + "client_id": client_id, + "limit": limit_count, + } + + return render_template("invoices/print_batch.html", invoices=invoices, settings=settings, filters=filters) + +@app.route("/invoices") +def invoices(): + refresh_overdue_invoices() + + start_date = (request.args.get("start_date") or "").strip() + end_date = (request.args.get("end_date") or "").strip() + status = (request.args.get("status") or "").strip() + client_id = (request.args.get("client_id") or "").strip() + limit_count = (request.args.get("limit") or "").strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + query = """ + SELECT + i.*, + c.client_code, + c.company_name, + COALESCE((SELECT COUNT(*) FROM payments p WHERE p.invoice_id = i.id AND p.payment_status = 'confirmed'), 0) AS payment_count + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE 1=1 + """ + params = [] + + if start_date: + query += " AND DATE(i.issued_at) >= %s" + params.append(start_date) + + if end_date: + query += " AND DATE(i.issued_at) <= %s" + params.append(end_date) + + if status: + query += " AND i.status = %s" + params.append(status) + + if client_id: + query += " AND i.client_id = %s" + params.append(client_id) + + query += " ORDER BY i.id DESC" + + if limit_count: + try: + limit_int = int(limit_count) + if limit_int > 0: + query += " LIMIT %s" + params.append(limit_int) + except ValueError: + pass + + cursor.execute(query, tuple(params)) + invoices = cursor.fetchall() + + cursor.execute(""" + SELECT id, client_code, company_name + FROM clients + ORDER BY company_name ASC + """) + clients = cursor.fetchall() + + conn.close() + + filters = { + "start_date": start_date, + "end_date": end_date, + "status": status, + "client_id": client_id, + "limit": limit_count, + } + for inv in invoices: + inv["paid_via"] = "-" + + if str(inv.get("status") or "").lower() not in {"paid", "partial"}: + continue + + pay_conn = get_db_connection() + pay_cursor = pay_conn.cursor(dictionary=True) + pay_cursor.execute(""" + SELECT payment_method, payment_currency + FROM payments + WHERE invoice_id = %s + AND payment_status = 'confirmed' + ORDER BY COALESCE(received_at, created_at) DESC, id DESC + LIMIT 1 + """, (inv["id"],)) + last_payment = pay_cursor.fetchone() + pay_conn.close() + + if last_payment: + inv["paid_via"] = payment_method_label( + last_payment.get("payment_method"), + last_payment.get("payment_currency"), + ) + + + + return render_template("invoices/list.html", invoices=invoices, filters=filters, clients=clients) + +@app.route("/invoices/new", methods=["GET", "POST"]) +def new_invoice(): + ensure_invoice_quote_columns() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + currency_code = request.form.get("currency_code", "").strip() + total_amount = request.form.get("total_amount", "").strip() + due_at = request.form.get("due_at", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_id: + errors.append("Service is required.") + if not currency_code: + errors.append("Currency is required.") + if not total_amount: + errors.append("Total amount is required.") + if not due_at: + errors.append("Due date is required.") + + if not errors: + try: + amount_value = float(total_amount) + if amount_value <= 0: + errors.append("Total amount must be greater than zero.") + except ValueError: + errors.append("Total amount must be a valid number.") + + if errors: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + + form_data = { + "client_id": client_id, + "service_id": service_id, + "currency_code": currency_code, + "total_amount": total_amount, + "due_at": due_at, + "notes": notes, + } + + return render_template( + "invoices/new.html", + clients=clients, + services=services, + errors=errors, + form_data=form_data, + ) + + invoice_number = generate_invoice_number() + + cursor.execute("SELECT service_name FROM services WHERE id = %s", (service_id,)) + service_row = cursor.fetchone() + service_name = (service_row or {}).get("service_name") or "Service" + + line_description = service_name + if notes: + line_description = f"{service_name} - {notes}" + + oracle_snapshot = fetch_oracle_quote_snapshot(currency_code, total_amount) + oracle_snapshot_json = json.dumps(oracle_snapshot, ensure_ascii=False) if oracle_snapshot else None + quote_expires_at = normalize_oracle_datetime((oracle_snapshot or {}).get("expires_at")) + quote_fiat_amount = total_amount if oracle_snapshot else None + quote_fiat_currency = currency_code if oracle_snapshot else None + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO invoices + ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + subtotal_amount, + issued_at, + due_at, + status, + notes, + quote_fiat_amount, + quote_fiat_currency, + quote_expires_at, + oracle_snapshot + ) + VALUES (%s, %s, %s, %s, %s, %s, UTC_TIMESTAMP(), %s, 'pending', %s, %s, %s, %s, %s) + """, ( + client_id, + service_id, + invoice_number, + currency_code, + total_amount, + total_amount, + due_at, + notes, + quote_fiat_amount, + quote_fiat_currency, + quote_expires_at, + oracle_snapshot_json + )) + + invoice_id = insert_cursor.lastrowid + + insert_cursor.execute(""" + INSERT INTO invoice_items + ( + invoice_id, + line_number, + item_type, + description, + quantity, + unit_amount, + line_total, + currency_code, + service_id + ) + VALUES (%s, 1, 'service', %s, 1.0000, %s, %s, %s, %s) + """, ( + invoice_id, + line_description, + total_amount, + total_amount, + currency_code, + service_id + )) + + conn.commit() + conn.close() + + return redirect("/invoices") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + + return render_template( + "invoices/new.html", + clients=clients, + services=services, + errors=[], + form_data={}, + ) + + + + + +@app.route("/invoices/pdf/") +def invoice_pdf(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + conn.close() + + settings = get_app_settings() + + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def draw_line(txt, x=left, font="Helvetica", size=11): + nonlocal y + pdf.setFont(font, size) + pdf.drawString(x, y, str(txt) if txt is not None else "") + y -= 16 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("payment_terms", "")), 90): + line_text = settings.get("payment_terms", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if invoice_payments: + y -= 8 + if y < 170: + pdf.showPage() + y = height - 50 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payments Applied") + y -= 16 + + for p in invoice_payments: + if y < 110: + pdf.showPage() + y = height - 50 + + pdf.setFont("Helvetica-Bold", 10) + pdf.drawString( + left, + y, + f"{p.get('payment_method_label', 'Unknown')} | {p.get('payment_amount_display', '')} {p.get('payment_currency', '')} | {str(p.get('payment_status') or '').upper()}" + ) + y -= 13 + + details_parts = [] + if p.get("received_at_local"): + details_parts.append(f"At: {p.get('received_at_local')}") + if p.get("txid"): + details_parts.append(f"TXID: {p.get('txid')}") + elif p.get("reference"): + details_parts.append(f"Ref: {p.get('reference')}") + if p.get("wallet_address"): + details_parts.append(f"Wallet: {p.get('wallet_address')}") + + details = " | ".join(details_parts) + if details: + pdf.setFont("Helvetica", 9) + for chunk_start in range(0, len(details), 108): + if y < 95: + pdf.showPage() + y = height - 50 + pdf.setFont("Helvetica", 9) + pdf.drawString(left + 10, y, details[chunk_start:chunk_start+108]) + y -= 11 + + y -= 6 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("invoice_footer", "")), 90): + line_text = settings.get("invoice_footer", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + + return send_file( + buffer, + mimetype="application/pdf", + as_attachment=True, + download_name=f"{invoice['invoice_number']}.pdf" + ) + + +@app.route("/invoices/view/") +def view_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + conn.close() + settings = get_app_settings() + invoice_payments = get_invoice_payments(invoice_id) + return render_template( + "invoices/view.html", + invoice=invoice, + settings=settings, + invoice_payments=invoice_payments + ) + + +@app.route("/invoices/edit/", methods=["GET", "POST"]) +def edit_invoice(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT i.*, + COALESCE((SELECT COUNT(*) FROM payments p WHERE p.invoice_id = i.id), 0) AS payment_count + FROM invoices i + WHERE i.id = %s + """, (invoice_id,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return "Invoice not found", 404 + + locked = invoice["payment_count"] > 0 or float(invoice["amount_paid"]) > 0 + + if request.method == "POST": + due_at = request.form.get("due_at", "").strip() + notes = request.form.get("notes", "").strip() + + if locked: + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET due_at = %s, + notes = %s + WHERE id = %s + """, ( + due_at or None, + notes or None, + invoice_id + )) + conn.commit() + conn.close() + return redirect("/invoices") + + client_id = request.form.get("client_id", "").strip() + service_id = request.form.get("service_id", "").strip() + currency_code = request.form.get("currency_code", "").strip() + total_amount = request.form.get("total_amount", "").strip() + status = request.form.get("status", "").strip() + + errors = [] + + if not client_id: + errors.append("Client is required.") + if not service_id: + errors.append("Service is required.") + if not currency_code: + errors.append("Currency is required.") + if not total_amount: + errors.append("Total amount is required.") + if not due_at: + errors.append("Due date is required.") + if not status: + errors.append("Status is required.") + + manual_statuses = {"draft", "pending", "cancelled"} + if status and status not in manual_statuses: + errors.append("Manual invoice status must be draft, pending, or cancelled.") + + if not errors: + try: + amount_value = float(total_amount) + if amount_value < 0: + errors.append("Total amount cannot be negative.") + except ValueError: + errors.append("Total amount must be a valid number.") + + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + if errors: + invoice["client_id"] = int(client_id) if client_id else invoice["client_id"] + invoice["service_id"] = int(service_id) if service_id else invoice["service_id"] + invoice["currency_code"] = currency_code or invoice["currency_code"] + invoice["total_amount"] = total_amount or invoice["total_amount"] + invoice["due_at"] = due_at or invoice["due_at"] + invoice["status"] = status or invoice["status"] + invoice["notes"] = notes + conn.close() + return render_template("invoices/edit.html", invoice=invoice, clients=clients, services=services, errors=errors, locked=locked) + + cursor.execute("SELECT service_name FROM services WHERE id = %s", (service_id,)) + service_row = cursor.fetchone() + service_name = (service_row or {}).get("service_name") or "Service" + + line_description = service_name + if notes: + line_description = f"{service_name} - {notes}" + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE invoices + SET client_id = %s, + service_id = %s, + currency_code = %s, + total_amount = %s, + subtotal_amount = %s, + due_at = %s, + status = %s, + notes = %s + WHERE id = %s + """, ( + client_id, + service_id, + currency_code, + total_amount, + total_amount, + due_at, + status, + notes or None, + invoice_id + )) + + update_cursor.execute("DELETE FROM invoice_items WHERE invoice_id = %s", (invoice_id,)) + update_cursor.execute(""" + INSERT INTO invoice_items + ( + invoice_id, + line_number, + item_type, + description, + quantity, + unit_amount, + line_total, + currency_code, + service_id + ) + VALUES (%s, 1, 'service', %s, 1.0000, %s, %s, %s, %s) + """, ( + invoice_id, + line_description, + total_amount, + total_amount, + currency_code, + service_id + )) + + conn.commit() + conn.close() + return redirect("/invoices") + + clients = [] + services = [] + + if not locked: + cursor.execute("SELECT id, client_code, company_name FROM clients ORDER BY company_name") + clients = cursor.fetchall() + + cursor.execute("SELECT id, service_code, service_name FROM services ORDER BY service_name") + services = cursor.fetchall() + + conn.close() + return render_template("invoices/edit.html", invoice=invoice, clients=clients, services=services, errors=[], locked=locked) + + + +@app.route("/payments/export.csv") +def export_payments_csv(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + p.id, + p.invoice_id, + i.invoice_number, + p.client_id, + c.client_code, + c.company_name, + p.payment_method, + p.payment_currency, + p.payment_amount, + p.cad_value_at_payment, + p.reference, + p.sender_name, + p.txid, + p.wallet_address, + p.payment_status, + p.received_at, + p.notes + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + ORDER BY p.id ASC + """) + rows = cursor.fetchall() + conn.close() + + output = StringIO() + writer = csv.writer(output) + writer.writerow([ + "id", + "invoice_id", + "invoice_number", + "client_id", + "client_code", + "company_name", + "payment_method", + "payment_currency", + "payment_amount", + "cad_value_at_payment", + "reference", + "sender_name", + "txid", + "wallet_address", + "payment_status", + "received_at", + "notes", + ]) + + for r in rows: + writer.writerow([ + r.get("id", ""), + r.get("invoice_id", ""), + r.get("invoice_number", ""), + r.get("client_id", ""), + r.get("client_code", ""), + r.get("company_name", ""), + r.get("payment_method", ""), + r.get("payment_currency", ""), + r.get("payment_amount", ""), + r.get("cad_value_at_payment", ""), + r.get("reference", ""), + r.get("sender_name", ""), + r.get("txid", ""), + r.get("wallet_address", ""), + r.get("payment_status", ""), + r.get("received_at", ""), + r.get("notes", ""), + ]) + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = "attachment; filename=payments.csv" + return response + +@app.route("/payments") +def payments(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + p.*, + i.invoice_number, + i.status AS invoice_status, + i.total_amount, + i.amount_paid, + i.currency_code AS invoice_currency_code, + c.client_code, + c.company_name + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + ORDER BY p.id DESC + """) + payments = cursor.fetchall() + + conn.close() + return render_template("payments/list.html", payments=payments) + +@app.route("/payments/new", methods=["GET", "POST"]) +def new_payment(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + if request.method == "POST": + invoice_id = request.form.get("invoice_id", "").strip() + payment_method = request.form.get("payment_method", "").strip() + payment_currency = request.form.get("payment_currency", "").strip() + payment_amount = request.form.get("payment_amount", "").strip() + cad_value_at_payment = request.form.get("cad_value_at_payment", "").strip() + reference = request.form.get("reference", "").strip() + sender_name = request.form.get("sender_name", "").strip() + txid = request.form.get("txid", "").strip() + wallet_address = request.form.get("wallet_address", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not invoice_id: + errors.append("Invoice is required.") + if not payment_method: + errors.append("Payment method is required.") + if not payment_currency: + errors.append("Payment currency is required.") + if not payment_amount: + errors.append("Payment amount is required.") + if not cad_value_at_payment: + errors.append("CAD value at payment is required.") + + if not errors: + try: + payment_amount_value = Decimal(str(payment_amount)) + if payment_amount_value <= Decimal("0"): + errors.append("Payment amount must be greater than zero.") + except Exception: + errors.append("Payment amount must be a valid number.") + + if not errors: + try: + cad_value_value = Decimal(str(cad_value_at_payment)) + if cad_value_value < Decimal("0"): + errors.append("CAD value at payment cannot be negative.") + except Exception: + errors.append("CAD value at payment must be a valid number.") + + invoice_row = None + + if not errors: + cursor.execute(""" + SELECT + i.id, + i.client_id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + """, (invoice_id,)) + invoice_row = cursor.fetchone() + + if not invoice_row: + errors.append("Selected invoice was not found.") + else: + allowed_statuses = {"pending", "partial", "overdue"} + if invoice_row["status"] not in allowed_statuses: + errors.append("Payments can only be recorded against pending, partial, or overdue invoices.") + else: + remaining_balance = to_decimal(invoice_row["total_amount"]) - to_decimal(invoice_row["amount_paid"]) + entered_amount = to_decimal(payment_amount) + + if remaining_balance <= Decimal("0"): + errors.append("This invoice has no remaining balance.") + elif entered_amount > remaining_balance: + errors.append( + f"Payment amount exceeds remaining balance. Remaining balance is {fmt_money(remaining_balance, invoice_row['currency_code'])} {invoice_row['currency_code']}." + ) + + if errors: + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY i.id DESC + """) + invoices = cursor.fetchall() + conn.close() + + form_data = { + "invoice_id": invoice_id, + "payment_method": payment_method, + "payment_currency": payment_currency, + "payment_amount": payment_amount, + "cad_value_at_payment": cad_value_at_payment, + "reference": reference, + "sender_name": sender_name, + "txid": txid, + "wallet_address": wallet_address, + "notes": notes, + } + + return render_template( + "payments/new.html", + invoices=invoices, + errors=errors, + form_data=form_data, + ) + + client_id = invoice_row["client_id"] + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'confirmed', UTC_TIMESTAMP(), %s) + """, ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference or None, + sender_name or None, + txid or None, + wallet_address or None, + notes or None + )) + + conn.commit() + conn.close() + + recalc_invoice_totals(invoice_id) + + try: + notify_conn = get_db_connection() + notify_cursor = notify_conn.cursor(dictionary=True) + notify_cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.currency_code, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice_id,)) + invoice_email_row = notify_cursor.fetchone() + notify_conn.close() + + if invoice_email_row and invoice_email_row.get("email"): + client_name = ( + invoice_email_row.get("contact_name") + or invoice_email_row.get("company_name") + or invoice_email_row.get("email") + ) + payment_amount_display = f"{to_decimal(cad_value_at_payment):.2f} CAD" + invoice_total_display = f"{to_decimal(invoice_email_row.get('total_amount')):.2f} {invoice_email_row.get('currency_code') or 'CAD'}" + + subject = f"Payment Received for Invoice {invoice_email_row.get('invoice_number')}" + body = f"""Hello {client_name}, + +We have received your payment for invoice {invoice_email_row.get('invoice_number')}. + +Amount Received: +{payment_amount_display} + +Invoice Total: +{invoice_total_display} + +Current Invoice Status: +{invoice_email_row.get('status')} + +You can view your invoice anytime in the client portal: +https://portal.outsidethebox.top/portal + +Thank you, +OutsideTheBox +support@outsidethebox.top +""" + + send_configured_email( + to_email=invoice_email_row.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="payment_received", + invoice_id=invoice_id + ) + except Exception: + pass + + return redirect("/payments") + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.client_code, + c.company_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.status IN ('pending', 'partial', 'overdue') + AND (i.total_amount - i.amount_paid) > 0 + ORDER BY i.id DESC + """) + invoices = cursor.fetchall() + conn.close() + + return render_template( + "payments/new.html", + invoices=invoices, + errors=[], + form_data={}, + ) + + + +@app.route("/payments/void/", methods=["POST"]) +def void_payment(payment_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, invoice_id, payment_status + FROM payments + WHERE id = %s + """, (payment_id,)) + payment = cursor.fetchone() + + if not payment: + conn.close() + return "Payment not found", 404 + + if payment["payment_status"] != "confirmed": + conn.close() + return redirect("/payments") + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_status = 'reversed' + WHERE id = %s + """, (payment_id,)) + + conn.commit() + conn.close() + + recalc_invoice_totals(payment["invoice_id"]) + + return redirect("/payments") + + recalc_invoice_totals(payment["invoice_id"]) + + return redirect("/payments") + +@app.route("/payments/edit/", methods=["GET", "POST"]) +def edit_payment(payment_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + p.*, + i.invoice_number, + c.client_code, + c.company_name + FROM payments p + JOIN invoices i ON p.invoice_id = i.id + JOIN clients c ON p.client_id = c.id + WHERE p.id = %s + """, (payment_id,)) + payment = cursor.fetchone() + + if not payment: + conn.close() + return "Payment not found", 404 + + if request.method == "POST": + payment_method = request.form.get("payment_method", "").strip() + payment_currency = request.form.get("payment_currency", "").strip() + payment_amount = request.form.get("payment_amount", "").strip() + cad_value_at_payment = request.form.get("cad_value_at_payment", "").strip() + reference = request.form.get("reference", "").strip() + sender_name = request.form.get("sender_name", "").strip() + txid = request.form.get("txid", "").strip() + wallet_address = request.form.get("wallet_address", "").strip() + notes = request.form.get("notes", "").strip() + + errors = [] + + if not payment_method: + errors.append("Payment method is required.") + if not payment_currency: + errors.append("Payment currency is required.") + if not payment_amount: + errors.append("Payment amount is required.") + if not cad_value_at_payment: + errors.append("CAD value at payment is required.") + + if not errors: + try: + amount_value = float(payment_amount) + if amount_value <= 0: + errors.append("Payment amount must be greater than zero.") + except ValueError: + errors.append("Payment amount must be a valid number.") + + try: + cad_value = float(cad_value_at_payment) + if cad_value < 0: + errors.append("CAD value at payment cannot be negative.") + except ValueError: + errors.append("CAD value at payment must be a valid number.") + + if errors: + payment["payment_method"] = payment_method or payment["payment_method"] + payment["payment_currency"] = payment_currency or payment["payment_currency"] + payment["payment_amount"] = payment_amount or payment["payment_amount"] + payment["cad_value_at_payment"] = cad_value_at_payment or payment["cad_value_at_payment"] + payment["reference"] = reference + payment["sender_name"] = sender_name + payment["txid"] = txid + payment["wallet_address"] = wallet_address + payment["notes"] = notes + conn.close() + return render_template("payments/edit.html", payment=payment, errors=errors) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET payment_method = %s, + payment_currency = %s, + payment_amount = %s, + cad_value_at_payment = %s, + reference = %s, + sender_name = %s, + txid = %s, + wallet_address = %s, + notes = %s + WHERE id = %s + """, ( + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference or None, + sender_name or None, + txid or None, + wallet_address or None, + notes or None, + payment_id + )) + conn.commit() + invoice_id = payment["invoice_id"] + conn.close() + + recalc_invoice_totals(invoice_id) + + return redirect("/payments") + + conn.close() + return render_template("payments/edit.html", payment=payment, errors=[]) + + +def _portal_current_client(): + client_id = session.get("portal_client_id") + if not client_id: + return None + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, company_name, contact_name, email, portal_enabled, portal_force_password_change + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + conn.close() + return client + +@app.route("/portal", methods=["GET"]) +def portal_index(): + if session.get("portal_client_id"): + return redirect("/portal/dashboard") + return render_template("portal_login.html") + +@app.route("/portal/login", methods=["POST"]) +def portal_login(): + email = (request.form.get("email") or "").strip().lower() + credential = (request.form.get("credential") or "").strip() + + if not email or not credential: + return render_template("portal_login.html", portal_message="Email and access code or password are required.", portal_email=email) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, company_name, contact_name, email, portal_enabled, portal_access_code, + portal_password_hash, portal_force_password_change + FROM clients + WHERE LOWER(email) = %s + LIMIT 1 + """, (email,)) + client = cursor.fetchone() + + if not client or not client.get("portal_enabled"): + conn.close() + return render_template("portal_login.html", portal_message="Portal access is not enabled for that email address.", portal_email=email) + + password_hash = client.get("portal_password_hash") + access_code = client.get("portal_access_code") or "" + + ok = False + first_login = False + + if password_hash: + ok = check_password_hash(password_hash, credential) + else: + ok = (credential == access_code) + first_login = ok + + if not ok and access_code and credential == access_code: + ok = True + first_login = True + + if not ok: + conn.close() + return render_template("portal_login.html", portal_message="Invalid credentials.", portal_email=email) + + session["portal_client_id"] = client["id"] + session["portal_email"] = client["email"] + + cursor.execute(""" + UPDATE clients + SET portal_last_login_at = UTC_TIMESTAMP() + WHERE id = %s + """, (client["id"],)) + conn.commit() + conn.close() + + if first_login or client.get("portal_force_password_change"): + return redirect("/portal/set-password") + + return redirect("/portal/dashboard") + +@app.route("/portal/set-password", methods=["GET", "POST"]) +def portal_set_password(): + client = _portal_current_client() + if not client: + return redirect("/portal") + + client_name = client.get("company_name") or client.get("contact_name") or client.get("email") + + if request.method == "GET": + return render_template("portal_set_password.html", client_name=client_name) + + password = (request.form.get("password") or "") + password2 = (request.form.get("password2") or "") + + if len(password) < 10: + return render_template("portal_set_password.html", client_name=client_name, portal_message="Password must be at least 10 characters long.") + if password != password2: + return render_template("portal_set_password.html", client_name=client_name, portal_message="Passwords do not match.") + + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_password_hash = %s, + portal_password_set_at = UTC_TIMESTAMP(), + portal_force_password_change = 0, + portal_access_code = NULL + WHERE id = %s + """, (generate_password_hash(password), client["id"])) + conn.commit() + conn.close() + + return redirect("/portal/dashboard") + + + +@app.route("/portal/invoices/download-all") +def portal_download_all_invoices(): + import io + import zipfile + + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, invoice_number + FROM invoices + WHERE client_id = %s + ORDER BY id + """, (client["id"],)) + invoices = cursor.fetchall() + conn.close() + + memory_file = io.BytesIO() + + with zipfile.ZipFile(memory_file, "w", zipfile.ZIP_DEFLATED) as zf: + for inv in invoices: + response = invoice_pdf(inv["id"]) + response.direct_passthrough = False + pdf_bytes = response.get_data() + + filename = f"{inv.get('invoice_number') or ('invoice_' + str(inv['id']))}.pdf" + zf.writestr(filename, pdf_bytes) + + memory_file.seek(0) + + return send_file( + memory_file, + download_name="all_invoices.zip", + as_attachment=True, + mimetype="application/zip", + ) + +@app.route("/portal/dashboard", methods=["GET"]) +def portal_dashboard(): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.created_at, + i.total_amount, + i.amount_paid, + p.payment_method, + p.payment_currency + FROM invoices i + LEFT JOIN ( + SELECT p1.invoice_id, p1.payment_method, p1.payment_currency + FROM payments p1 + INNER JOIN ( + SELECT invoice_id, MAX(id) AS max_id + FROM payments + GROUP BY invoice_id + ) latest + ON latest.invoice_id = p1.invoice_id + AND latest.max_id = p1.id + ) p + ON p.invoice_id = i.id + WHERE i.client_id = %s + ORDER BY i.created_at DESC + """, (client["id"],)) + invoices = cursor.fetchall() + + def _fmt_money(value): + return f"{to_decimal(value):.2f}" + + def _payment_method_label(method, currency): + method_key = str(method or "").strip().lower() + currency_key = str(currency or "").strip().upper() + + if method_key == "square": + return "Square" + if method_key == "etransfer": + return "e-Transfer" + if method_key == "cash": + return "Cash" + if method_key == "crypto_etho": + return "ETHO" + if method_key == "crypto_egaz": + return "EGAZ" + if method_key == "crypto_alt": + return "ALT" + if method_key == "other" and currency_key: + return currency_key + if currency_key: + return currency_key + return "" + + for row in invoices: + outstanding = to_decimal(row.get("total_amount")) - to_decimal(row.get("amount_paid")) + row["outstanding"] = _fmt_money(outstanding) + row["total_amount"] = _fmt_money(row.get("total_amount")) + row["amount_paid"] = _fmt_money(row.get("amount_paid")) + row["created_at"] = fmt_local(row.get("created_at")) + row["payment_method_label"] = _payment_method_label( + row.get("payment_method"), + row.get("payment_currency"), + ) + + total_outstanding = sum((to_decimal(r["outstanding"]) for r in invoices), to_decimal("0")) + total_paid = sum((to_decimal(r["amount_paid"]) for r in invoices), to_decimal("0")) + + conn.close() + + return render_template( + "portal_dashboard.html", + client=client, + invoices=invoices, + invoice_count=len(invoices), + total_outstanding=f"{total_outstanding:.2f}", + total_paid=f"{total_paid:.2f}", + ) + + +@app.route("/portal/invoice//pdf", methods=["GET"]) +def portal_invoice_pdf(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + i.*, + c.client_code, + c.company_name, + c.contact_name, + c.email, + c.phone, + s.service_code, + s.service_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + LEFT JOIN services s ON i.service_id = s.id + WHERE i.id = %s AND i.client_id = %s + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + conn.close() + + settings = get_app_settings() + + buffer = BytesIO() + pdf = canvas.Canvas(buffer, pagesize=letter) + width, height = letter + + left = 50 + right = 560 + y = height - 50 + + def draw_line(txt, x=left, font="Helvetica", size=11): + nonlocal y + pdf.setFont(font, size) + pdf.drawString(x, y, str(txt) if txt is not None else "") + y -= 16 + + def money(value, currency="CAD"): + return f"{to_decimal(value):.2f} {currency}" + + pdf.setTitle(f"Invoice {invoice['invoice_number']}") + + logo_url = (settings.get("business_logo_url") or "").strip() + if logo_url.startswith("/static/"): + local_logo_path = str(BASE_DIR) + logo_url + try: + pdf.drawImage(ImageReader(local_logo_path), left, y - 35, width=42, height=42, preserveAspectRatio=True, mask='auto') + except Exception: + pass + + pdf.setFont("Helvetica-Bold", 22) + pdf.drawString(left + 60, y, f"Invoice {invoice['invoice_number']}") + + pdf.setFont("Helvetica-Bold", 14) + pdf.drawRightString(right, y, settings.get("business_name") or "OTB Billing") + y -= 18 + pdf.setFont("Helvetica", 12) + pdf.drawRightString(right, y, settings.get("business_tagline") or "") + y -= 15 + + right_lines = [ + settings.get("business_address", ""), + settings.get("business_email", ""), + settings.get("business_phone", ""), + settings.get("business_website", ""), + ] + for item in right_lines: + if item: + pdf.drawRightString(right, y, item[:80]) + y -= 14 + + y -= 10 + + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, "Status:") + pdf.setFont("Helvetica", 12) + pdf.drawString(left + 45, y, str(invoice["status"]).upper()) + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Bill To") + y -= 20 + pdf.setFont("Helvetica-Bold", 12) + pdf.drawString(left, y, invoice["company_name"] or "") + y -= 16 + pdf.setFont("Helvetica", 11) + if invoice.get("contact_name"): + pdf.drawString(left, y, str(invoice["contact_name"])) + y -= 15 + if invoice.get("email"): + pdf.drawString(left, y, str(invoice["email"])) + y -= 15 + if invoice.get("phone"): + pdf.drawString(left, y, str(invoice["phone"])) + y -= 15 + pdf.drawString(left, y, f"Client Code: {invoice.get('client_code', '')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 13) + pdf.drawString(left, y, "Invoice Details") + y -= 20 + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, f"Invoice #: {invoice['invoice_number']}") + y -= 15 + pdf.drawString(left, y, f"Issued: {fmt_local(invoice.get('issued_at'))}") + y -= 15 + pdf.drawString(left, y, f"Due: {fmt_local(invoice.get('due_at'))}") + y -= 15 + if invoice.get("paid_at"): + pdf.drawString(left, y, f"Paid: {fmt_local(invoice.get('paid_at'))}") + y -= 15 + pdf.drawString(left, y, f"Currency: {invoice.get('currency_code', 'CAD')}") + y -= 28 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Service Code") + pdf.drawString(180, y, "Service") + pdf.drawString(330, y, "Description") + pdf.drawRightString(right, y, "Total") + y -= 14 + pdf.line(left, y, right, y) + y -= 18 + + pdf.setFont("Helvetica", 11) + pdf.drawString(left, y, str(invoice.get("service_code") or "-")) + pdf.drawString(180, y, str(invoice.get("service_name") or "-")) + pdf.drawString(330, y, str(invoice.get("notes") or "-")[:28]) + pdf.drawRightString(right, y, money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))) + y -= 28 + + totals_x_label = 360 + totals_x_value = right + + totals = [ + ("Subtotal", money(invoice.get("subtotal_amount"), invoice.get("currency_code", "CAD"))), + ((settings.get("tax_label") or "Tax"), money(invoice.get("tax_amount"), invoice.get("currency_code", "CAD"))), + ("Total", money(invoice.get("total_amount"), invoice.get("currency_code", "CAD"))), + ("Paid", money(invoice.get("amount_paid"), invoice.get("currency_code", "CAD"))), + ] + + remaining = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + + for label, value in totals: + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, label) + pdf.setFont("Helvetica", 11) + pdf.drawRightString(totals_x_value, y, value) + y -= 18 + + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(totals_x_label, y, "Remaining") + pdf.drawRightString(totals_x_value, y, f"{remaining:.2f} {invoice.get('currency_code', 'CAD')}") + y -= 25 + + if settings.get("tax_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"{settings.get('tax_label') or 'Tax'} Number: {settings.get('tax_number')}") + y -= 14 + + if settings.get("business_number"): + pdf.setFont("Helvetica", 10) + pdf.drawString(left, y, f"Business Number: {settings.get('business_number')}") + y -= 14 + + if settings.get("payment_terms"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Payment Terms") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("payment_terms", "")), 90): + line_text = settings.get("payment_terms", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + if settings.get("invoice_footer"): + y -= 8 + pdf.setFont("Helvetica-Bold", 11) + pdf.drawString(left, y, "Footer") + y -= 15 + pdf.setFont("Helvetica", 10) + for chunk_start in range(0, len(settings.get("invoice_footer", "")), 90): + line_text = settings.get("invoice_footer", "")[chunk_start:chunk_start+90] + pdf.drawString(left, y, line_text) + y -= 13 + + pdf.showPage() + pdf.save() + buffer.seek(0) + + return send_file( + buffer, + mimetype="application/pdf", + as_attachment=True, + download_name=f"{invoice['invoice_number']}.pdf" + ) + + +@app.route("/portal/invoice/", methods=["GET"]) +def portal_invoice_detail(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + ensure_invoice_quote_columns() + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_id, invoice_number, status, created_at, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + cursor.execute(""" + SELECT description, quantity, unit_amount AS unit_price, line_total + FROM invoice_items + WHERE invoice_id = %s + ORDER BY id ASC + """, (invoice_id,)) + items = cursor.fetchall() + + def _fmt_money(value): + return f"{to_decimal(value):.2f}" + + outstanding = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + invoice["outstanding"] = _fmt_money(outstanding) + invoice["total_amount"] = _fmt_money(invoice.get("total_amount")) + invoice["amount_paid"] = _fmt_money(invoice.get("amount_paid")) + invoice["created_at"] = fmt_local(invoice.get("created_at")) + invoice["quote_expires_at_local"] = fmt_local(invoice.get("quote_expires_at")) + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + for item in items: + item["quantity"] = _fmt_money(item.get("quantity")) + item["unit_price"] = _fmt_money(item.get("unit_price")) + item["line_total"] = _fmt_money(item.get("line_total")) + + pay_mode = (request.args.get("pay") or "").strip().lower() + crypto_error = (request.args.get("crypto_error") or "").strip() + + crypto_options = get_invoice_crypto_options(invoice) + selected_crypto_option = None + pending_crypto_payment = None + crypto_quote_window_expires_iso = None + crypto_quote_window_expires_local = None + + if (invoice.get("status") or "").lower() != "paid": + if pay_mode != "crypto": + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, updated_at, txid, confirmations, + confirmation_required, notes + FROM payments + WHERE invoice_id = %s + AND client_id = %s + AND payment_status = 'pending' + AND notes LIKE '%%portal_crypto_intent:%%' + ORDER BY id DESC + LIMIT 1 + """, (invoice_id, client["id"])) + auto_pending_payment = cursor.fetchone() + if auto_pending_payment: + pending_crypto_payment = auto_pending_payment + pay_mode = "crypto" + if not request.args.get("payment_id"): + selected_crypto_option = next( + (o for o in crypto_options if o["payment_currency"] == str(auto_pending_payment.get("payment_currency") or "").upper()), + None + ) + + if pay_mode == "crypto" and crypto_options and (invoice.get("status") or "").lower() != "paid": + quote_key = f"portal_crypto_quote_window_{invoice_id}_{client['id']}" + now_utc = datetime.now(timezone.utc) + + stored_start = session.get(quote_key) + quote_start_dt = None + if stored_start: + try: + quote_start_dt = datetime.fromisoformat(str(stored_start).replace("Z", "+00:00")) + if quote_start_dt.tzinfo is None: + quote_start_dt = quote_start_dt.replace(tzinfo=timezone.utc) + except Exception: + quote_start_dt = None + + if request.args.get("refresh_quote") == "1" or not quote_start_dt or (now_utc - quote_start_dt).total_seconds() > 90: + quote_start_dt = now_utc + session[quote_key] = quote_start_dt.isoformat() + + quote_expires_dt = quote_start_dt + timedelta(seconds=90) + crypto_quote_window_expires_iso = quote_expires_dt.astimezone(timezone.utc).isoformat() + crypto_quote_window_expires_local = fmt_local(quote_expires_dt) + + selected_asset = (request.args.get("asset") or "").strip().upper() + if selected_asset: + selected_crypto_option = next((o for o in crypto_options if o["symbol"] == selected_asset), None) + + payment_id = (request.args.get("payment_id") or "").strip() + if not payment_id and pending_crypto_payment: + payment_id = str(pending_crypto_payment.get("id") or "").strip() + + if payment_id.isdigit(): + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, received_at, txid, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (payment_id, invoice_id, client["id"])) + pending_crypto_payment = cursor.fetchone() + + if pending_crypto_payment: + created_dt = pending_crypto_payment.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + + if created_dt: + lock_expires_dt = created_dt + timedelta(minutes=2) + pending_crypto_payment["created_at_local"] = fmt_local(created_dt) + pending_crypto_payment["lock_expires_at_local"] = fmt_local(lock_expires_dt) + pending_crypto_payment["lock_expires_at_iso"] = lock_expires_dt.astimezone(timezone.utc).isoformat() + pending_crypto_payment["lock_expired"] = datetime.now(timezone.utc) >= lock_expires_dt + else: + pending_crypto_payment["created_at_local"] = "" + pending_crypto_payment["lock_expires_at_local"] = "" + pending_crypto_payment["lock_expires_at_iso"] = "" + pending_crypto_payment["lock_expired"] = True + + received_dt = pending_crypto_payment.get("received_at") + if received_dt and received_dt.tzinfo is None: + received_dt = received_dt.replace(tzinfo=timezone.utc) + + if received_dt: + processing_expires_dt = received_dt + timedelta(minutes=15) + pending_crypto_payment["received_at_local"] = fmt_local(received_dt) + pending_crypto_payment["processing_expires_at_local"] = fmt_local(processing_expires_dt) + pending_crypto_payment["processing_expires_at_iso"] = processing_expires_dt.astimezone(timezone.utc).isoformat() + pending_crypto_payment["processing_expired"] = datetime.now(timezone.utc) >= processing_expires_dt + else: + pending_crypto_payment["received_at_local"] = "" + pending_crypto_payment["processing_expires_at_local"] = "" + pending_crypto_payment["processing_expires_at_iso"] = "" + pending_crypto_payment["processing_expired"] = False + + if not selected_crypto_option: + selected_crypto_option = next( + (o for o in crypto_options if o["payment_currency"] == str(pending_crypto_payment.get("payment_currency") or "").upper()), + None + ) + + if pending_crypto_payment.get("txid") and str(pending_crypto_payment.get("payment_status") or "").lower() == "pending": + reconcile_result = reconcile_pending_crypto_payment(pending_crypto_payment) + + cursor.execute(""" + SELECT id, client_id, invoice_number, status, created_at, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + refreshed_invoice = cursor.fetchone() + if refreshed_invoice: + invoice.update(refreshed_invoice) + + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_amount, cad_value_at_payment, + reference, wallet_address, payment_status, created_at, updated_at, txid, confirmations, + confirmation_required, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (payment_id, invoice_id, client["id"])) + refreshed_payment = cursor.fetchone() + if refreshed_payment: + pending_crypto_payment = refreshed_payment + + if reconcile_result.get("state") == "confirmed": + outstanding = to_decimal(invoice.get("total_amount")) - to_decimal(invoice.get("amount_paid")) + invoice["outstanding"] = _fmt_money(outstanding) + invoice["total_amount"] = _fmt_money(invoice.get("total_amount")) + invoice["amount_paid"] = _fmt_money(invoice.get("amount_paid")) + elif reconcile_result.get("state") in {"timeout", "failed_receipt"}: + crypto_error = "Transaction was not confirmed in time. Please refresh your quote and try again." + + pdf_url = f"/invoices/pdf/{invoice_id}" + invoice_payments = get_invoice_payments(invoice_id) + + conn.close() + + return render_template( + "portal_invoice_detail.html", + client=client, + invoice=invoice, + items=items, + pdf_url=pdf_url, + pay_mode=pay_mode, + crypto_error=crypto_error, + crypto_options=crypto_options, + selected_crypto_option=selected_crypto_option, + pending_crypto_payment=pending_crypto_payment, + crypto_quote_window_expires_iso=crypto_quote_window_expires_iso, + crypto_quote_window_expires_local=crypto_quote_window_expires_local, + invoice_payments=invoice_payments, + ) + + +@app.route("/portal/logout", methods=["GET"]) +def portal_logout(): + session.pop("portal_client_id", None) + session.pop("portal_email", None) + return redirect("/portal") + + + +@app.route("/clients/portal/enable/", methods=["POST"]) +def client_portal_enable(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, portal_enabled, portal_access_code, portal_password_hash + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("portal_access_code") and not client.get("portal_password_hash"): + new_code = generate_portal_access_code() + cursor2 = conn.cursor() + cursor2.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + else: + cursor2 = conn.cursor() + cursor2.execute(""" + UPDATE clients + SET portal_enabled = 1 + WHERE id = %s + """, (client_id,)) + + conn.commit() + conn.close() + return redirect(f"/clients/edit/{client_id}") + +@app.route("/clients/portal/disable/", methods=["POST"]) +def client_portal_disable(client_id): + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_enabled = 0 + WHERE id = %s + """, (client_id,)) + conn.commit() + conn.close() + return redirect(f"/clients/edit/{client_id}") + +@app.route("/clients/portal/reset-code/", methods=["POST"]) +def client_portal_reset_code(client_id): + new_code = generate_portal_access_code() + + conn = get_db_connection() + cursor = conn.cursor() + cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + conn.commit() + conn.close() + + return redirect(f"/clients/edit/{client_id}") + + +@app.route("/clients/portal/send-invite/", methods=["POST"]) +def client_portal_send_invite(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled, + portal_access_code, + portal_password_hash, + portal_password_set_at + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("email"): + conn.close() + return redirect(f"/clients/edit/{client_id}?portal_email_status=missing_email") + + access_code = client.get("portal_access_code") + + # If no active one-time code exists, generate a fresh one and require password setup again. + if not access_code: + access_code = generate_portal_access_code() + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (access_code, client_id)) + conn.commit() + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled, + portal_access_code, + portal_password_hash, + portal_password_set_at + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + elif not client.get("portal_enabled"): + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1 + WHERE id = %s + """, (client_id,)) + conn.commit() + + conn.close() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_email = client.get("email") or "" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Client Portal Access" + body = f"""Hello {contact_name}, + +Your OutsideTheBox client portal access is now ready. + +Portal URL: +{portal_url} + +Login email: +{portal_email} + +Single-use access code: +{client.get("portal_access_code")} + +Important: +- This access code is single-use. +- After your first successful login, you will be asked to create your password. +- Once your password is created, this access code is cleared and future logins will use your email address and password. + +If you have any trouble signing in, contact support: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=portal_email, + subject=subject, + body=body, + attachments=None, + email_type="portal_invite", + invoice_id=None + ) + return redirect(f"/clients/edit/{client_id}?portal_email_status=sent") + except Exception: + return redirect(f"/clients/edit/{client_id}?portal_email_status=error") + + +@app.route("/clients/portal/send-password-reset/", methods=["POST"]) +def client_portal_send_password_reset(client_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT + id, + company_name, + contact_name, + email, + portal_enabled + FROM clients + WHERE id = %s + LIMIT 1 + """, (client_id,)) + client = cursor.fetchone() + + if not client: + conn.close() + return redirect("/clients") + + if not client.get("email"): + conn.close() + return redirect(f"/clients/edit/{client_id}?portal_reset_status=missing_email") + + new_code = generate_portal_access_code() + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_enabled = 1, + portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1 + WHERE id = %s + """, (new_code, client_id)) + conn.commit() + conn.close() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_email = client.get("email") or "" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Portal Password Reset" + body = f"""Hello {contact_name}, + +A password reset has been issued for your OutsideTheBox client portal access. + +Portal URL: +{portal_url} + +Login email: +{portal_email} + +New single-use access code: +{new_code} + +Important: +- This access code is single-use. +- It replaces your previous portal password. +- After you sign in, you will be asked to create a new password. +- Once your new password is created, this access code is cleared and future logins will use your email address and password. + +If you did not expect this reset, contact support immediately: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=portal_email, + subject=subject, + body=body, + attachments=None, + email_type="portal_password_reset", + invoice_id=None + ) + return redirect(f"/clients/edit/{client_id}?portal_reset_status=sent") + except Exception: + return redirect(f"/clients/edit/{client_id}?portal_reset_status=error") + +@app.route("/portal/forgot-password", methods=["GET", "POST"]) +def portal_forgot_password(): + if request.method == "GET": + return render_template("portal_forgot_password.html", error=None, message=None, form_email="") + + email = (request.form.get("email") or "").strip().lower() + + if not email: + return render_template( + "portal_forgot_password.html", + error="Email address is required.", + message=None, + form_email="" + ) + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, company_name, contact_name, email + FROM clients + WHERE LOWER(email) = %s + LIMIT 1 + """, (email,)) + client = cursor.fetchone() + + if client: + new_code = generate_portal_access_code() + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE clients + SET portal_access_code = %s, + portal_access_code_created_at = UTC_TIMESTAMP(), + portal_password_hash = NULL, + portal_password_set_at = NULL, + portal_force_password_change = 1, + portal_enabled = 1 + WHERE id = %s + """, (new_code, client["id"])) + conn.commit() + + contact_name = client.get("contact_name") or client.get("company_name") or "Client" + portal_url = "https://portal.outsidethebox.top" + support_email = "support@outsidethebox.top" + + subject = "Your OutsideTheBox Portal Password Reset" + + body = f"""Hello {contact_name}, + +A password reset was requested for your OutsideTheBox client portal. + +Portal URL: +{portal_url} + +Login email: +{client.get("email")} + +Single-use access code: +{new_code} + +Important: +- This access code is single-use. +- It replaces your previous portal password. +- After you sign in, you will be asked to create a new password. +- Once your new password is created, this access code is cleared and future logins will use your email address and password. + +If you did not request this reset, contact support immediately: +{support_email} + +Regards, +OutsideTheBox +""" + + try: + send_configured_email( + to_email=client.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="portal_forgot_password", + invoice_id=None + ) + except Exception: + pass + + conn.close() + + return render_template( + "portal_forgot_password.html", + error=None, + message="If that email exists in our system, a reset message has been sent.", + form_email=email + ) + + + + +@app.route("/portal/invoice//pay-crypto", methods=["POST"]) +def portal_invoice_pay_crypto(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + ensure_invoice_quote_columns() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT id, client_id, invoice_number, status, total_amount, amount_paid, + quote_fiat_amount, quote_fiat_currency, quote_expires_at, oracle_snapshot, + created_at + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return redirect("/portal/dashboard") + + status = (invoice.get("status") or "").lower() + if status == "paid": + conn.close() + return redirect(f"/portal/invoice/{invoice_id}") + + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + options = get_invoice_crypto_options(invoice) + chosen_symbol = (request.form.get("asset") or "").strip().upper() + selected_option = next((o for o in options if o["symbol"] == chosen_symbol), None) + + quote_key = f"portal_crypto_quote_window_{invoice_id}_{client['id']}" + now_utc = datetime.now(timezone.utc) + stored_start = session.get(quote_key) + quote_start_dt = None + if stored_start: + try: + quote_start_dt = datetime.fromisoformat(str(stored_start).replace("Z", "+00:00")) + if quote_start_dt.tzinfo is None: + quote_start_dt = quote_start_dt.replace(tzinfo=timezone.utc) + except Exception: + quote_start_dt = None + + if not quote_start_dt or (now_utc - quote_start_dt).total_seconds() > 90: + session.pop(quote_key, None) + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error=price+has+expired+-+please+refresh+your+view+to+update&refresh_quote=1") + + if not selected_option: + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error=Please+choose+a+valid+crypto+asset") + + if not selected_option.get("available"): + conn.close() + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&crypto_error={selected_option['symbol']}+is+not+currently+available") + + cursor.execute(""" + SELECT id, payment_currency, payment_amount, wallet_address, reference, payment_status, created_at, notes + FROM payments + WHERE invoice_id = %s + AND client_id = %s + AND payment_status = 'pending' + AND payment_currency = %s + ORDER BY id DESC + LIMIT 1 + """, (invoice_id, client["id"], selected_option["payment_currency"])) + existing = cursor.fetchone() + + pending_payment_id = None + + if existing: + created_dt = existing.get("created_at") + if created_dt and created_dt.tzinfo is None: + created_dt = created_dt.replace(tzinfo=timezone.utc) + + if created_dt and (now_utc - created_dt).total_seconds() <= 120: + pending_payment_id = existing["id"] + + if not pending_payment_id: + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, 'other', %s, %s, %s, %s, %s, NULL, %s, 'pending', NULL, %s) + """, ( + invoice["id"], + invoice["client_id"], + selected_option["payment_currency"], + str(selected_option["display_amount"]), + str(invoice.get("quote_fiat_amount") or invoice.get("total_amount") or "0"), + invoice["invoice_number"], + client.get("email") or client.get("company_name") or "Portal Client", + selected_option["wallet_address"], + f"portal_crypto_intent:{selected_option['symbol']}:{selected_option['chain']}|invoice:{invoice['invoice_number']}|frozen_quote" + )) + conn.commit() + pending_payment_id = insert_cursor.lastrowid + + session.pop(quote_key, None) + conn.close() + + return redirect(f"/portal/invoice/{invoice_id}?pay=crypto&asset={selected_option['symbol']}&payment_id={pending_payment_id}") + +@app.route("/portal/invoice//submit-crypto-tx", methods=["POST"]) +def portal_submit_crypto_tx(invoice_id): + client = _portal_current_client() + if not client: + return jsonify({"ok": False, "error": "not_authenticated"}), 401 + + ensure_invoice_quote_columns() + + try: + payload = request.get_json(force=True) or {} + except Exception: + payload = {} + + payment_id = str(payload.get("payment_id") or "").strip() + asset = str(payload.get("asset") or "").strip().upper() + tx_hash = str(payload.get("tx_hash") or "").strip() + + if not payment_id.isdigit(): + return jsonify({"ok": False, "error": "invalid_payment_id"}), 400 + if not asset: + return jsonify({"ok": False, "error": "missing_asset"}), 400 + if not tx_hash or not tx_hash.startswith("0x"): + return jsonify({"ok": False, "error": "missing_tx_hash"}), 400 + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + cursor.execute(""" + SELECT id, client_id, invoice_number, oracle_snapshot + FROM invoices + WHERE id = %s AND client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return jsonify({"ok": False, "error": "invoice_not_found"}), 404 + + invoice["oracle_quote"] = None + if invoice.get("oracle_snapshot"): + try: + invoice["oracle_quote"] = json.loads(invoice["oracle_snapshot"]) + except Exception: + invoice["oracle_quote"] = None + + crypto_options = get_invoice_crypto_options(invoice) + selected_option = next((o for o in crypto_options if o["symbol"] == asset), None) + + if not selected_option: + conn.close() + return jsonify({"ok": False, "error": "invalid_asset"}), 400 + + cursor.execute(""" + SELECT id, invoice_id, client_id, payment_currency, payment_status, txid, notes + FROM payments + WHERE id = %s + AND invoice_id = %s + AND client_id = %s + LIMIT 1 + """, (int(payment_id), invoice_id, client["id"])) + payment = cursor.fetchone() + + if not payment: + conn.close() + return jsonify({"ok": False, "error": "payment_not_found"}), 404 + + if str(payment.get("payment_currency") or "").upper() != selected_option["payment_currency"]: + conn.close() + return jsonify({"ok": False, "error": "payment_currency_mismatch"}), 400 + + if str(payment.get("payment_status") or "").lower() != "pending": + conn.close() + return jsonify({"ok": False, "error": "payment_not_pending"}), 400 + + new_notes = append_payment_note( + payment.get("notes"), + f"[portal wallet submit] tx hash accepted: {tx_hash}" + ) + + update_cursor = conn.cursor() + update_cursor.execute(""" + UPDATE payments + SET txid = %s, + payment_status = 'pending', + notes = %s + WHERE id = %s + """, ( + tx_hash, + new_notes, + payment["id"] + )) + conn.commit() + conn.close() + + return jsonify({ + "ok": True, + "redirect_url": f"/portal/invoice/{invoice_id}?pay=crypto&asset={asset}&payment_id={payment['id']}" + }) + + +@app.route("/portal/invoice//pay-square", methods=["GET"]) +def portal_invoice_pay_square(invoice_id): + client = _portal_current_client() + if not client: + return redirect("/portal") + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + i.*, + c.email AS client_email, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s AND i.client_id = %s + LIMIT 1 + """, (invoice_id, client["id"])) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return redirect("/portal/dashboard") + + status = (invoice.get("status") or "").lower() + if status == "paid": + return redirect(f"/portal/invoice/{invoice_id}") + + square_url = create_square_payment_link_for_invoice(invoice, invoice.get("client_email") or "") + return redirect(square_url) + +@app.route("/invoices/pay-square/", methods=["GET"]) +def admin_invoice_pay_square(invoice_id): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + i.*, + c.email AS client_email, + c.company_name, + c.contact_name + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice_id,)) + invoice = cursor.fetchone() + conn.close() + + if not invoice: + return "Invoice not found", 404 + + status = (invoice.get("status") or "").lower() + if status == "paid": + return redirect(f"/invoices/view/{invoice_id}") + + square_url = create_square_payment_link_for_invoice(invoice, invoice.get("client_email") or "") + return redirect(square_url) + + + +def auto_apply_square_payment(parsed_event): + try: + data_obj = (((parsed_event.get("data") or {}).get("object")) or {}) + payment = data_obj.get("payment") or {} + + payment_id = payment.get("id") or "" + payment_status = (payment.get("status") or "").upper() + note = (payment.get("note") or "").strip() + buyer_email = (payment.get("buyer_email_address") or "").strip() + amount_money = (payment.get("amount_money") or {}).get("amount") + currency = (payment.get("amount_money") or {}).get("currency") or "CAD" + + if not payment_id or payment_status != "COMPLETED": + return {"processed": False, "reason": "not_completed_or_missing_id"} + + m = re.search(r'Invoice\s+([A-Za-z0-9\-]+)', note, re.IGNORECASE) + if not m: + return {"processed": False, "reason": "invoice_note_not_found", "note": note} + + invoice_number = m.group(1).strip() + + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + + # Deduplicate by Square payment ID + cursor.execute(""" + SELECT id + FROM payments + WHERE txid = %s + LIMIT 1 + """, (payment_id,)) + existing = cursor.fetchone() + if existing: + conn.close() + return {"processed": False, "reason": "duplicate_payment_id", "payment_id": payment_id} + + cursor.execute(""" + SELECT + i.id, + i.client_id, + i.invoice_number, + i.currency_code, + i.total_amount, + i.amount_paid, + i.status, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.invoice_number = %s + LIMIT 1 + """, (invoice_number,)) + invoice = cursor.fetchone() + + if not invoice: + conn.close() + return {"processed": False, "reason": "invoice_not_found", "invoice_number": invoice_number} + + payment_amount = to_decimal(amount_money) / to_decimal("100") + + insert_cursor = conn.cursor() + insert_cursor.execute(""" + INSERT INTO payments + ( + invoice_id, + client_id, + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + reference, + sender_name, + txid, + wallet_address, + payment_status, + received_at, + notes + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, UTC_TIMESTAMP(), %s) + """, ( + invoice["id"], + invoice["client_id"], + "square", + currency, + payment_amount, + payment_amount if currency == "CAD" else payment_amount, + invoice_number, + buyer_email or "Square Customer", + payment_id, + "", + "confirmed", + f"Auto-recorded from Square webhook. Note: {note or ''}".strip() + )) + conn.commit() + conn.close() + + recalc_invoice_totals(invoice["id"]) + + try: + notify_conn = get_db_connection() + notify_cursor = notify_conn.cursor(dictionary=True) + notify_cursor.execute(""" + SELECT + i.id, + i.invoice_number, + i.status, + i.total_amount, + i.amount_paid, + i.currency_code, + c.company_name, + c.contact_name, + c.email + FROM invoices i + JOIN clients c ON i.client_id = c.id + WHERE i.id = %s + LIMIT 1 + """, (invoice["id"],)) + invoice_email_row = notify_cursor.fetchone() + notify_conn.close() + + if invoice_email_row and invoice_email_row.get("email"): + client_name = ( + invoice_email_row.get("contact_name") + or invoice_email_row.get("company_name") + or invoice_email_row.get("email") + ) + payment_amount_display = f"{to_decimal(payment_amount):.2f} {currency}" + invoice_total_display = f"{to_decimal(invoice_email_row.get('total_amount')):.2f} {invoice_email_row.get('currency_code') or 'CAD'}" + + subject = f"Payment Received for Invoice {invoice_email_row.get('invoice_number')}" + body = f"""Hello {client_name}, + +We have received your payment for invoice {invoice_email_row.get('invoice_number')}. + +Amount Received: +{payment_amount_display} + +Invoice Total: +{invoice_total_display} + +Current Invoice Status: +{invoice_email_row.get('status')} + +You can view your invoice anytime in the client portal: +https://portal.outsidethebox.top/portal + +Thank you, +OutsideTheBox +support@outsidethebox.top +""" + + send_configured_email( + to_email=invoice_email_row.get("email"), + subject=subject, + body=body, + attachments=None, + email_type="payment_received", + invoice_id=invoice["id"] + ) + except Exception: + pass + + return { + "processed": True, + "invoice_number": invoice_number, + "payment_id": payment_id, + "amount": str(payment_amount), + "currency": currency, + } + + except Exception as e: + return {"processed": False, "reason": "exception", "error": str(e)} + + + + +@app.route("/accountbook/export.csv") +def accountbook_export_csv(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + payment_status, + received_at + FROM payments + WHERE payment_status = 'confirmed' + ORDER BY received_at DESC + """) + payments = cursor.fetchall() + conn.close() + + now_local = datetime.now(LOCAL_TZ) + today_str = now_local.strftime("%Y-%m-%d") + month_prefix = now_local.strftime("%Y-%m") + year_prefix = now_local.strftime("%Y") + + categories = [ + ("cash", "Cash"), + ("etransfer", "eTransfer"), + ("square", "Square"), + ("etho", "ETHO"), + ("eti", "ETI"), + ("egaz", "EGAZ"), + ("eth", "ETH"), + ("other", "Other"), + ] + + periods = { + "today": {"label": "Today", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "month": {"label": "This Month", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "ytd": {"label": "Year to Date", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + } + + def norm_method(method): + m = (method or "").strip().lower() + if m in ("cash",): + return "cash" + if m in ("etransfer", "e-transfer", "interac", "interac e-transfer", "email money transfer"): + return "etransfer" + if m in ("square",): + return "square" + if m in ("etho",): + return "etho" + if m in ("eti",): + return "eti" + if m in ("egaz",): + return "egaz" + if m in ("eth", "ethereum"): + return "eth" + return "other" + + for pay in payments: + received = pay.get("received_at") + if not received: + continue + + if isinstance(received, str): + received_local_str = received[:10] + received_month = received[:7] + received_year = received[:4] + else: + if received.tzinfo is None: + received = received.replace(tzinfo=timezone.utc) + received_local = received.astimezone(LOCAL_TZ) + received_local_str = received_local.strftime("%Y-%m-%d") + received_month = received_local.strftime("%Y-%m") + received_year = received_local.strftime("%Y") + + bucket = norm_method(pay.get("payment_method")) + amount = to_decimal(pay.get("cad_value_at_payment") or pay.get("payment_amount") or "0") + + if received_year == year_prefix: + periods["ytd"]["totals"][bucket] += amount + periods["ytd"]["grand"] += amount + + if received_month == month_prefix: + periods["month"]["totals"][bucket] += amount + periods["month"]["grand"] += amount + + if received_local_str == today_str: + periods["today"]["totals"][bucket] += amount + periods["today"]["grand"] += amount + + output = StringIO() + writer = csv.writer(output) + writer.writerow(["Period", "Category", "Total CAD"]) + + for period_key in ("today", "month", "ytd"): + period = periods[period_key] + for cat_key, cat_label in categories: + writer.writerow([period["label"], cat_label, f"{period['totals'][cat_key]:.2f}"]) + writer.writerow([period["label"], "Grand Total", f"{period['grand']:.2f}"]) + + response = make_response(output.getvalue()) + response.headers["Content-Type"] = "text/csv; charset=utf-8" + response.headers["Content-Disposition"] = "attachment; filename=accountbook_summary.csv" + return response + + +@app.route("/accountbook") +def accountbook(): + conn = get_db_connection() + cursor = conn.cursor(dictionary=True) + cursor.execute(""" + SELECT + payment_method, + payment_currency, + payment_amount, + cad_value_at_payment, + payment_status, + received_at + FROM payments + WHERE payment_status = 'confirmed' + ORDER BY received_at DESC + """) + payments = cursor.fetchall() + conn.close() + + now_local = datetime.now(LOCAL_TZ) + today_str = now_local.strftime("%Y-%m-%d") + month_prefix = now_local.strftime("%Y-%m") + year_prefix = now_local.strftime("%Y") + + categories = [ + ("cash", "Cash"), + ("etransfer", "eTransfer"), + ("square", "Square"), + ("etho", "ETHO"), + ("eti", "ETI"), + ("egaz", "EGAZ"), + ("eth", "ETH"), + ("other", "Other"), + ] + + periods = { + "today": {"label": "Today", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "month": {"label": "This Month", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + "ytd": {"label": "Year to Date", "totals": {k: Decimal("0") for k, _ in categories}, "grand": Decimal("0")}, + } + + def norm_method(method): + m = (method or "").strip().lower() + if m in ("cash",): + return "cash" + if m in ("etransfer", "e-transfer", "interac", "interac e-transfer", "email money transfer"): + return "etransfer" + if m in ("square",): + return "square" + if m in ("etho",): + return "etho" + if m in ("eti",): + return "eti" + if m in ("egaz",): + return "egaz" + if m in ("eth", "ethereum"): + return "eth" + return "other" + + for p in payments: + received = p.get("received_at") + if not received: + continue + + if isinstance(received, str): + received_local_str = received[:10] + received_month = received[:7] + received_year = received[:4] + else: + if received.tzinfo is None: + received = received.replace(tzinfo=timezone.utc) + received_local = received.astimezone(LOCAL_TZ) + received_local_str = received_local.strftime("%Y-%m-%d") + received_month = received_local.strftime("%Y-%m") + received_year = received_local.strftime("%Y") + + bucket = norm_method(p.get("payment_method")) + amount = to_decimal(p.get("cad_value_at_payment") or p.get("payment_amount") or "0") + + if received_year == year_prefix: + periods["ytd"]["totals"][bucket] += amount + periods["ytd"]["grand"] += amount + + if received_month == month_prefix: + periods["month"]["totals"][bucket] += amount + periods["month"]["grand"] += amount + + if received_local_str == today_str: + periods["today"]["totals"][bucket] += amount + periods["today"]["grand"] += amount + + period_cards = [] + for key in ("today", "month", "ytd"): + block = periods[key] + lines = [] + for cat_key, cat_label in categories: + lines.append(f"{cat_label}{block['totals'][cat_key]:.2f}") + period_cards.append(f""" +
+

{block['label']}

+
{block['grand']:.2f}
+ + + {''.join(lines)} + +
+
+ """) + + html = f""" + + + + + Accountbook - OTB Billing + + + + + +
+
+
+

Accountbook

+

Confirmed payment totals by period and payment type.

+
+ +
+ +
+ {''.join(period_cards)} +
+
+ +""" + return Response(html, mimetype="text/html") + + +@app.route("/square/reconciliation") +def square_reconciliation(): + log_path = Path(SQUARE_WEBHOOK_LOG) + events = [] + + if log_path.exists(): + lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines() + for line in reversed(lines[-400:]): + try: + row = json.loads(line) + events.append(row) + except Exception: + continue + + summary_cards = { + "processed_true": 0, + "duplicates": 0, + "failures": 0, + "sig_invalid": 0, + } + + for row in events[:150]: + if row.get("signature_valid") is False: + summary_cards["sig_invalid"] += 1 + auto_apply_result = row.get("auto_apply_result") + if isinstance(auto_apply_result, dict): + if auto_apply_result.get("processed") is True: + summary_cards["processed_true"] += 1 + elif auto_apply_result.get("reason") == "duplicate_payment_id": + summary_cards["duplicates"] += 1 + else: + summary_cards["failures"] += 1 + + summary_html = f""" + + """ + + filter_mode = (request.args.get("filter") or "").strip().lower() + + filtered_events = [] + for row in events[:150]: + auto_apply_result = row.get("auto_apply_result") + sig_valid = row.get("signature_valid") + + include = True + if filter_mode == "processed": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("processed") is True + elif filter_mode == "duplicates": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("reason") == "duplicate_payment_id" + elif filter_mode == "failures": + include = isinstance(auto_apply_result, dict) and auto_apply_result.get("processed") is False and auto_apply_result.get("reason") != "duplicate_payment_id" + elif filter_mode == "invalid": + include = (sig_valid is False) + + if include: + filtered_events.append(row) + + rows_html = [] + for row in filtered_events: + logged_at = row.get("logged_at_utc", "") + event_type = row.get("event_type", row.get("source", "")) + payment_id = row.get("payment_id", "") + note = row.get("note", "") + amount_money = row.get("amount_money", "") + signature_valid = row.get("signature_valid", "") + auto_apply_result = row.get("auto_apply_result") + + if isinstance(auto_apply_result, dict): + if auto_apply_result.get("processed") is True: + result_text = f"processed: true / invoice {auto_apply_result.get('invoice_number','')}" + result_class = "ok" + else: + result_text = f"processed: false / {auto_apply_result.get('reason','')}" + if auto_apply_result.get("error"): + result_text += f" / {auto_apply_result.get('error')}" + result_class = "warn" + else: + result_text = "" + result_class = "" + + signature_text = "true" if signature_valid is True else ("false" if signature_valid is False else "") + + rows_html.append(f""" + + {logged_at} + {event_type} + {payment_id} + {amount_money} + {note} + {signature_text} + {result_text} + + """) + + html = f""" + + + + + Square Reconciliation - OTB Billing + + + + + +
+
+
+

Square Reconciliation

+

Recent Square webhook events and auto-apply outcomes.

+
+ +
+ +

Log file: {SQUARE_WEBHOOK_LOG}

+

Current Filter: {filter_mode or "all"}

+ + {summary_html} + + + + + + + + + + + + + + + {''.join(rows_html) if rows_html else ''} + +
Logged At (UTC)EventPayment IDAmount (cents)NoteSig ValidAuto Apply Result
No webhook events found.
+
+ +""" + return Response(html, mimetype="text/html") + + +@app.route("/square/webhook", methods=["POST"]) +def square_webhook(): + raw_body = request.get_data() + signature_header = request.headers.get("x-square-hmacsha256-signature", "") + notification_url = SQUARE_WEBHOOK_NOTIFICATION_URL or request.url + + valid = square_signature_is_valid(signature_header, raw_body, notification_url) + + parsed = None + try: + parsed = json.loads(raw_body.decode("utf-8")) + except Exception: + parsed = None + + event_id = None + event_type = None + payment_id = None + payment_status = None + amount_money = None + reference_id = None + note = None + order_id = None + customer_id = None + receipt_number = None + source_type = None + + try: + if isinstance(parsed, dict): + event_id = parsed.get("event_id") + event_type = parsed.get("type") + data_obj = (((parsed.get("data") or {}).get("object")) or {}) + payment = data_obj.get("payment") or {} + payment_id = payment.get("id") + payment_status = payment.get("status") + amount_money = (((payment.get("amount_money") or {}).get("amount"))) + reference_id = payment.get("reference_id") + note = payment.get("note") + order_id = payment.get("order_id") + customer_id = payment.get("customer_id") + receipt_number = payment.get("receipt_number") + source_type = ((payment.get("source_type")) or "") + except Exception: + pass + + append_square_webhook_log({ + "logged_at_utc": datetime.utcnow().isoformat() + "Z", + "signature_valid": valid, + "event_id": event_id, + "event_type": event_type, + "payment_id": payment_id, + "payment_status": payment_status, + "amount_money": amount_money, + "reference_id": reference_id, + "note": note, + "order_id": order_id, + "customer_id": customer_id, + "receipt_number": receipt_number, + "source_type": source_type, + "headers": { + "x-square-hmacsha256-signature": bool(signature_header), + "content-type": request.headers.get("content-type", ""), + "user-agent": request.headers.get("user-agent", ""), + }, + "raw_json": parsed, + }) + + if not valid: + return jsonify({"ok": False, "error": "invalid signature"}), 403 + + result = auto_apply_square_payment(parsed or {}) + append_square_webhook_log({ + "logged_at_utc": datetime.utcnow().isoformat() + "Z", + "auto_apply_result": result, + "source": "square_webhook_postprocess" + }) + + return jsonify({"ok": True, "result": result}), 200 + +register_health_routes(app) +if __name__ == "__main__": + app.run(host="0.0.0.0", port=5050, debug=False, use_reloader=False) \ No newline at end of file diff --git a/backups/portal-theme-cleanup-20260322-215133/portal_dashboard.html b/backups/portal-theme-cleanup-20260322-215133/portal_dashboard.html new file mode 100644 index 0000000..2c6d2c4 --- /dev/null +++ b/backups/portal-theme-cleanup-20260322-215133/portal_dashboard.html @@ -0,0 +1,125 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% if row.payment_method_label %} +
+ {{ row.payment_method_label }} +
+ {% endif %} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} +
{{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + +
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-theme-cleanup-20260322-215133/portal_forgot_password.html b/backups/portal-theme-cleanup-20260322-215133/portal_forgot_password.html new file mode 100644 index 0000000..4477003 --- /dev/null +++ b/backups/portal-theme-cleanup-20260322-215133/portal_forgot_password.html @@ -0,0 +1,21 @@ + + + Forgot Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Reset Portal Password

Enter your email address and a new single-use access code will be sent if your account exists.

{% if error %}
{{ error }}
{% endif %} {% if message %}
{{ message }}
{% endif %}
+
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-theme-cleanup-20260322-215133/portal_invoice_detail.html b/backups/portal-theme-cleanup-20260322-215133/portal_invoice_detail.html new file mode 100644 index 0000000..b27c46d --- /dev/null +++ b/backups/portal-theme-cleanup-20260322-215133/portal_invoice_detail.html @@ -0,0 +1,31 @@ + + + Invoice Detail - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Invoice Detail

{{ client.company_name or client.contact_name or client.email }}

{% if (invoice.status or "")|lower == "paid" %}
βœ“ This invoice has been paid. Thank you!
{% endif %} {% if crypto_error %}
{{ crypto_error }}
{% endif %}

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Status

{% set s = (invoice.status or "")|lower %} {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} processing {% elif s == "paid" %}{{ invoice.status }} {% elif s == "pending" %}{{ invoice.status }} {% elif s == "overdue" %}{{ invoice.status }} {% else %}{{ invoice.status }}{% endif %}

Created

{{ invoice.created_at }}

Total

{{ invoice.total_amount }}

Paid

{{ invoice.amount_paid }}

Outstanding

{{ invoice.outstanding }}

Invoice Items

{% for item in items %} {% else %} {% endfor %}
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
{% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %}

Pay Now

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Credit Card (Square)

Pay with Credit Card
{% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %}

Crypto Quote Snapshot

Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
{% if pending_crypto_payment %}
Your quote is protected after acceptance.
{% else %}
Select a crypto asset to accept the quote.
{% endif %}
{% if pending_crypto_payment and pending_crypto_payment.txid %}
--:--
Watching transaction / waiting for confirmation
{% elif pending_crypto_payment %}
--:--
Quote protected while you open wallet
{% else %}
--:--
This price times out:
{% endif %}
{% if pending_crypto_payment and selected_crypto_option %}

{{ selected_crypto_option.label }} Payment Instructions

Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
Destination wallet:
{{ pending_crypto_payment.wallet_address }}
Reference / Invoice:
{{ pending_crypto_payment.reference }} {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %}
Open in MetaMask Mobile

Fastest way to pay

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

2. If that does not open your wallet, click Open in MetaMask Mobile.

3. If needed, use Copy Payment Details and send manually.

You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet.
{% elif pending_crypto_payment.txid %}
Transaction Hash:
{{ pending_crypto_payment.txid }}
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
{% elif pending_crypto_payment.lock_expired %}
price has expired - please refresh your quote to update
{% endif %}
{% else %}
{% for q in crypto_options %} {% endfor %}
AssetQuoted AmountCAD PriceStatusAction
{{ q.label }} {% if q.recommended %}recommended{% endif %} {% if q.wallet_capable %}wallet{% endif %} {{ q.display_amount or "β€”" }} {% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %} {% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
{% endif %}
{% else %}

No crypto quote snapshot is available for this invoice yet.

{% endif %}
{% endif %} {% if invoice_payments %}

Payments Applied

{% for p in invoice_payments %} {% endfor %}
Method Amount Status Received Reference / TXID
{{ p.payment_method_label }} {{ p.payment_amount_display }} {{ p.payment_currency }} {{ p.payment_status }} {{ p.received_at_local }} {% if p.txid %} {{ p.txid }} {% elif p.reference %} {{ p.reference }} {% else %} - {% endif %} {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %}
{% endif %} {% if pdf_url %} {% endif %} +
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-theme-cleanup-20260322-215133/portal_login.html b/backups/portal-theme-cleanup-20260322-215133/portal_login.html new file mode 100644 index 0000000..9d6f708 --- /dev/null +++ b/backups/portal-theme-cleanup-20260322-215133/portal_login.html @@ -0,0 +1,64 @@ + + + + + + Client Portal - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Customer Support +
+
+ + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ + +
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-theme-cleanup-20260322-215133/portal_set_password.html b/backups/portal-theme-cleanup-20260322-215133/portal_set_password.html new file mode 100644 index 0000000..57a9b6b --- /dev/null +++ b/backups/portal-theme-cleanup-20260322-215133/portal_set_password.html @@ -0,0 +1,21 @@ + + + Set Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Create Your Portal Password

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

{% if portal_message %}
{{ portal_message }}
{% endif %}
+
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-toggle-cleanup-20260322-213704/portal_dashboard.html b/backups/portal-toggle-cleanup-20260322-213704/portal_dashboard.html new file mode 100644 index 0000000..2c6d2c4 --- /dev/null +++ b/backups/portal-toggle-cleanup-20260322-213704/portal_dashboard.html @@ -0,0 +1,125 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% if row.payment_method_label %} +
+ {{ row.payment_method_label }} +
+ {% endif %} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} +
{{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + +
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-toggle-cleanup-20260322-213704/portal_forgot_password.html b/backups/portal-toggle-cleanup-20260322-213704/portal_forgot_password.html new file mode 100644 index 0000000..4477003 --- /dev/null +++ b/backups/portal-toggle-cleanup-20260322-213704/portal_forgot_password.html @@ -0,0 +1,21 @@ + + + Forgot Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Reset Portal Password

Enter your email address and a new single-use access code will be sent if your account exists.

{% if error %}
{{ error }}
{% endif %} {% if message %}
{{ message }}
{% endif %}
+
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-toggle-cleanup-20260322-213704/portal_invoice_detail.html b/backups/portal-toggle-cleanup-20260322-213704/portal_invoice_detail.html new file mode 100644 index 0000000..b27c46d --- /dev/null +++ b/backups/portal-toggle-cleanup-20260322-213704/portal_invoice_detail.html @@ -0,0 +1,31 @@ + + + Invoice Detail - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Invoice Detail

{{ client.company_name or client.contact_name or client.email }}

{% if (invoice.status or "")|lower == "paid" %}
βœ“ This invoice has been paid. Thank you!
{% endif %} {% if crypto_error %}
{{ crypto_error }}
{% endif %}

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Status

{% set s = (invoice.status or "")|lower %} {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} processing {% elif s == "paid" %}{{ invoice.status }} {% elif s == "pending" %}{{ invoice.status }} {% elif s == "overdue" %}{{ invoice.status }} {% else %}{{ invoice.status }}{% endif %}

Created

{{ invoice.created_at }}

Total

{{ invoice.total_amount }}

Paid

{{ invoice.amount_paid }}

Outstanding

{{ invoice.outstanding }}

Invoice Items

{% for item in items %} {% else %} {% endfor %}
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
{% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %}

Pay Now

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Credit Card (Square)

Pay with Credit Card
{% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %}

Crypto Quote Snapshot

Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
{% if pending_crypto_payment %}
Your quote is protected after acceptance.
{% else %}
Select a crypto asset to accept the quote.
{% endif %}
{% if pending_crypto_payment and pending_crypto_payment.txid %}
--:--
Watching transaction / waiting for confirmation
{% elif pending_crypto_payment %}
--:--
Quote protected while you open wallet
{% else %}
--:--
This price times out:
{% endif %}
{% if pending_crypto_payment and selected_crypto_option %}

{{ selected_crypto_option.label }} Payment Instructions

Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
Destination wallet:
{{ pending_crypto_payment.wallet_address }}
Reference / Invoice:
{{ pending_crypto_payment.reference }} {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %}
Open in MetaMask Mobile

Fastest way to pay

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

2. If that does not open your wallet, click Open in MetaMask Mobile.

3. If needed, use Copy Payment Details and send manually.

You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet.
{% elif pending_crypto_payment.txid %}
Transaction Hash:
{{ pending_crypto_payment.txid }}
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
{% elif pending_crypto_payment.lock_expired %}
price has expired - please refresh your quote to update
{% endif %}
{% else %}
{% for q in crypto_options %} {% endfor %}
AssetQuoted AmountCAD PriceStatusAction
{{ q.label }} {% if q.recommended %}recommended{% endif %} {% if q.wallet_capable %}wallet{% endif %} {{ q.display_amount or "β€”" }} {% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %} {% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
{% endif %}
{% else %}

No crypto quote snapshot is available for this invoice yet.

{% endif %}
{% endif %} {% if invoice_payments %}

Payments Applied

{% for p in invoice_payments %} {% endfor %}
Method Amount Status Received Reference / TXID
{{ p.payment_method_label }} {{ p.payment_amount_display }} {{ p.payment_currency }} {{ p.payment_status }} {{ p.received_at_local }} {% if p.txid %} {{ p.txid }} {% elif p.reference %} {{ p.reference }} {% else %} - {% endif %} {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %}
{% endif %} {% if pdf_url %} {% endif %} +
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-toggle-cleanup-20260322-213704/portal_login.html b/backups/portal-toggle-cleanup-20260322-213704/portal_login.html new file mode 100644 index 0000000..9d6f708 --- /dev/null +++ b/backups/portal-toggle-cleanup-20260322-213704/portal_login.html @@ -0,0 +1,64 @@ + + + + + + Client Portal - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Customer Support +
+
+ + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ + +
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/portal-toggle-cleanup-20260322-213704/portal_set_password.html b/backups/portal-toggle-cleanup-20260322-213704/portal_set_password.html new file mode 100644 index 0000000..57a9b6b --- /dev/null +++ b/backups/portal-toggle-cleanup-20260322-213704/portal_set_password.html @@ -0,0 +1,21 @@ + + + Set Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Create Your Portal Password

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

{% if portal_message %}
{{ portal_message }}
{% endif %}
+
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/saas-panel-20260322-034651/portal_dashboard.html b/backups/saas-panel-20260322-034651/portal_dashboard.html new file mode 100644 index 0000000..561162c --- /dev/null +++ b/backups/saas-panel-20260322-034651/portal_dashboard.html @@ -0,0 +1,12 @@ + + + Client Dashboard - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Client Dashboard

{{ client.company_name or client.contact_name or client.email }}

Total Invoices

{{ invoice_count }}

Total Outstanding

{{ total_outstanding }}

Total Paid

{{ total_paid }}

Invoices

{% for row in invoices %} {% else %} {% endfor %}
Invoice Status Created Total Paid Outstanding
{{ row.invoice_number or ("INV-" ~ row.id) }} {% set s = (row.status or "")|lower %} {% if s == "paid" %} {{ row.status }} {% elif s == "pending" %} {{ row.status }} {% elif s == "overdue" %} {{ row.status }} {% else %} {{ row.status }} {% endif %} {{ row.created_at }} {{ row.total_amount }} {{ row.amount_paid }} {{ row.outstanding }}
No invoices available.
+
{% include "footer.html" %} + + diff --git a/backups/saas-panel-20260322-034651/portal_login.html b/backups/saas-panel-20260322-034651/portal_login.html new file mode 100644 index 0000000..e42fa3b --- /dev/null +++ b/backups/saas-panel-20260322-034651/portal_login.html @@ -0,0 +1,9 @@ + + + Client Portal - OutsideTheBox + + +{% include "includes/site_nav.html" %}

OutsideTheBox Client Portal

Secure access for invoices, balances, and account information.

{% if portal_message %}
{{ portal_message }}
{% endif %}

First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. This access code is single-use and is cleared after password setup. Future logins use your email address and password.

+
{% include "footer.html" %} + + diff --git a/backups/saas-panel-20260322-034651/style.css b/backups/saas-panel-20260322-034651/style.css new file mode 100644 index 0000000..566adfd --- /dev/null +++ b/backups/saas-panel-20260322-034651/style.css @@ -0,0 +1,134 @@ +/* ===== GLOBAL ===== */ +body { + background: linear-gradient(135deg, #0a1628, #0c1f3f); + color: #e6edf3; + font-family: system-ui, -apple-system, sans-serif; + margin: 0; +} + +/* ===== CONTAINER ===== */ +.container { + max-width: 1100px; + margin: 40px auto; + padding: 0 20px; +} + +/* ===== HEADERS ===== */ +h1 { + font-size: 28px; + margin-bottom: 5px; +} + +.subtext { + color: #9fb3c8; + margin-bottom: 25px; +} + +/* ===== ACTION BAR ===== */ +.action-bar { + display: flex; + gap: 10px; + margin-bottom: 25px; + flex-wrap: wrap; +} + +.btn { + background: #132a4a; + border: 1px solid #2c4d75; + color: #e6edf3; + padding: 10px 16px; + border-radius: 8px; + text-decoration: none; + font-size: 14px; + transition: all 0.2s; +} + +.btn:hover { + background: #1a3a66; + border-color: #3d6ea8; +} + +.btn-primary { + background: #1e6fff; + border-color: #1e6fff; +} + +.btn-primary:hover { + background: #3b82ff; +} + +/* ===== STATS ===== */ +.stats { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 15px; + margin-bottom: 30px; +} + +.stat-card { + background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.08); + border-radius: 12px; + padding: 18px; +} + +.stat-card h3 { + font-size: 14px; + color: #9fb3c8; + margin-bottom: 8px; +} + +.stat-card p { + font-size: 20px; + font-weight: bold; +} + +/* ===== TABLE ===== */ +.table-container { + background: rgba(255,255,255,0.03); + border: 1px solid rgba(255,255,255,0.08); + border-radius: 12px; + overflow: hidden; +} + +table { + width: 100%; + border-collapse: collapse; +} + +th { + text-align: left; + padding: 12px; + font-size: 13px; + color: #9fb3c8; + background: rgba(255,255,255,0.05); +} + +td { + padding: 12px; + border-top: 1px solid rgba(255,255,255,0.05); +} + +tr:hover { + background: rgba(255,255,255,0.03); +} + +/* ===== STATUS ===== */ +.status-paid { + color: #22c55e; + font-weight: bold; +} + +.status-unpaid { + color: #f59e0b; +} + +/* ===== LINKS ===== */ +a { + color: #60a5fa; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} diff --git a/backups/shared-brand-20260322-212608/portal_dashboard.html b/backups/shared-brand-20260322-212608/portal_dashboard.html new file mode 100644 index 0000000..2c6d2c4 --- /dev/null +++ b/backups/shared-brand-20260322-212608/portal_dashboard.html @@ -0,0 +1,125 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% if row.payment_method_label %} +
+ {{ row.payment_method_label }} +
+ {% endif %} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} +
{{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + +
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/shared-brand-20260322-212608/portal_forgot_password.html b/backups/shared-brand-20260322-212608/portal_forgot_password.html new file mode 100644 index 0000000..4477003 --- /dev/null +++ b/backups/shared-brand-20260322-212608/portal_forgot_password.html @@ -0,0 +1,21 @@ + + + Forgot Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Reset Portal Password

Enter your email address and a new single-use access code will be sent if your account exists.

{% if error %}
{{ error }}
{% endif %} {% if message %}
{{ message }}
{% endif %}
+
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/shared-brand-20260322-212608/portal_invoice_detail.html b/backups/shared-brand-20260322-212608/portal_invoice_detail.html new file mode 100644 index 0000000..b27c46d --- /dev/null +++ b/backups/shared-brand-20260322-212608/portal_invoice_detail.html @@ -0,0 +1,31 @@ + + + Invoice Detail - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Invoice Detail

{{ client.company_name or client.contact_name or client.email }}

{% if (invoice.status or "")|lower == "paid" %}
βœ“ This invoice has been paid. Thank you!
{% endif %} {% if crypto_error %}
{{ crypto_error }}
{% endif %}

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Status

{% set s = (invoice.status or "")|lower %} {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} processing {% elif s == "paid" %}{{ invoice.status }} {% elif s == "pending" %}{{ invoice.status }} {% elif s == "overdue" %}{{ invoice.status }} {% else %}{{ invoice.status }}{% endif %}

Created

{{ invoice.created_at }}

Total

{{ invoice.total_amount }}

Paid

{{ invoice.amount_paid }}

Outstanding

{{ invoice.outstanding }}

Invoice Items

{% for item in items %} {% else %} {% endfor %}
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
{% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %}

Pay Now

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Credit Card (Square)

Pay with Credit Card
{% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %}

Crypto Quote Snapshot

Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
{% if pending_crypto_payment %}
Your quote is protected after acceptance.
{% else %}
Select a crypto asset to accept the quote.
{% endif %}
{% if pending_crypto_payment and pending_crypto_payment.txid %}
--:--
Watching transaction / waiting for confirmation
{% elif pending_crypto_payment %}
--:--
Quote protected while you open wallet
{% else %}
--:--
This price times out:
{% endif %}
{% if pending_crypto_payment and selected_crypto_option %}

{{ selected_crypto_option.label }} Payment Instructions

Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
Destination wallet:
{{ pending_crypto_payment.wallet_address }}
Reference / Invoice:
{{ pending_crypto_payment.reference }} {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %}
Open in MetaMask Mobile

Fastest way to pay

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

2. If that does not open your wallet, click Open in MetaMask Mobile.

3. If needed, use Copy Payment Details and send manually.

You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet.
{% elif pending_crypto_payment.txid %}
Transaction Hash:
{{ pending_crypto_payment.txid }}
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
{% elif pending_crypto_payment.lock_expired %}
price has expired - please refresh your quote to update
{% endif %}
{% else %}
{% for q in crypto_options %} {% endfor %}
AssetQuoted AmountCAD PriceStatusAction
{{ q.label }} {% if q.recommended %}recommended{% endif %} {% if q.wallet_capable %}wallet{% endif %} {{ q.display_amount or "β€”" }} {% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %} {% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
{% endif %}
{% else %}

No crypto quote snapshot is available for this invoice yet.

{% endif %}
{% endif %} {% if invoice_payments %}

Payments Applied

{% for p in invoice_payments %} {% endfor %}
Method Amount Status Received Reference / TXID
{{ p.payment_method_label }} {{ p.payment_amount_display }} {{ p.payment_currency }} {{ p.payment_status }} {{ p.received_at_local }} {% if p.txid %} {{ p.txid }} {% elif p.reference %} {{ p.reference }} {% else %} - {% endif %} {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %}
{% endif %} {% if pdf_url %} {% endif %} +
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/shared-brand-20260322-212608/portal_login.html b/backups/shared-brand-20260322-212608/portal_login.html new file mode 100644 index 0000000..9d6f708 --- /dev/null +++ b/backups/shared-brand-20260322-212608/portal_login.html @@ -0,0 +1,64 @@ + + + + + + Client Portal - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Customer Support +
+
+ + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ + +
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/shared-brand-20260322-212608/portal_set_password.html b/backups/shared-brand-20260322-212608/portal_set_password.html new file mode 100644 index 0000000..57a9b6b --- /dev/null +++ b/backups/shared-brand-20260322-212608/portal_set_password.html @@ -0,0 +1,21 @@ + + + Set Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Create Your Portal Password

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

{% if portal_message %}
{{ portal_message }}
{% endif %}
+
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + diff --git a/backups/shared-brand-20260322-212608/site_nav.html b/backups/shared-brand-20260322-212608/site_nav.html new file mode 100644 index 0000000..33992fb --- /dev/null +++ b/backups/shared-brand-20260322-212608/site_nav.html @@ -0,0 +1,28 @@ +
+ +
diff --git a/backups/shared-brand-20260322-212608/style.css b/backups/shared-brand-20260322-212608/style.css new file mode 100644 index 0000000..4ca2338 --- /dev/null +++ b/backups/shared-brand-20260322-212608/style.css @@ -0,0 +1,794 @@ +:root{ + --bg:#0b0f14; + --card:#121825; + --card-soft:rgba(18,24,37,.78); + --text:#e8eefc; + --muted:#aab6d6; + --line:#24304a; + --accent:#7aa2ff; + --accent2:#62e6b7; + --success:#4ade80; + --warn:#fbbf24; + --danger:#f87171; + --radius:16px; + --shadow:0 16px 40px rgba(0,0,0,.35); +} + +*{box-sizing:border-box} +html,body{height:100%} + +body{ + margin:0; + font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, "Apple Color Emoji","Segoe UI Emoji"; + background: + radial-gradient(1200px 600px at 20% 0%, rgba(122,162,255,.22), transparent 60%), + radial-gradient(900px 500px at 90% 20%, rgba(98,230,183,.15), transparent 60%), + linear-gradient(180deg, #081225 0%, #09172d 100%); + color:var(--text); + line-height:1.45; +} + +a{color:inherit} + +/* ===== Shared container ===== */ +.container{ + max-width:1100px; + margin:0 auto; + padding:20px 18px; +} + +/* ===== Header / branded nav ===== */ +.header{width:100%} + +.nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + padding:12px 0 22px 0; +} + +.brand{ + display:flex; + align-items:center; + gap:14px; + text-decoration:none; +} + +.brand img{ + height:60px; + width:auto; + display:block; + object-fit:contain; + background: rgba(255,255,255,0.92); + padding: 6px 12px; + border-radius: 999px; + box-shadow: 0 8px 24px rgba(0,0,0,0.35); +} + +.title{ + display:flex; + flex-direction:column; + line-height:1.1; +} + +.title strong{letter-spacing:.2px} +.title span{ + color:var(--muted); + font-size:13px; + margin-top:2px; +} + +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; +} + +.navlinks a{ + text-decoration:none; + padding:8px 10px; + border-radius:12px; + color:var(--muted); + border:1px solid transparent; +} + +.navlinks a:hover{ + color:var(--text); + border-color:rgba(255,255,255,.08); + background:rgba(255,255,255,.03); +} + +.navlinks a.active{ + color:var(--text); + border-color:rgba(255,255,255,.10); + background:rgba(255,255,255,.04); +} + +/* ===== Generic portal shell ===== */ +.portal-shell{ + max-width:1100px; + margin:16px auto 28px auto; + padding:0 18px 20px 18px; +} + +.portal-card, +.detail-card, +.summary-card, +.pay-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); +} + +.portal-card{ + max-width:760px; + margin:24px auto 12px auto; + padding:22px; +} + +.portal-page-header{ + display:flex; + align-items:flex-start; + justify-content:space-between; + gap:16px; + flex-wrap:wrap; + margin:6px 0 18px 0; +} + +.portal-page-title{ + margin:0; + font-size:24px; + line-height:1.1; +} + +.portal-page-subtitle{ + margin:8px 0 0 0; + color:var(--muted); +} + +.portal-client-name{ + margin:8px 0 0 0; + color:var(--text); + font-size:15px; +} + +.portal-toolbar{ + display:flex; + gap:10px; + flex-wrap:wrap; + align-items:center; +} + +.portal-btn, +.btn, +.pay-btn, +.quote-pick-btn{ + display:inline-flex; + align-items:center; + justify-content:center; + gap:8px; + min-height:42px; + padding:10px 14px; + border-radius:12px; + text-decoration:none; + border:1px solid rgba(255,255,255,.10); + background: rgba(255,255,255,.05); + color:var(--text); + font-weight:600; + cursor:pointer; +} + +.portal-btn:hover, +.btn:hover, +.pay-btn:hover, +.quote-pick-btn:hover{ + border-color:rgba(122,162,255,.45); + box-shadow:0 0 0 4px rgba(122,162,255,.12); + text-decoration:none; +} + +.portal-btn.primary, +.btn.primary{ + background: linear-gradient(135deg, rgba(122,162,255,.95), rgba(98,230,183,.85)); + border-color: transparent; + color:#071017; + font-weight:700; +} + +.portal-btn.primary:hover, +.btn.primary:hover{ + box-shadow:0 0 0 4px rgba(98,230,183,.18); +} + +/* ===== Login / forms ===== */ +.portal-sub{ + color:var(--muted); + margin:0 0 16px 0; +} + +.portal-form{ + display:grid; + gap:14px; +} + +.portal-form label{ + display:block; + font-weight:600; + margin-bottom:6px; +} + +.portal-form input, +.portal-form select, +.pay-selector{ + width:100%; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.14); + background: rgba(255,255,255,.06); + color:var(--text); + box-sizing:border-box; + outline:none; +} + +.portal-form input:focus, +.portal-form select:focus, +.pay-selector:focus{ + border-color:rgba(122,162,255,.65); + box-shadow:0 0 0 4px rgba(122,162,255,.12); +} + +.portal-actions{ + display:flex; + gap:10px; + flex-wrap:wrap; + margin-top:4px; +} + +.portal-note{ + margin-top:16px; + color:var(--muted); + font-size:14px; + line-height:1.5; +} + +.portal-msg, +.error-box, +.success-box{ + margin-bottom:16px; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.16); + background: rgba(255,255,255,.04); +} + +.error-box{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); + color: #fecaca; +} + +.success-box{ + border-color: rgba(34, 197, 94, 0.55); + background: rgba(22, 101, 52, 0.18); + color: #dcfce7; +} + +/* ===== Dashboard ===== */ +.portal-wrap{ + max-width:1100px; + margin:0 auto; + padding:0; +} + +.summary-grid, +.detail-grid{ + display:grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap:14px; + margin: 0 0 18px 0; +} + +.summary-card, +.detail-card{ + padding:18px; +} + +.summary-card h3, +.detail-card h3{ + margin:0 0 8px 0; + font-size:14px; + color:var(--muted); +} + +.summary-card .summary-value, +.detail-card .detail-value{ + font-size:28px; + font-weight:800; + line-height:1.1; + color:var(--text); +} + +.summary-card .summary-sub{ + margin-top:6px; + font-size:12px; + color:var(--muted); +} + +.section-title{ + margin:18px 0 10px 0; + font-size:22px; +} + +.table-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); + overflow:hidden; +} + +/* ===== Tables ===== */ +table, +.portal-table, +.quote-table{ + width:100%; + border-collapse: collapse; +} + +table.portal-table th, +table.portal-table td, +.quote-table th, +.quote-table td{ + padding: 0.9rem 0.85rem; + border-bottom: 1px solid rgba(255,255,255,0.10); + text-align: left; + vertical-align: middle; +} + +table.portal-table th, +.quote-table th{ + background: rgba(255,255,255,.06); + color: var(--text); + font-size:13px; + letter-spacing:.02em; +} + +table.portal-table tr:hover td, +.quote-table tr:hover td{ + background: rgba(255,255,255,.02); +} + +.invoice-link{ + color: var(--text); + text-decoration: none; + font-weight: 700; +} + +.invoice-link:hover{ + color: var(--accent); + text-decoration: underline; +} + +/* ===== Badges ===== */ +.status-badge, +.quote-badge{ + display: inline-block; + padding: 0.22rem 0.62rem; + border-radius: 999px; + font-size: 0.82rem; + font-weight: 700; +} + +.status-paid{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.status-pending{ background: rgba(245, 158, 11, 0.20); color: var(--warn); } +.status-overdue{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } +.status-other{ background: rgba(148, 163, 184, 0.20); color: #cbd5e1; } + +.quote-live{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.quote-stale{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } + +/* ===== Payments / invoice detail ===== */ +.pay-card{ + padding:18px; + margin-top: 1.25rem; +} + +.pay-selector-row{ + display:flex; + gap:0.75rem; + align-items:center; + flex-wrap:wrap; + margin-top:0.75rem; +} + +.pay-panel{ + margin-top: 1rem; + padding: 1rem; + border: 1px solid rgba(255,255,255,0.12); + border-radius: 12px; + background: rgba(255,255,255,0.02); +} + +.pay-panel.hidden{ display:none; } + +.pay-btn-square { background:#16a34a; border-color:transparent; color:#fff; } +.pay-btn-wallet { background:#2563eb; border-color:transparent; color:#fff; } +.pay-btn-mobile { background:#7c3aed; border-color:transparent; color:#fff; } +.pay-btn-copy { background:#374151; border-color:transparent; color:#fff; } + +.snapshot-wrap{ + position: relative; + margin-top: 1rem; + border: 1px solid rgba(255,255,255,0.14); + border-radius: 14px; + padding: 1rem; + background: rgba(255,255,255,0.02); +} + +.snapshot-header{ + display:flex; + justify-content:space-between; + gap:1rem; + align-items:flex-start; +} + +.snapshot-meta{ + flex: 1 1 auto; + min-width: 0; + line-height: 1.65; +} + +.snapshot-timer-box{ + width: 220px; + min-height: 132px; + border: 1px solid rgba(255,255,255,0.16); + border-radius: 14px; + background: rgba(0,0,0,0.18); + display:flex; + flex-direction:column; + justify-content:center; + align-items:center; + text-align:center; + padding: 0.9rem; +} + +.snapshot-timer-value{ + font-size: 2rem; + font-weight: 800; + line-height: 1.1; +} + +.snapshot-timer-label{ + margin-top: 0.55rem; + font-size: 0.95rem; + opacity: 0.95; +} + +.snapshot-timer-expired{ color: var(--danger); } + +.lock-box{ + margin-top: 1rem; + border: 1px solid rgba(34, 197, 94, 0.28); + background: rgba(22, 101, 52, 0.16); + border-radius: 12px; + padding: 1rem; +} + +.lock-box.expired{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); +} + +.lock-grid{ + display:grid; + grid-template-columns: 1fr 220px; + gap:1rem; + align-items:start; +} + +.lock-code{ + display:block; + margin-top:0.35rem; + padding:0.65rem 0.8rem; + background: rgba(0,0,0,0.22); + border-radius: 8px; + overflow-wrap:anywhere; +} + +.wallet-actions{ + display:flex; + gap:0.75rem; + flex-wrap:wrap; + margin-top:0.9rem; + align-items:center; +} + +.wallet-help{ + margin-top: 0.85rem; + padding: 0.9rem 1rem; + border-radius: 10px; + background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.10); +} + +.wallet-help h4{ + margin: 0 0 0.55rem 0; + font-size: 1rem; +} + +.wallet-help p{ margin: 0.35rem 0; } +.wallet-note{ opacity:0.9; margin-top:0.65rem; } +.mono{ font-family: monospace; } + +.copy-row{ + display:flex; + gap:0.5rem; + flex-wrap:wrap; + align-items:center; + margin-top:0.65rem; +} + +.copy-target{ + flex: 1 1 420px; + min-width: 220px; +} + +.copy-status{ + display:inline-block; + margin-left: 0.5rem; + opacity: 0.9; +} + +/* ===== Footer ===== */ +footer{ + margin:28px auto 20px auto; + max-width:1100px; + padding:0 18px; + color:var(--muted); + font-size:13px; +} + +/* ===== Responsive ===== */ +@media (max-width: 900px){ + .summary-grid, + .detail-grid{ + grid-template-columns:1fr; + } + + .nav{ + align-items:flex-start; + flex-direction:column; + } + + .navlinks{ + justify-content:flex-start; + } + + .brand img{ + height:54px; + } +} + +@media (max-width: 820px){ + .snapshot-header, + .lock-grid{ + grid-template-columns: 1fr; + display:block; + } + + .snapshot-timer-box{ + width: 100%; + margin-top: 1rem; + min-height: 110px; + } +} + + +/* ===== Fixed CAD / Oracle status bar ===== */ +body{ + padding-bottom: 56px; +} + +.otb-statusbar{ + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 9999; + display: flex; + align-items: center; + justify-content: center; + min-height: 42px; + padding: 8px 14px; + background: rgba(8, 16, 32, 0.94); + border-top: 1px solid rgba(255,255,255,.10); + backdrop-filter: blur(8px); + box-shadow: 0 -8px 24px rgba(0,0,0,.28); +} + +.otb-statusbar-inner{ + width: 100%; + max-width: 1100px; + display: flex; + gap: 10px; + align-items: center; + justify-content: center; + flex-wrap: wrap; + text-align: center; + color: var(--muted); + font-size: 12px; + line-height: 1.35; +} + +.otb-statusbar strong{ + color: var(--text); + font-weight: 700; +} + +.otb-statusbar a{ + color: var(--accent2); + text-decoration: none; + font-weight: 600; +} + +.otb-statusbar a:hover{ + text-decoration: underline; +} + +.otb-dot{ + width: 6px; + height: 6px; + border-radius: 999px; + display: inline-block; + background: rgba(255,255,255,.25); + flex: 0 0 auto; +} + +/* ===== Payment method chips ===== */ +.payment-method{ + display: inline-flex; + align-items: center; + gap: 7px; + margin-top: 7px; + padding: 4px 9px; + border-radius: 999px; + background: rgba(255,255,255,.05); + border: 1px solid rgba(255,255,255,.08); + color: var(--muted); + font-size: 11px; + font-weight: 700; + letter-spacing: .01em; +} + +.payment-method::before{ + content: ""; + width: 8px; + height: 8px; + border-radius: 999px; + display: inline-block; + background: #7aa2ff; + box-shadow: 0 0 0 3px rgba(255,255,255,.04); +} + +.payment-square::before{ background: #7dd3fc; } +.payment-etransfer::before{ background: #86efac; } +.payment-etho::before{ background: #b084ff; } +.payment-etica::before{ background: #4fd1c5; } +.payment-alt::before{ background: #fbbf24; } +.payment-cad::before{ background: #cbd5e1; } + +/* ===== Slightly stronger row hover ===== */ +table.portal-table tbody tr:hover td, +.quote-table tbody tr:hover td{ + background: rgba(255,255,255,.035); + transition: background .14s ease; +} + +@media (max-width: 700px){ + body{ + padding-bottom: 72px; + } + + .otb-statusbar-inner{ + font-size: 11px; + line-height: 1.25; + } +} + + +@media (max-width: 900px){ + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } +} + + +/* ===== Shared services dropdown ===== */ +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; + align-items:center; +} + +.dropdown{ + position:relative; + display:inline-block; +} + +.dropdown-toggle{ + display:inline-block; + cursor:pointer; +} + +.dropdown-menu{ + position:absolute; + top:calc(100% + 8px); + right:0; + min-width:220px; + display:none; + padding:10px; + border-radius:14px; + background:rgba(18,24,37,.98); + border:1px solid rgba(255,255,255,.08); + box-shadow:0 16px 40px rgba(0,0,0,.35); + z-index:9999; +} + +.dropdown:hover .dropdown-menu, +.dropdown:focus-within .dropdown-menu{ + display:block; +} + +.dropdown-menu a{ + display:block; + padding:9px 10px; + border-radius:10px; + color:var(--muted); + text-decoration:none; + white-space:nowrap; + margin:0; +} + +.dropdown-menu a + a{ + margin-top:4px; +} + +.dropdown-menu a:hover{ + color:var(--text); + background:rgba(255,255,255,.04); +} + +@media (max-width: 900px){ + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } +} diff --git a/backups/shared-brand-20260322-221933/portal_dashboard.html b/backups/shared-brand-20260322-221933/portal_dashboard.html new file mode 100644 index 0000000..4988060 --- /dev/null +++ b/backups/shared-brand-20260322-221933/portal_dashboard.html @@ -0,0 +1,126 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% if row.payment_method_label %} +
+ {{ row.payment_method_label }} +
+ {% endif %} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} +
{{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + +
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + + diff --git a/backups/shared-brand-20260322-221933/portal_forgot_password.html b/backups/shared-brand-20260322-221933/portal_forgot_password.html new file mode 100644 index 0000000..0e161b4 --- /dev/null +++ b/backups/shared-brand-20260322-221933/portal_forgot_password.html @@ -0,0 +1,22 @@ + + + Forgot Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Reset Portal Password

Enter your email address and a new single-use access code will be sent if your account exists.

{% if error %}
{{ error }}
{% endif %} {% if message %}
{{ message }}
{% endif %}
+
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + + diff --git a/backups/shared-brand-20260322-221933/portal_invoice_detail.html b/backups/shared-brand-20260322-221933/portal_invoice_detail.html new file mode 100644 index 0000000..f6e7d3a --- /dev/null +++ b/backups/shared-brand-20260322-221933/portal_invoice_detail.html @@ -0,0 +1,32 @@ + + + Invoice Detail - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Invoice Detail

{{ client.company_name or client.contact_name or client.email }}

{% if (invoice.status or "")|lower == "paid" %}
βœ“ This invoice has been paid. Thank you!
{% endif %} {% if crypto_error %}
{{ crypto_error }}
{% endif %}

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Status

{% set s = (invoice.status or "")|lower %} {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} processing {% elif s == "paid" %}{{ invoice.status }} {% elif s == "pending" %}{{ invoice.status }} {% elif s == "overdue" %}{{ invoice.status }} {% else %}{{ invoice.status }}{% endif %}

Created

{{ invoice.created_at }}

Total

{{ invoice.total_amount }}

Paid

{{ invoice.amount_paid }}

Outstanding

{{ invoice.outstanding }}

Invoice Items

{% for item in items %} {% else %} {% endfor %}
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
{% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %}

Pay Now

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Credit Card (Square)

Pay with Credit Card
{% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %}

Crypto Quote Snapshot

Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
{% if pending_crypto_payment %}
Your quote is protected after acceptance.
{% else %}
Select a crypto asset to accept the quote.
{% endif %}
{% if pending_crypto_payment and pending_crypto_payment.txid %}
--:--
Watching transaction / waiting for confirmation
{% elif pending_crypto_payment %}
--:--
Quote protected while you open wallet
{% else %}
--:--
This price times out:
{% endif %}
{% if pending_crypto_payment and selected_crypto_option %}

{{ selected_crypto_option.label }} Payment Instructions

Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
Destination wallet:
{{ pending_crypto_payment.wallet_address }}
Reference / Invoice:
{{ pending_crypto_payment.reference }} {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %}
Open in MetaMask Mobile

Fastest way to pay

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

2. If that does not open your wallet, click Open in MetaMask Mobile.

3. If needed, use Copy Payment Details and send manually.

You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet.
{% elif pending_crypto_payment.txid %}
Transaction Hash:
{{ pending_crypto_payment.txid }}
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
{% elif pending_crypto_payment.lock_expired %}
price has expired - please refresh your quote to update
{% endif %}
{% else %}
{% for q in crypto_options %} {% endfor %}
AssetQuoted AmountCAD PriceStatusAction
{{ q.label }} {% if q.recommended %}recommended{% endif %} {% if q.wallet_capable %}wallet{% endif %} {{ q.display_amount or "β€”" }} {% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %} {% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
{% endif %}
{% else %}

No crypto quote snapshot is available for this invoice yet.

{% endif %}
{% endif %} {% if invoice_payments %}

Payments Applied

{% for p in invoice_payments %} {% endfor %}
Method Amount Status Received Reference / TXID
{{ p.payment_method_label }} {{ p.payment_amount_display }} {{ p.payment_currency }} {{ p.payment_status }} {{ p.received_at_local }} {% if p.txid %} {{ p.txid }} {% elif p.reference %} {{ p.reference }} {% else %} - {% endif %} {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %}
{% endif %} {% if pdf_url %} {% endif %} +
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + + diff --git a/backups/shared-brand-20260322-221933/portal_login.html b/backups/shared-brand-20260322-221933/portal_login.html new file mode 100644 index 0000000..a8da333 --- /dev/null +++ b/backups/shared-brand-20260322-221933/portal_login.html @@ -0,0 +1,65 @@ + + + + + + Client Portal - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Customer Support +
+
+ + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ + +
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + + diff --git a/backups/shared-brand-20260322-221933/portal_set_password.html b/backups/shared-brand-20260322-221933/portal_set_password.html new file mode 100644 index 0000000..13f05cf --- /dev/null +++ b/backups/shared-brand-20260322-221933/portal_set_password.html @@ -0,0 +1,22 @@ + + + Set Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Create Your Portal Password

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

{% if portal_message %}
{{ portal_message }}
{% endif %}
+
+
+
+ Billing base currency: πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + Methods: Credit Card (via Square), e-Transfer, and enabled crypto assets +
+
+ + + {% include "footer.html" %} + + + diff --git a/backups/shared-brand-20260322-221933/site_nav.html b/backups/shared-brand-20260322-221933/site_nav.html new file mode 100644 index 0000000..7177302 --- /dev/null +++ b/backups/shared-brand-20260322-221933/site_nav.html @@ -0,0 +1,35 @@ + diff --git a/backups/shared-brand-20260322-221933/style.css b/backups/shared-brand-20260322-221933/style.css new file mode 100644 index 0000000..1e26b43 --- /dev/null +++ b/backups/shared-brand-20260322-221933/style.css @@ -0,0 +1,1096 @@ +:root{ + --bg:#0b0f14; + --card:#121825; + --card-soft:rgba(18,24,37,.78); + --text:#e8eefc; + --muted:#aab6d6; + --line:#24304a; + --accent:#7aa2ff; + --accent2:#62e6b7; + --success:#4ade80; + --warn:#fbbf24; + --danger:#f87171; + --radius:16px; + --shadow:0 16px 40px rgba(0,0,0,.35); +} + +*{box-sizing:border-box} +html,body{height:100%} + +body{ + margin:0; + font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, "Apple Color Emoji","Segoe UI Emoji"; + background: + radial-gradient(1200px 600px at 20% 0%, rgba(122,162,255,.22), transparent 60%), + radial-gradient(900px 500px at 90% 20%, rgba(98,230,183,.15), transparent 60%), + linear-gradient(180deg, #081225 0%, #09172d 100%); + color:var(--text); + line-height:1.45; +} + +a{color:inherit} + +/* ===== Shared container ===== */ +.container{ + max-width:1100px; + margin:0 auto; + padding:20px 18px; +} + +/* ===== Header / branded nav ===== */ +.header{width:100%} + +.nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + padding:12px 0 22px 0; +} + +.brand{ + display:flex; + align-items:center; + gap:14px; + text-decoration:none; +} + +.brand img{ + height:60px; + width:auto; + display:block; + object-fit:contain; + background: rgba(255,255,255,0.92); + padding: 6px 12px; + border-radius: 999px; + box-shadow: 0 8px 24px rgba(0,0,0,0.35); +} + +.title{ + display:flex; + flex-direction:column; + line-height:1.1; +} + +.title strong{letter-spacing:.2px} +.title span{ + color:var(--muted); + font-size:13px; + margin-top:2px; +} + +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; +} + +.navlinks a{ + text-decoration:none; + padding:8px 10px; + border-radius:12px; + color:var(--muted); + border:1px solid transparent; +} + +.navlinks a:hover{ + color:var(--text); + border-color:rgba(255,255,255,.08); + background:rgba(255,255,255,.03); +} + +.navlinks a.active{ + color:var(--text); + border-color:rgba(255,255,255,.10); + background:rgba(255,255,255,.04); +} + +/* ===== Generic portal shell ===== */ +.portal-shell{ + max-width:1100px; + margin:16px auto 28px auto; + padding:0 18px 20px 18px; +} + +.portal-card, +.detail-card, +.summary-card, +.pay-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); +} + +.portal-card{ + max-width:760px; + margin:24px auto 12px auto; + padding:22px; +} + +.portal-page-header{ + display:flex; + align-items:flex-start; + justify-content:space-between; + gap:16px; + flex-wrap:wrap; + margin:6px 0 18px 0; +} + +.portal-page-title{ + margin:0; + font-size:24px; + line-height:1.1; +} + +.portal-page-subtitle{ + margin:8px 0 0 0; + color:var(--muted); +} + +.portal-client-name{ + margin:8px 0 0 0; + color:var(--text); + font-size:15px; +} + +.portal-toolbar{ + display:flex; + gap:10px; + flex-wrap:wrap; + align-items:center; +} + +.portal-btn, +.btn, +.pay-btn, +.quote-pick-btn{ + display:inline-flex; + align-items:center; + justify-content:center; + gap:8px; + min-height:42px; + padding:10px 14px; + border-radius:12px; + text-decoration:none; + border:1px solid rgba(255,255,255,.10); + background: rgba(255,255,255,.05); + color:var(--text); + font-weight:600; + cursor:pointer; +} + +.portal-btn:hover, +.btn:hover, +.pay-btn:hover, +.quote-pick-btn:hover{ + border-color:rgba(122,162,255,.45); + box-shadow:0 0 0 4px rgba(122,162,255,.12); + text-decoration:none; +} + +.portal-btn.primary, +.btn.primary{ + background: linear-gradient(135deg, rgba(122,162,255,.95), rgba(98,230,183,.85)); + border-color: transparent; + color:#071017; + font-weight:700; +} + +.portal-btn.primary:hover, +.btn.primary:hover{ + box-shadow:0 0 0 4px rgba(98,230,183,.18); +} + +/* ===== Login / forms ===== */ +.portal-sub{ + color:var(--muted); + margin:0 0 16px 0; +} + +.portal-form{ + display:grid; + gap:14px; +} + +.portal-form label{ + display:block; + font-weight:600; + margin-bottom:6px; +} + +.portal-form input, +.portal-form select, +.pay-selector{ + width:100%; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.14); + background: rgba(255,255,255,.06); + color:var(--text); + box-sizing:border-box; + outline:none; +} + +.portal-form input:focus, +.portal-form select:focus, +.pay-selector:focus{ + border-color:rgba(122,162,255,.65); + box-shadow:0 0 0 4px rgba(122,162,255,.12); +} + +.portal-actions{ + display:flex; + gap:10px; + flex-wrap:wrap; + margin-top:4px; +} + +.portal-note{ + margin-top:16px; + color:var(--muted); + font-size:14px; + line-height:1.5; +} + +.portal-msg, +.error-box, +.success-box{ + margin-bottom:16px; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.16); + background: rgba(255,255,255,.04); +} + +.error-box{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); + color: #fecaca; +} + +.success-box{ + border-color: rgba(34, 197, 94, 0.55); + background: rgba(22, 101, 52, 0.18); + color: #dcfce7; +} + +/* ===== Dashboard ===== */ +.portal-wrap{ + max-width:1100px; + margin:0 auto; + padding:0; +} + +.summary-grid, +.detail-grid{ + display:grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap:14px; + margin: 0 0 18px 0; +} + +.summary-card, +.detail-card{ + padding:18px; +} + +.summary-card h3, +.detail-card h3{ + margin:0 0 8px 0; + font-size:14px; + color:var(--muted); +} + +.summary-card .summary-value, +.detail-card .detail-value{ + font-size:28px; + font-weight:800; + line-height:1.1; + color:var(--text); +} + +.summary-card .summary-sub{ + margin-top:6px; + font-size:12px; + color:var(--muted); +} + +.section-title{ + margin:18px 0 10px 0; + font-size:22px; +} + +.table-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); + overflow:hidden; +} + +/* ===== Tables ===== */ +table, +.portal-table, +.quote-table{ + width:100%; + border-collapse: collapse; +} + +table.portal-table th, +table.portal-table td, +.quote-table th, +.quote-table td{ + padding: 0.9rem 0.85rem; + border-bottom: 1px solid rgba(255,255,255,0.10); + text-align: left; + vertical-align: middle; +} + +table.portal-table th, +.quote-table th{ + background: rgba(255,255,255,.06); + color: var(--text); + font-size:13px; + letter-spacing:.02em; +} + +table.portal-table tr:hover td, +.quote-table tr:hover td{ + background: rgba(255,255,255,.02); +} + +.invoice-link{ + color: var(--text); + text-decoration: none; + font-weight: 700; +} + +.invoice-link:hover{ + color: var(--accent); + text-decoration: underline; +} + +/* ===== Badges ===== */ +.status-badge, +.quote-badge{ + display: inline-block; + padding: 0.22rem 0.62rem; + border-radius: 999px; + font-size: 0.82rem; + font-weight: 700; +} + +.status-paid{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.status-pending{ background: rgba(245, 158, 11, 0.20); color: var(--warn); } +.status-overdue{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } +.status-other{ background: rgba(148, 163, 184, 0.20); color: #cbd5e1; } + +.quote-live{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.quote-stale{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } + +/* ===== Payments / invoice detail ===== */ +.pay-card{ + padding:18px; + margin-top: 1.25rem; +} + +.pay-selector-row{ + display:flex; + gap:0.75rem; + align-items:center; + flex-wrap:wrap; + margin-top:0.75rem; +} + +.pay-panel{ + margin-top: 1rem; + padding: 1rem; + border: 1px solid rgba(255,255,255,0.12); + border-radius: 12px; + background: rgba(255,255,255,0.02); +} + +.pay-panel.hidden{ display:none; } + +.pay-btn-square { background:#16a34a; border-color:transparent; color:#fff; } +.pay-btn-wallet { background:#2563eb; border-color:transparent; color:#fff; } +.pay-btn-mobile { background:#7c3aed; border-color:transparent; color:#fff; } +.pay-btn-copy { background:#374151; border-color:transparent; color:#fff; } + +.snapshot-wrap{ + position: relative; + margin-top: 1rem; + border: 1px solid rgba(255,255,255,0.14); + border-radius: 14px; + padding: 1rem; + background: rgba(255,255,255,0.02); +} + +.snapshot-header{ + display:flex; + justify-content:space-between; + gap:1rem; + align-items:flex-start; +} + +.snapshot-meta{ + flex: 1 1 auto; + min-width: 0; + line-height: 1.65; +} + +.snapshot-timer-box{ + width: 220px; + min-height: 132px; + border: 1px solid rgba(255,255,255,0.16); + border-radius: 14px; + background: rgba(0,0,0,0.18); + display:flex; + flex-direction:column; + justify-content:center; + align-items:center; + text-align:center; + padding: 0.9rem; +} + +.snapshot-timer-value{ + font-size: 2rem; + font-weight: 800; + line-height: 1.1; +} + +.snapshot-timer-label{ + margin-top: 0.55rem; + font-size: 0.95rem; + opacity: 0.95; +} + +.snapshot-timer-expired{ color: var(--danger); } + +.lock-box{ + margin-top: 1rem; + border: 1px solid rgba(34, 197, 94, 0.28); + background: rgba(22, 101, 52, 0.16); + border-radius: 12px; + padding: 1rem; +} + +.lock-box.expired{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); +} + +.lock-grid{ + display:grid; + grid-template-columns: 1fr 220px; + gap:1rem; + align-items:start; +} + +.lock-code{ + display:block; + margin-top:0.35rem; + padding:0.65rem 0.8rem; + background: rgba(0,0,0,0.22); + border-radius: 8px; + overflow-wrap:anywhere; +} + +.wallet-actions{ + display:flex; + gap:0.75rem; + flex-wrap:wrap; + margin-top:0.9rem; + align-items:center; +} + +.wallet-help{ + margin-top: 0.85rem; + padding: 0.9rem 1rem; + border-radius: 10px; + background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.10); +} + +.wallet-help h4{ + margin: 0 0 0.55rem 0; + font-size: 1rem; +} + +.wallet-help p{ margin: 0.35rem 0; } +.wallet-note{ opacity:0.9; margin-top:0.65rem; } +.mono{ font-family: monospace; } + +.copy-row{ + display:flex; + gap:0.5rem; + flex-wrap:wrap; + align-items:center; + margin-top:0.65rem; +} + +.copy-target{ + flex: 1 1 420px; + min-width: 220px; +} + +.copy-status{ + display:inline-block; + margin-left: 0.5rem; + opacity: 0.9; +} + +/* ===== Footer ===== */ +footer{ + margin:28px auto 20px auto; + max-width:1100px; + padding:0 18px; + color:var(--muted); + font-size:13px; +} + +/* ===== Responsive ===== */ +@media (max-width: 900px){ + .summary-grid, + .detail-grid{ + grid-template-columns:1fr; + } + + .nav{ + align-items:flex-start; + flex-direction:column; + } + + .navlinks{ + justify-content:flex-start; + } + + .brand img{ + height:54px; + } +} + +@media (max-width: 820px){ + .snapshot-header, + .lock-grid{ + grid-template-columns: 1fr; + display:block; + } + + .snapshot-timer-box{ + width: 100%; + margin-top: 1rem; + min-height: 110px; + } +} + + +/* ===== Fixed CAD / Oracle status bar ===== */ +body{ + padding-bottom: 56px; +} + +.otb-statusbar{ + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 9999; + display: flex; + align-items: center; + justify-content: center; + min-height: 42px; + padding: 8px 14px; + background: rgba(8, 16, 32, 0.94); + border-top: 1px solid rgba(255,255,255,.10); + backdrop-filter: blur(8px); + box-shadow: 0 -8px 24px rgba(0,0,0,.28); +} + +.otb-statusbar-inner{ + width: 100%; + max-width: 1100px; + display: flex; + gap: 10px; + align-items: center; + justify-content: center; + flex-wrap: wrap; + text-align: center; + color: var(--muted); + font-size: 12px; + line-height: 1.35; +} + +.otb-statusbar strong{ + color: var(--text); + font-weight: 700; +} + +.otb-statusbar a{ + color: var(--accent2); + text-decoration: none; + font-weight: 600; +} + +.otb-statusbar a:hover{ + text-decoration: underline; +} + +.otb-dot{ + width: 6px; + height: 6px; + border-radius: 999px; + display: inline-block; + background: rgba(255,255,255,.25); + flex: 0 0 auto; +} + +/* ===== Payment method chips ===== */ +.payment-method{ + display: inline-flex; + align-items: center; + gap: 7px; + margin-top: 7px; + padding: 4px 9px; + border-radius: 999px; + background: rgba(255,255,255,.05); + border: 1px solid rgba(255,255,255,.08); + color: var(--muted); + font-size: 11px; + font-weight: 700; + letter-spacing: .01em; +} + +.payment-method::before{ + content: ""; + width: 8px; + height: 8px; + border-radius: 999px; + display: inline-block; + background: #7aa2ff; + box-shadow: 0 0 0 3px rgba(255,255,255,.04); +} + +.payment-square::before{ background: #7dd3fc; } +.payment-etransfer::before{ background: #86efac; } +.payment-etho::before{ background: #b084ff; } +.payment-etica::before{ background: #4fd1c5; } +.payment-alt::before{ background: #fbbf24; } +.payment-cad::before{ background: #cbd5e1; } + +/* ===== Slightly stronger row hover ===== */ +table.portal-table tbody tr:hover td, +.quote-table tbody tr:hover td{ + background: rgba(255,255,255,.035); + transition: background .14s ease; +} + +@media (max-width: 700px){ + body{ + padding-bottom: 72px; + } + + .otb-statusbar-inner{ + font-size: 11px; + line-height: 1.25; + } +} + + +@media (max-width: 900px){ + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } +} + + +/* ===== Shared services dropdown ===== */ +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; + align-items:center; +} + +.dropdown{ + position:relative; + display:inline-block; +} + +.dropdown-toggle{ + display:inline-block; + cursor:pointer; +} + +.dropdown-menu{ + position:absolute; + top:calc(100% + 8px); + right:0; + min-width:220px; + display:none; + padding:10px; + border-radius:14px; + background:rgba(18,24,37,.98); + border:1px solid rgba(255,255,255,.08); + box-shadow:0 16px 40px rgba(0,0,0,.35); + z-index:9999; +} + +.dropdown:hover .dropdown-menu, +.dropdown:focus-within .dropdown-menu{ + display:block; +} + +.dropdown-menu a{ + display:block; + padding:9px 10px; + border-radius:10px; + color:var(--muted); + text-decoration:none; + white-space:nowrap; + margin:0; +} + +.dropdown-menu a + a{ + margin-top:4px; +} + +.dropdown-menu a:hover{ + color:var(--text); + background:rgba(255,255,255,.04); +} + +@media (max-width: 900px){ + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } +} + + +/* ===== OTB shared branding ===== */ +html[data-theme="dark"]{ + --otb-bg:#081225; + --otb-bg2:#09172d; + --otb-text:#e8eefc; + --otb-muted:#aab6d6; + --otb-panel:rgba(18,24,37,.98); + --otb-panel-soft:rgba(18,24,37,.78); + --otb-line:rgba(255,255,255,.08); +} + +html[data-theme="light"]{ + --otb-bg:#f4f7fb; + --otb-bg2:#eef3f9; + --otb-text:#0f172a; + --otb-muted:#475569; + --otb-panel:rgba(255,255,255,.98); + --otb-panel-soft:rgba(255,255,255,.88); + --otb-line:rgba(15,23,42,.10); +} + +body{ + padding-bottom:56px; +} + +.site-container{ + max-width:1100px; + margin:0 auto; + padding:20px 18px 0 18px; +} + +.site-header{ + width:100%; +} + +.site-nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + padding:12px 0 22px 0; +} + +.site-brand{ + display:flex; + align-items:center; + gap:14px; + text-decoration:none; + color:inherit; +} + +.site-brand img{ + height:60px; + width:auto; + display:block; + object-fit:contain; + background:rgba(255,255,255,0.92); + padding:6px 12px; + border-radius:999px; + box-shadow:0 8px 24px rgba(0,0,0,0.35); +} + +.site-title{ + display:flex; + flex-direction:column; + line-height:1.1; +} + +.site-title strong{ + letter-spacing:.2px; + color:var(--otb-text); +} + +.site-title span{ + color:var(--otb-muted); + font-size:13px; + margin-top:2px; +} + +.site-nav-right{ + display:flex; + align-items:center; + gap:14px; + flex-wrap:wrap; + justify-content:flex-end; +} + +.site-navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; + align-items:center; +} + +.site-navlinks > a, +.dropdown-toggle{ + text-decoration:none; + padding:8px 10px; + border-radius:12px; + color:var(--otb-muted); + border:1px solid transparent; +} + +.site-navlinks > a:hover, +.dropdown-toggle:hover{ + color:var(--otb-text); + border-color:var(--otb-line); + background:rgba(255,255,255,.03); +} + +.dropdown{ + position:relative; + display:inline-block; +} + +.dropdown-toggle{ + display:inline-block; + cursor:pointer; +} + +.dropdown-menu{ + position:absolute; + top:calc(100% + 8px); + right:0; + min-width:220px; + display:none; + padding:10px; + border-radius:14px; + background:var(--otb-panel); + border:1px solid var(--otb-line); + box-shadow:0 16px 40px rgba(0,0,0,.35); + z-index:9999; +} + +.dropdown:hover .dropdown-menu, +.dropdown:focus-within .dropdown-menu{ + display:block; +} + +.dropdown-menu a{ + display:block; + padding:9px 10px; + border-radius:10px; + color:var(--otb-muted); + text-decoration:none; + white-space:nowrap; + margin:0; +} + +.dropdown-menu a + a{ + margin-top:4px; +} + +.dropdown-menu a:hover{ + color:var(--otb-text); + background:rgba(255,255,255,.04); +} + +.otb-theme-switch{ + position:relative; + display:inline-block; + width:54px; + height:30px; + flex:0 0 auto; +} + +.otb-theme-switch input{ + opacity:0; + width:0; + height:0; +} + +.otb-theme-slider{ + position:absolute; + inset:0; + cursor:pointer; + background:rgba(255,255,255,.10); + border:1px solid var(--otb-line); + transition:.2s; + border-radius:999px; +} + +.otb-theme-slider:before{ + content:""; + position:absolute; + height:22px; + width:22px; + left:3px; + top:3px; + background:var(--otb-text); + transition:.2s; + border-radius:50%; +} + +.otb-theme-switch input:checked + .otb-theme-slider:before{ + transform:translateX(24px); +} + +.otb-statusbar{ + position:fixed; + left:0; + right:0; + bottom:0; + z-index:9999; + display:flex; + align-items:center; + justify-content:center; + min-height:42px; + padding:8px 14px; + background:var(--otb-panel); + border-top:1px solid var(--otb-line); + backdrop-filter:blur(8px); + box-shadow:0 -8px 24px rgba(0,0,0,.28); +} + +.otb-statusbar-inner{ + width:100%; + max-width:1100px; + display:flex; + gap:10px; + align-items:center; + justify-content:center; + flex-wrap:wrap; + text-align:center; + color:var(--otb-muted); + font-size:12px; + line-height:1.35; +} + +.otb-statusbar strong{ + color:var(--otb-text); + font-weight:700; +} + +.otb-statusbar a{ + color:#62e6b7; + text-decoration:none; + font-weight:600; +} + +.otb-statusbar a:hover{ + text-decoration:underline; +} + +.otb-dot{ + width:6px; + height:6px; + border-radius:999px; + display:inline-block; + background:rgba(255,255,255,.25); + flex:0 0 auto; +} + +@media (max-width: 900px){ + .site-nav{ + align-items:flex-start; + flex-direction:column; + } + + .site-nav-right{ + width:100%; + justify-content:space-between; + } + + .site-navlinks{ + justify-content:flex-start; + } + + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } + + .site-brand img{ + height:54px; + } +} + +@media (max-width: 700px){ + body{ + padding-bottom:72px; + } + + .otb-statusbar-inner{ + font-size:11px; + line-height:1.25; + } +} \ No newline at end of file diff --git a/backups/shared-brand-20260322-222018/portal_dashboard.html b/backups/shared-brand-20260322-222018/portal_dashboard.html new file mode 100644 index 0000000..2be783e --- /dev/null +++ b/backups/shared-brand-20260322-222018/portal_dashboard.html @@ -0,0 +1,129 @@ + + + + + + Client Dashboard - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ + +
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% if row.payment_method_label %} +
+ {{ row.payment_method_label }} +
+ {% endif %} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} +
{{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+
+
+ + + + +
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
+ + + + diff --git a/backups/shared-brand-20260322-222018/portal_forgot_password.html b/backups/shared-brand-20260322-222018/portal_forgot_password.html new file mode 100644 index 0000000..cd25561 --- /dev/null +++ b/backups/shared-brand-20260322-222018/portal_forgot_password.html @@ -0,0 +1,25 @@ + + + Forgot Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Reset Portal Password

Enter your email address and a new single-use access code will be sent if your account exists.

{% if error %}
{{ error }}
{% endif %} {% if message %}
{{ message }}
{% endif %}
+
+
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
+ + + + diff --git a/backups/shared-brand-20260322-222018/portal_invoice_detail.html b/backups/shared-brand-20260322-222018/portal_invoice_detail.html new file mode 100644 index 0000000..de79118 --- /dev/null +++ b/backups/shared-brand-20260322-222018/portal_invoice_detail.html @@ -0,0 +1,35 @@ + + + Invoice Detail - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Invoice Detail

{{ client.company_name or client.contact_name or client.email }}

{% if (invoice.status or "")|lower == "paid" %}
βœ“ This invoice has been paid. Thank you!
{% endif %} {% if crypto_error %}
{{ crypto_error }}
{% endif %}

Invoice

{{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Status

{% set s = (invoice.status or "")|lower %} {% if pending_crypto_payment and pending_crypto_payment.txid and not pending_crypto_payment.processing_expired and s != "paid" %} processing {% elif s == "paid" %}{{ invoice.status }} {% elif s == "pending" %}{{ invoice.status }} {% elif s == "overdue" %}{{ invoice.status }} {% else %}{{ invoice.status }}{% endif %}

Created

{{ invoice.created_at }}

Total

{{ invoice.total_amount }}

Paid

{{ invoice.amount_paid }}

Outstanding

{{ invoice.outstanding }}

Invoice Items

{% for item in items %} {% else %} {% endfor %}
DescriptionQtyUnit PriceLine Total
{{ item.description }}{{ item.quantity }}{{ item.unit_price }}{{ item.line_total }}
No invoice line items found.
{% if (invoice.status or "")|lower != "paid" and invoice.outstanding != "0.00" %}

Pay Now

Interac e-Transfer
Send payment to:
payment@outsidethebox.top
Reference: Invoice {{ invoice.invoice_number or ("INV-" ~ invoice.id) }}

Credit Card (Square)

Pay with Credit Card
{% if invoice.oracle_quote and invoice.oracle_quote.quotes and crypto_options %}

Crypto Quote Snapshot

Quoted At: {{ invoice.oracle_quote.quoted_at or "β€”" }}
Source Status: {{ invoice.oracle_quote.source_status or "β€”" }}
Frozen Amount: {{ invoice.oracle_quote.amount or invoice.quote_fiat_amount or invoice.total_amount }} {{ invoice.oracle_quote.fiat or invoice.quote_fiat_currency or "CAD" }}
{% if pending_crypto_payment %}
Your quote is protected after acceptance.
{% else %}
Select a crypto asset to accept the quote.
{% endif %}
{% if pending_crypto_payment and pending_crypto_payment.txid %}
--:--
Watching transaction / waiting for confirmation
{% elif pending_crypto_payment %}
--:--
Quote protected while you open wallet
{% else %}
--:--
This price times out:
{% endif %}
{% if pending_crypto_payment and selected_crypto_option %}

{{ selected_crypto_option.label }} Payment Instructions

Send exactly: {{ pending_crypto_payment.payment_amount }} {{ pending_crypto_payment.payment_currency }}
Destination wallet:
{{ pending_crypto_payment.wallet_address }}
Reference / Invoice:
{{ pending_crypto_payment.reference }} {% if selected_crypto_option.wallet_capable and not pending_crypto_payment.txid and not pending_crypto_payment.lock_expired %}
Open in MetaMask Mobile

Fastest way to pay

1. Click Open MetaMask / Rabby if your wallet is installed in this browser.

2. If that does not open your wallet, click Open in MetaMask Mobile.

3. If needed, use Copy Payment Details and send manually.

You do not need to finish everything inside the short quote timer. Once accepted, the quote is protected while you open your wallet.
{% elif pending_crypto_payment.txid %}
Transaction Hash:
{{ pending_crypto_payment.txid }}
Transaction submitted and detected on RPC. Watching transaction / waiting for confirmation.
{% elif pending_crypto_payment.lock_expired %}
price has expired - please refresh your quote to update
{% endif %}
{% else %}
{% for q in crypto_options %} {% endfor %}
AssetQuoted AmountCAD PriceStatusAction
{{ q.label }} {% if q.recommended %}recommended{% endif %} {% if q.wallet_capable %}wallet{% endif %} {{ q.display_amount or "β€”" }} {% if q.price_cad is not none %}{{ "%.8f"|format(q.price_cad|float) }}{% else %}β€”{% endif %} {% if q.available %}live{% else %}{{ q.reason or "unavailable" }}{% endif %}
{% endif %}
{% else %}

No crypto quote snapshot is available for this invoice yet.

{% endif %}
{% endif %} {% if invoice_payments %}

Payments Applied

{% for p in invoice_payments %} {% endfor %}
Method Amount Status Received Reference / TXID
{{ p.payment_method_label }} {{ p.payment_amount_display }} {{ p.payment_currency }} {{ p.payment_status }} {{ p.received_at_local }} {% if p.txid %} {{ p.txid }} {% elif p.reference %} {{ p.reference }} {% else %} - {% endif %} {% if p.wallet_address %}
{{ p.wallet_address }}{% endif %}
{% endif %} {% if pdf_url %} {% endif %} +
+
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
+ + + + diff --git a/backups/shared-brand-20260322-222018/portal_login.html b/backups/shared-brand-20260322-222018/portal_login.html new file mode 100644 index 0000000..2aa0e40 --- /dev/null +++ b/backups/shared-brand-20260322-222018/portal_login.html @@ -0,0 +1,68 @@ + + + + + + Client Portal - OutsideTheBox + + + + + {% include "includes/site_nav.html" %} + +
+
+

OutsideTheBox Client Portal

+

Secure access for invoices, balances, and account information.

+ + {% if portal_message %} +
{{ portal_message }}
+ {% endif %} + +
+
+ + +
+ +
+ + +
+ +
+ + Customer Support +
+
+ + + +

+ First-time users should sign in with the one-time access code provided by OutsideTheBox, then set a password. + This access code is single-use and is cleared after password setup. Future logins use your email address and password. +

+
+
+ + +
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
+ + + + diff --git a/backups/shared-brand-20260322-222018/portal_set_password.html b/backups/shared-brand-20260322-222018/portal_set_password.html new file mode 100644 index 0000000..1ef6e8e --- /dev/null +++ b/backups/shared-brand-20260322-222018/portal_set_password.html @@ -0,0 +1,25 @@ + + + Set Portal Password - OutsideTheBox + + +{% include "includes/site_nav.html" %}

Create Your Portal Password

Welcome, {{ client_name }}. Your one-time access code worked. Please create a password for future logins.

{% if portal_message %}
{{ portal_message }}
{% endif %}
+
+
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
+ + + + diff --git a/backups/shared-brand-20260322-222018/site_nav.html b/backups/shared-brand-20260322-222018/site_nav.html new file mode 100644 index 0000000..7177302 --- /dev/null +++ b/backups/shared-brand-20260322-222018/site_nav.html @@ -0,0 +1,35 @@ + diff --git a/backups/shared-brand-20260322-222018/style.css b/backups/shared-brand-20260322-222018/style.css new file mode 100644 index 0000000..1e26b43 --- /dev/null +++ b/backups/shared-brand-20260322-222018/style.css @@ -0,0 +1,1096 @@ +:root{ + --bg:#0b0f14; + --card:#121825; + --card-soft:rgba(18,24,37,.78); + --text:#e8eefc; + --muted:#aab6d6; + --line:#24304a; + --accent:#7aa2ff; + --accent2:#62e6b7; + --success:#4ade80; + --warn:#fbbf24; + --danger:#f87171; + --radius:16px; + --shadow:0 16px 40px rgba(0,0,0,.35); +} + +*{box-sizing:border-box} +html,body{height:100%} + +body{ + margin:0; + font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Arial, "Apple Color Emoji","Segoe UI Emoji"; + background: + radial-gradient(1200px 600px at 20% 0%, rgba(122,162,255,.22), transparent 60%), + radial-gradient(900px 500px at 90% 20%, rgba(98,230,183,.15), transparent 60%), + linear-gradient(180deg, #081225 0%, #09172d 100%); + color:var(--text); + line-height:1.45; +} + +a{color:inherit} + +/* ===== Shared container ===== */ +.container{ + max-width:1100px; + margin:0 auto; + padding:20px 18px; +} + +/* ===== Header / branded nav ===== */ +.header{width:100%} + +.nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + padding:12px 0 22px 0; +} + +.brand{ + display:flex; + align-items:center; + gap:14px; + text-decoration:none; +} + +.brand img{ + height:60px; + width:auto; + display:block; + object-fit:contain; + background: rgba(255,255,255,0.92); + padding: 6px 12px; + border-radius: 999px; + box-shadow: 0 8px 24px rgba(0,0,0,0.35); +} + +.title{ + display:flex; + flex-direction:column; + line-height:1.1; +} + +.title strong{letter-spacing:.2px} +.title span{ + color:var(--muted); + font-size:13px; + margin-top:2px; +} + +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; +} + +.navlinks a{ + text-decoration:none; + padding:8px 10px; + border-radius:12px; + color:var(--muted); + border:1px solid transparent; +} + +.navlinks a:hover{ + color:var(--text); + border-color:rgba(255,255,255,.08); + background:rgba(255,255,255,.03); +} + +.navlinks a.active{ + color:var(--text); + border-color:rgba(255,255,255,.10); + background:rgba(255,255,255,.04); +} + +/* ===== Generic portal shell ===== */ +.portal-shell{ + max-width:1100px; + margin:16px auto 28px auto; + padding:0 18px 20px 18px; +} + +.portal-card, +.detail-card, +.summary-card, +.pay-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); +} + +.portal-card{ + max-width:760px; + margin:24px auto 12px auto; + padding:22px; +} + +.portal-page-header{ + display:flex; + align-items:flex-start; + justify-content:space-between; + gap:16px; + flex-wrap:wrap; + margin:6px 0 18px 0; +} + +.portal-page-title{ + margin:0; + font-size:24px; + line-height:1.1; +} + +.portal-page-subtitle{ + margin:8px 0 0 0; + color:var(--muted); +} + +.portal-client-name{ + margin:8px 0 0 0; + color:var(--text); + font-size:15px; +} + +.portal-toolbar{ + display:flex; + gap:10px; + flex-wrap:wrap; + align-items:center; +} + +.portal-btn, +.btn, +.pay-btn, +.quote-pick-btn{ + display:inline-flex; + align-items:center; + justify-content:center; + gap:8px; + min-height:42px; + padding:10px 14px; + border-radius:12px; + text-decoration:none; + border:1px solid rgba(255,255,255,.10); + background: rgba(255,255,255,.05); + color:var(--text); + font-weight:600; + cursor:pointer; +} + +.portal-btn:hover, +.btn:hover, +.pay-btn:hover, +.quote-pick-btn:hover{ + border-color:rgba(122,162,255,.45); + box-shadow:0 0 0 4px rgba(122,162,255,.12); + text-decoration:none; +} + +.portal-btn.primary, +.btn.primary{ + background: linear-gradient(135deg, rgba(122,162,255,.95), rgba(98,230,183,.85)); + border-color: transparent; + color:#071017; + font-weight:700; +} + +.portal-btn.primary:hover, +.btn.primary:hover{ + box-shadow:0 0 0 4px rgba(98,230,183,.18); +} + +/* ===== Login / forms ===== */ +.portal-sub{ + color:var(--muted); + margin:0 0 16px 0; +} + +.portal-form{ + display:grid; + gap:14px; +} + +.portal-form label{ + display:block; + font-weight:600; + margin-bottom:6px; +} + +.portal-form input, +.portal-form select, +.pay-selector{ + width:100%; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.14); + background: rgba(255,255,255,.06); + color:var(--text); + box-sizing:border-box; + outline:none; +} + +.portal-form input:focus, +.portal-form select:focus, +.pay-selector:focus{ + border-color:rgba(122,162,255,.65); + box-shadow:0 0 0 4px rgba(122,162,255,.12); +} + +.portal-actions{ + display:flex; + gap:10px; + flex-wrap:wrap; + margin-top:4px; +} + +.portal-note{ + margin-top:16px; + color:var(--muted); + font-size:14px; + line-height:1.5; +} + +.portal-msg, +.error-box, +.success-box{ + margin-bottom:16px; + padding:12px 14px; + border-radius:12px; + border:1px solid rgba(255,255,255,.16); + background: rgba(255,255,255,.04); +} + +.error-box{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); + color: #fecaca; +} + +.success-box{ + border-color: rgba(34, 197, 94, 0.55); + background: rgba(22, 101, 52, 0.18); + color: #dcfce7; +} + +/* ===== Dashboard ===== */ +.portal-wrap{ + max-width:1100px; + margin:0 auto; + padding:0; +} + +.summary-grid, +.detail-grid{ + display:grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap:14px; + margin: 0 0 18px 0; +} + +.summary-card, +.detail-card{ + padding:18px; +} + +.summary-card h3, +.detail-card h3{ + margin:0 0 8px 0; + font-size:14px; + color:var(--muted); +} + +.summary-card .summary-value, +.detail-card .detail-value{ + font-size:28px; + font-weight:800; + line-height:1.1; + color:var(--text); +} + +.summary-card .summary-sub{ + margin-top:6px; + font-size:12px; + color:var(--muted); +} + +.section-title{ + margin:18px 0 10px 0; + font-size:22px; +} + +.table-card{ + background: var(--card-soft); + border: 1px solid rgba(255,255,255,.07); + border-radius: var(--radius); + box-shadow: var(--shadow); + overflow:hidden; +} + +/* ===== Tables ===== */ +table, +.portal-table, +.quote-table{ + width:100%; + border-collapse: collapse; +} + +table.portal-table th, +table.portal-table td, +.quote-table th, +.quote-table td{ + padding: 0.9rem 0.85rem; + border-bottom: 1px solid rgba(255,255,255,0.10); + text-align: left; + vertical-align: middle; +} + +table.portal-table th, +.quote-table th{ + background: rgba(255,255,255,.06); + color: var(--text); + font-size:13px; + letter-spacing:.02em; +} + +table.portal-table tr:hover td, +.quote-table tr:hover td{ + background: rgba(255,255,255,.02); +} + +.invoice-link{ + color: var(--text); + text-decoration: none; + font-weight: 700; +} + +.invoice-link:hover{ + color: var(--accent); + text-decoration: underline; +} + +/* ===== Badges ===== */ +.status-badge, +.quote-badge{ + display: inline-block; + padding: 0.22rem 0.62rem; + border-radius: 999px; + font-size: 0.82rem; + font-weight: 700; +} + +.status-paid{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.status-pending{ background: rgba(245, 158, 11, 0.20); color: var(--warn); } +.status-overdue{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } +.status-other{ background: rgba(148, 163, 184, 0.20); color: #cbd5e1; } + +.quote-live{ background: rgba(34, 197, 94, 0.18); color: var(--success); } +.quote-stale{ background: rgba(239, 68, 68, 0.18); color: var(--danger); } + +/* ===== Payments / invoice detail ===== */ +.pay-card{ + padding:18px; + margin-top: 1.25rem; +} + +.pay-selector-row{ + display:flex; + gap:0.75rem; + align-items:center; + flex-wrap:wrap; + margin-top:0.75rem; +} + +.pay-panel{ + margin-top: 1rem; + padding: 1rem; + border: 1px solid rgba(255,255,255,0.12); + border-radius: 12px; + background: rgba(255,255,255,0.02); +} + +.pay-panel.hidden{ display:none; } + +.pay-btn-square { background:#16a34a; border-color:transparent; color:#fff; } +.pay-btn-wallet { background:#2563eb; border-color:transparent; color:#fff; } +.pay-btn-mobile { background:#7c3aed; border-color:transparent; color:#fff; } +.pay-btn-copy { background:#374151; border-color:transparent; color:#fff; } + +.snapshot-wrap{ + position: relative; + margin-top: 1rem; + border: 1px solid rgba(255,255,255,0.14); + border-radius: 14px; + padding: 1rem; + background: rgba(255,255,255,0.02); +} + +.snapshot-header{ + display:flex; + justify-content:space-between; + gap:1rem; + align-items:flex-start; +} + +.snapshot-meta{ + flex: 1 1 auto; + min-width: 0; + line-height: 1.65; +} + +.snapshot-timer-box{ + width: 220px; + min-height: 132px; + border: 1px solid rgba(255,255,255,0.16); + border-radius: 14px; + background: rgba(0,0,0,0.18); + display:flex; + flex-direction:column; + justify-content:center; + align-items:center; + text-align:center; + padding: 0.9rem; +} + +.snapshot-timer-value{ + font-size: 2rem; + font-weight: 800; + line-height: 1.1; +} + +.snapshot-timer-label{ + margin-top: 0.55rem; + font-size: 0.95rem; + opacity: 0.95; +} + +.snapshot-timer-expired{ color: var(--danger); } + +.lock-box{ + margin-top: 1rem; + border: 1px solid rgba(34, 197, 94, 0.28); + background: rgba(22, 101, 52, 0.16); + border-radius: 12px; + padding: 1rem; +} + +.lock-box.expired{ + border-color: rgba(239, 68, 68, 0.55); + background: rgba(127, 29, 29, 0.22); +} + +.lock-grid{ + display:grid; + grid-template-columns: 1fr 220px; + gap:1rem; + align-items:start; +} + +.lock-code{ + display:block; + margin-top:0.35rem; + padding:0.65rem 0.8rem; + background: rgba(0,0,0,0.22); + border-radius: 8px; + overflow-wrap:anywhere; +} + +.wallet-actions{ + display:flex; + gap:0.75rem; + flex-wrap:wrap; + margin-top:0.9rem; + align-items:center; +} + +.wallet-help{ + margin-top: 0.85rem; + padding: 0.9rem 1rem; + border-radius: 10px; + background: rgba(255,255,255,0.04); + border: 1px solid rgba(255,255,255,0.10); +} + +.wallet-help h4{ + margin: 0 0 0.55rem 0; + font-size: 1rem; +} + +.wallet-help p{ margin: 0.35rem 0; } +.wallet-note{ opacity:0.9; margin-top:0.65rem; } +.mono{ font-family: monospace; } + +.copy-row{ + display:flex; + gap:0.5rem; + flex-wrap:wrap; + align-items:center; + margin-top:0.65rem; +} + +.copy-target{ + flex: 1 1 420px; + min-width: 220px; +} + +.copy-status{ + display:inline-block; + margin-left: 0.5rem; + opacity: 0.9; +} + +/* ===== Footer ===== */ +footer{ + margin:28px auto 20px auto; + max-width:1100px; + padding:0 18px; + color:var(--muted); + font-size:13px; +} + +/* ===== Responsive ===== */ +@media (max-width: 900px){ + .summary-grid, + .detail-grid{ + grid-template-columns:1fr; + } + + .nav{ + align-items:flex-start; + flex-direction:column; + } + + .navlinks{ + justify-content:flex-start; + } + + .brand img{ + height:54px; + } +} + +@media (max-width: 820px){ + .snapshot-header, + .lock-grid{ + grid-template-columns: 1fr; + display:block; + } + + .snapshot-timer-box{ + width: 100%; + margin-top: 1rem; + min-height: 110px; + } +} + + +/* ===== Fixed CAD / Oracle status bar ===== */ +body{ + padding-bottom: 56px; +} + +.otb-statusbar{ + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 9999; + display: flex; + align-items: center; + justify-content: center; + min-height: 42px; + padding: 8px 14px; + background: rgba(8, 16, 32, 0.94); + border-top: 1px solid rgba(255,255,255,.10); + backdrop-filter: blur(8px); + box-shadow: 0 -8px 24px rgba(0,0,0,.28); +} + +.otb-statusbar-inner{ + width: 100%; + max-width: 1100px; + display: flex; + gap: 10px; + align-items: center; + justify-content: center; + flex-wrap: wrap; + text-align: center; + color: var(--muted); + font-size: 12px; + line-height: 1.35; +} + +.otb-statusbar strong{ + color: var(--text); + font-weight: 700; +} + +.otb-statusbar a{ + color: var(--accent2); + text-decoration: none; + font-weight: 600; +} + +.otb-statusbar a:hover{ + text-decoration: underline; +} + +.otb-dot{ + width: 6px; + height: 6px; + border-radius: 999px; + display: inline-block; + background: rgba(255,255,255,.25); + flex: 0 0 auto; +} + +/* ===== Payment method chips ===== */ +.payment-method{ + display: inline-flex; + align-items: center; + gap: 7px; + margin-top: 7px; + padding: 4px 9px; + border-radius: 999px; + background: rgba(255,255,255,.05); + border: 1px solid rgba(255,255,255,.08); + color: var(--muted); + font-size: 11px; + font-weight: 700; + letter-spacing: .01em; +} + +.payment-method::before{ + content: ""; + width: 8px; + height: 8px; + border-radius: 999px; + display: inline-block; + background: #7aa2ff; + box-shadow: 0 0 0 3px rgba(255,255,255,.04); +} + +.payment-square::before{ background: #7dd3fc; } +.payment-etransfer::before{ background: #86efac; } +.payment-etho::before{ background: #b084ff; } +.payment-etica::before{ background: #4fd1c5; } +.payment-alt::before{ background: #fbbf24; } +.payment-cad::before{ background: #cbd5e1; } + +/* ===== Slightly stronger row hover ===== */ +table.portal-table tbody tr:hover td, +.quote-table tbody tr:hover td{ + background: rgba(255,255,255,.035); + transition: background .14s ease; +} + +@media (max-width: 700px){ + body{ + padding-bottom: 72px; + } + + .otb-statusbar-inner{ + font-size: 11px; + line-height: 1.25; + } +} + + +@media (max-width: 900px){ + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } +} + + +/* ===== Shared services dropdown ===== */ +.navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; + align-items:center; +} + +.dropdown{ + position:relative; + display:inline-block; +} + +.dropdown-toggle{ + display:inline-block; + cursor:pointer; +} + +.dropdown-menu{ + position:absolute; + top:calc(100% + 8px); + right:0; + min-width:220px; + display:none; + padding:10px; + border-radius:14px; + background:rgba(18,24,37,.98); + border:1px solid rgba(255,255,255,.08); + box-shadow:0 16px 40px rgba(0,0,0,.35); + z-index:9999; +} + +.dropdown:hover .dropdown-menu, +.dropdown:focus-within .dropdown-menu{ + display:block; +} + +.dropdown-menu a{ + display:block; + padding:9px 10px; + border-radius:10px; + color:var(--muted); + text-decoration:none; + white-space:nowrap; + margin:0; +} + +.dropdown-menu a + a{ + margin-top:4px; +} + +.dropdown-menu a:hover{ + color:var(--text); + background:rgba(255,255,255,.04); +} + +@media (max-width: 900px){ + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } +} + + +/* ===== OTB shared branding ===== */ +html[data-theme="dark"]{ + --otb-bg:#081225; + --otb-bg2:#09172d; + --otb-text:#e8eefc; + --otb-muted:#aab6d6; + --otb-panel:rgba(18,24,37,.98); + --otb-panel-soft:rgba(18,24,37,.78); + --otb-line:rgba(255,255,255,.08); +} + +html[data-theme="light"]{ + --otb-bg:#f4f7fb; + --otb-bg2:#eef3f9; + --otb-text:#0f172a; + --otb-muted:#475569; + --otb-panel:rgba(255,255,255,.98); + --otb-panel-soft:rgba(255,255,255,.88); + --otb-line:rgba(15,23,42,.10); +} + +body{ + padding-bottom:56px; +} + +.site-container{ + max-width:1100px; + margin:0 auto; + padding:20px 18px 0 18px; +} + +.site-header{ + width:100%; +} + +.site-nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:18px; + padding:12px 0 22px 0; +} + +.site-brand{ + display:flex; + align-items:center; + gap:14px; + text-decoration:none; + color:inherit; +} + +.site-brand img{ + height:60px; + width:auto; + display:block; + object-fit:contain; + background:rgba(255,255,255,0.92); + padding:6px 12px; + border-radius:999px; + box-shadow:0 8px 24px rgba(0,0,0,0.35); +} + +.site-title{ + display:flex; + flex-direction:column; + line-height:1.1; +} + +.site-title strong{ + letter-spacing:.2px; + color:var(--otb-text); +} + +.site-title span{ + color:var(--otb-muted); + font-size:13px; + margin-top:2px; +} + +.site-nav-right{ + display:flex; + align-items:center; + gap:14px; + flex-wrap:wrap; + justify-content:flex-end; +} + +.site-navlinks{ + display:flex; + gap:12px; + flex-wrap:wrap; + justify-content:flex-end; + align-items:center; +} + +.site-navlinks > a, +.dropdown-toggle{ + text-decoration:none; + padding:8px 10px; + border-radius:12px; + color:var(--otb-muted); + border:1px solid transparent; +} + +.site-navlinks > a:hover, +.dropdown-toggle:hover{ + color:var(--otb-text); + border-color:var(--otb-line); + background:rgba(255,255,255,.03); +} + +.dropdown{ + position:relative; + display:inline-block; +} + +.dropdown-toggle{ + display:inline-block; + cursor:pointer; +} + +.dropdown-menu{ + position:absolute; + top:calc(100% + 8px); + right:0; + min-width:220px; + display:none; + padding:10px; + border-radius:14px; + background:var(--otb-panel); + border:1px solid var(--otb-line); + box-shadow:0 16px 40px rgba(0,0,0,.35); + z-index:9999; +} + +.dropdown:hover .dropdown-menu, +.dropdown:focus-within .dropdown-menu{ + display:block; +} + +.dropdown-menu a{ + display:block; + padding:9px 10px; + border-radius:10px; + color:var(--otb-muted); + text-decoration:none; + white-space:nowrap; + margin:0; +} + +.dropdown-menu a + a{ + margin-top:4px; +} + +.dropdown-menu a:hover{ + color:var(--otb-text); + background:rgba(255,255,255,.04); +} + +.otb-theme-switch{ + position:relative; + display:inline-block; + width:54px; + height:30px; + flex:0 0 auto; +} + +.otb-theme-switch input{ + opacity:0; + width:0; + height:0; +} + +.otb-theme-slider{ + position:absolute; + inset:0; + cursor:pointer; + background:rgba(255,255,255,.10); + border:1px solid var(--otb-line); + transition:.2s; + border-radius:999px; +} + +.otb-theme-slider:before{ + content:""; + position:absolute; + height:22px; + width:22px; + left:3px; + top:3px; + background:var(--otb-text); + transition:.2s; + border-radius:50%; +} + +.otb-theme-switch input:checked + .otb-theme-slider:before{ + transform:translateX(24px); +} + +.otb-statusbar{ + position:fixed; + left:0; + right:0; + bottom:0; + z-index:9999; + display:flex; + align-items:center; + justify-content:center; + min-height:42px; + padding:8px 14px; + background:var(--otb-panel); + border-top:1px solid var(--otb-line); + backdrop-filter:blur(8px); + box-shadow:0 -8px 24px rgba(0,0,0,.28); +} + +.otb-statusbar-inner{ + width:100%; + max-width:1100px; + display:flex; + gap:10px; + align-items:center; + justify-content:center; + flex-wrap:wrap; + text-align:center; + color:var(--otb-muted); + font-size:12px; + line-height:1.35; +} + +.otb-statusbar strong{ + color:var(--otb-text); + font-weight:700; +} + +.otb-statusbar a{ + color:#62e6b7; + text-decoration:none; + font-weight:600; +} + +.otb-statusbar a:hover{ + text-decoration:underline; +} + +.otb-dot{ + width:6px; + height:6px; + border-radius:999px; + display:inline-block; + background:rgba(255,255,255,.25); + flex:0 0 auto; +} + +@media (max-width: 900px){ + .site-nav{ + align-items:flex-start; + flex-direction:column; + } + + .site-nav-right{ + width:100%; + justify-content:space-between; + } + + .site-navlinks{ + justify-content:flex-start; + } + + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + width:100%; + } + + .dropdown-menu{ + position:static; + right:auto; + top:auto; + min-width:100%; + margin-top:6px; + } + + .site-brand img{ + height:54px; + } +} + +@media (max-width: 700px){ + body{ + padding-bottom:72px; + } + + .otb-statusbar-inner{ + font-size:11px; + line-height:1.25; + } +} \ No newline at end of file diff --git a/logs/crypto_reconciliation_worker.log b/logs/crypto_reconciliation_worker.log new file mode 100644 index 0000000..cf0f1d0 --- /dev/null +++ b/logs/crypto_reconciliation_worker.log @@ -0,0 +1,1937 @@ +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/crypto_reconciliation_worker.py", line 545, in main + log(f"crypto reconciliation complete mode={run_mode} scanned={scanned} resolved={resolved} flagged={flagged}") + File "/home/def/otb_billing/scripts/crypto_reconciliation_worker.py", line 29, in log + with open(LOG_PATH, "a", encoding="utf-8") as fh: +PermissionError: [Errno 13] Permission denied: '/home/def/otb_billing/logs/crypto_reconciliation_worker.log' + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/crypto_reconciliation_worker.py", line 565, in + main() + File "/home/def/otb_billing/scripts/crypto_reconciliation_worker.py", line 548, in main + log(msg) + File "/home/def/otb_billing/scripts/crypto_reconciliation_worker.py", line 29, in log + with open(LOG_PATH, "a", encoding="utf-8") as fh: +PermissionError: [Errno 13] Permission denied: '/home/def/otb_billing/logs/crypto_reconciliation_worker.log' +[2026-03-22T02:03:52.227834+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T02:18:54.725702+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T02:34:28.489383+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T02:35:23.452143+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T02:50:37.152422+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T03:05:48.561136+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T03:21:37.198992+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T03:36:37.621372+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T03:51:53.897281+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T04:00:13.496458+00:00] crypto reconciliation complete mode=daily scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=daily scanned=0 resolved=0 flagged=0 +[2026-03-22T04:07:02.383545+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T04:22:37.169079+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T04:38:32.338414+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T04:53:37.179753+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T05:08:37.600706+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T05:24:37.180966+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T05:39:37.584972+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T05:54:51.368659+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:09:54.365560+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:18:47.778868+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:22:44.141009+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:23:16.128634+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:24:35.794670+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:37:35.601877+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:40:37.615042+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:43:55.513463+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T06:59:15.376193+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T07:14:18.416813+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T07:29:21.629735+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T07:44:24.372394+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T07:59:27.378326+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T08:14:30.343200+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T08:29:37.157973+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T08:44:37.615196+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T09:00:13.538413+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T09:15:37.145242+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T09:30:37.594120+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T09:45:51.378222+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T10:00:54.394268+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T10:15:57.374310+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T10:31:00.365255+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T10:46:37.159029+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T11:02:30.375175+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T11:17:37.165425+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T11:32:37.582846+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T11:48:37.189174+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T12:03:37.586856+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T12:18:48.357112+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T12:33:51.371866+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T12:48:54.402731+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T13:03:57.341540+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T13:19:00.365101+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T13:34:22.447911+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T13:49:37.219455+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T14:04:37.598258+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T14:20:12.737308+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T14:35:18.355310+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T14:50:21.385298+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T15:05:24.348541+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T15:20:27.346393+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T15:35:30.343916+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T15:50:37.184652+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T16:05:37.567037+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T16:21:37.166834+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T16:36:37.614054+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T16:51:48.390120+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T17:06:51.349485+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T17:21:54.342624+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T17:36:57.378290+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T17:52:00.358112+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T18:07:03.370656+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T18:22:32.728664+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T18:37:37.155560+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T18:52:37.581925+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T19:08:18.370803+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T19:23:21.348513+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T19:38:24.335270+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T19:53:27.385683+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T20:08:30.365809+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T20:23:33.399295+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T20:38:37.147458+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T20:54:37.151185+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T21:09:37.594400+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T21:24:47.155065+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T21:39:47.585264+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T21:54:55.367887+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T22:09:58.356155+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T22:25:01.364385+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T22:40:35.715166+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T22:55:37.159441+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T23:10:37.604242+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T23:26:16.393254+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T23:41:37.158429+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-22T23:56:37.592510+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T00:11:37.663388+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T00:27:37.175253+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T00:42:37.597386+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T00:57:46.969366+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T01:12:49.929861+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T01:27:52.940917+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T01:42:55.922488+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T01:57:58.920029+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T02:13:00.276012+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T02:28:37.208829+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T02:43:37.587016+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T02:59:13.923970+00:00] crypto reconciliation complete mode=interval scanned=0 resolved=0 flagged=0 +[2026-03-23T03:09:58.203877+00:00] email skipped: subject='Payment update for your invoice' to=['natural_gas_fitter@yahoo.ca'] +[2026-03-23T03:09:58.254965+00:00] email skipped: subject='Payment update for your invoice' to=['natural_gas_fitter@yahoo.ca'] +[2026-03-23T03:09:58.266946+00:00] crypto reconciliation complete mode=interval scanned=2 resolved=0 flagged=0 +[2026-03-23T03:12:18.472092+00:00] email skipped: subject='Payment update for your invoice' to=['natural_gas_fitter@yahoo.ca'] +[2026-03-23T03:12:18.490119+00:00] email skipped: subject='Payment update for your invoice' to=['natural_gas_fitter@yahoo.ca'] +[2026-03-23T03:12:18.519512+00:00] crypto reconciliation complete mode=interval scanned=2 resolved=0 flagged=0 +[2026-03-23T03:14:16.933396+00:00] crypto reconciliation complete mode=interval scanned=2 resolved=0 flagged=0 +[2026-03-23T03:29:19.976080+00:00] crypto reconciliation complete mode=interval scanned=2 resolved=0 flagged=0 +[2026-03-23T03:29:34.959275+00:00] crypto reconciliation complete mode=interval scanned=2 resolved=0 flagged=0 +[2026-03-23T03:32:47.275060+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-23T03:44:47.263681+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-23T03:59:33.062202+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-23T04:00:13.555076+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-03-23T04:11:15.975131+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-23T04:14:37.289925+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-23T04:29:37.692202+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-23T04:45:37.236964+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T05:00:42.667290+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=1 flagged=0 +[2026-03-23T05:15:50.239831+00:00] crypto reconciliation complete mode=interval scanned=11 resolved=0 flagged=0 +[2026-03-23T05:31:37.300980+00:00] crypto reconciliation complete mode=interval scanned=11 resolved=0 flagged=0 +[2026-03-23T05:46:40.161753+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T06:02:19.466526+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T06:17:24.527882+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T06:32:40.225468+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T06:48:40.211542+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T07:03:48.446119+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T07:18:49.436518+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T07:33:54.433423+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T07:49:40.129770+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T08:04:40.611169+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T08:20:17.390641+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T08:35:20.474856+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T08:50:40.280839+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T09:06:40.159218+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T09:21:49.463897+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T09:37:40.271446+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T09:52:40.659906+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T10:08:19.494989+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T10:23:22.352074+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T10:38:25.434475+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T10:53:40.251210+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T11:08:40.643337+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T11:24:40.276372+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T11:39:47.499864+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T11:54:50.498343+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T12:10:40.252743+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T12:26:16.459195+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T12:41:19.423151+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T12:56:40.170194+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T13:12:40.205793+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T13:28:10.119313+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T13:43:05.419636+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T13:58:30.643943+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T14:13:40.244929+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T14:28:40.817237+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T14:44:29.416343+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T14:59:34.440616+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T15:14:40.248610+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T15:29:40.777130+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T15:45:40.189378+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T16:00:40.683000+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T16:15:57.543790+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T16:31:40.315667+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T16:46:40.605576+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T17:02:27.663599+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T17:17:40.171754+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T17:32:40.796771+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T17:48:40.154906+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T18:03:40.772787+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T18:19:07.860583+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T18:33:58.485121+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T18:49:01.375879+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T19:04:40.160579+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T19:19:40.665749+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T19:35:25.394228+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T19:50:32.473617+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T20:05:40.254015+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T20:20:40.677882+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T20:36:40.347586+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T20:51:40.760489+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T21:06:59.439085+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T21:22:02.476791+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T21:37:40.237386+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T21:52:40.831358+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T21:56:28.433185+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T21:57:28.726958+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T22:08:30.332371+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T22:23:31.413169+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T22:38:32.135561+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T22:53:40.232117+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T23:08:40.932826+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T23:24:40.259207+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T23:39:41.016127+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-23T23:55:30.183866+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T00:10:40.197875+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T00:26:40.168049+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T00:41:40.392426+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T00:56:40.721257+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T01:12:40.400008+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T01:27:42.140475+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T01:42:46.471221+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T01:57:52.512951+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T02:12:55.493290+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T02:28:40.216746+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T02:44:19.255867+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T02:59:20.215480+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T03:14:29.517036+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T03:29:40.303039+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T03:44:40.925849+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T04:00:16.554284+00:00] crypto reconciliation complete mode=daily scanned=12 resolved=0 flagged=0 +[2026-03-24T04:00:16.612017+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T04:15:40.266661+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T04:30:40.690156+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T04:45:52.504861+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T05:01:02.363451+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T05:16:40.446927+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T05:31:40.747521+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T05:47:41.977520+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T06:02:40.548407+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T06:18:37.686544+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T06:33:40.286022+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T06:48:40.783608+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T07:04:30.180036+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T07:19:40.345702+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T07:34:40.581514+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T07:50:40.298241+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T08:06:00.438465+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T08:21:40.150538+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T08:36:40.685314+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T08:52:30.305784+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T09:07:40.081598+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T09:22:40.599469+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T09:38:40.166807+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T09:54:40.324705+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T10:09:40.643532+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T10:25:30.229384+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T10:40:40.192511+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T10:55:40.755632+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T11:11:40.215620+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T11:26:40.569723+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T11:42:36.780289+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T11:57:40.296182+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T12:12:40.571836+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T12:28:30.336742+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T12:43:40.167929+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T12:58:40.636169+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T13:14:40.140419+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T13:30:40.366767+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T13:46:31.398119+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T14:01:40.302387+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T14:16:40.640548+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T14:32:40.304753+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T14:48:40.315839+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T15:04:30.202267+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T15:19:40.147482+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T15:34:40.654206+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T15:50:40.199075+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T16:06:40.262325+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T16:22:24.071711+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T16:37:30.256419+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T16:52:40.195330+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T17:08:40.181642+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T17:24:40.322666+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T17:39:42.549977+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T17:55:30.237823+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T18:10:40.091231+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T18:25:40.705076+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T18:41:40.316219+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T18:56:40.585156+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T19:12:40.213090+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T19:28:00.556842+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T19:43:30.144548+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T19:58:40.198311+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T20:14:40.221329+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T20:30:40.174523+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T20:46:30.394207+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T21:01:40.252668+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T21:16:40.629438+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T21:32:40.316500+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T21:48:40.325770+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T22:03:40.744744+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T22:19:30.244680+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T22:34:40.114334+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T22:50:40.290015+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T23:06:40.297708+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T23:21:40.759545+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T23:37:30.303467+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-24T23:52:40.343549+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T00:08:40.289356+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T00:24:40.265464+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T00:39:56.714980+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T00:55:30.238385+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T01:10:30.497901+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T01:25:40.245237+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T01:40:40.649131+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T01:56:40.336352+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T02:12:40.217959+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T02:27:40.596527+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T02:42:42.419013+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T02:57:44.338912+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T03:12:45.410493+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T03:28:05.878499+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T03:43:30.130062+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T03:58:40.225768+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T04:00:16.518551+00:00] crypto reconciliation complete mode=daily scanned=12 resolved=0 flagged=0 +[2026-03-25T04:13:40.606160+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T04:29:18.605631+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T04:44:21.308669+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T04:59:22.014888+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T05:14:23.209257+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T05:29:25.280187+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T05:44:42.055489+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T05:59:40.686428+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T06:15:40.236434+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T06:30:40.642279+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T06:46:30.186175+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T07:01:40.212424+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T07:17:20.401595+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T07:32:41.313414+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T07:47:45.720168+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T08:03:41.254955+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T08:18:41.604895+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T08:34:31.251033+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T08:49:40.277126+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T09:04:40.683199+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T09:20:41.261578+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T09:36:41.380288+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T09:51:40.569346+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T10:07:30.105113+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T10:22:45.312622+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T10:37:44.801302+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T10:53:36.934212+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T11:08:43.337674+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T11:23:44.828183+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T11:39:44.302367+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T11:54:44.654504+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T12:10:02.818857+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T12:25:35.252522+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T12:40:44.420942+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T12:55:43.792972+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T13:11:47.315963+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T13:26:47.029596+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T13:42:41.215603+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T13:58:34.300786+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T14:13:43.316932+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T14:28:46.938811+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T14:44:42.150946+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T14:59:46.701862+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T15:15:43.331400+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T15:30:42.713716+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T15:46:34.383354+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T16:01:43.366110+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T16:16:47.136202+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T16:32:40.396385+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T16:48:44.591887+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T17:04:32.519262+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T17:19:47.664828+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T17:34:41.868931+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T17:50:44.684035+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T18:05:46.066655+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T18:21:46.737725+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T18:36:46.020683+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T18:51:50.755327+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T19:07:31.463952+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T19:22:41.428198+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T19:37:42.948126+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T19:53:45.625051+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T20:08:49.231610+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T20:24:46.589092+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T20:40:37.741640+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T20:55:43.667466+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T21:10:46.026384+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T21:26:43.576787+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T21:41:44.010253+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T21:57:46.803839+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T22:12:43.879774+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T22:28:36.657753+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T22:43:46.650834+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T22:58:45.002508+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T23:14:42.520737+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T23:30:44.634539+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-25T23:45:43.928546+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T00:01:32.457316+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T00:16:43.552360+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T00:31:46.097296+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T00:47:27.682140+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T01:02:46.676822+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T01:18:46.663607+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T01:33:46.163215+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T01:49:37.660574+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T02:04:45.551596+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T02:20:17.851247+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T02:35:23.002888+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-26T02:50:37.336721+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T03:05:46.711599+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T03:20:44.126806+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T03:35:46.504058+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T03:50:47.946327+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T04:00:05.257108+00:00] crypto reconciliation complete mode=daily scanned=12 resolved=0 flagged=0 +[2026-03-26T04:05:46.521274+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T04:21:44.668878+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T04:36:43.835961+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T04:52:28.942269+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T05:07:35.656210+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T05:22:42.515130+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T05:38:43.595418+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T05:53:48.208040+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T06:09:48.808303+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T06:24:43.975216+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T06:40:32.515575+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T06:55:42.499672+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T07:10:40.863882+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T07:26:44.517598+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T07:42:43.584514+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T07:58:33.500043+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T08:13:42.483778+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T08:28:44.044227+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T08:44:41.562779+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T08:59:40.827780+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T09:15:40.497266+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T09:30:41.836181+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T09:46:32.526948+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T10:01:41.417081+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T10:16:41.027763+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T10:32:44.523929+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T10:47:40.903015+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T11:03:23.250074+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T11:18:41.441381+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T11:34:30.459292+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T11:49:41.490422+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T12:04:41.767616+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T12:20:42.534447+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T12:36:40.262277+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T12:51:40.819375+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T13:07:31.401272+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T13:22:41.402593+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T13:38:42.484222+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T13:54:44.505612+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T14:10:31.456785+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T14:25:43.549583+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T14:40:41.929958+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T14:56:41.572013+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T15:12:42.502531+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T15:28:32.568568+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T15:43:40.423898+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T15:58:44.974177+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T16:14:42.478214+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T16:30:43.561562+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T16:46:30.535080+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T17:01:40.306591+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T17:16:40.876893+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T17:32:41.397929+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T17:48:09.494478+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T18:03:40.390868+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T18:18:41.756174+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T18:34:31.410546+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T18:49:41.442000+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T19:04:43.929790+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T19:20:40.412938+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T19:36:41.247793+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T19:52:32.407985+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T20:07:43.377008+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T20:22:41.801022+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T20:38:42.324952+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T20:54:42.595710+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T21:10:32.388451+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T21:25:40.483876+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T21:40:42.870348+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T21:56:40.306418+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T22:12:40.371547+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T22:28:31.312332+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T22:43:41.302864+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T22:58:42.970100+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T23:14:45.528026+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T23:30:47.565843+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-26T23:46:37.815181+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T00:08:57.876459+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T00:31:18.909512+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T00:42:38.042381+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T00:55:57.928852+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T01:13:38.427105+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T01:34:08.425803+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T01:49:18.516361+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T02:04:41.893630+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T02:20:18.368160+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T02:35:18.979300+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T02:51:18.424799+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T03:06:20.660232+00:00] crypto reconciliation complete mode=interval scanned=12 resolved=0 flagged=0 +[2026-03-27T03:21:52.914080+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T03:36:57.894573+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T03:52:18.570793+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T04:07:18.859790+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T04:14:41.651574+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-03-27T04:22:19.294721+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T04:37:42.882019+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T04:52:43.498714+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T05:08:18.524453+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T05:23:18.863178+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T05:39:18.471122+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T05:55:08.418983+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T06:10:18.552828+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T06:25:19.146256+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T06:41:18.603910+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T06:56:47.179735+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T07:12:16.879897+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T07:27:18.458609+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T07:40:44.207427+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T07:44:55.014868+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T07:58:30.030480+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T08:13:40.100858+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T08:28:44.692278+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T08:44:42.187806+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T08:59:40.646061+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T09:15:41.261905+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T09:30:40.777121+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T09:46:31.211240+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T10:01:41.338448+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T10:16:40.541382+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T10:32:41.166272+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T10:48:41.178402+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T11:04:03.369399+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T11:19:31.268477+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T11:34:40.204288+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T11:50:41.229022+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T12:06:40.250275+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T12:22:32.204874+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T12:37:41.199285+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T12:52:40.602027+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T13:08:41.220318+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T13:24:41.188356+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T13:40:30.198582+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T13:55:41.295285+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T14:10:40.672385+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T14:26:41.298381+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T14:42:41.278204+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T14:57:40.524268+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T15:13:30.131158+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T15:28:31.149285+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T15:43:41.303085+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T15:58:43.696804+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T16:14:07.216155+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T16:29:41.093414+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T16:44:40.476144+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T17:00:42.185036+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T17:16:07.433609+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T17:31:32.217986+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T17:46:42.281638+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T18:02:42.288553+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T18:17:41.605145+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T18:33:41.213515+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T18:48:40.652931+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T19:03:51.904611+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T19:18:53.950372+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T19:33:59.121166+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T19:49:30.174195+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T20:04:40.134324+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T20:19:41.646913+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T20:35:41.340082+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T20:50:40.639376+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T21:05:53.800672+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T21:21:40.261199+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T21:36:42.727348+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T21:52:32.460539+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T22:07:41.296892+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T22:22:43.691591+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T22:38:40.176558+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T22:54:42.202134+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T23:10:32.335463+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T23:25:42.114405+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T23:40:40.754890+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-27T23:56:40.158264+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T00:12:40.161845+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T00:28:04.260628+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T00:43:20.043274+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T00:58:32.233060+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T01:13:43.225459+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T01:28:41.652443+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T01:44:19.928702+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T01:59:40.215467+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T02:14:41.722043+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T02:30:40.360503+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T02:45:40.553003+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T03:01:32.306684+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T03:16:41.227885+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T03:31:40.607040+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T03:47:44.291619+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T04:00:19.265836+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-03-28T04:02:41.650290+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T04:18:41.187604+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T04:33:40.706928+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T04:49:32.158117+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T05:04:42.171552+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T05:19:40.483646+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T05:35:40.221334+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T05:50:42.714910+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T06:06:40.252938+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T06:22:31.178400+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T06:37:42.184626+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T06:52:40.680759+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T07:08:40.155640+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T07:23:43.671104+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T07:39:40.125764+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T07:54:40.595396+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T08:10:31.296056+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T08:25:41.159664+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T08:40:40.603298+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T08:56:40.156928+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T09:11:41.689786+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T09:27:42.238191+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T09:42:45.720061+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T09:58:32.149525+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T10:13:40.276811+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T10:28:42.664804+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T10:44:42.302766+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T11:00:40.130780+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T11:16:06.938295+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T11:31:32.137286+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T11:46:42.136825+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T12:01:41.560942+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T12:17:40.125867+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T12:32:40.626021+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T12:48:43.363376+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T13:03:41.681736+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T13:19:33.306809+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T13:34:41.266080+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T13:50:41.278063+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T14:06:42.372298+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T14:22:34.313567+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T14:37:42.284849+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T14:52:42.634906+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T15:08:40.131114+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T15:23:42.686791+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T15:39:40.155456+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T15:54:42.779243+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T16:10:30.221978+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T16:25:41.262139+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T16:40:41.600228+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T16:56:41.292923+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T17:12:41.143190+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T17:28:31.342677+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T17:43:42.254617+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T17:58:42.608966+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T18:14:40.127825+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T18:29:41.691923+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T18:45:23.528933+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T19:00:41.270959+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T19:16:06.018391+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T19:31:30.196139+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T19:46:40.170539+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T20:02:41.140038+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T20:17:40.719471+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T20:33:44.415983+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T20:48:45.809707+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T21:03:44.406406+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T21:19:33.229409+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T21:34:40.132338+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T21:50:40.257157+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T22:05:40.689034+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T22:21:45.332353+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T22:36:40.605392+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T22:52:30.138908+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T23:07:47.395560+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T23:22:42.735271+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T23:38:42.354209+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-28T23:54:41.345501+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T00:10:31.165725+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T00:25:44.279334+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T00:40:44.735569+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T00:56:44.301695+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T01:11:40.406444+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T01:26:43.784565+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T01:42:40.208366+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T01:58:35.337890+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T02:13:43.129385+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T02:28:41.634768+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T02:44:42.322441+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T03:00:41.196471+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T03:16:05.161645+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T03:31:30.195011+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T03:46:40.258697+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T04:00:18.101184+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-03-29T04:02:31.554796+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T04:17:40.199746+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T04:32:43.672004+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T04:48:45.571117+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T05:04:31.210955+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T05:19:40.291977+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T05:34:41.576445+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T05:50:46.328331+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T06:06:44.194214+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T06:22:30.547811+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T06:37:42.171762+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T06:52:42.668478+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T07:08:42.251150+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T07:24:43.251022+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T07:40:31.233099+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T07:55:40.301522+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T08:10:43.797517+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T08:26:41.218041+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T08:41:40.560004+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T08:57:40.221250+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T09:12:43.702141+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T09:28:32.198518+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T09:43:45.298613+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T09:58:41.744952+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T10:14:43.249955+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T10:30:41.202513+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T10:46:32.129660+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T11:01:42.286141+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T11:16:40.626735+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T11:32:41.214224+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T11:48:43.401545+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T12:04:32.344472+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T12:19:43.133595+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T12:34:42.667270+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T12:50:42.340281+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T13:06:07.991285+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T13:21:41.236539+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T13:36:42.730572+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T13:52:31.159560+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T14:07:40.143009+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T14:22:44.808178+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T14:38:41.289335+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T14:54:40.265189+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T15:10:30.128275+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T15:25:42.203971+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T15:40:41.581803+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T15:56:42.206979+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T16:12:41.117580+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T16:28:31.118150+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T16:43:42.163890+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T16:58:40.543109+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T17:14:42.325344+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T17:30:40.076493+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T17:46:30.164172+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T18:01:41.196018+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T18:16:41.576978+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T18:32:00.203764+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T18:47:42.279301+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T19:02:44.074079+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T19:18:42.229183+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T19:34:31.272036+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T19:49:40.283812+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T20:04:40.605696+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T20:20:41.226121+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T20:36:42.257334+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T20:51:41.650874+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T21:07:30.182904+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T21:22:40.152651+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T21:37:41.666975+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T21:53:41.228718+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T22:08:41.643229+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T22:24:43.299249+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T22:40:30.194433+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T22:55:41.195180+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T23:10:40.624911+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T23:26:42.377856+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T23:42:44.420593+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-29T23:58:00.533257+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T00:13:33.240405+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T00:28:43.280822+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T00:43:40.599994+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T00:59:40.133965+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T01:14:40.540757+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T01:30:41.247894+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T01:46:34.312203+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T02:01:40.173664+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T02:16:40.631463+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T02:32:41.192727+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T02:48:40.164971+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T03:04:32.241424+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T03:19:41.184369+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T03:34:40.623655+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T03:50:40.230315+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T04:00:19.642331+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-03-30T04:06:43.404825+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T04:21:42.696480+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T04:37:33.248974+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T04:52:42.321910+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T05:08:40.191568+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T05:24:42.296792+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T05:39:43.706042+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T05:55:32.210866+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T06:10:40.213914+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T06:26:44.337791+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T06:41:43.572420+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T06:57:40.282578+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T07:12:42.718493+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T07:28:33.272329+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T07:43:41.288016+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T07:58:40.560986+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T08:14:43.301766+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T08:30:40.189204+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T08:46:30.171501+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T09:01:42.089984+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T09:16:45.694789+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T09:32:40.080565+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T09:48:40.191444+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T10:04:33.281200+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T10:19:42.363569+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T10:34:43.756644+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T10:50:40.131890+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T11:06:40.251765+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T11:21:41.537308+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T11:37:30.128694+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T11:52:42.364403+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T12:08:41.231418+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T12:24:40.247710+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T12:40:33.184639+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T12:55:41.156189+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T13:10:42.668214+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T13:26:40.228151+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T13:42:40.135803+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T13:58:34.540711+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T14:13:41.154228+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T14:28:42.776189+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T14:44:40.190098+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T15:00:40.163782+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T15:16:08.313144+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T15:31:32.202349+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T15:46:40.064453+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T16:02:23.633290+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T16:17:42.258016+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T16:32:40.623382+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T16:48:43.194014+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T17:04:31.327926+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T17:19:44.252374+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T17:34:40.698967+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T17:50:41.242781+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T18:05:41.641630+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T18:21:43.213106+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T18:36:40.558048+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T18:52:31.251159+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T19:07:40.172849+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T19:22:40.582431+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T19:38:40.247805+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T19:54:42.240538+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T20:10:31.252610+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T20:25:42.318938+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T20:40:40.551960+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T20:56:44.301838+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T21:11:43.754142+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T21:27:40.133949+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T21:42:44.653170+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T21:58:32.158653+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T22:13:41.224997+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T22:28:42.652462+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T22:44:45.359275+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T23:00:45.380476+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T23:15:42.681073+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T23:31:32.325643+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-30T23:46:41.177104+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T00:01:44.701109+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T00:17:42.322336+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T00:32:41.666835+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T00:48:31.610455+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T01:03:43.240509+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T01:18:40.651950+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T01:34:30.094260+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T01:49:40.136988+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T02:04:42.605118+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T02:20:40.287055+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T02:36:42.208758+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T02:52:30.184745+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T03:07:42.232724+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T03:22:41.667310+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T03:38:44.297356+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T03:54:40.195242+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T04:00:16.488406+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-03-31T04:10:35.316953+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T04:25:42.298876+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T04:40:42.692964+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T04:56:40.194230+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T05:11:43.705243+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T05:27:43.311852+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T05:42:46.781928+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T05:58:30.099187+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T06:13:44.231561+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T06:28:44.720849+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T06:44:43.205675+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T07:00:42.266215+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T07:15:46.642463+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T07:31:32.230071+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T07:46:42.226253+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T08:01:43.761804+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T08:17:42.356431+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T08:32:41.583745+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T08:48:43.264162+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T09:04:33.315638+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T09:19:41.194231+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T09:34:41.590727+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T09:50:42.394915+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T10:06:45.358928+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T10:22:32.163884+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T10:37:45.309752+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T10:52:42.799679+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T11:08:40.185532+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T11:24:40.152871+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T11:40:30.135748+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T11:55:41.217122+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T12:10:40.625984+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T12:26:40.147280+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T12:41:40.623899+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T12:57:40.090396+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T13:12:42.563894+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T13:28:05.557834+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T13:43:30.110062+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T13:58:40.087956+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T14:14:40.214817+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T14:30:43.247298+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T14:45:42.702231+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T15:01:34.279267+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T15:16:44.294674+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T15:32:40.180983+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T15:47:40.549919+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T16:03:40.000594+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T16:18:44.968816+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T16:34:31.059584+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T16:49:42.127972+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T17:04:40.472792+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T17:20:40.126959+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T17:36:41.117816+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T17:52:30.250478+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T18:07:44.198849+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T18:22:41.539950+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T18:38:42.156409+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T18:53:40.660882+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T19:09:40.039616+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T19:24:40.590776+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T19:40:30.135178+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T19:55:40.171789+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T20:10:42.692659+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T20:26:42.262184+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T20:42:42.256894+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T20:57:44.691298+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T21:13:30.074398+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T21:28:40.245971+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T21:44:40.081603+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T21:59:43.592293+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T22:15:40.139891+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T22:30:41.663637+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T22:46:34.223269+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T23:01:42.220033+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T23:16:41.983653+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T23:32:40.135736+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-03-31T23:48:43.579285+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T00:04:31.332781+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T00:19:40.139865+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T00:34:41.642858+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T00:50:40.131313+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T01:06:40.209174+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T01:22:30.123489+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T01:37:40.270781+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T01:52:40.481527+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T02:08:40.230189+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T02:23:59.848673+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T02:39:40.121094+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T02:54:40.550484+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T03:10:30.155668+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T03:25:40.000522+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T03:40:40.668367+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T03:56:40.035991+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T04:00:16.498422+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-01T04:12:40.084805+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T04:27:40.451990+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T04:43:30.227297+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T04:58:40.041128+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T05:14:40.098303+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T05:30:40.085418+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T05:46:30.218903+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T06:01:39.992237+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T06:16:40.671711+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T06:32:40.163553+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T06:48:40.443416+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T07:04:30.062509+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T07:19:40.186010+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T07:34:40.461518+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T07:50:40.182511+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T08:06:40.018741+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T08:22:30.169199+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T08:37:40.137267+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T08:52:40.601605+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T09:08:40.116624+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T09:24:40.231106+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T09:40:30.086273+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T09:55:40.113271+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T10:10:40.545947+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T10:26:40.165851+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T10:42:40.108872+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T10:57:40.533474+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T11:13:29.997166+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T11:28:40.110117+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T11:44:40.059918+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T12:00:40.103204+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T12:16:04.304865+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T12:31:30.237124+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T12:46:40.112330+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T13:01:48.662088+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T13:17:40.027250+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T13:32:40.664585+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T13:48:40.150615+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T14:04:30.142551+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T14:19:40.034094+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T14:34:40.683870+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T14:50:40.125386+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T15:06:40.061773+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T15:22:30.082557+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T15:37:40.187924+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T15:52:40.586007+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T16:08:40.103730+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T16:23:40.630878+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T16:39:40.206029+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T16:54:40.531070+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T17:10:30.209167+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T17:25:40.112855+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T17:40:40.591289+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T17:56:40.128559+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T18:12:40.072912+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T18:27:40.545239+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T18:43:30.112047+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T18:58:33.665733+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T19:13:40.169269+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T19:28:40.453809+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T19:44:40.131489+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T20:00:40.102749+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T20:16:04.518581+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T20:31:30.049275+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T20:46:40.236180+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T21:01:40.510252+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T21:17:40.121860+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T21:32:40.552752+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T21:48:40.214455+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T22:03:40.501382+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T22:19:30.280991+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T22:34:39.945952+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T22:50:40.119577+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T23:06:40.096215+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T23:21:40.595436+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T23:37:30.076474+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-01T23:52:40.097858+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T00:08:40.199936+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T00:24:40.094349+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T00:39:40.538781+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T00:55:30.060177+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T01:10:40.036629+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T01:25:40.642775+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T01:41:40.129148+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T01:56:40.546570+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T02:12:40.014642+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T02:27:40.607723+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T02:43:30.018293+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T02:58:40.136589+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T03:14:40.009123+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T03:29:41.647135+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T03:45:40.058625+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T04:00:16.528291+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-02T04:00:41.572527+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T04:16:04.657987+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T04:31:30.097031+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T04:46:40.037016+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T05:01:40.624556+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T05:17:40.121548+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T05:32:40.565851+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T05:48:40.020254+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T06:04:30.154108+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T06:19:59.893452+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T06:34:40.569208+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T06:50:40.060370+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T07:06:40.111565+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T07:21:40.539244+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T07:37:30.224114+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T07:52:40.053316+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T08:08:40.149354+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T08:24:40.456664+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T08:40:30.090197+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T08:55:40.078338+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T09:10:40.584767+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T09:26:40.072959+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T09:42:40.187096+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T09:58:30.003284+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T10:13:40.075535+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T10:28:40.463391+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T10:44:40.656499+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T11:00:40.191191+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T11:16:04.932558+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T11:31:30.086550+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T11:46:40.019994+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T12:02:39.973903+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T12:17:40.526423+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T12:33:40.007454+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T12:48:40.570637+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T13:04:30.119281+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T13:19:41.149040+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T13:34:40.544466+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T13:50:06.897985+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T14:05:40.058571+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T14:20:40.515731+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T14:36:40.143262+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T14:51:40.620158+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T15:07:29.967721+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T15:22:40.080794+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T15:38:39.938808+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T15:54:40.207797+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T16:10:30.105195+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T16:25:40.223270+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T16:40:40.484142+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T16:56:40.182565+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T17:11:40.655241+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T17:27:40.197189+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T17:42:40.478468+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T17:58:30.177802+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T18:13:40.091411+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T18:28:40.648979+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T18:44:40.027629+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T19:00:40.143666+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T19:16:06.012019+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T19:31:30.147282+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T19:46:40.135083+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T20:02:40.065621+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T20:18:40.069465+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T20:34:30.142277+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T20:49:40.057363+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T21:04:40.552545+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T21:20:39.972407+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T21:36:40.146042+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T21:51:40.494277+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T22:07:30.094938+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T22:22:40.101539+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T22:37:40.565136+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T22:53:40.015703+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T23:08:40.512877+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T23:24:40.086980+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T23:39:40.671912+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-02T23:55:30.111264+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T00:10:40.235454+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T00:26:40.152898+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T00:41:40.548945+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T00:57:40.048597+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T01:12:40.586404+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T01:28:30.102308+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T01:43:40.097127+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T01:58:40.506133+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T02:14:40.090292+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T02:29:40.457503+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T02:45:40.146320+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T03:00:40.506969+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T03:16:04.195317+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T03:31:30.049586+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T03:46:40.199550+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T04:00:16.430796+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-03T04:02:30.463130+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T04:17:40.074225+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T04:32:40.473882+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T04:48:06.771429+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T05:03:40.102257+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T05:18:40.534010+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T05:34:30.031935+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T05:49:40.297568+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T06:04:40.544556+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T06:20:40.120328+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T06:36:40.072353+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T06:52:30.207314+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T07:07:40.068559+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T07:22:40.467115+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T07:38:40.079276+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T07:54:40.062187+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T08:10:50.036242+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T08:25:40.189957+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T08:40:40.503878+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T08:56:40.145055+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T09:11:40.601443+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T09:27:40.122673+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T09:42:40.401097+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T09:58:30.128967+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T10:13:40.124525+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T10:28:40.492031+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T10:44:40.012656+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T11:00:40.127413+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T11:16:04.397625+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T11:31:30.013243+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T11:46:40.067132+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T12:01:40.621875+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T12:17:40.052828+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T12:32:40.548510+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T12:48:40.020661+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T13:04:30.131976+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T13:19:40.051907+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T13:34:40.679443+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T13:50:40.180880+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T14:05:40.596186+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T14:21:40.063138+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T14:36:40.554702+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T14:52:30.142320+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T15:07:41.016847+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T15:22:40.466459+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T15:38:40.233882+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T15:54:16.341831+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T16:09:41.674267+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T16:24:40.487796+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T16:40:30.239575+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T16:55:40.154805+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T17:10:40.578996+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T17:26:40.061712+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T17:42:40.152548+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T17:57:40.583796+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T18:13:30.084847+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T18:28:40.090908+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T18:44:40.131947+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T18:59:40.598710+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T19:15:40.025648+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T19:30:40.605525+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T19:46:30.142629+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T20:01:40.109569+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T20:16:40.575006+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T20:32:40.231924+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T20:48:40.161504+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T21:04:30.162599+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T21:19:40.171881+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T21:34:40.514318+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T21:50:40.168391+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T22:06:40.094604+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T22:22:30.101359+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T22:37:40.201393+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T22:52:40.660983+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T23:08:40.080482+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T23:24:40.165539+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T23:39:40.659192+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-03T23:55:30.070885+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T00:10:40.082562+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T00:26:40.165665+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T00:41:40.567797+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T00:57:40.225579+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T01:12:40.557576+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T01:28:30.195390+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T01:43:40.180456+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T01:58:40.654144+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T02:14:40.220528+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T02:30:40.237664+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T02:46:30.057093+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T03:01:40.122820+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T03:16:40.609112+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T03:32:40.228549+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T03:48:40.150367+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T04:00:16.435432+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-04T04:04:30.153908+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T04:19:40.093245+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T04:34:40.722545+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T04:50:40.114813+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T05:06:40.211306+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T05:22:30.161716+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T05:37:40.224272+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T05:52:40.464270+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T06:08:40.210849+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T06:23:40.487824+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T06:39:40.205022+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T06:54:40.489676+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T07:10:30.263747+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T07:25:40.031570+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T07:40:40.674595+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T07:56:40.102979+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T08:11:40.586465+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T08:27:40.133628+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T08:42:40.669171+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T08:58:30.102646+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T09:13:40.080470+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T09:28:40.491064+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T09:44:40.049419+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T10:00:40.057389+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T10:15:40.995993+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T10:31:30.017588+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T10:46:40.123498+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T11:01:40.550772+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T11:17:40.101385+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T11:32:40.549008+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T11:48:40.116002+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T12:04:30.114503+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T12:19:40.234113+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T12:34:40.608732+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T12:50:40.250016+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T13:06:40.059462+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T13:21:40.620127+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T13:37:30.191520+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T13:52:40.157411+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T14:07:40.503731+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T14:23:40.181269+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T14:38:40.595290+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T14:54:40.160639+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T15:10:30.121460+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T15:25:40.061442+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T15:40:40.584890+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T15:56:40.129060+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T16:12:40.092601+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T16:28:30.135452+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T16:43:40.094905+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T16:58:40.585942+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T17:14:40.082045+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T17:29:40.640513+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T17:45:40.120764+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T18:00:40.636351+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T18:16:05.344899+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T18:31:30.190499+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T18:46:41.378698+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T19:02:41.914222+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T19:20:58.782163+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T19:36:42.272259+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T19:52:32.195133+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T20:07:42.080328+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T20:22:42.424410+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T20:38:42.630255+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T20:53:42.560355+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T21:09:42.901221+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T21:24:42.593542+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T21:40:32.740977+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T21:55:42.008893+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T22:10:42.307427+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T22:26:42.470482+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T22:42:42.029307+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T22:58:31.990156+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T23:13:41.823990+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T23:28:42.695530+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T23:44:42.216398+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-04T23:59:43.124443+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T00:15:42.318699+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T00:30:42.203726+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T00:46:32.030145+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T01:01:41.242875+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T01:16:40.841829+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T01:32:40.386919+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T01:47:40.867508+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T02:03:40.492836+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T02:18:40.865865+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T02:34:30.244284+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T02:49:40.423585+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T03:04:40.762973+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T03:20:40.491311+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T03:35:40.828343+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T03:51:09.406064+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T04:00:16.568522+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-05T04:06:40.414967+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T04:22:30.364635+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T04:37:40.240664+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T04:52:40.802514+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T05:08:40.271162+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T05:24:40.303620+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T05:39:40.811035+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T05:55:30.298154+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T06:10:40.271545+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T06:26:40.364764+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T06:42:40.191772+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T06:58:30.349896+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T07:13:40.213639+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T07:28:40.774743+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T07:44:40.273849+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T07:59:40.850737+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T08:15:40.270555+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T08:30:40.644777+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T08:46:30.298304+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T09:01:40.390515+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T09:16:40.679022+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T09:32:40.278683+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T09:47:40.670391+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T10:03:40.295333+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T10:18:40.735402+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T10:34:30.302031+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T10:49:40.255775+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T11:04:40.700612+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T11:20:40.227947+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T11:36:40.396193+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T11:52:30.326066+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T12:07:40.404665+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T12:22:40.700802+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T12:38:40.266898+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T12:54:40.301317+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T13:10:30.467540+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T13:25:40.201551+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T13:40:40.758708+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T13:56:40.284812+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T14:11:40.805473+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T14:27:40.258114+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T14:42:40.804116+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T14:58:30.192778+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T15:13:40.269253+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T15:28:40.637833+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T15:44:40.382331+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T16:00:40.310109+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T16:16:04.695168+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T16:31:30.298532+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T16:46:40.339715+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T17:02:26.030548+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T17:17:40.165639+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T17:32:40.707063+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T17:48:40.401518+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T18:03:40.639591+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T18:19:30.306995+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T18:34:40.507026+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T18:50:40.497527+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T19:06:40.324712+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T19:21:40.797375+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T19:37:30.230425+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T19:52:40.358221+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T20:08:40.433869+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T20:24:40.371675+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T20:40:30.223366+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T20:55:40.281290+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T21:10:40.736025+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T21:26:40.422761+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T21:41:40.697152+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T21:57:29.034450+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T22:12:40.177612+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T22:27:40.644907+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T22:43:30.250595+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T22:58:40.264275+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T23:14:40.206695+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T23:30:40.357211+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-05T23:46:30.255975+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T00:01:40.367084+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T00:16:40.579082+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T00:32:40.344222+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T00:47:40.790128+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T01:03:40.298904+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T01:18:40.735427+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T01:34:30.328615+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T01:49:40.222172+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T02:04:40.680324+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T02:20:40.254331+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T02:35:40.777951+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T02:51:40.215625+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T03:06:40.796194+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T03:22:30.242080+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T03:37:40.353421+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T03:52:40.668963+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T04:00:16.729412+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-06T04:08:40.380297+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T04:23:40.766302+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T04:39:40.348093+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T04:54:40.706148+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T05:10:30.335877+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T05:25:40.382664+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T05:40:40.860378+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T05:56:40.282987+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T06:12:30.713383+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T06:27:40.198696+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T06:42:40.686349+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T06:58:30.308488+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T07:13:40.372412+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T07:28:40.720190+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T07:44:40.286353+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T08:00:40.380285+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T08:16:05.238834+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T08:31:30.193008+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T08:46:40.391376+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T09:02:30.694683+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T09:17:40.231080+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T09:32:40.566582+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T09:48:40.411510+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T10:04:30.307937+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T10:19:40.351549+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T10:34:40.542753+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T10:50:40.340373+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T11:06:40.476636+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T11:22:30.320221+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T11:37:40.204583+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T11:52:40.800401+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T12:08:40.286085+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T12:24:40.212025+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T12:39:40.662798+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T12:55:30.436738+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T13:10:40.235320+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T13:26:40.327007+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T13:42:40.212358+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T13:58:30.357636+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T14:13:40.238985+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T14:28:40.780448+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T14:44:40.245060+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T15:00:40.325403+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T15:16:04.388897+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T15:31:30.313710+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T15:46:40.566102+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T16:01:40.873579+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T16:17:40.232627+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T16:32:40.725317+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T16:48:40.196928+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T17:04:30.374996+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T17:19:40.292939+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T17:34:40.660263+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T17:50:40.293909+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T18:05:40.839774+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T18:21:41.254346+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T18:36:40.756013+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T18:52:30.227310+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T19:07:40.375977+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T19:22:40.679401+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T19:37:54.245972+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T19:53:05.044291+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T20:08:40.327520+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T20:23:40.712872+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T20:39:40.312917+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T20:54:40.680651+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T21:10:30.598836+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T21:25:35.566484+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T21:40:40.230479+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T21:55:40.685977+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T22:10:48.713518+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T22:26:20.668664+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T22:41:40.333724+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T22:56:40.732189+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T23:12:40.260868+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T23:27:40.654598+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T23:42:59.053332+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-06T23:58:40.331792+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T00:14:22.033145+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T00:29:24.578525+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T00:44:27.153741+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T00:59:40.352291+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T01:14:40.970497+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T01:30:40.306617+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T01:45:47.337820+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T02:00:56.064292+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T02:15:58.062427+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T02:31:30.227642+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T02:46:40.234437+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T03:03:09.641910+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T03:18:09.500114+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T03:34:11.199012+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T03:49:10.799857+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T04:00:47.315461+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-07T04:04:34.609097+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T04:20:01.440486+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T04:35:10.289154+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T04:51:11.788456+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T05:06:12.121127+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T05:22:12.237462+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T05:37:10.167046+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T05:52:58.860357+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T06:07:40.194270+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T06:22:40.639790+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T06:38:40.214319+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T06:53:40.524046+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T07:09:40.057580+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T07:24:40.661329+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T07:40:30.075477+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T07:55:40.105613+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T08:10:40.521528+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T08:26:40.117740+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T08:42:39.995399+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T08:58:30.102241+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T09:13:40.068391+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T09:28:40.558858+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T09:43:43.225217+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T09:59:40.123077+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T10:14:40.576587+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T10:30:40.169855+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T10:46:30.130023+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T11:01:40.275497+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T11:16:40.634058+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T11:32:40.168283+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T11:48:40.154255+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T12:04:30.187483+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T12:19:40.098906+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T12:34:40.618416+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T12:50:40.152676+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T13:06:40.283906+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T13:22:30.100128+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T13:37:40.197449+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T13:52:40.560927+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T14:08:40.069623+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T14:24:40.190128+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T14:40:30.190164+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T14:55:40.112372+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T15:10:40.533272+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T15:26:12.103618+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T15:41:40.097186+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T15:56:40.670638+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T16:12:40.191806+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T16:27:40.539456+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T16:43:30.269567+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T16:58:40.101887+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T17:14:40.024291+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T17:29:40.552449+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T17:45:40.071842+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T18:00:40.823480+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T18:16:04.992412+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T18:31:30.076937+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T18:46:40.207586+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T19:01:40.679284+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T19:17:40.175850+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T19:32:40.446766+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T19:48:40.191781+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T20:04:30.128535+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T20:19:40.069123+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T20:34:40.536048+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T20:50:40.085985+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T21:06:40.098766+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T21:21:40.661802+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T21:37:30.366901+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T21:52:40.160645+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T22:07:40.619604+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T22:23:41.187800+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T22:38:41.765411+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T22:54:40.857375+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T23:10:30.927372+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T23:25:41.233002+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T23:40:41.144775+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-07T23:56:40.056046+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T00:11:40.577948+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T00:27:40.136716+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T00:42:40.545314+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T00:58:30.083280+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T01:13:40.098125+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T01:28:40.577193+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T01:44:40.040581+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T02:00:40.158043+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T02:16:05.118748+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T02:31:30.057973+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T02:46:40.062442+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T03:01:40.522437+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T03:17:40.347867+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T03:32:40.598437+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T03:48:40.327245+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T04:00:16.396904+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-08T04:04:30.071505+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T04:19:40.158256+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T04:34:40.582071+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T04:50:40.080736+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T05:05:40.494647+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T05:21:39.988031+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T05:36:40.491210+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T05:52:30.074747+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T06:07:40.136332+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T06:22:40.563341+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T06:38:40.191981+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T06:54:40.144736+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T07:10:30.117995+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T07:25:40.193337+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T07:40:41.641380+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T07:56:40.156314+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T08:12:40.140766+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T08:28:30.098801+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T08:43:40.121072+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T08:58:40.651563+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T09:14:40.078030+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T09:30:40.066529+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T09:46:30.169681+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T10:01:40.136853+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T10:16:40.521092+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T10:32:40.281297+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T10:48:40.191867+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T11:04:30.103179+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T11:19:40.185027+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T11:34:40.638341+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T11:50:40.053254+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T12:06:40.168809+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T12:22:30.237520+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T12:37:40.209519+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T12:52:40.561933+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T13:08:40.185494+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T13:24:40.069387+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T13:40:30.112273+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T13:55:40.175608+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T14:10:40.589923+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T14:26:40.102298+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T14:42:40.058733+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T14:58:30.106568+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T15:13:40.148546+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T15:28:40.655879+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T15:44:40.192858+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T16:00:40.124425+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T16:15:40.516807+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T16:31:30.127948+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T16:46:40.128574+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T17:02:40.146367+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T17:18:40.084022+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T17:34:30.093667+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T17:49:40.140115+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T18:04:40.676867+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T18:20:39.991886+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T18:35:40.605901+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T18:51:40.122467+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T19:06:40.531626+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T19:22:30.072908+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T19:37:40.292344+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T19:52:40.669711+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T20:08:40.302518+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T20:24:40.312834+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T20:39:40.615477+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T20:55:30.396161+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T21:10:42.215013+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T21:26:40.611707+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T21:42:40.714359+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T21:58:30.778089+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T22:13:40.900181+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T22:28:40.999982+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T22:44:40.919615+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T22:59:41.290169+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T23:15:40.760601+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T23:30:41.163837+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-08T23:46:30.920857+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T00:01:40.846583+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T00:16:41.583770+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T00:32:40.889243+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T00:48:40.891109+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T01:04:50.701520+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T01:19:40.785567+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T01:34:41.222450+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T01:50:41.005408+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T02:05:41.328752+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T02:21:41.094020+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T02:36:41.525185+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T02:52:30.727157+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T03:07:41.672516+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T03:22:41.136287+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T03:38:40.762758+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T03:54:40.850938+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T04:00:17.029317+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-09T04:10:31.216645+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T04:25:41.065376+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T04:40:41.247340+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T04:56:30.954251+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T05:11:40.675101+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T05:26:40.975533+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T05:42:40.553626+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T05:58:30.630106+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T06:13:40.740751+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T06:28:41.058813+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T06:44:31.185903+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T06:59:40.770855+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T07:14:40.922061+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T07:30:40.691081+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T07:46:12.037342+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T08:01:30.657056+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T08:16:40.773094+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T08:32:40.627123+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T08:47:41.114894+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T09:03:40.566155+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T09:18:41.040880+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T09:34:50.772209+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T09:49:40.641445+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T10:04:41.162682+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T10:20:40.559110+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T10:36:40.704663+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T10:51:41.118478+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T11:07:30.775513+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T11:22:40.643041+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T11:37:41.101523+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T11:53:40.534227+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T12:08:41.006134+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T12:24:40.729624+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T12:40:30.677150+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T12:55:40.742433+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T13:10:41.005089+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T13:26:40.727335+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T13:42:40.696208+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T13:58:30.570258+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T14:13:40.616970+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T14:28:41.010967+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T14:44:40.705287+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T15:00:40.528010+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T15:16:05.718575+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T15:31:30.598924+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T15:46:40.932111+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T16:02:40.762411+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T16:18:40.670329+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T16:34:30.583452+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T16:49:40.619976+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T17:04:40.995660+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T17:20:40.810643+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T17:36:40.619074+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T17:52:30.648456+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T18:07:40.498309+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T18:22:41.049682+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T18:38:40.531774+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T18:54:40.709763+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T19:10:10.796040+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T19:25:30.752367+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T19:40:40.571386+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T19:56:40.830745+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T20:11:40.983054+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T20:27:40.636959+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T20:42:41.273385+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T20:58:30.660918+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T21:13:40.635928+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T21:28:40.558943+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T21:44:40.075594+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T22:00:40.178645+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T22:15:40.598372+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T22:31:30.155215+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T22:46:40.127762+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T23:02:40.085013+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T23:17:40.559861+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T23:33:40.124351+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-09T23:48:40.500079+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T00:04:30.172234+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T00:19:40.117080+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T00:34:40.508758+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T00:50:40.046454+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T01:05:40.582148+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T01:21:40.041373+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T01:36:40.540297+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T01:51:55.379836+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T02:06:58.909283+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T02:22:30.110062+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T02:37:40.115334+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T02:52:40.487802+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T03:08:40.448445+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T03:24:40.066107+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T03:40:31.050875+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T03:55:40.152743+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T04:00:16.453388+00:00] crypto reconciliation complete mode=daily scanned=13 resolved=0 flagged=0 +[2026-04-10T04:10:40.519529+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T04:26:40.112540+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T04:42:40.153123+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T04:58:30.034383+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T05:13:40.049361+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T05:28:40.533973+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T05:44:25.769343+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T05:59:28.547950+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T06:14:31.451353+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T06:29:34.213204+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T06:44:40.223272+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T06:59:40.462991+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T07:15:33.737506+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T07:30:40.058921+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T07:45:40.574088+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T08:01:30.015095+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T08:17:00.095488+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T08:31:40.457641+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T08:47:18.080335+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T09:02:40.012407+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T09:19:00.067991+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T09:34:30.197069+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T09:49:40.072495+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T10:04:40.582406+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T10:20:40.232620+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T10:36:39.991974+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T10:51:40.538006+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T11:07:29.941664+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T11:22:40.162715+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T11:38:39.942884+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T11:53:40.621037+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T12:09:40.069391+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T12:24:40.590404+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T12:40:49.930323+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T12:55:40.135720+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T13:10:40.558845+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T13:26:40.169212+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T13:42:40.081740+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T13:58:30.146399+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T14:13:40.063962+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T14:28:40.629827+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T14:44:39.991315+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T14:59:40.630615+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T15:15:40.057897+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T15:30:40.520217+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T15:46:29.123596+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T16:01:30.152498+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T16:16:40.121693+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T16:32:40.091111+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T16:48:40.048445+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T17:03:40.558739+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T17:19:30.071990+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T17:34:40.065802+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T17:50:40.153948+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T18:05:40.555943+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T18:21:40.073417+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T18:36:40.444519+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T18:52:30.104568+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T19:07:40.055069+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T19:22:40.474145+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T19:38:40.089127+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T19:53:40.467193+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T20:09:40.115085+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T20:24:40.451026+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T20:40:30.017699+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T20:55:39.992487+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T21:10:40.520007+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T21:26:40.165671+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T21:42:40.202751+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T21:58:30.017469+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T22:14:00.049017+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T22:28:40.609449+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T22:44:40.054327+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T23:00:40.108992+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T23:15:40.663069+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T23:31:30.024003+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-10T23:46:40.104053+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-11T00:02:30.482457+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-11T00:17:40.157855+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-11T00:32:40.470848+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-11T00:48:40.242952+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-11T01:03:40.531627+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-11T01:19:30.117863+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 +[2026-04-11T01:34:40.057937+00:00] crypto reconciliation complete mode=interval scanned=13 resolved=0 flagged=0 diff --git a/logs/invoice_reminder_worker.log b/logs/invoice_reminder_worker.log new file mode 100644 index 0000000..d23ad9d --- /dev/null +++ b/logs/invoice_reminder_worker.log @@ -0,0 +1,91 @@ +[2026-03-14T16:31:25.037816] invoice_reminder_worker starting +[2026-03-14T16:31:25.042017] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-15T09:00:13.715512] invoice_reminder_worker starting +[2026-03-15T09:00:13.720030] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-16T09:00:14.708047] invoice_reminder_worker starting +[2026-03-16T09:00:14.712832] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-17T09:00:14.931911] invoice_reminder_worker starting +[2026-03-17T09:00:14.936172] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-18T09:00:15.000417] invoice_reminder_worker starting +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 123, in + main() + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 98, in main + {recalc_invoice_totals(inv['id'])['total']} +TypeError: 'NoneType' object is not subscriptable +[2026-03-19T09:00:15.181181] invoice_reminder_worker starting +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 123, in + main() + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 98, in main + {recalc_invoice_totals(inv['id'])['total']} +TypeError: 'NoneType' object is not subscriptable +[2026-03-20T09:00:14.989596] invoice_reminder_worker starting +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 123, in + main() + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 98, in main + {recalc_invoice_totals(inv['id'])['total']} +TypeError: 'NoneType' object is not subscriptable +[2026-03-21T09:00:15.739604] invoice_reminder_worker starting +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 123, in + main() + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 98, in main + {recalc_invoice_totals(inv['id'])['total']} +TypeError: 'NoneType' object is not subscriptable +[2026-03-22T09:00:13.788887] invoice_reminder_worker starting +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 123, in + main() + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 98, in main + {recalc_invoice_totals(inv['id'])['total']} +TypeError: 'NoneType' object is not subscriptable +[2026-03-23T09:00:13.812301] invoice_reminder_worker starting +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 123, in + main() + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 98, in main + {recalc_invoice_totals(inv['id'])['total']} +TypeError: 'NoneType' object is not subscriptable +[2026-03-24T09:00:13.771598] invoice_reminder_worker starting +Traceback (most recent call last): + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 123, in + main() + File "/home/def/otb_billing/scripts/invoice_reminder_worker.py", line 98, in main + {recalc_invoice_totals(inv['id'])['total']} +TypeError: 'NoneType' object is not subscriptable +[2026-03-25T09:00:13.760118] invoice_reminder_worker starting +[2026-03-25T09:00:13.764319] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-26T09:00:13.774724] invoice_reminder_worker starting +[2026-03-26T09:00:13.778712] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-27T09:00:13.773589] invoice_reminder_worker starting +[2026-03-27T09:00:13.778961] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-28T09:00:13.783764] invoice_reminder_worker starting +[2026-03-28T09:00:13.787845] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-29T09:00:13.762998] invoice_reminder_worker starting +[2026-03-29T09:00:13.768366] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-30T09:00:14.699862] invoice_reminder_worker starting +[2026-03-30T09:00:14.703938] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-03-31T09:00:14.573494] invoice_reminder_worker starting +[2026-03-31T09:00:14.577931] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-01T09:00:14.690808] invoice_reminder_worker starting +[2026-04-01T09:00:14.695185] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-02T09:00:14.626933] invoice_reminder_worker starting +[2026-04-02T09:00:14.631353] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-03T09:00:14.702593] invoice_reminder_worker starting +[2026-04-03T09:00:14.708129] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-04T09:00:14.832769] invoice_reminder_worker starting +[2026-04-04T09:00:14.837022] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-05T09:00:15.412774] invoice_reminder_worker starting +[2026-04-05T09:00:15.429713] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-06T09:00:13.997050] invoice_reminder_worker starting +[2026-04-06T09:00:14.004077] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-07T09:00:13.691922] invoice_reminder_worker starting +[2026-04-07T09:00:13.696346] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-08T09:00:13.765715] invoice_reminder_worker starting +[2026-04-08T09:00:13.770314] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-09T09:00:14.898994] invoice_reminder_worker starting +[2026-04-09T09:00:14.906306] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 +[2026-04-10T09:00:14.318241] invoice_reminder_worker starting +[2026-04-10T09:00:14.322748] checked=0 reminders_sent=0 overdue_sent=0 skipped=0 diff --git a/logs/square_webhook_events.log b/logs/square_webhook_events.log new file mode 100644 index 0000000..5a832e8 --- /dev/null +++ b/logs/square_webhook_events.log @@ -0,0 +1,60 @@ +{"logged_at_utc": "2026-03-14T05:10:59.807869Z", "signature_valid": false, "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": null, "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "created_at": "2026-03-14T05:10:57.777Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T05:11:01.733352Z", "signature_valid": false, "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "created_at": "2026-03-14T05:11:00.565Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T05:11:03.205419Z", "signature_valid": false, "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "created_at": "2026-03-14T05:11:01.956Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 5}}}}} +{"logged_at_utc": "2026-03-14T05:12:01.385922Z", "signature_valid": false, "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": null, "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "created_at": "2026-03-14T05:10:57.777Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T05:12:03.522320Z", "signature_valid": false, "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "created_at": "2026-03-14T05:11:00.565Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T05:12:04.891809Z", "signature_valid": false, "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "created_at": "2026-03-14T05:11:01.956Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 5}}}}} +{"logged_at_utc": "2026-03-14T05:13:02.386103Z", "signature_valid": false, "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "created_at": "2026-03-14T05:13:00.22Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:12:58.413Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:59.262Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T05:14:03.349099Z", "signature_valid": false, "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": null, "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "created_at": "2026-03-14T05:10:57.777Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T05:14:03.754842Z", "signature_valid": false, "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "created_at": "2026-03-14T05:13:00.22Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:12:58.413Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:59.262Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T05:14:04.236518Z", "signature_valid": false, "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "created_at": "2026-03-14T05:11:00.565Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T05:14:07.092388Z", "signature_valid": false, "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "created_at": "2026-03-14T05:11:01.956Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 5}}}}} +{"logged_at_utc": "2026-03-14T05:16:05.430532Z", "signature_valid": false, "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "created_at": "2026-03-14T05:13:00.22Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:12:58.413Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:59.262Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T05:18:04.632060Z", "signature_valid": false, "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": null, "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "created_at": "2026-03-14T05:10:57.777Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T05:18:05.352753Z", "signature_valid": false, "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "created_at": "2026-03-14T05:11:00.565Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T05:18:08.274611Z", "signature_valid": false, "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "created_at": "2026-03-14T05:11:01.956Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 5}}}}} +{"logged_at_utc": "2026-03-14T05:20:07.191931Z", "signature_valid": false, "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "created_at": "2026-03-14T05:13:00.22Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:12:58.413Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:59.262Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T05:24:55.023227Z", "signature_valid": true, "event_id": "07fa8d31-9774-3ea3-bca2-64c99bb49c72", "event_type": "payment.updated", "payment_id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "payment_status": "COMPLETED", "amount_money": 500, "reference_id": null, "note": null, "order_id": "wOSOaIura0Z5f0poRV2JCcbKJwcZY", "customer_id": null, "receipt_number": "vZrP", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "07fa8d31-9774-3ea3-bca2-64c99bb49c72", "created_at": "2026-03-14T05:24:52.649Z", "data": {"type": "payment", "id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "object": {"payment": {"amount_money": {"amount": 500, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 500, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "03544Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:24:51.483Z", "captured_at": "2026-03-14T05:24:51.734Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:24:51.128Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:24:51.128Z", "id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "location_id": "1TSPHT78106WX", "order_id": "wOSOaIura0Z5f0poRV2JCcbKJwcZY", "receipt_number": "vZrP", "receipt_url": "https://squareup.com/receipt/preview/vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "risk_evaluation": {"created_at": "2026-03-14T05:24:51.637Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 500, "currency": "CAD"}, "updated_at": "2026-03-14T05:24:52.642Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T05:24:57.441325Z", "signature_valid": true, "event_id": "da9033d0-1c96-3c4c-b9e1-e43ff0ff31e2", "event_type": "payment.updated", "payment_id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "payment_status": "COMPLETED", "amount_money": 500, "reference_id": null, "note": null, "order_id": "wOSOaIura0Z5f0poRV2JCcbKJwcZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "vZrP", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "da9033d0-1c96-3c4c-b9e1-e43ff0ff31e2", "created_at": "2026-03-14T05:24:55.385Z", "data": {"type": "payment", "id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "object": {"payment": {"amount_money": {"amount": 500, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 500, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "03544Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:24:51.483Z", "captured_at": "2026-03-14T05:24:51.734Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:24:51.128Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:24:51.128Z", "id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "location_id": "1TSPHT78106WX", "order_id": "wOSOaIura0Z5f0poRV2JCcbKJwcZY", "receipt_number": "vZrP", "receipt_url": "https://squareup.com/receipt/preview/vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "risk_evaluation": {"created_at": "2026-03-14T05:24:51.637Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 500, "currency": "CAD"}, "updated_at": "2026-03-14T05:24:52.642Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T05:24:57.898937Z", "signature_valid": true, "event_id": "287d3396-e4f9-3712-8cd3-a957d0bc21ac", "event_type": "payment.updated", "payment_id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "payment_status": "COMPLETED", "amount_money": 500, "reference_id": null, "note": null, "order_id": "wOSOaIura0Z5f0poRV2JCcbKJwcZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "vZrP", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "287d3396-e4f9-3712-8cd3-a957d0bc21ac", "created_at": "2026-03-14T05:24:56.581Z", "data": {"type": "payment", "id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "object": {"payment": {"amount_money": {"amount": 500, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 500, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "03544Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:24:51.483Z", "captured_at": "2026-03-14T05:24:51.734Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:24:51.128Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:24:51.128Z", "id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "location_id": "1TSPHT78106WX", "order_id": "wOSOaIura0Z5f0poRV2JCcbKJwcZY", "processing_fee": [{"amount_money": {"amount": 44, "currency": "CAD"}, "effective_at": "2026-03-14T07:24:52.000Z", "type": "INITIAL"}], "receipt_number": "vZrP", "receipt_url": "https://squareup.com/receipt/preview/vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "risk_evaluation": {"created_at": "2026-03-14T05:24:51.637Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 500, "currency": "CAD"}, "updated_at": "2026-03-14T05:24:52.642Z", "version": 5}}}}} +{"logged_at_utc": "2026-03-14T05:26:05.676307Z", "signature_valid": true, "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": null, "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "9761932d-8ca4-3fe4-a395-36bd00338003", "created_at": "2026-03-14T05:10:57.777Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T05:26:06.519391Z", "signature_valid": true, "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "e91dca11-e52c-3517-b8a4-fe88f5bdf015", "created_at": "2026-03-14T05:11:00.565Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T05:26:09.701016Z", "signature_valid": true, "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "8c0cf843-6ab2-3f63-973e-8a5233d55e16", "created_at": "2026-03-14T05:11:01.956Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:10:57.075Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:57.768Z", "version": 5}}}}} +{"logged_at_utc": "2026-03-14T05:26:56.488427Z", "signature_valid": true, "event_id": "840dee01-c02c-3327-ad9b-84f7ca4ede51", "event_type": "payment.updated", "payment_id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "payment_status": "COMPLETED", "amount_money": 500, "reference_id": null, "note": null, "order_id": "wOSOaIura0Z5f0poRV2JCcbKJwcZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "vZrP", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "840dee01-c02c-3327-ad9b-84f7ca4ede51", "created_at": "2026-03-14T05:26:55.105Z", "data": {"type": "payment", "id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "object": {"payment": {"amount_money": {"amount": 500, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 500, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "03544Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:24:51.483Z", "captured_at": "2026-03-14T05:24:51.734Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:24:51.128Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:24:51.128Z", "id": "vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "location_id": "1TSPHT78106WX", "order_id": "wOSOaIura0Z5f0poRV2JCcbKJwcZY", "processing_fee": [{"amount_money": {"amount": 44, "currency": "CAD"}, "effective_at": "2026-03-14T07:24:52.000Z", "type": "INITIAL"}], "receipt_number": "vZrP", "receipt_url": "https://squareup.com/receipt/preview/vZrPHn8aeo4YCCKnwaqLT7aw3fLZY", "risk_evaluation": {"created_at": "2026-03-14T05:26:53.360Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 500, "currency": "CAD"}, "updated_at": "2026-03-14T05:24:54.485Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T05:28:08.347050Z", "signature_valid": true, "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "event_type": "payment.updated", "payment_id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "payment_status": "COMPLETED", "amount_money": 1000, "reference_id": null, "note": null, "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "9OGV", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "6617e08a-1f5b-3fe7-9e14-7200493c5bd4", "created_at": "2026-03-14T05:13:00.22Z", "data": {"type": "payment", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "object": {"payment": {"amount_money": {"amount": 1000, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 1000, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "01706Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:10:56.920Z", "captured_at": "2026-03-14T05:10:57.164Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:10:56.418Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:10:56.418Z", "id": "9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "location_id": "1TSPHT78106WX", "order_id": "gMFKyP8YM0mrEw9IfxDn6iqyJpCZY", "processing_fee": [{"amount_money": {"amount": 58, "currency": "CAD"}, "effective_at": "2026-03-14T07:10:57.000Z", "type": "INITIAL"}], "receipt_number": "9OGV", "receipt_url": "https://squareup.com/receipt/preview/9OGVXM2nIH6fNQeSoMZ2u1WhhCSZY", "risk_evaluation": {"created_at": "2026-03-14T05:12:58.413Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 1000, "currency": "CAD"}, "updated_at": "2026-03-14T05:10:59.262Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T05:53:12.459570Z", "signature_valid": true, "event_id": "8aa0dea1-f9fe-32ee-b36e-8b9a897c3d02", "event_type": "payment.updated", "payment_id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "payment_status": "COMPLETED", "amount_money": 100, "reference_id": null, "note": "Invoice INV-0007", "order_id": "4Mng9GT9VvP3JLo678vxz5yeFFYZY", "customer_id": null, "receipt_number": "VWSM", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "8aa0dea1-f9fe-32ee-b36e-8b9a897c3d02", "created_at": "2026-03-14T05:53:10.138Z", "data": {"type": "payment", "id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "object": {"payment": {"amount_money": {"amount": 100, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 100, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "09248Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:53:08.286Z", "captured_at": "2026-03-14T05:53:08.542Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:53:07.763Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:53:07.763Z", "id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0007", "order_id": "4Mng9GT9VvP3JLo678vxz5yeFFYZY", "receipt_number": "VWSM", "receipt_url": "https://squareup.com/receipt/preview/VWSMtz71gQTsLvjeTUXVUhxovBFZY", "risk_evaluation": {"created_at": "2026-03-14T05:53:08.452Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 100, "currency": "CAD"}, "updated_at": "2026-03-14T05:53:10.129Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T05:53:13.186847Z", "signature_valid": true, "event_id": "b343d274-ceb3-3e5b-9b98-065c9e8b8527", "event_type": "payment.updated", "payment_id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "payment_status": "COMPLETED", "amount_money": 100, "reference_id": null, "note": "Invoice INV-0007", "order_id": "4Mng9GT9VvP3JLo678vxz5yeFFYZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "VWSM", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "b343d274-ceb3-3e5b-9b98-065c9e8b8527", "created_at": "2026-03-14T05:53:12.342Z", "data": {"type": "payment", "id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "object": {"payment": {"amount_money": {"amount": 100, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 100, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "09248Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:53:08.286Z", "captured_at": "2026-03-14T05:53:08.542Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:53:07.763Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:53:07.763Z", "id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0007", "order_id": "4Mng9GT9VvP3JLo678vxz5yeFFYZY", "receipt_number": "VWSM", "receipt_url": "https://squareup.com/receipt/preview/VWSMtz71gQTsLvjeTUXVUhxovBFZY", "risk_evaluation": {"created_at": "2026-03-14T05:53:08.452Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 100, "currency": "CAD"}, "updated_at": "2026-03-14T05:53:10.129Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T05:53:18.292165Z", "signature_valid": true, "event_id": "637b358b-4b74-3867-8d4b-ecc6c7409303", "event_type": "payment.updated", "payment_id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "payment_status": "COMPLETED", "amount_money": 100, "reference_id": null, "note": "Invoice INV-0007", "order_id": "4Mng9GT9VvP3JLo678vxz5yeFFYZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "VWSM", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "637b358b-4b74-3867-8d4b-ecc6c7409303", "created_at": "2026-03-14T05:53:16.249Z", "data": {"type": "payment", "id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "object": {"payment": {"amount_money": {"amount": 100, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 100, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "09248Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:53:08.286Z", "captured_at": "2026-03-14T05:53:08.542Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:53:07.763Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:53:07.763Z", "id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0007", "order_id": "4Mng9GT9VvP3JLo678vxz5yeFFYZY", "processing_fee": [{"amount_money": {"amount": 33, "currency": "CAD"}, "effective_at": "2026-03-14T07:53:10.000Z", "type": "INITIAL"}], "receipt_number": "VWSM", "receipt_url": "https://squareup.com/receipt/preview/VWSMtz71gQTsLvjeTUXVUhxovBFZY", "risk_evaluation": {"created_at": "2026-03-14T05:53:08.452Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 100, "currency": "CAD"}, "updated_at": "2026-03-14T05:53:11.556Z", "version": 6}}}}} +{"logged_at_utc": "2026-03-14T05:55:14.375294Z", "signature_valid": true, "event_id": "1dfde57e-c85a-33b4-981b-9004d19a190c", "event_type": "payment.updated", "payment_id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "payment_status": "COMPLETED", "amount_money": 100, "reference_id": null, "note": "Invoice INV-0007", "order_id": "4Mng9GT9VvP3JLo678vxz5yeFFYZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "VWSM", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "1dfde57e-c85a-33b4-981b-9004d19a190c", "created_at": "2026-03-14T05:55:13.104Z", "data": {"type": "payment", "id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "object": {"payment": {"amount_money": {"amount": 100, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 100, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "09248Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T05:53:08.286Z", "captured_at": "2026-03-14T05:53:08.542Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T05:53:07.763Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T05:53:07.763Z", "id": "VWSMtz71gQTsLvjeTUXVUhxovBFZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0007", "order_id": "4Mng9GT9VvP3JLo678vxz5yeFFYZY", "processing_fee": [{"amount_money": {"amount": 33, "currency": "CAD"}, "effective_at": "2026-03-14T07:53:10.000Z", "type": "INITIAL"}], "receipt_number": "VWSM", "receipt_url": "https://squareup.com/receipt/preview/VWSMtz71gQTsLvjeTUXVUhxovBFZY", "risk_evaluation": {"created_at": "2026-03-14T05:55:11.004Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 100, "currency": "CAD"}, "updated_at": "2026-03-14T05:53:11.556Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T06:36:44.885383Z", "signature_valid": true, "event_id": "d821abb0-39a3-3f49-a81f-69e542372875", "event_type": "payment.updated", "payment_id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "payment_status": "COMPLETED", "amount_money": 100, "reference_id": null, "note": "Invoice INV-0008", "order_id": "k2HlCuwFYqXIvF6cAgkbl00CnUaZY", "customer_id": null, "receipt_number": "RCJg", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "d821abb0-39a3-3f49-a81f-69e542372875", "created_at": "2026-03-14T06:36:42.975Z", "data": {"type": "payment", "id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "object": {"payment": {"amount_money": {"amount": 100, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 100, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "09237Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T06:36:41.282Z", "captured_at": "2026-03-14T06:36:41.528Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T06:36:40.924Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T06:36:40.924Z", "id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0008", "order_id": "k2HlCuwFYqXIvF6cAgkbl00CnUaZY", "receipt_number": "RCJg", "receipt_url": "https://squareup.com/receipt/preview/RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "risk_evaluation": {"created_at": "2026-03-14T06:36:41.445Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 100, "currency": "CAD"}, "updated_at": "2026-03-14T06:36:42.967Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T06:36:44.889174Z", "auto_apply_result": {"processed": false, "reason": "exception", "error": "1265 (01000): Data truncated for column 'payment_status' at row 1"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T06:36:46.670969Z", "signature_valid": true, "event_id": "0883f437-4a5d-33c5-a8c9-8d1dac075ff7", "event_type": "payment.updated", "payment_id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "payment_status": "COMPLETED", "amount_money": 100, "reference_id": null, "note": "Invoice INV-0008", "order_id": "k2HlCuwFYqXIvF6cAgkbl00CnUaZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "RCJg", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "0883f437-4a5d-33c5-a8c9-8d1dac075ff7", "created_at": "2026-03-14T06:36:45.132Z", "data": {"type": "payment", "id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "object": {"payment": {"amount_money": {"amount": 100, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 100, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "09237Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T06:36:41.282Z", "captured_at": "2026-03-14T06:36:41.528Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T06:36:40.924Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T06:36:40.924Z", "id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0008", "order_id": "k2HlCuwFYqXIvF6cAgkbl00CnUaZY", "receipt_number": "RCJg", "receipt_url": "https://squareup.com/receipt/preview/RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "risk_evaluation": {"created_at": "2026-03-14T06:36:41.445Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 100, "currency": "CAD"}, "updated_at": "2026-03-14T06:36:42.967Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T06:36:46.673965Z", "auto_apply_result": {"processed": false, "reason": "exception", "error": "1265 (01000): Data truncated for column 'payment_status' at row 1"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T06:36:47.790729Z", "signature_valid": true, "event_id": "8d2dde65-54e5-3b28-aab2-d08ee19e035c", "event_type": "payment.updated", "payment_id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "payment_status": "COMPLETED", "amount_money": 100, "reference_id": null, "note": "Invoice INV-0008", "order_id": "k2HlCuwFYqXIvF6cAgkbl00CnUaZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "RCJg", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "8d2dde65-54e5-3b28-aab2-d08ee19e035c", "created_at": "2026-03-14T06:36:45.826Z", "data": {"type": "payment", "id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "object": {"payment": {"amount_money": {"amount": 100, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 100, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "09237Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T06:36:41.282Z", "captured_at": "2026-03-14T06:36:41.528Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T06:36:40.924Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T06:36:40.924Z", "id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0008", "order_id": "k2HlCuwFYqXIvF6cAgkbl00CnUaZY", "processing_fee": [{"amount_money": {"amount": 33, "currency": "CAD"}, "effective_at": "2026-03-14T08:36:42.000Z", "type": "INITIAL"}], "receipt_number": "RCJg", "receipt_url": "https://squareup.com/receipt/preview/RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "risk_evaluation": {"created_at": "2026-03-14T06:36:41.445Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 100, "currency": "CAD"}, "updated_at": "2026-03-14T06:36:42.967Z", "version": 5}}}}} +{"logged_at_utc": "2026-03-14T06:36:47.793700Z", "auto_apply_result": {"processed": false, "reason": "exception", "error": "1265 (01000): Data truncated for column 'payment_status' at row 1"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T06:38:46.901770Z", "signature_valid": true, "event_id": "4bdb57ad-bd86-344e-be76-5685a8155a6d", "event_type": "payment.updated", "payment_id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "payment_status": "COMPLETED", "amount_money": 100, "reference_id": null, "note": "Invoice INV-0008", "order_id": "k2HlCuwFYqXIvF6cAgkbl00CnUaZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "RCJg", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "4bdb57ad-bd86-344e-be76-5685a8155a6d", "created_at": "2026-03-14T06:38:45.529Z", "data": {"type": "payment", "id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "object": {"payment": {"amount_money": {"amount": 100, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 100, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "09237Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T06:36:41.282Z", "captured_at": "2026-03-14T06:36:41.528Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T06:36:40.924Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T06:36:40.924Z", "id": "RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0008", "order_id": "k2HlCuwFYqXIvF6cAgkbl00CnUaZY", "processing_fee": [{"amount_money": {"amount": 33, "currency": "CAD"}, "effective_at": "2026-03-14T08:36:42.000Z", "type": "INITIAL"}], "receipt_number": "RCJg", "receipt_url": "https://squareup.com/receipt/preview/RCJgXNGImLgbRA5LI5PcAwBB7ZHZY", "risk_evaluation": {"created_at": "2026-03-14T06:38:43.686Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 100, "currency": "CAD"}, "updated_at": "2026-03-14T06:36:44.328Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T06:38:46.904854Z", "auto_apply_result": {"processed": false, "reason": "exception", "error": "1265 (01000): Data truncated for column 'payment_status' at row 1"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T06:55:22.652981Z", "signature_valid": true, "event_id": "aa9ab0ec-c93d-38a1-b003-8d4a28a5ee6d", "event_type": "payment.updated", "payment_id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "payment_status": "COMPLETED", "amount_money": 99, "reference_id": null, "note": "Invoice INV-0009", "order_id": "ckwvdrMNOuDSwb0ZxrkyseT9U1NZY", "customer_id": null, "receipt_number": "lGYf", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "aa9ab0ec-c93d-38a1-b003-8d4a28a5ee6d", "created_at": "2026-03-14T06:55:21.182Z", "data": {"type": "payment", "id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "object": {"payment": {"amount_money": {"amount": 99, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 99, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "05602Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T06:55:20.121Z", "captured_at": "2026-03-14T06:55:20.379Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T06:55:19.694Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T06:55:19.694Z", "id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0009", "order_id": "ckwvdrMNOuDSwb0ZxrkyseT9U1NZY", "receipt_number": "lGYf", "receipt_url": "https://squareup.com/receipt/preview/lGYf4SB7eivSQgohyP4P2mYzZReZY", "risk_evaluation": {"created_at": "2026-03-14T06:55:20.287Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 99, "currency": "CAD"}, "updated_at": "2026-03-14T06:55:21.172Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T06:55:22.656914Z", "auto_apply_result": {"processed": false, "reason": "exception", "error": "1265 (01000): Data truncated for column 'payment_status' at row 1"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T06:55:25.316670Z", "signature_valid": true, "event_id": "065f16b5-adef-3cb5-b4df-59e239c3efc2", "event_type": "payment.updated", "payment_id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "payment_status": "COMPLETED", "amount_money": 99, "reference_id": null, "note": "Invoice INV-0009", "order_id": "ckwvdrMNOuDSwb0ZxrkyseT9U1NZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "lGYf", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "065f16b5-adef-3cb5-b4df-59e239c3efc2", "created_at": "2026-03-14T06:55:23.71Z", "data": {"type": "payment", "id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "object": {"payment": {"amount_money": {"amount": 99, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 99, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "05602Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T06:55:20.121Z", "captured_at": "2026-03-14T06:55:20.379Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T06:55:19.694Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T06:55:19.694Z", "id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0009", "order_id": "ckwvdrMNOuDSwb0ZxrkyseT9U1NZY", "receipt_number": "lGYf", "receipt_url": "https://squareup.com/receipt/preview/lGYf4SB7eivSQgohyP4P2mYzZReZY", "risk_evaluation": {"created_at": "2026-03-14T06:55:20.287Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 99, "currency": "CAD"}, "updated_at": "2026-03-14T06:55:21.172Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T06:55:25.319761Z", "auto_apply_result": {"processed": false, "reason": "exception", "error": "1265 (01000): Data truncated for column 'payment_status' at row 1"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T06:55:30.025644Z", "signature_valid": true, "event_id": "9f61211f-7dff-31dc-8bc2-327411c9d5a6", "event_type": "payment.updated", "payment_id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "payment_status": "COMPLETED", "amount_money": 99, "reference_id": null, "note": "Invoice INV-0009", "order_id": "ckwvdrMNOuDSwb0ZxrkyseT9U1NZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "lGYf", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "9f61211f-7dff-31dc-8bc2-327411c9d5a6", "created_at": "2026-03-14T06:55:28.265Z", "data": {"type": "payment", "id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "object": {"payment": {"amount_money": {"amount": 99, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 99, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "05602Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T06:55:20.121Z", "captured_at": "2026-03-14T06:55:20.379Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T06:55:19.694Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T06:55:19.694Z", "id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0009", "order_id": "ckwvdrMNOuDSwb0ZxrkyseT9U1NZY", "processing_fee": [{"amount_money": {"amount": 33, "currency": "CAD"}, "effective_at": "2026-03-14T08:55:21.000Z", "type": "INITIAL"}], "receipt_number": "lGYf", "receipt_url": "https://squareup.com/receipt/preview/lGYf4SB7eivSQgohyP4P2mYzZReZY", "risk_evaluation": {"created_at": "2026-03-14T06:55:20.287Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 99, "currency": "CAD"}, "updated_at": "2026-03-14T06:55:23.345Z", "version": 6}}}}} +{"logged_at_utc": "2026-03-14T06:55:30.028630Z", "auto_apply_result": {"processed": false, "reason": "exception", "error": "1265 (01000): Data truncated for column 'payment_status' at row 1"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T06:57:24.276328Z", "signature_valid": true, "event_id": "dc5ef862-34f4-35e9-9bf0-2d9b185c372a", "event_type": "payment.updated", "payment_id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "payment_status": "COMPLETED", "amount_money": 99, "reference_id": null, "note": "Invoice INV-0009", "order_id": "ckwvdrMNOuDSwb0ZxrkyseT9U1NZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "lGYf", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "dc5ef862-34f4-35e9-9bf0-2d9b185c372a", "created_at": "2026-03-14T06:57:22.935Z", "data": {"type": "payment", "id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "object": {"payment": {"amount_money": {"amount": 99, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 99, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "05602Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T06:55:20.121Z", "captured_at": "2026-03-14T06:55:20.379Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T06:55:19.694Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T06:55:19.694Z", "id": "lGYf4SB7eivSQgohyP4P2mYzZReZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0009", "order_id": "ckwvdrMNOuDSwb0ZxrkyseT9U1NZY", "processing_fee": [{"amount_money": {"amount": 33, "currency": "CAD"}, "effective_at": "2026-03-14T08:55:21.000Z", "type": "INITIAL"}], "receipt_number": "lGYf", "receipt_url": "https://squareup.com/receipt/preview/lGYf4SB7eivSQgohyP4P2mYzZReZY", "risk_evaluation": {"created_at": "2026-03-14T06:57:21.975Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 99, "currency": "CAD"}, "updated_at": "2026-03-14T06:55:23.345Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T06:57:24.279407Z", "auto_apply_result": {"processed": false, "reason": "exception", "error": "1265 (01000): Data truncated for column 'payment_status' at row 1"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T14:36:10.005773Z", "signature_valid": true, "event_id": "52c9222e-d7ab-37a2-931f-48c730a87786", "event_type": "payment.updated", "payment_id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "payment_status": "COMPLETED", "amount_money": 99, "reference_id": null, "note": "Invoice INV-0009", "order_id": "KHWRIEWqhOdjN3HadCllFOPGuM8YY", "customer_id": null, "receipt_number": "BSvR", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "52c9222e-d7ab-37a2-931f-48c730a87786", "created_at": "2026-03-14T14:36:08.453Z", "data": {"type": "payment", "id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "object": {"payment": {"amount_money": {"amount": 99, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 99, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "08219Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T14:36:07.360Z", "captured_at": "2026-03-14T14:36:07.641Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T14:36:06.991Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T14:36:06.991Z", "id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0009", "order_id": "KHWRIEWqhOdjN3HadCllFOPGuM8YY", "receipt_number": "BSvR", "receipt_url": "https://squareup.com/receipt/preview/BSvRb43MBiY3mO7XJjtCUjw10pfZY", "risk_evaluation": {"created_at": "2026-03-14T14:36:07.541Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 99, "currency": "CAD"}, "updated_at": "2026-03-14T14:36:08.445Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-14T14:36:11.745429Z", "auto_apply_result": {"processed": true, "invoice_number": "INV-0009", "payment_id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "amount": "0.99", "currency": "CAD"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T14:36:12.316668Z", "signature_valid": true, "event_id": "e4364ad1-028f-3c8b-947b-f579e68a1c8a", "event_type": "payment.updated", "payment_id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "payment_status": "COMPLETED", "amount_money": 99, "reference_id": null, "note": "Invoice INV-0009", "order_id": "KHWRIEWqhOdjN3HadCllFOPGuM8YY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "BSvR", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "e4364ad1-028f-3c8b-947b-f579e68a1c8a", "created_at": "2026-03-14T14:36:11.083Z", "data": {"type": "payment", "id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "object": {"payment": {"amount_money": {"amount": 99, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 99, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "08219Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T14:36:07.360Z", "captured_at": "2026-03-14T14:36:07.641Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T14:36:06.991Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T14:36:06.991Z", "id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0009", "order_id": "KHWRIEWqhOdjN3HadCllFOPGuM8YY", "receipt_number": "BSvR", "receipt_url": "https://squareup.com/receipt/preview/BSvRb43MBiY3mO7XJjtCUjw10pfZY", "risk_evaluation": {"created_at": "2026-03-14T14:36:07.541Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 99, "currency": "CAD"}, "updated_at": "2026-03-14T14:36:08.445Z", "version": 4}}}}} +{"logged_at_utc": "2026-03-14T14:36:12.318683Z", "auto_apply_result": {"processed": false, "reason": "duplicate_payment_id", "payment_id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T14:36:16.127831Z", "signature_valid": true, "event_id": "73d6f8d4-4f0f-39fc-b1da-6a5d41d641b6", "event_type": "payment.updated", "payment_id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "payment_status": "COMPLETED", "amount_money": 99, "reference_id": null, "note": "Invoice INV-0009", "order_id": "KHWRIEWqhOdjN3HadCllFOPGuM8YY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "BSvR", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "73d6f8d4-4f0f-39fc-b1da-6a5d41d641b6", "created_at": "2026-03-14T14:36:14.549Z", "data": {"type": "payment", "id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "object": {"payment": {"amount_money": {"amount": 99, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 99, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "08219Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T14:36:07.360Z", "captured_at": "2026-03-14T14:36:07.641Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T14:36:06.991Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T14:36:06.991Z", "id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0009", "order_id": "KHWRIEWqhOdjN3HadCllFOPGuM8YY", "processing_fee": [{"amount_money": {"amount": 33, "currency": "CAD"}, "effective_at": "2026-03-14T16:36:08.000Z", "type": "INITIAL"}], "receipt_number": "BSvR", "receipt_url": "https://squareup.com/receipt/preview/BSvRb43MBiY3mO7XJjtCUjw10pfZY", "risk_evaluation": {"created_at": "2026-03-14T14:36:07.541Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 99, "currency": "CAD"}, "updated_at": "2026-03-14T14:36:10.016Z", "version": 6}}}}} +{"logged_at_utc": "2026-03-14T14:36:16.130140Z", "auto_apply_result": {"processed": false, "reason": "duplicate_payment_id", "payment_id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-14T14:46:38.025483Z", "signature_valid": true, "event_id": "26207de8-bf9f-30fc-8992-582bf7ae37e9", "event_type": "payment.updated", "payment_id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "payment_status": "COMPLETED", "amount_money": 99, "reference_id": null, "note": "Invoice INV-0009", "order_id": "KHWRIEWqhOdjN3HadCllFOPGuM8YY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "BSvR", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "26207de8-bf9f-30fc-8992-582bf7ae37e9", "created_at": "2026-03-14T14:46:35.874Z", "data": {"type": "payment", "id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "object": {"payment": {"amount_money": {"amount": 99, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 99, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "natural_gas_fitter@yahoo.ca", "card_details": {"auth_result_code": "08219Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-14T14:36:07.360Z", "captured_at": "2026-03-14T14:36:07.641Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-14T14:36:06.991Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-03-21T14:36:06.991Z", "id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0009", "order_id": "KHWRIEWqhOdjN3HadCllFOPGuM8YY", "processing_fee": [{"amount_money": {"amount": 33, "currency": "CAD"}, "effective_at": "2026-03-14T16:36:08.000Z", "type": "INITIAL"}], "receipt_number": "BSvR", "receipt_url": "https://squareup.com/receipt/preview/BSvRb43MBiY3mO7XJjtCUjw10pfZY", "risk_evaluation": {"created_at": "2026-03-14T14:38:09.432Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 99, "currency": "CAD"}, "updated_at": "2026-03-14T14:36:10.016Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-14T14:46:38.027685Z", "auto_apply_result": {"processed": false, "reason": "duplicate_payment_id", "payment_id": "BSvRb43MBiY3mO7XJjtCUjw10pfZY"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-25T00:17:40.603654Z", "signature_valid": true, "event_id": "7b97f15b-22bc-31fe-bfe5-979e229fe93a", "event_type": "payment.updated", "payment_id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "payment_status": "COMPLETED", "amount_money": 500, "reference_id": null, "note": "Invoice INV-0023", "order_id": "69RxNIovUfaLxcPqc4A3CxojzMeZY", "customer_id": null, "receipt_number": "Pp3T", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "7b97f15b-22bc-31fe-bfe5-979e229fe93a", "created_at": "2026-03-25T00:17:38.336Z", "data": {"type": "payment", "id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "object": {"payment": {"amount_money": {"amount": 500, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 500, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "def@etica-stats.org", "card_details": {"auth_result_code": "02119Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-25T00:17:37.289Z", "captured_at": "2026-03-25T00:17:37.554Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-25T00:17:36.880Z", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-04-01T00:17:36.880Z", "id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0023", "order_id": "69RxNIovUfaLxcPqc4A3CxojzMeZY", "receipt_number": "Pp3T", "receipt_url": "https://squareup.com/receipt/preview/Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "risk_evaluation": {"created_at": "2026-03-25T00:17:37.462Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 500, "currency": "CAD"}, "updated_at": "2026-03-25T00:17:38.327Z", "version": 3}}}}} +{"logged_at_utc": "2026-03-25T00:17:42.524797Z", "signature_valid": true, "event_id": "7718ab51-913a-37af-b19d-6657a4b11585", "event_type": "payment.updated", "payment_id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "payment_status": "COMPLETED", "amount_money": 500, "reference_id": null, "note": "Invoice INV-0023", "order_id": "69RxNIovUfaLxcPqc4A3CxojzMeZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "Pp3T", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "7718ab51-913a-37af-b19d-6657a4b11585", "created_at": "2026-03-25T00:17:41.591Z", "data": {"type": "payment", "id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "object": {"payment": {"amount_money": {"amount": 500, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 500, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "def@etica-stats.org", "card_details": {"auth_result_code": "02119Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-25T00:17:37.289Z", "captured_at": "2026-03-25T00:17:37.554Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-25T00:17:36.880Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-04-01T00:17:36.880Z", "id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0023", "order_id": "69RxNIovUfaLxcPqc4A3CxojzMeZY", "receipt_number": "Pp3T", "receipt_url": "https://squareup.com/receipt/preview/Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "risk_evaluation": {"created_at": "2026-03-25T00:17:37.462Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 500, "currency": "CAD"}, "updated_at": "2026-03-25T00:17:39.470Z", "version": 5}}}}} +{"logged_at_utc": "2026-03-25T00:17:42.544221Z", "auto_apply_result": {"processed": false, "reason": "duplicate_payment_id", "payment_id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-25T00:17:42.711632Z", "auto_apply_result": {"processed": true, "invoice_number": "INV-0023", "payment_id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "amount": "5", "currency": "CAD"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-25T00:17:43.837492Z", "signature_valid": true, "event_id": "d2c61152-9e9a-33b8-b406-e98cc05177c7", "event_type": "payment.updated", "payment_id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "payment_status": "COMPLETED", "amount_money": 500, "reference_id": null, "note": "Invoice INV-0023", "order_id": "69RxNIovUfaLxcPqc4A3CxojzMeZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "Pp3T", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "d2c61152-9e9a-33b8-b406-e98cc05177c7", "created_at": "2026-03-25T00:17:42.663Z", "data": {"type": "payment", "id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "object": {"payment": {"amount_money": {"amount": 500, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 500, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "def@etica-stats.org", "card_details": {"auth_result_code": "02119Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-25T00:17:37.289Z", "captured_at": "2026-03-25T00:17:37.554Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-25T00:17:36.880Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-04-01T00:17:36.880Z", "id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0023", "order_id": "69RxNIovUfaLxcPqc4A3CxojzMeZY", "processing_fee": [{"amount_money": {"amount": 44, "currency": "CAD"}, "effective_at": "2026-03-25T02:17:38.000Z", "type": "INITIAL"}], "receipt_number": "Pp3T", "receipt_url": "https://squareup.com/receipt/preview/Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "risk_evaluation": {"created_at": "2026-03-25T00:17:37.462Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 500, "currency": "CAD"}, "updated_at": "2026-03-25T00:17:39.470Z", "version": 6}}}}} +{"logged_at_utc": "2026-03-25T00:17:43.839682Z", "auto_apply_result": {"processed": false, "reason": "duplicate_payment_id", "payment_id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY"}, "source": "square_webhook_postprocess"} +{"logged_at_utc": "2026-03-25T00:19:42.535885Z", "signature_valid": true, "event_id": "46a1f931-6759-3039-8505-17c815d0c866", "event_type": "payment.updated", "payment_id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "payment_status": "COMPLETED", "amount_money": 500, "reference_id": null, "note": "Invoice INV-0023", "order_id": "69RxNIovUfaLxcPqc4A3CxojzMeZY", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "receipt_number": "Pp3T", "source_type": "CARD", "headers": {"x-square-hmacsha256-signature": true, "content-type": "application/json", "user-agent": "Square Connect v2"}, "raw_json": {"merchant_id": "R7SSS62AHJZ3B", "type": "payment.updated", "event_id": "46a1f931-6759-3039-8505-17c815d0c866", "created_at": "2026-03-25T00:19:40.711Z", "data": {"type": "payment", "id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "object": {"payment": {"amount_money": {"amount": 500, "currency": "CAD"}, "application_details": {"application_id": "sq0idp-w46nJ_NCNDMSOywaCY0mwA", "square_product": "ECOMMERCE_API"}, "approved_money": {"amount": 500, "currency": "CAD"}, "billing_address": {"first_name": "don", "last_name": "kingdon"}, "buyer_email_address": "def@etica-stats.org", "card_details": {"auth_result_code": "02119Z", "avs_status": "AVS_ACCEPTED", "card": {"bin": "544612", "card_brand": "MASTERCARD", "card_type": "CREDIT", "exp_month": 1, "exp_year": 2030, "fingerprint": "sq-1-0HCleVPC1ZYOjvq63GeaIbnaDfzJpyjZiXqjvfd2Wrpm18vTHq4pVFBQWT78yeo6cQ", "last_4": "0333", "payment_account_reference": "5001EL1YH45Y1GSAINIWNL7SJ2PUV", "prepaid_type": "NOT_PREPAID"}, "card_payment_timeline": {"authorized_at": "2026-03-25T00:17:37.289Z", "captured_at": "2026-03-25T00:17:37.554Z"}, "cvv_status": "CVV_ACCEPTED", "entry_method": "KEYED", "statement_description": "SQ *DK CONTRACTING", "status": "CAPTURED"}, "created_at": "2026-03-25T00:17:36.880Z", "customer_id": "93KDZQG8G3RCE2SK49Q68FZTW0", "delay_action": "CANCEL", "delay_duration": "PT168H", "delayed_until": "2026-04-01T00:17:36.880Z", "id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "location_id": "1TSPHT78106WX", "note": "Invoice INV-0023", "order_id": "69RxNIovUfaLxcPqc4A3CxojzMeZY", "processing_fee": [{"amount_money": {"amount": 44, "currency": "CAD"}, "effective_at": "2026-03-25T02:17:38.000Z", "type": "INITIAL"}], "receipt_number": "Pp3T", "receipt_url": "https://squareup.com/receipt/preview/Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY", "risk_evaluation": {"created_at": "2026-03-25T00:19:39.655Z", "risk_level": "NORMAL"}, "shipping_address": {"first_name": "don", "last_name": "kingdon"}, "source_type": "CARD", "status": "COMPLETED", "tip_money": {"amount": 0, "currency": "CAD"}, "total_money": {"amount": 500, "currency": "CAD"}, "updated_at": "2026-03-25T00:17:39.470Z", "version": 7}}}}} +{"logged_at_utc": "2026-03-25T00:19:42.537678Z", "auto_apply_result": {"processed": false, "reason": "duplicate_payment_id", "payment_id": "Pp3ToOksSRwWp7X1Ts6s7hQJ6yTZY"}, "source": "square_webhook_postprocess"} diff --git a/patch.sh b/patch.sh new file mode 100755 index 0000000..05219db --- /dev/null +++ b/patch.sh @@ -0,0 +1,80 @@ +cd /home/def/otb_billing || exit 1 +set -e + +STAMP="$(date +%Y%m%d-%H%M%S)" + +echo "===== backups =====" +cp templates/includes/site_nav.html "templates/includes/site_nav.html.bak.${STAMP}" +cp templates/portal_login.html "templates/portal_login.html.bak.${STAMP}" +cp templates/portal_dashboard.html "templates/portal_dashboard.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_set_password.html "templates/portal_set_password.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_terms.html "templates/portal_terms.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_invoice_detail.html "templates/portal_invoice_detail.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_forgot_password.html "templates/portal_forgot_password.html.bak.${STAMP}" 2>/dev/null || true + +echo "===== replace shared nav include from otb-shared-brand =====" +cp /opt/otb/otb-shared-brand/fragments/header.html templates/includes/site_nav.html + +echo "===== create shared portal statusbar include =====" +cat > templates/includes/otb_statusbar.html <<'EOF' +
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
+EOF + +echo "===== replace inline portal statusbars with include =====" +python3 <<'PY' +from pathlib import Path +import re + +files = [ + Path("templates/portal_login.html"), + Path("templates/portal_dashboard.html"), + Path("templates/portal_set_password.html"), + Path("templates/portal_terms.html"), + Path("templates/portal_invoice_detail.html"), + Path("templates/portal_forgot_password.html"), +] + +replacement = '{% include "includes/otb_statusbar.html" %}' + +for p in files: + if not p.exists(): + continue + text = p.read_text() + + new_text = re.sub( + r'
.*?
\s*', + replacement, + text, + count=1, + flags=re.S + ) + + if new_text != text: + p.write_text(new_text) + print(f"updated: {p}") + else: + print(f"no inline statusbar found: {p}") +PY + +echo "===== verify includes =====" +grep -n "video.outsidethebox.top" templates/includes/site_nav.html +grep -Rni 'includes/otb_statusbar.html' templates/portal_*.html | sed -n '1,50p' + +echo "===== restart service =====" +sudo systemctl restart otb-billing + +echo "===== quick verify from template side =====" +sed -n '1,40p' templates/includes/site_nav.html diff --git a/patch1.sh b/patch1.sh new file mode 100755 index 0000000..8a4bb42 --- /dev/null +++ b/patch1.sh @@ -0,0 +1,57 @@ +cd /home/def/otb_billing || exit 1 +set -e + +STAMP="$(date +%Y%m%d-%H%M%S)" + +cp templates/includes/otb_statusbar.html "templates/includes/otb_statusbar.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_login.html "templates/portal_login.html.bak.footer.${STAMP}" +cp templates/portal_dashboard.html "templates/portal_dashboard.html.bak.footer.${STAMP}" 2>/dev/null || true +cp templates/portal_set_password.html "templates/portal_set_password.html.bak.footer.${STAMP}" 2>/dev/null || true +cp templates/portal_terms.html "templates/portal_terms.html.bak.footer.${STAMP}" 2>/dev/null || true +cp templates/portal_invoice_detail.html "templates/portal_invoice_detail.html.bak.footer.${STAMP}" 2>/dev/null || true +cp templates/portal_forgot_password.html "templates/portal_forgot_password.html.bak.footer.${STAMP}" 2>/dev/null || true + +cat > templates/includes/otb_footer.html <<'EOF' +{% include "includes/otb_statusbar.html" %} + +EOF + +python3 <<'PY' +from pathlib import Path +import re + +files = [ + Path("templates/portal_login.html"), + Path("templates/portal_dashboard.html"), + Path("templates/portal_set_password.html"), + Path("templates/portal_terms.html"), + Path("templates/portal_invoice_detail.html"), + Path("templates/portal_forgot_password.html"), +] + +for p in files: + if not p.exists(): + continue + text = p.read_text() + + text = re.sub( + r'\{\%\s*include\s+"includes/otb_statusbar\.html"\s*\%\}\s*', + '{% include "includes/otb_footer.html" %}', + text, + count=1, + flags=re.S + ) + + text = re.sub( + r'\{\%\s*include\s+"includes/otb_statusbar\.html"\s*\%\}', + '{% include "includes/otb_footer.html" %}', + text, + count=1, + flags=re.S + ) + + p.write_text(text) + print(f"updated: {p}") +PY + +sudo systemctl restart otb_billing diff --git a/patch2.sh b/patch2.sh new file mode 100755 index 0000000..702f769 --- /dev/null +++ b/patch2.sh @@ -0,0 +1,102 @@ +cd /home/def/otb_billing || exit 1 +set -e + +STAMP="$(date +%Y%m%d-%H%M%S)" + +echo "===== backups =====" +cp templates/includes/site_nav.html "templates/includes/site_nav.html.bak.${STAMP}" +cp templates/includes/otb_statusbar.html "templates/includes/otb_statusbar.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_login.html "templates/portal_login.html.bak.${STAMP}" +cp templates/portal_dashboard.html "templates/portal_dashboard.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_set_password.html "templates/portal_set_password.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_terms.html "templates/portal_terms.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_invoice_detail.html "templates/portal_invoice_detail.html.bak.${STAMP}" 2>/dev/null || true +cp templates/portal_forgot_password.html "templates/portal_forgot_password.html.bak.${STAMP}" 2>/dev/null || true +cp static/css/style.css "static/css/style.css.bak.${STAMP}" 2>/dev/null || true +cp static/brand.js "static/brand.js.bak.${STAMP}" 2>/dev/null || true + +echo "===== sync shared nav/footer assets from mintme-backed shared brand =====" +cp /opt/otb/otb-shared-brand/fragments/header.html templates/includes/site_nav.html + +cat > templates/includes/otb_footer.html <<'EOF' +
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
+ +EOF + +echo "===== sync shared css/js =====" +cp /var/www/outsidethebox.top/assets/brand.js static/brand.js + +python3 <<'PY' +from pathlib import Path +src = Path("/var/www/outsidethebox.top/assets/style.css") +dst = Path("/home/def/otb_billing/static/css/style.css") +text = src.read_text() + +# keep the portal's own css file as the shared base for now +dst.write_text(text) +print("synced style.css from shared public shell") +PY + +echo "===== replace portal footer/statusbar blocks with shared footer include =====" +python3 <<'PY' +from pathlib import Path +import re + +files = [ + Path("templates/portal_login.html"), + Path("templates/portal_dashboard.html"), + Path("templates/portal_set_password.html"), + Path("templates/portal_terms.html"), + Path("templates/portal_invoice_detail.html"), + Path("templates/portal_forgot_password.html"), +] + +for p in files: + if not p.exists(): + continue + text = p.read_text() + + text = re.sub( + r'
.*?
\s*\s*', + '{% include "includes/otb_footer.html" %}', + text, + count=1, + flags=re.S + ) + + text = re.sub( + r'\{\%\s*include\s+"includes/otb_statusbar\.html"\s*\%\}\s*', + '{% include "includes/otb_footer.html" %}', + text, + count=1, + flags=re.S + ) + + text = re.sub( + r'\{\%\s*include\s+"includes/otb_statusbar\.html"\s*\%\}', + '{% include "includes/otb_footer.html" %}', + text, + count=1, + flags=re.S + ) + + p.write_text(text) + print(f"updated: {p}") +PY + +sudo systemctl restart otb_billing + +echo "===== done =====" diff --git a/patch3.sh b/patch3.sh new file mode 100755 index 0000000..d4e6a65 --- /dev/null +++ b/patch3.sh @@ -0,0 +1,174 @@ +cd /opt/otb_tracker || exit 1 +cat > /tmp/otb_tracker_shared_brand_patch.sh <<'EOF' +#!/usr/bin/env bash +set -euo pipefail + +APP_ROOT="/opt/otb_tracker" +SHARED_ROOT="/opt/otb/otb-shared-brand" +STAMP="$(date +%Y%m%d-%H%M%S)" + +cd "$APP_ROOT" || exit 1 + +echo "===== detect template/static roots =====" +TPL_ROOT="" +STATIC_ROOT="" + +if [ -d "$APP_ROOT/templates" ]; then + TPL_ROOT="$APP_ROOT/templates" +elif [ -d "$APP_ROOT/backend/templates" ]; then + TPL_ROOT="$APP_ROOT/backend/templates" +else + echo "ERROR: no templates dir found" + exit 1 +fi + +if [ -d "$APP_ROOT/static" ]; then + STATIC_ROOT="$APP_ROOT/static" +elif [ -d "$APP_ROOT/backend/static" ]; then + STATIC_ROOT="$APP_ROOT/backend/static" +else + echo "ERROR: no static dir found" + exit 1 +fi + +echo "Templates: $TPL_ROOT" +echo "Static: $STATIC_ROOT" + +echo "===== ensure shared brand exists and is current =====" +cd "$SHARED_ROOT" || exit 1 +git pull origin main +cd "$APP_ROOT" || exit 1 + +echo "===== backup =====" +mkdir -p "$APP_ROOT/backups/shared-brand-$STAMP" +cp -a "$TPL_ROOT" "$APP_ROOT/backups/shared-brand-$STAMP/templates" +cp -a "$STATIC_ROOT" "$APP_ROOT/backups/shared-brand-$STAMP/static" + +echo "===== create includes dir =====" +mkdir -p "$TPL_ROOT/includes" +mkdir -p "$STATIC_ROOT/css" + +echo "===== sync shared assets =====" +cp "$SHARED_ROOT/brand.css" "$STATIC_ROOT/css/brand.css" +cp "$SHARED_ROOT/brand.js" "$STATIC_ROOT/brand.js" + +echo "===== sync shared header include =====" +cp "$SHARED_ROOT/fragments/header.html" "$TPL_ROOT/includes/site_nav.html" + +echo "===== write canonical shared footer includes =====" +cat > "$TPL_ROOT/includes/otb_statusbar.html" <<'EOT' +
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
+EOT + +cat > "$TPL_ROOT/includes/otb_footer.html" <<'EOT' +{% include "includes/otb_statusbar.html" %} + +EOT + +echo "===== patch html templates =====" +python3 <)', + r'\\1\n ', + text, + count=1 + ) + text = re.sub( + r'()', + r'\\1\n ', + text, + count=1 + ) + + # normalize brand css/js cache versions + text = text.replace('/static/css/brand.css?v=0.3.5', '/static/css/brand.css?v=0.3.6') + text = text.replace('/static/css/brand.css?v=0.3.6?v=0.3.6', '/static/css/brand.css?v=0.3.6') + text = text.replace('/static/brand.js?v=0.3.5', '/static/brand.js?v=0.3.6') + text = text.replace('/static/brand.js?v=0.3.6?v=0.3.6', '/static/brand.js?v=0.3.6') + + # replace inline shared header block if present + text = re.sub( + r'', + '{% include "includes/site_nav.html" %}', + text, + count=1, + flags=re.S + ) + + # replace older nav block if present + text = re.sub( + r'
\s*\s*', + '{% include "includes/site_nav.html" %}\n', + text, + count=1, + flags=re.S + ) + + # if no shared nav include and no obvious header/nav remains, insert after + if '{% include "includes/site_nav.html" %}' not in text: + if '' in text: + text = text.replace('', '\n {% include "includes/site_nav.html" %}', 1) + + # replace inline statusbar/footer block with shared footer include + text = re.sub( + r'
.*?
\s*
\s*(\s*', + '\n', + text, + flags=re.S + ) + + # if footer include absent, append before + if '{% include "includes/otb_footer.html" %}' not in text: + text = text.replace('', ' {% include "includes/otb_footer.html" %}\n', 1) + + p.write_text(text, encoding="utf-8") + print(f"patched: {p}") +PY + +echo "===== restart service =====" +sudo systemctl restart otb-tracker.service + +echo "===== verify =====" +grep -Rni 'includes/site_nav.html\|includes/otb_footer.html\|/static/css/brand.css\|video.outsidethebox.top' "$TPL_ROOT" | sed -n '1,200p' +ls -l "$STATIC_ROOT/css/brand.css" "$STATIC_ROOT/brand.js" + +echo "===== done =====" +EOF + +chmod +x /tmp/otb_tracker_shared_brand_patch.sh +/tmp/otb_tracker_shared_brand_patch.sh diff --git a/patch4.sh b/patch4.sh new file mode 100755 index 0000000..52ac120 --- /dev/null +++ b/patch4.sh @@ -0,0 +1,143 @@ +cd /home/def/otb_billing || exit 1 + +cp templates/portal/services_here.html templates/portal/services_here.html.bak.$(date +%Y%m%d-%H%M%S) + +cat > templates/portal/services_here.html <<'EOF' + + + + + + Services - OutsideTheBox + + + + + + + +{% include "includes/site_nav.html" %} + +
+
+ +
+
+

Services

+

{{ client_name }}

+

Launch available OTB services from one place.

+
+ +
+ + +
+
Logged in as: {{ client_name }}
+
+
+
+ +
+ {% for service in services %} +
+
+
+

{{ service.name }}

+

{{ service.summary }}

+
+ +
+ {% if service.status == 'beta' %} + Beta + {% elif service.status == 'coming_soon' %} + Coming Soon + {% else %} + Available + {% endif %} +
+
+ +
+ {% if service.enabled %} + {{ service.button_text }} + {% else %} + + {% endif %} +
+
+ {% endfor %} +
+ +
+
+ + + +{% include "includes/otb_footer.html" %} + + + +EOF + +sudo systemctl restart otb_billing.service diff --git a/patch5.sh b/patch5.sh new file mode 100755 index 0000000..0204a77 --- /dev/null +++ b/patch5.sh @@ -0,0 +1,272 @@ +cd /home/def/otb_billing || exit 1 +set -e + +STAMP="$(date +%Y%m%d-%H%M%S)" + +cp templates/portal_dashboard.html "templates/portal_dashboard.html.bak.${STAMP}" +cp templates/portal/services_here.html "templates/portal/services_here.html.bak.${STAMP}" + +cat > templates/portal_base.html <<'EOF' + + + + + + {% block title %}Portal - OutsideTheBox{% endblock %} + + + + {% block head_extra %}{% endblock %} + + + {% include "includes/site_nav.html" %} + +
+
+ {% block portal_content %}{% endblock %} +
+
+ + {% block scripts %}{% endblock %} + + {% include "includes/otb_footer.html" %} + + +EOF + +cat > templates/portal_dashboard.html <<'EOF' +{% extends "portal_base.html" %} + +{% block title %}Client Dashboard - OutsideTheBox{% endblock %} + +{% block portal_content %} +
+
+

Client Dashboard

+

{{ client.company_name or client.contact_name or client.email }}

+

Invoices, balances, and account activity in one place.

+
+ +
+ +
+
Logged in as: {{ client.contact_name or client.company_name or client.email }}
+ {% if client_credit_balance and client_credit_balance != "0.00" %} +
+ + 🏦 Credit: ${{ client_credit_balance }} + +
+ {% endif %} +
+
+
+ +
+
+

Total Invoices

+
{{ invoice_count }}
+
Invoices currently visible in your portal
+
+ +
+

Total Outstanding

+
{{ total_outstanding }}
+
Current unpaid balance
+
+ +
+

Total Paid

+
{{ total_paid }}
+
Payments already applied
+
+
+ +

Invoices

+ +
+ + + + + + + + + + + + + {% for row in invoices %} + + + + + + + + + {% else %} + + + + {% endfor %} + +
InvoiceStatusCreatedTotalPaidOutstanding
+ + {{ row.invoice_number or ("INV-" ~ row.id) }} + + + {% set s = (row.status or "")|lower %} + {% if s == "paid" %} + {{ row.status }} + {% if row.payment_method_label %} +
+ {{ row.payment_method_label }} +
+ {% endif %} + {% elif s == "pending" %} + {{ row.status }} + {% elif s == "overdue" %} + {{ row.status }} + {% else %} + {{ row.status }} + {% endif %} +
{{ row.created_at }}{{ row.total_amount }}{{ row.amount_paid }}{{ row.outstanding }}
No invoices available.
+
+{% endblock %} + +{% block scripts %} + +{% endblock %} +EOF + +cat > templates/portal/services_here.html <<'EOF' +{% extends "portal_base.html" %} + +{% block title %}Services - OutsideTheBox{% endblock %} + +{% block portal_content %} +
+
+

Services

+

{{ client_name }}

+

Launch available OTB services from one place.

+
+ +
+ + +
+
Logged in as: {{ client_name }}
+
+
+
+ +
+ {% for service in services %} +
+
+
+

{{ service.name }}

+

{{ service.summary }}

+
+ +
+ {% if service.status == 'beta' %} + Beta + {% elif service.status == 'coming_soon' %} + Coming Soon + {% else %} + Available + {% endif %} +
+
+ +
+ {% if service.enabled %} + {{ service.button_text }} + {% else %} + + {% endif %} +
+
+ {% endfor %} +
+ + +{% endblock %} +EOF + +sudo systemctl restart otb_billing.service +sudo systemctl status otb_billing.service --no-pager -l | sed -n '1,30p' diff --git a/patch6.sh b/patch6.sh new file mode 100755 index 0000000..6163bcb --- /dev/null +++ b/patch6.sh @@ -0,0 +1,78 @@ +cd /home/def/otb_billing || exit 1 + +cp backend/routes/portal_services.py backend/routes/portal_services.py.bak.$(date +%Y%m%d-%H%M%S) + +cat > backend/routes/portal_services.py <<'EOF' +from flask import Blueprint, render_template, session, redirect, url_for, flash + +portal_services_bp = Blueprint("portal_services", __name__) + +def _portal_user_is_logged_in() -> bool: + return bool( + session.get("portal_user_id") + or session.get("client_user_id") + or session.get("portal_client_id") + or session.get("client_id") + or session.get("user_id") + ) + +@portal_services_bp.route("/portal/services") +def portal_services_home(): + if not _portal_user_is_logged_in(): + flash("Please sign in to access services.", "warning") + return redirect(url_for("portal_login")) + + client = { + "contact_name": session.get("portal_contact_name"), + "company_name": session.get("portal_company_name"), + "email": session.get("portal_email"), + } + + client_name = ( + client.get("contact_name") + or client.get("company_name") + or client.get("email") + or "Client" + ) + + services = [ + { + "key": "follow_me", + "name": "Follow-me Tracker", + "summary": "Create and manage your GPS tracking network. Free for up to 2 users.", + "status": "beta", + "enabled": True, + "href": "/follow-me", + "button_text": "Open Follow-me", + }, + { + "key": "video_render", + "name": "Video Rendering / Streaming", + "summary": "Submit video rendering, conversion, and hosted streaming jobs.", + "status": "coming_soon", + "enabled": False, + "href": "#", + "button_text": "Coming Soon", + }, + { + "key": "miner_rentals", + "name": "Miner Rentals", + "summary": "Rent available OTB hashpower by time or package.", + "status": "coming_soon", + "enabled": False, + "href": "#", + "button_text": "Coming Soon", + }, + ] + + return render_template( + "portal/services_here.html", + client=client, + client_name=client_name, + services=services, + ) +EOF + +python3 -m py_compile backend/routes/portal_services.py +sudo systemctl restart otb_billing.service +sudo systemctl status otb_billing.service --no-pager -l | sed -n '1,30p' diff --git a/patch7.sh b/patch7.sh new file mode 100755 index 0000000..37937e1 --- /dev/null +++ b/patch7.sh @@ -0,0 +1,157 @@ +cd /home/def/otb_billing || exit 1 +set -e + +STAMP="$(date +%Y%m%d-%H%M%S)" +NEW_VERSION="v0.6.0" +ZIP_NAME="otb_billing-${NEW_VERSION}.zip" + +echo "===== backups =====" +cp VERSION "VERSION.bak.${STAMP}" +cp README.md "README.md.bak.${STAMP}" +cp PROJECT_STATE.md "PROJECT_STATE.md.bak.${STAMP}" + +echo "===== version bump =====" +printf '%s\n' "${NEW_VERSION}" > VERSION + +echo "===== update README + PROJECT_STATE =====" +python3 <<'PY' +from pathlib import Path +from datetime import datetime, timezone + +root = Path("/home/def/otb_billing") +version = "v0.6.0" +stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") +utc_stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC") + +readme = root / "README.md" +project_state = root / "PROJECT_STATE.md" + +readme_text = readme.read_text() if readme.exists() else "" +project_text = project_state.read_text() if project_state.exists() else "" + +readme_entry = f"""## {version} - {stamp} + +### Highlights +- Added authenticated `/portal/services` page as a new service hub inside the billing portal. +- Added modular route file `backend/routes/portal_services.py` instead of expanding the main app with another large inline route block. +- Added shared `templates/portal_base.html` layout using Jinja `{% extends %}` / block pattern. +- Converted portal pages to the shared base-template structure for cleaner reuse and consistent branding. +- Added branded service cards for: + - Follow-me Tracker + - Video Rendering / Streaming + - Miner Rentals +- Fixed portal services layout so it uses the same nav, footer, styling, and light/dark toggle behavior as the working portal/dashboard pages. +- Corrected the Follow-me service link to use the real external service domain. +- Updated service launch buttons so external services open in a new tab. +- Improved portal services identity display to prepare for showing real logged-in client identity instead of a generic placeholder. + +### Notes +- This is the first successful rollout of the reusable `portal_base.html` structure and it should be used for future portal pages and future project builds. +- This release establishes the billing portal as the launch point for OTB services. + +""" + +project_entry = f"""# Project State Update - {version} +Updated: {utc_stamp} + +## Current Version +{version} + +## Current Status +OTB Billing has been advanced from a billing-only portal toward a unified service-launch platform. + +## Completed This Session +- Created `/portal/services` authenticated service hub. +- Added modular route file: `backend/routes/portal_services.py` +- Added shared Jinja portal base template: `templates/portal_base.html` +- Converted: + - `templates/portal_dashboard.html` + - `templates/portal/services_here.html` + to the new shared base-template architecture. +- Restored consistent OTB branding, nav, footer, spacing, and dark/light toggle behavior on the services page. +- Added service cards for: + - Follow-me Tracker (active/beta) + - Video Rendering / Streaming (coming soon) + - Miner Rentals (coming soon) +- Fixed service routing so Follow-me points to the real service domain. +- Updated external service launch links to open in a new tab. +- Confirmed the new shared template architecture is successful and should be reused in future pages/projects. + +## Architectural Direction +The portal now has a proven reusable pattern: +- `templates/portal_base.html` +- child templates using `{{% extends "portal_base.html" %}}` +- focused page content blocks instead of duplicating full HTML shell on each page + +This is now the preferred portal/page structure going forward. + +## Next Logical Steps +- Unify logged-in client identity handling across portal routes. +- Add real service-aware handoff / account linkage for Follow-me. +- Add future service cards/pages without duplicating layout shell. +- Move page-specific inline service-card CSS into shared stylesheet when ready. + +""" + +def prepend_once(existing: str, new_block: str, marker: str) -> str: + if marker in existing: + return existing + if existing.startswith("# "): + return existing.rstrip() + "\n\n" + new_block + return new_block + existing + +readme.write_text(prepend_once(readme_text, readme_entry, f"## {version} - ")) +project_state.write_text(prepend_once(project_text, project_entry, f"# Project State Update - {version}")) +PY + +echo "===== build full zip snapshot =====" +rm -f "releases/${ZIP_NAME}" +mkdir -p releases + +python3 <<'PY' +from pathlib import Path +import zipfile + +root = Path("/home/def/otb_billing") +zip_path = root / "releases" / "otb_billing-v0.6.0.zip" + +exclude_parts = { + ".git", + "__pycache__", + ".pytest_cache", +} + +exclude_suffixes = { + ".pyc", + ".pyo", +} + +with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf: + for path in root.rglob("*"): + rel = path.relative_to(root) + if any(part in exclude_parts for part in rel.parts): + continue + if path.suffix in exclude_suffixes: + continue + if path == zip_path: + continue + zf.write(path, arcname=str(Path("otb_billing-v0.6.0") / rel)) +print(zip_path) +PY + +echo "===== quick verify =====" +echo +echo "--- VERSION ---" +cat VERSION +echo +echo "--- README.md top 40 ---" +sed -n '1,40p' README.md +echo +echo "--- PROJECT_STATE.md top 60 ---" +sed -n '1,60p' PROJECT_STATE.md +echo +echo "--- ZIP snapshot ---" +ls -lh "releases/${ZIP_NAME}" +echo +echo "===== optional git review =====" +git status --short diff --git a/patch8.sh b/patch8.sh new file mode 100755 index 0000000..041cd89 --- /dev/null +++ b/patch8.sh @@ -0,0 +1,125 @@ +cd /home/def/otb_billing || exit 1 +set -e + +STAMP="$(date +%Y%m%d-%H%M%S)" +NEW_VERSION="v0.6.0" +ZIP_NAME="otb_billing-${NEW_VERSION}.zip" + +echo "===== backups =====" +cp VERSION "VERSION.bak.${STAMP}" +cp README.md "README.md.bak.${STAMP}" +cp PROJECT_STATE.md "PROJECT_STATE.md.bak.${STAMP}" + +echo "===== version bump =====" +printf '%s\n' "${NEW_VERSION}" > VERSION + +echo "===== update README + PROJECT_STATE =====" +python3 <<'PY' +from pathlib import Path +from datetime import datetime, timezone + +root = Path("/home/def/otb_billing") +version = "v0.6.0" +stamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") +utc_stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC") + +readme = root / "README.md" +project_state = root / "PROJECT_STATE.md" + +readme_text = readme.read_text() if readme.exists() else "" +project_text = project_state.read_text() if project_state.exists() else "" + +readme_entry = """## v0.6.0 - {stamp} + +### Highlights +- Added authenticated /portal/services page as a service hub +- Introduced modular route backend/routes/portal_services.py +- Created shared templates/portal_base.html layout +- Converted portal pages to base-template architecture +- Added service cards (Follow-me, Video, Miner Rentals) +- Fixed branding, nav, footer, and toggle consistency +- Corrected Follow-me external link +- External services now open in new tabs +- Improved identity display for logged-in user + +### Notes +- portal_base.html is now the standard structure for future pages and projects +- Billing portal is now the launch point for all OTB services + +""".replace("{stamp}", stamp) + +project_entry = """# Project State Update - v0.6.0 +Updated: {utc_stamp} + +## Current Version +v0.6.0 + +## Current Status +OTB Billing is now a service-launch platform, not just billing. + +## Completed This Session +- Added /portal/services page +- Added portal_services.py route module +- Created portal_base.html shared template +- Converted dashboard + services page to shared layout +- Restored consistent branding, nav, footer, toggle +- Added service cards (Follow-me, Video, Miner) +- Fixed external service routing +- Enabled new-tab launch for services + +## Architecture +Using shared base template: +templates/portal_base.html + +All pages now: +{% extends "portal_base.html" %} + +## Next Steps +- Unify client identity across all routes +- Add Follow-me provisioning + billing linkage +- Move inline CSS into shared styles later + +""".replace("{utc_stamp}", utc_stamp) + +def prepend(existing, new_block, marker): + if marker in existing: + return existing + if existing.startswith("# "): + return existing.rstrip() + "\n\n" + new_block + return new_block + existing + +readme.write_text(prepend(readme_text, readme_entry, "## v0.6.0")) +project_state.write_text(prepend(project_text, project_entry, "# Project State Update - v0.6.0")) +PY + +echo "===== build full zip snapshot =====" +rm -f "releases/${ZIP_NAME}" +mkdir -p releases + +python3 <<'PY' +from pathlib import Path +import zipfile + +root = Path("/home/def/otb_billing") +zip_path = root / "releases" / "otb_billing-v0.6.0.zip" + +exclude_parts = {".git", "__pycache__", ".pytest_cache"} +exclude_suffixes = {".pyc", ".pyo"} + +with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf: + for path in root.rglob("*"): + rel = path.relative_to(root) + if any(part in exclude_parts for part in rel.parts): + continue + if path.suffix in exclude_suffixes: + continue + if path == zip_path: + continue + zf.write(path, arcname=str(Path("otb_billing-v0.6.0") / rel)) + +print(zip_path) +PY + +echo "===== verify =====" +cat VERSION +ls -lh "releases/${ZIP_NAME}" diff --git a/run/otb_billing.err b/run/otb_billing.err new file mode 100644 index 0000000..6594f83 Binary files /dev/null and b/run/otb_billing.err differ diff --git a/run/otb_billing.out b/run/otb_billing.out new file mode 100644 index 0000000..5d577fd --- /dev/null +++ b/run/otb_billing.out @@ -0,0 +1,2 @@ + * Serving Flask app 'app' + * Debug mode: off diff --git a/static/brand.js b/static/brand.js index 9b37576..c971b62 100644 --- a/static/brand.js +++ b/static/brand.js @@ -1,44 +1,54 @@ (function () { - const STORAGE_KEY = "otb_theme"; const root = document.documentElement; + const KEY = "otb-theme"; - function getPreferredTheme() { - const saved = localStorage.getItem(STORAGE_KEY); - if (saved === "light" || saved === "dark") return saved; - return "dark"; + function applyTheme(theme) { + const resolved = theme === "light" ? "light" : "dark"; + root.setAttribute("data-theme", resolved); + document.body.classList.toggle("otb-dark", resolved === "dark"); + document.body.classList.toggle("otb-light", resolved === "light"); + + const toggle = document.getElementById("otbThemeToggle") || document.getElementById("themeToggle"); + if (toggle) toggle.checked = resolved === "light"; } - function applyTheme(theme) { - root.setAttribute("data-theme", theme); - const toggle = document.getElementById("otbThemeToggle"); - if (toggle) { - toggle.checked = theme === "dark"; + function savedTheme() { + try { + return localStorage.getItem(KEY) || "dark"; + } catch (e) { + return "dark"; } } function saveTheme(theme) { - localStorage.setItem(STORAGE_KEY, theme); + try { + localStorage.setItem(KEY, theme); + } catch (e) {} } - function initThemeToggle() { - const toggle = document.getElementById("otbThemeToggle"); - if (!toggle) return; + function setupMenu() { + const btn = document.getElementById("otbMenuToggle"); + const nav = document.getElementById("otbNavWrap"); + if (!btn || !nav) return; - toggle.addEventListener("change", function () { - const theme = toggle.checked ? "dark" : "light"; - applyTheme(theme); - saveTheme(theme); + btn.addEventListener("click", function () { + const open = nav.classList.toggle("otb-nav-open"); + btn.setAttribute("aria-expanded", open ? "true" : "false"); }); } - function init() { - applyTheme(getPreferredTheme()); - initThemeToggle(); - } + document.addEventListener("DOMContentLoaded", function () { + applyTheme(savedTheme()); - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", init); - } else { - init(); - } + const toggle = document.getElementById("otbThemeToggle") || document.getElementById("themeToggle"); + if (toggle) { + toggle.addEventListener("change", function () { + const next = toggle.checked ? "light" : "dark"; + saveTheme(next); + applyTheme(next); + }); + } + + setupMenu(); + }); })(); diff --git a/static/css/brand.css b/static/css/brand.css new file mode 100644 index 0000000..95e5365 --- /dev/null +++ b/static/css/brand.css @@ -0,0 +1,549 @@ +/* ===== OTB shared theme system ===== */ + +:root{ + --otb-bg-main:#050b19; + --otb-bg-grad-1:#1f2a57; + --otb-bg-grad-2:#08111f; + --otb-bg-grad-3:#143c2d; + --otb-panel:#0b1330; + --otb-text:#f1f5ff; + --otb-muted:#c5cde4; + --otb-link:#9fd2ff; + --otb-accent:#62f0cf; + --otb-border:rgba(255,255,255,0.08); + --otb-shadow:0 16px 40px rgba(0,0,0,0.28); +} + +html[data-theme="light"]{ + --otb-bg-main:#eef3fb; + --otb-bg-grad-1:#f7f9fd; + --otb-bg-grad-2:#edf3fb; + --otb-bg-grad-3:#e7f2ec; + --otb-panel:#ffffff; + --otb-text:#172033; + --otb-muted:#55627c; + --otb-link:#0b63ce; + --otb-accent:#0e8f73; + --otb-border:rgba(18,32,60,0.10); + --otb-shadow:0 10px 28px rgba(16,24,40,0.08); +} + +html, body{ + background: + linear-gradient(90deg, var(--otb-bg-grad-1) 0%, var(--otb-bg-grad-2) 48%, var(--otb-bg-grad-3) 100%), + var(--otb-bg-main) !important; + color:var(--otb-text) !important; +} + +a{ color:var(--otb-link); } + +.site-header{ background:transparent; } + +.site-brand strong, +.site-navlinks > a, +.dropdown-toggle, +.site-title strong, +.site-title span{ + color:var(--otb-text) !important; +} + +.site-title span, +.small, +.lead, +.sub, +.portal-sub, +.portal-note, +.muted{ + color:var(--otb-muted) !important; +} + +.card, +.heroCard, +.sideCard, +.feature, +.portal-card, +.detail-card, +.pay-card, +.snapshot-wrap, +.note, +.tableWrap{ + background:var(--otb-panel) !important; + border:1px solid var(--otb-border) !important; + color:var(--otb-text) !important; + box-shadow:var(--otb-shadow); +} + +.dropdown-menu{ + background:var(--otb-panel) !important; + border:1px solid var(--otb-border) !important; + box-shadow:var(--otb-shadow); +} + +.dropdown-menu a{ + color:var(--otb-text) !important; +} + +input, +select, +textarea{ + background:rgba(255,255,255,0.06) !important; + color:var(--otb-text) !important; + border:1px solid var(--otb-border) !important; +} + +html[data-theme="light"] input, +html[data-theme="light"] select, +html[data-theme="light"] textarea{ + background:#f6f8fc !important; +} + +::placeholder{ + color:var(--otb-muted); + opacity:0.85; +} + +.btn, +.portal-btn{ + border:1px solid var(--otb-border) !important; +} + +.otb-statusbar{ + background:#0b1326 !important; + border-top:1px solid rgba(255,255,255,0.06); +} + +.otb-statusbar-inner{ + max-width:1200px; + margin:0 auto; + padding:10px 18px; + color:#f3f7ff; + display:flex; + justify-content:center; + align-items:center; + gap:10px; + flex-wrap:wrap; + font-size:13px; + line-height:1.4; +} + +.otb-statusbar strong{ color:#f8fbff; } + +.otb-statusbar a{ + color:#62f0cf !important; + text-decoration:none; +} + +.otb-dot{ + width:4px; + height:4px; + border-radius:50%; + background:rgba(255,255,255,0.25); + display:inline-block; +} + +html[data-theme="light"] .otb-statusbar{ + background:#edf2fb !important; + border-top:1px solid rgba(18,32,60,0.08); +} + +html[data-theme="light"] .otb-statusbar-inner{ + color:#23314a; +} + +html[data-theme="light"] .otb-statusbar strong{ + color:#16233a; +} + +html[data-theme="light"] .otb-dot{ + background:rgba(23,32,51,0.22); +} + +.portal-shell, +.portal-wrap{ + max-width:1200px; + margin:0 auto; + padding:32px 20px 72px; +} + +.portal-card{ + max-width:760px; + margin:0 auto; +} + +@media (max-width: 1100px){ + .site-container, + .container{ + padding-left:16px !important; + padding-right:16px !important; + } + + .site-nav{ + display:flex; + flex-direction:column; + align-items:flex-start; + gap:14px; + } + + .site-nav-right{ + width:100%; + display:flex; + flex-direction:column; + align-items:flex-start; + gap:12px; + } + + .site-navlinks{ + width:100%; + display:flex; + flex-wrap:wrap; + gap:10px 16px; + align-items:center; + } + + .dropdown-menu{ + min-width:220px; + } + + .portal-shell, + .portal-wrap{ + padding:24px 16px 64px; + } +} + +@media (max-width: 640px){ + .site-brand img{ + width:48px; + height:48px; + } + + .site-title strong{ + font-size:20px; + } + + .site-title span{ + font-size:13px; + } + + .site-navlinks{ + gap:8px 14px; + } + + .otb-statusbar-inner{ + font-size:12px; + gap:8px; + padding:10px 12px; + } + + .portal-card{ + max-width:100%; + } +} + + + +/* ===== OTB hamburger nav ===== */ +.otb-menu-toggle{ + display:none !important; + margin-left:auto; + width:46px; + height:42px; + border:1px solid var(--otb-border); + background:rgba(255,255,255,0.04); + border-radius:12px; + padding:0; + align-items:center; + justify-content:center; + flex-direction:column; + gap:5px; + cursor:pointer; +} + +.otb-menu-toggle span{ + display:block; + width:20px; + height:2px; + background:var(--otb-text); + border-radius:2px; + transition:transform 0.2s ease, opacity 0.2s ease; +} + +.site-nav-right{ + display:flex; + align-items:center; + gap:16px; +} + +@media (max-width: 1100px){ + .otb-menu-toggle{ + display:flex !important; + } + + .site-nav{ + display:flex; + align-items:center; + justify-content:space-between; + gap:14px; + flex-wrap:wrap; + } + + .site-brand{ + min-width:0; + flex:1 1 auto; + } + + .site-nav-right{ + display:none; + width:100%; + flex-direction:column; + align-items:flex-start; + gap:14px; + padding-top:10px; + } + + .site-nav-right.otb-nav-open{ + display:flex; + } + + .site-navlinks{ + width:100%; + display:flex; + flex-direction:column; + align-items:flex-start; + gap:10px; + } + + .site-navlinks > a, + .dropdown{ + width:100%; + } + + .dropdown-toggle{ + display:inline-flex; + width:100%; + justify-content:flex-start; + } + + .dropdown-menu{ + position:static !important; + display:none; + min-width:0; + width:100%; + margin-top:8px; + } + + .dropdown:hover .dropdown-menu, + .dropdown:focus-within .dropdown-menu{ + display:block; + } +} + + + +/* ===== stronger mobile nav override ===== */ +@media (max-width: 1100px){ + .otb-menu-toggle{ + display:flex !important; + } + + .site-nav{ + display:flex !important; + align-items:center !important; + justify-content:space-between !important; + gap:14px !important; + flex-wrap:wrap !important; + } + + .site-nav-right{ + display:none !important; + width:100% !important; + flex-direction:column !important; + align-items:flex-start !important; + gap:14px !important; + padding-top:10px !important; + } + + .site-nav-right.otb-nav-open{ + display:flex !important; + } + + .site-navlinks{ + width:100% !important; + display:flex !important; + flex-direction:column !important; + align-items:flex-start !important; + gap:10px !important; + } + + .site-navlinks > a, + .dropdown{ + width:100% !important; + } + + .dropdown-toggle{ + width:100% !important; + justify-content:flex-start !important; + } + + .dropdown-menu{ + position:static !important; + min-width:0 !important; + width:100% !important; + margin-top:8px !important; + } +} + + +/* ===== desktop nav force ===== */ +@media (min-width: 1101px){ + .otb-menu-toggle{ + display:none !important; + } + + .site-nav-right{ + display:flex !important; + width:auto !important; + flex-direction:row !important; + align-items:center !important; + gap:16px !important; + padding-top:0 !important; + } + + .site-navlinks{ + display:flex !important; + flex-direction:row !important; + align-items:center !important; + width:auto !important; + gap:16px !important; + } +} + +/* ===== OTB hamburger hard fix ===== */ +.otb-menu-toggle{ + display:none !important; + appearance:none !important; + -webkit-appearance:none !important; + background:transparent !important; + border:0 !important; + box-shadow:none !important; + outline:none !important; + padding:0 !important; + margin:0 0 0 auto !important; + width:46px !important; + height:42px !important; + align-items:center !important; + justify-content:center !important; + flex-direction:column !important; + gap:5px !important; + cursor:pointer !important; +} + +.otb-menu-toggle::before, +.otb-menu-toggle::after{ + content:none !important; + display:none !important; +} + +.otb-menu-toggle span{ + display:block !important; + width:20px !important; + height:2px !important; + min-height:2px !important; + max-height:2px !important; + background:var(--otb-text) !important; + border-radius:2px !important; + margin:0 !important; + padding:0 !important; +} + +@media (min-width: 1101px){ + .otb-menu-toggle{ + display:none !important; + visibility:hidden !important; + pointer-events:none !important; + width:0 !important; + height:0 !important; + overflow:hidden !important; + } + + .site-nav-right{ + display:flex !important; + width:auto !important; + flex-direction:row !important; + align-items:center !important; + gap:16px !important; + padding-top:0 !important; + } + + .site-navlinks{ + display:flex !important; + flex-direction:row !important; + align-items:center !important; + width:auto !important; + gap:16px !important; + } +} + +@media (max-width: 1100px){ + .otb-menu-toggle{ + display:flex !important; + visibility:visible !important; + pointer-events:auto !important; + width:46px !important; + height:42px !important; + overflow:visible !important; + border:1px solid var(--otb-border) !important; + background:rgba(255,255,255,0.04) !important; + border-radius:12px !important; + } + + .site-nav{ + display:flex !important; + align-items:center !important; + justify-content:space-between !important; + gap:14px !important; + flex-wrap:wrap !important; + } + + .site-brand{ + min-width:0 !important; + flex:1 1 auto !important; + } + + .site-nav-right{ + display:none !important; + width:100% !important; + flex-direction:column !important; + align-items:flex-start !important; + gap:14px !important; + padding-top:10px !important; + } + + .site-nav-right.otb-nav-open{ + display:flex !important; + } + + .site-navlinks{ + width:100% !important; + display:flex !important; + flex-direction:column !important; + align-items:flex-start !important; + gap:10px !important; + } + + .site-navlinks > a, + .dropdown{ + width:100% !important; + } + + .dropdown-toggle{ + width:100% !important; + justify-content:flex-start !important; + } + + .dropdown-menu{ + position:static !important; + min-width:0 !important; + width:100% !important; + margin-top:8px !important; + } +} diff --git a/templates/base.html b/templates/base.html index c6df824..260f6b4 100644 --- a/templates/base.html +++ b/templates/base.html @@ -4,7 +4,7 @@ {{ page_title }} - + diff --git a/templates/includes/otb_footer.html b/templates/includes/otb_footer.html new file mode 100644 index 0000000..5858f0b --- /dev/null +++ b/templates/includes/otb_footer.html @@ -0,0 +1,2 @@ +{% include "includes/otb_statusbar.html" %} + diff --git a/templates/includes/otb_statusbar.html b/templates/includes/otb_statusbar.html new file mode 100644 index 0000000..c13121d --- /dev/null +++ b/templates/includes/otb_statusbar.html @@ -0,0 +1,14 @@ +
+
+ All billing is calculated in πŸ‡¨πŸ‡¦ CAD + + Crypto conversions use the OTB Oracle + + + Methods: + Credit Card (via Square), + e-Transfer, + and enabled crypto assets + +
+
diff --git a/templates/includes/site_nav.html b/templates/includes/site_nav.html index 7177302..6eb4baa 100644 --- a/templates/includes/site_nav.html +++ b/templates/includes/site_nav.html @@ -9,7 +9,13 @@ -