-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathapp.py
More file actions
2569 lines (2171 loc) · 105 KB
/
Copy pathapp.py
File metadata and controls
2569 lines (2171 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Invoice Management Web Application
Features: Save invoices, USD to EUR conversion, PDF generation, filtering
"""
from flask import Flask, render_template, request, redirect, url_for, send_file, flash, session, Response
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from functools import wraps
import io
import os
import sys
import hashlib
# When started with `python app.py`, this module is '__main__'. Register it
# under its import name as well, *before* any `from app import ...` runs (here
# or in plugin modules / InvoiceService). Otherwise that import re-executes this
# file as a separate 'app' module with a second SQLAlchemy()/db, and ORM calls
# made through the import fail with "current Flask app is not registered with
# this 'SQLAlchemy' instance". Aliasing keeps a single module/db.
if __name__ == '__main__':
sys.modules.setdefault('app', sys.modules['__main__'])
from currency_converter import get_exchange_rate, convert_usd_to_eur, get_currency_symbol
import logging
import logging.config
class _RequestIdFilter(logging.Filter):
"""Inject the current request id into log records for cross-worker tracing.
Falls back to '-' outside a request context."""
def filter(self, record):
try:
from flask import g, has_request_context
record.request_id = (getattr(g, 'request_id', '-')
if has_request_context() else '-')
except Exception:
record.request_id = '-'
return True
# Module-level logging config: applies whether started via
# `python app.py` or gunicorn — basicConfig in __main__ has no effect under
# gunicorn, so configure here at import time instead.
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'filters': {'request_id': {'()': _RequestIdFilter}},
'formatters': {
'default': {'format': '%(asctime)s [%(name)s] [%(request_id)s] %(levelname)s: %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S'},
},
'handlers': {
'console': {'class': 'logging.StreamHandler', 'formatter': 'default',
'filters': ['request_id']},
},
'root': {'level': 'INFO', 'handlers': ['console']},
})
logger = logging.getLogger(__name__)
app = Flask(__name__)
APP_VERSION = '1'
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
'DATABASE_URL', 'sqlite:///invoices.db')
# --- SECRET_KEY: require in production, warn in dev ---
_secret = os.environ.get('SECRET_KEY', '')
_is_dev = (os.environ.get('FLASK_DEBUG') == '1'
or os.environ.get('FLASK_ENV') == 'development')
if not _secret:
if _is_dev:
_secret = 'dev-only-insecure-key-' + hashlib.sha256(os.urandom(16)).hexdigest()
logger.warning('SECRET_KEY not set — using random dev key. Sessions will reset on restart.')
else:
# Fail hard in production: a random per-restart key silently invalidates
# every session on each container restart.
raise RuntimeError(
"SECRET_KEY environment variable is required in production. "
"Generate one with: "
"python -c \"import secrets; print(secrets.token_hex(32))\""
)
app.config['SECRET_KEY'] = _secret
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
from constants import MAX_CONTENT_LENGTH_BYTES, SESSION_LIFETIME_SECONDS
# --- Upload size cap: reject oversized bodies before they fill disk ---
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH_BYTES
# --- SQLAlchemy engine options: safe on SQLite, sane for Postgres ---
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
'pool_pre_ping': True, # verify a connection before use (avoids stale-conn errors)
'pool_recycle': 300, # recycle connections every 5 minutes
}
# --- Session security ---
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
_force_https = os.environ.get('FORCE_HTTPS', '').lower() in ('1', 'true', 'yes')
app.config['SESSION_COOKIE_SECURE'] = _force_https
app.config['PERMANENT_SESSION_LIFETIME'] = SESSION_LIFETIME_SECONDS
db = SQLAlchemy(app)
# --- SQLite pragmas: WAL for concurrent reads, enforce foreign keys.
# Listen on the generic Engine (works at import time, no app context needed); the
# isinstance check means it only touches SQLite connections. ---
from sqlalchemy import event as _sa_event
from sqlalchemy.engine import Engine as _SAEngine
import sqlite3 as _sqlite3
@_sa_event.listens_for(_SAEngine, 'connect')
def _set_sqlite_pragma(dbapi_conn, _connection_record):
if isinstance(dbapi_conn, _sqlite3.Connection):
cur = dbapi_conn.cursor()
cur.execute('PRAGMA journal_mode=WAL')
cur.execute('PRAGMA synchronous=NORMAL')
cur.execute('PRAGMA foreign_keys=ON')
cur.close()
# --- CSRF protection ---
try:
from flask_wtf.csrf import CSRFProtect, CSRFError
csrf = CSRFProtect(app)
except ImportError:
csrf = None
logger.warning('flask-wtf not installed — CSRF protection disabled')
# --- Rate limiting ---
try:
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
limiter = Limiter(
get_remote_address,
app=app,
default_limits=[],
storage_uri='memory://',
)
except ImportError:
limiter = None
logger.warning('flask-limiter not installed — rate limiting disabled')
# --- Optional Sentry error tracking (env-gated) ---
_sentry_dsn = os.environ.get('SENTRY_DSN')
if _sentry_dsn:
try:
import sentry_sdk
from sentry_sdk.integrations.flask import FlaskIntegration
sentry_sdk.init(dsn=_sentry_dsn, integrations=[FlaskIntegration()])
logger.info('Sentry error tracking enabled')
except ImportError:
logger.warning('SENTRY_DSN set but sentry-sdk not installed — skipping')
# --- Request correlation id (for tracing across interleaved worker logs) ---
@app.before_request
def _assign_request_id():
import uuid
from flask import g
g.request_id = uuid.uuid4().hex[:8]
@app.after_request
def _add_request_id_header(response):
from flask import g
rid = getattr(g, 'request_id', None)
if rid:
response.headers['X-Request-ID'] = rid
return response
# --- Security headers ---
@app.after_request
def set_security_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
# CSP in report-only first: the app emits inline styles/scripts and
# module-generated HTML, so report violations before enforcing. Tighten and
# switch to 'Content-Security-Policy' after auditing reports.
response.headers['Content-Security-Policy-Report-Only'] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"frame-ancestors 'none';"
)
if _force_https:
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
return response
# --- Error handlers ---
@app.errorhandler(404)
def page_not_found(e):
flash('Page not found', 'danger')
return redirect(url_for('dashboard'))
@app.errorhandler(500)
def internal_error(e):
db.session.rollback()
flash('Internal server error', 'danger')
return redirect(url_for('dashboard'))
@app.errorhandler(413)
def request_entity_too_large(e):
# friendly response instead of a stack trace when MAX_CONTENT_LENGTH
# is exceeded. JSON for the API, flash+redirect for the web UI.
if request.path.startswith('/api/'):
from flask import jsonify
return jsonify(error='payload_too_large',
message='Request body too large (max 50 MB)'), 413
flash('File too large. Maximum size is 50 MB.', 'danger')
# Redirect to a fixed internal page — never request.referrer — to avoid an
# open redirect via a crafted Referer header.
return redirect(url_for('dashboard'))
from jinja2.exceptions import TemplateNotFound
@app.errorhandler(TemplateNotFound)
def template_not_found(e):
flash('Page not found', 'danger')
return redirect(url_for('dashboard'))
# CSRF error handler
try:
from flask_wtf.csrf import CSRFError
@app.errorhandler(CSRFError)
def handle_csrf_error(e):
flash('Session expired or invalid request. Please try again.', 'danger')
# Redirect to a fixed internal page — never to request.referrer — so a
# crafted Referer can't drive an open redirect.
return redirect(url_for('dashboard'))
except ImportError:
pass # flask-wtf not installed — CSRF error handler not registered
# Module Manager - initialized after models are defined (see bottom of file)
module_manager = None
# --- Health probe: checks DB + storage, for Docker/uptime monitors ---
@app.route('/health')
def health_check():
from flask import jsonify
from sqlalchemy import text
checks = {'db': False, 'storage': False}
try:
db.session.execute(text('SELECT 1'))
checks['db'] = True
except Exception as e:
# Probe only: DB unreachable is reported via the 503 below, not raised.
logger.warning('health: db probe failed: %s', e)
try:
if module_manager is not None:
module_manager.core.storage.exists('__health_probe__')
checks['storage'] = True
except Exception as e:
# Probe only: storage backend unreachable is reported via the 503.
logger.warning('health: storage probe failed: %s', e)
return jsonify(checks), (200 if all(checks.values()) else 503)
def log_activity(action, category='system', details=None):
"""Log user/system activity via core logger (safe to call before init)"""
if module_manager:
module_manager.core.log_activity(action, category, details)
# Login required decorator
def login_required(f):
"""Decorator to require login for routes"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not session.get('authenticated'):
return redirect(url_for('auth.login'))
return f(*args, **kwargs)
return decorated_function
def find_customer_by_name(model, name):
"""Find a customer by normalized name (case-insensitive, stripped)."""
normalized = name.strip()
if not normalized:
return None
return model.query.filter(model.name.ilike(normalized)).first()
class Customer(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), nullable=False)
vat_number = db.Column(db.String(100))
address = db.Column(db.Text)
city = db.Column(db.String(100))
postal_code = db.Column(db.String(20))
country = db.Column(db.String(100))
email = db.Column(db.String(200))
phone = db.Column(db.String(50))
is_default = db.Column(db.Boolean, default=False)
tax_type = db.Column(db.String(20), default='eu_b2b') # non_eu, eu_b2b, standard
created_at = db.Column(db.DateTime, default=datetime.utcnow)
invoices = db.relationship('Invoice', backref='customer', lazy=True)
def __repr__(self):
return f'<Customer {self.name}>'
class Invoice(db.Model):
id = db.Column(db.Integer, primary_key=True)
invoice_number = db.Column(db.String(50), unique=True, nullable=False)
client_name = db.Column(db.String(200), nullable=False)
amount_usd = db.Column(db.Float, nullable=False)
amount_eur = db.Column(db.Float, nullable=False)
exchange_rate = db.Column(db.Float, nullable=False)
invoice_date = db.Column(db.Date, nullable=False)
due_date = db.Column(db.Date, nullable=True)
description = db.Column(db.Text)
quantity = db.Column(db.Float, default=1)
unit_price_usd = db.Column(db.Float, nullable=True)
notes = db.Column(db.Text)
status = db.Column(db.String(20), default='draft') # draft, issued, paid, cancelled (legacy: pending)
pdf_hash = db.Column(db.String(64)) # SHA256 hash of the PDF file
pdf_storage_key = db.Column(db.String(500)) # Storage key for PDF (local path or remote ID)
currency = db.Column(db.String(10), default='USD') # Invoice currency
payment_method = db.Column(db.String(100), default='Bank Transfer')
created_at = db.Column(db.DateTime, default=datetime.utcnow)
customer_id = db.Column(db.Integer, db.ForeignKey('customer.id'), nullable=True)
bank_id = db.Column(db.Integer, db.ForeignKey('bank.id'), nullable=True)
# F2 — lifecycle: series + per-series sequence assigned at ISSUE time.
series = db.Column(db.String(20))
sequence_number = db.Column(db.Integer)
issued_at = db.Column(db.DateTime)
# F2-D3 — facturas rectificativas linkage.
rectifies_invoice_id = db.Column(db.Integer, db.ForeignKey('invoice.id'), nullable=True)
rectification_type = db.Column(db.String(20)) # 'sustitucion' | 'diferencias'
# F2-D4 — fiscal snapshot frozen at issue (so later customer/settings edits
# never change an issued invoice's meaning).
snap_vat_rate = db.Column(db.Float)
snap_vat_amount = db.Column(db.Float)
snap_taxable_base = db.Column(db.Float)
snap_customer = db.Column(db.Text) # JSON: name, vat_number, country, tax_type
items = db.relationship('InvoiceItem', backref='invoice', lazy=True, cascade='all, delete-orphan',
foreign_keys='InvoiceItem.invoice_id')
def __repr__(self):
return f'<Invoice {self.invoice_number}>'
class InvoiceItem(db.Model):
id = db.Column(db.Integer, primary_key=True)
invoice_id = db.Column(db.Integer, db.ForeignKey('invoice.id'), nullable=False)
description = db.Column(db.Text, nullable=False)
quantity = db.Column(db.Float, nullable=False, default=1)
unit_price_usd = db.Column(db.Float, nullable=False)
subtotal_usd = db.Column(db.Float, nullable=False)
# F2-D4 — per-line VAT rate (nullable; defaults to the header rate at issue).
vat_rate = db.Column(db.Float)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return f'<InvoiceItem {self.description}>'
class Bank(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), nullable=False)
iban = db.Column(db.String(100), nullable=False)
swift = db.Column(db.String(50))
bank_name = db.Column(db.String(200))
is_default = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
invoices = db.relationship('Invoice', backref='bank', lazy=True)
def __repr__(self):
return f'<Bank {self.name}>'
class Settings(db.Model):
id = db.Column(db.Integer, primary_key=True)
# Personal/Business Info
business_name = db.Column(db.String(200))
owner_name = db.Column(db.String(200))
vat_number = db.Column(db.String(100))
nie_number = db.Column(db.String(100))
address = db.Column(db.Text)
city = db.Column(db.String(100))
postal_code = db.Column(db.String(20))
country = db.Column(db.String(100))
phone = db.Column(db.String(50))
email = db.Column(db.String(200))
# Other
default_payment_terms = db.Column(db.String(200))
default_description = db.Column(db.Text)
default_notes = db.Column(db.Text)
default_currency = db.Column(db.String(10), default='USD')
tracked_currencies = db.Column(db.Text, default='USD,EUR,GBP,CZK') # Comma-separated list
base_currency = db.Column(db.String(10), default='EUR') # Base currency for conversions and display
report_template = db.Column(db.String(100), default='official_template') # Report template name
invoice_template = db.Column(db.String(100), default='default_template') # Invoice PDF template name
# Dashboard settings
show_currency_panel = db.Column(db.Boolean, default=True) # Show currency/holidays panel on dashboard
show_tax_panel = db.Column(db.Boolean, default=True) # Show tax obligations panel on dashboard
# Backup settings
auto_backup_enabled = db.Column(db.Boolean, default=False) # Enable automatic backup on startup
backup_retention_count = db.Column(db.Integer, default=5) # Number of backups to keep (deprecated, use daily_backup_retention_count)
daily_backup_retention_count = db.Column(db.Integer, default=4) # Number of daily backups to keep
# Social Security settings
social_security_monthly = db.Column(db.Float, default=0.0) # Monthly SS quota (cuota autónomo)
# Logging settings
log_path = db.Column(db.String(500), default='') # Custom log directory
log_retention_days = db.Column(db.Integer, default=30) # 0 = keep forever
log_use_external_storage = db.Column(db.Boolean, default=False)
log_storage = db.Column(db.String(10), default='file') # 'file' or 'db'
# Tax rates (configurable per country)
default_vat_rate = db.Column(db.Float, default=21.0) # VAT/IVA rate in %
default_irpf_rate = db.Column(db.Float, default=20.0) # Income tax retention rate in %
# Currency provider settings
currency_provider = db.Column(db.String(50), default='ecb') # Active exchange rate provider
currency_provider_api_key = db.Column(db.String(200), default='') # API key for providers that need it
payment_methods = db.Column(db.Text, default='Bank Transfer,PayPal,Credit Card,Cash,Crypto')
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
def __repr__(self):
return f'<Settings {self.business_name}>'
class Contractor(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(200), nullable=False)
vat_number = db.Column(db.String(100))
address = db.Column(db.Text)
city = db.Column(db.String(100))
postal_code = db.Column(db.String(20))
country = db.Column(db.String(100))
email = db.Column(db.String(200))
phone = db.Column(db.String(50))
notes = db.Column(db.Text)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
expenses = db.relationship('Expense', backref='contractor', lazy=True)
def __repr__(self):
return f'<Contractor {self.name}>'
class Expense(db.Model):
id = db.Column(db.Integer, primary_key=True)
contractor_id = db.Column(db.Integer, db.ForeignKey('contractor.id'))
amount = db.Column(db.Float, nullable=False) # gross total (kept for back-compat)
currency = db.Column(db.String(10), default='EUR')
category = db.Column(db.String(100))
description = db.Column(db.Text)
expense_date = db.Column(db.Date, nullable=False)
file_path = db.Column(db.String(500))
invoice_number = db.Column(db.String(100))
notes = db.Column(db.Text)
# F4 — VAT breakdown & deductibility. NULL on legacy rows = "VAT unknown"
# (excluded from Modelo 303 deductible math with a visible nudge).
net_amount = db.Column(db.Float) # taxable base (gross - vat)
vat_rate = db.Column(db.Float) # IVA soportado rate, %
vat_amount = db.Column(db.Float) # IVA soportado amount
deductible = db.Column(db.Boolean, default=True)
deductible_pct = db.Column(db.Float, default=100.0)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return f'<Expense {self.id} - {self.amount} {self.currency}>'
class TaxForm(db.Model):
id = db.Column(db.Integer, primary_key=True)
form_type = db.Column(db.String(50), nullable=False) # 349, 390, 303, 130, 100
year = db.Column(db.Integer, nullable=False)
quarter = db.Column(db.Integer) # 1-4 for quarterly forms, NULL for annual
file_path = db.Column(db.String(500), nullable=False)
original_filename = db.Column(db.String(200))
uploaded_at = db.Column(db.DateTime, default=datetime.utcnow)
notes = db.Column(db.Text)
def __repr__(self):
if self.quarter:
return f'<TaxForm {self.form_type}-Q{self.quarter} {self.year}>'
return f'<TaxForm {self.form_type} {self.year}>'
class Document(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(300), nullable=False)
source = db.Column(db.String(100)) # Agencia Tributaria, Seguridad Social, etc.
document_date = db.Column(db.Date)
description = db.Column(db.Text)
file_path = db.Column(db.String(500), nullable=False)
original_filename = db.Column(db.String(300))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return f'<Document {self.name}>'
class SSPayment(db.Model):
id = db.Column(db.Integer, primary_key=True)
payment_date = db.Column(db.Date, nullable=False)
amount = db.Column(db.Float, nullable=False)
description = db.Column(db.String(300))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return f'<SSPayment {self.payment_date} {self.amount}>'
@app.route('/customers')
@login_required
def customers():
"""Redirect to settings page where customers are now managed"""
return redirect(url_for('settings') + '#customers')
@app.route('/customers/create', methods=['GET', 'POST'])
@login_required
def create_customer():
if request.method == 'POST':
customer = Customer(
name=request.form['name'],
vat_number=request.form.get('vat_number'),
address=request.form.get('address'),
city=request.form.get('city'),
postal_code=request.form.get('postal_code'),
country=request.form.get('country'),
email=request.form.get('email'),
phone=request.form.get('phone'),
tax_type=request.form.get('tax_type', 'eu_b2b')
)
db.session.add(customer)
db.session.commit()
flash('Customer created successfully!', 'success')
return redirect(url_for('settings') + '#customers')
return render_template('customer_form.html', customer=None)
@app.route('/customers/<int:id>')
@login_required
def view_customer(id):
customer = Customer.query.get_or_404(id)
# Get base currency from settings
app_settings = Settings.query.first()
base_currency = app_settings.base_currency if app_settings and app_settings.base_currency else 'EUR'
base_currency_symbol = get_currency_symbol(base_currency)
return render_template('customer_view.html', customer=customer,
base_currency=base_currency,
base_currency_symbol=base_currency_symbol)
@app.route('/customers/<int:id>/edit', methods=['GET', 'POST'])
@login_required
def edit_customer(id):
customer = Customer.query.get_or_404(id)
if request.method == 'POST':
customer.name = request.form['name']
customer.vat_number = request.form.get('vat_number')
customer.address = request.form.get('address')
customer.city = request.form.get('city')
customer.postal_code = request.form.get('postal_code')
customer.country = request.form.get('country')
customer.email = request.form.get('email')
customer.phone = request.form.get('phone')
customer.tax_type = request.form.get('tax_type', 'eu_b2b')
db.session.commit()
flash('Customer updated successfully!', 'success')
return redirect(url_for('view_customer', id=customer.id))
return render_template('customer_form.html', customer=customer)
@app.route('/customers/<int:id>/delete')
@login_required
def delete_customer(id):
customer = Customer.query.get_or_404(id)
db.session.delete(customer)
db.session.commit()
flash('Customer deleted successfully!', 'success')
return redirect(url_for('settings') + '#customers')
def _get_upcoming_tax_deadlines():
"""
Get upcoming Spanish Autónomo tax deadlines grouped by date.
If a deadline falls on weekend, it moves to the next business day.
"""
from datetime import date, timedelta
today = date.today()
year = today.year
# All deadlines: (date, list of forms)
raw_deadlines = [
(date(year, 1, 20), [
('130, 303, 349', f'Q4 {year-1}'),
]),
(date(year, 1, 30), [
('390', f'Annual VAT {year-1}'),
]),
(date(year, 4, 20), [
('130, 303, 349', f'Q1 {year}'),
]),
(date(year, 6, 30), [
('100', f'Renta {year-1}'),
]),
(date(year, 7, 20), [
('130, 303, 349', f'Q2 {year}'),
]),
(date(year, 10, 20), [
('130, 303, 349', f'Q3 {year}'),
]),
(date(year + 1, 1, 20), [
('130, 303, 349', f'Q4 {year}'),
]),
(date(year + 1, 1, 30), [
('390', f'Annual VAT {year}'),
]),
]
def adjust_to_business_day(d):
while d.weekday() >= 5:
d += timedelta(days=1)
return d
upcoming = []
for deadline_date, forms in raw_deadlines:
adjusted = adjust_to_business_day(deadline_date)
if adjusted >= today:
days_left = (adjusted - today).days
upcoming.append({
'date': adjusted.strftime('%d/%m/%Y'),
'days_left': days_left,
'urgent': days_left <= 14,
'forms': forms,
})
upcoming.sort(key=lambda x: x['days_left'])
return upcoming[:4]
@app.route('/')
@login_required
def dashboard():
"""Main dashboard page with invoice summary table"""
# Get all invoices with valid invoice_date
invoices = Invoice.query.filter(Invoice.invoice_date != None).order_by(Invoice.invoice_date.desc()).all()
# Additional safety check - filter out any None objects or invoices with None dates
invoices = [inv for inv in invoices if inv is not None and hasattr(inv, 'invoice_date') and inv.invoice_date is not None]
# Get settings for tracked currencies and base currency
app_settings = Settings.query.first()
tracked_currencies = []
base_currency = 'EUR'
if app_settings:
if app_settings.tracked_currencies:
tracked_currencies = [c.strip() for c in app_settings.tracked_currencies.split(',') if c.strip()]
else:
tracked_currencies = ['USD', 'EUR', 'GBP', 'CZK']
base_currency = app_settings.base_currency or 'EUR'
else:
tracked_currencies = ['USD', 'EUR', 'GBP', 'CZK']
# Get current exchange rates for tracked currencies
from datetime import date
from currency_converter import get_multiple_exchange_rates
today = date.today().strftime('%Y-%m-%d')
exchange_rates = get_multiple_exchange_rates(today, tracked_currencies, base_currency=base_currency)
# Currency symbols
base_currency_symbol = get_currency_symbol(base_currency)
# Tax rate from settings (default 20% for backward compat)
tax_rate = (app_settings.default_irpf_rate / 100.0) if app_settings and app_settings.default_irpf_rate is not None else 0.20
# Group invoices by year and quarter
invoices_by_year = {}
for invoice in invoices:
if not invoice or not hasattr(invoice, 'invoice_date') or invoice.invoice_date is None:
continue # Skip if somehow None
year = invoice.invoice_date.year
quarter = (invoice.invoice_date.month - 1) // 3 + 1 # Q1, Q2, Q3, Q4
if year not in invoices_by_year:
invoices_by_year[year] = {}
if quarter not in invoices_by_year[year]:
invoices_by_year[year][quarter] = []
# Calculate amounts in base currency
if base_currency == 'EUR':
invoice.amount_base = invoice.amount_eur
elif base_currency == 'USD':
invoice.amount_base = invoice.amount_usd
else:
# Convert from EUR to base currency
# exchange_rates gives us "1 base_currency = X EUR"
# So to convert EUR to base_currency: EUR_amount / EUR_rate
eur_rate = exchange_rates.get('EUR', 1.0)
if eur_rate > 0:
invoice.amount_base = invoice.amount_eur / eur_rate
else:
invoice.amount_base = invoice.amount_eur
# Calculate display rate (invoice currency to base currency)
invoice_currency = invoice.currency or 'USD'
if invoice_currency == base_currency:
# Same currency
invoice.display_rate = 1.0
elif invoice_currency == 'EUR' and base_currency == 'USD':
# EUR to USD
invoice.display_rate = invoice.amount_usd / invoice.amount_eur if invoice.amount_eur > 0 else 1.0
elif invoice_currency == 'USD' and base_currency == 'EUR':
# USD to EUR
invoice.display_rate = invoice.amount_eur / invoice.amount_usd if invoice.amount_usd > 0 else 1.0
elif invoice_currency == 'EUR':
# EUR to other currency
eur_rate = exchange_rates.get('EUR', 1.0)
invoice.display_rate = 1 / eur_rate if eur_rate > 0 else 1.0
elif invoice_currency == 'USD':
# USD to other currency (via EUR)
eur_rate = exchange_rates.get('EUR', 1.0)
usd_to_eur = invoice.amount_eur / invoice.amount_usd if invoice.amount_usd > 0 else 1.0
invoice.display_rate = usd_to_eur / eur_rate if eur_rate > 0 else 1.0
else:
# Fallback
invoice.display_rate = 1.0
# Calculate tax for each invoice
invoice.tax_usd = invoice.amount_usd * tax_rate
invoice.tax_eur = invoice.amount_eur * tax_rate
invoice.tax_base = invoice.amount_base * tax_rate
invoice.quarterly_sum_usd = invoice.amount_usd
invoices_by_year[year][quarter].append(invoice)
# Calculate quarter totals
quarter_totals = {}
for year in invoices_by_year:
quarter_totals[year] = {}
for quarter, quarter_invoices in invoices_by_year[year].items():
quarter_totals[year][quarter] = {
'sum_usd': sum(inv.amount_usd for inv in quarter_invoices),
'sum_eur': sum(inv.amount_eur for inv in quarter_invoices),
'sum_base': sum(inv.amount_base for inv in quarter_invoices),
'quarterly_sum_usd': sum(inv.amount_usd for inv in quarter_invoices),
'tax_usd': sum(inv.amount_usd * tax_rate for inv in quarter_invoices),
'tax_eur': sum(inv.amount_eur * tax_rate for inv in quarter_invoices),
'tax_base': sum(inv.amount_base * tax_rate for inv in quarter_invoices),
'quarterly_tax_usd': sum(inv.amount_usd * tax_rate for inv in quarter_invoices)
}
# Calculate year totals
year_totals = {}
for year in invoices_by_year:
all_year_invoices = []
for quarter_invoices in invoices_by_year[year].values():
all_year_invoices.extend(quarter_invoices)
year_totals[year] = {
'sum_usd': sum(inv.amount_usd for inv in all_year_invoices),
'sum_eur': sum(inv.amount_eur for inv in all_year_invoices),
'sum_base': sum(inv.amount_base for inv in all_year_invoices),
'quarterly_sum_usd': sum(inv.amount_usd for inv in all_year_invoices),
'tax_usd': sum(inv.amount_usd * tax_rate for inv in all_year_invoices),
'tax_eur': sum(inv.amount_eur * tax_rate for inv in all_year_invoices),
'tax_base': sum(inv.amount_base * tax_rate for inv in all_year_invoices),
'quarterly_tax_usd': sum(inv.amount_usd * tax_rate for inv in all_year_invoices)
}
# Calculate grand totals
totals = {
'sum_usd': sum(inv.amount_usd for inv in invoices),
'sum_eur': sum(inv.amount_eur for inv in invoices),
'sum_base': sum(inv.amount_base for inv in invoices),
'quarterly_sum_usd': sum(inv.amount_usd for inv in invoices),
'tax_usd': sum(inv.amount_usd * tax_rate for inv in invoices),
'tax_eur': sum(inv.amount_eur * tax_rate for inv in invoices),
'tax_base': sum(inv.amount_base * tax_rate for inv in invoices),
'quarterly_tax_usd': sum(inv.amount_usd * tax_rate for inv in invoices)
}
# Calculate stats
stats = {
'total_count': len(invoices),
'total_usd': sum(inv.amount_usd for inv in invoices),
'total_eur': sum(inv.amount_eur for inv in invoices),
'total_base': sum(inv.amount_base for inv in invoices),
'pending_count': len([inv for inv in invoices if inv.status == 'pending'])
}
# Calculate current year tax obligations
from datetime import datetime
current_year = datetime.now().year
current_year_invoices = [inv for inv in invoices if inv.invoice_date.year == current_year and inv.status == 'paid']
# Income for current year
current_year_income = sum(inv.amount_base for inv in current_year_invoices)
# VAT collected — let modules override, fallback to configured rate
vat_rate = (app_settings.default_vat_rate or 21.0) / 100.0 if app_settings else 0.21
vat_collected = 0
if module_manager:
vat_override = module_manager.calculate_vat({
'invoices': current_year_invoices,
'settings': app_settings,
'base_currency': base_currency,
})
if vat_override:
vat_collected = vat_override['vat_collected']
vat_rate = vat_override.get('vat_rate', vat_rate)
if not vat_collected:
for inv in current_year_invoices:
if inv.customer and inv.customer.tax_type == 'standard':
vat_collected += inv.amount_base * vat_rate
# Collect tax obligation contributions from enabled modules
module_deductions = 0
module_tax_total = 0
module_summary_columns = []
module_breakdown_rows = []
module_notes = []
if module_manager:
tax_context = {
'current_year': current_year,
'base_currency': base_currency,
'exchange_rates': exchange_rates,
'settings': app_settings,
'vat_collected': vat_collected,
'currency_symbol': base_currency_symbol
}
for item in module_manager.get_tax_obligations(tax_context):
module_deductions += item.get('deductions', 0)
module_tax_total += item.get('tax_total', 0)
module_summary_columns.extend(item.get('summary_columns', []))
module_breakdown_rows.extend(item.get('breakdown_rows', []))
module_notes.extend(item.get('notes', []))
# Calculate taxable income (income - deductions from modules)
taxable_income = current_year_income - module_deductions
# Income tax — let modules override, fallback to Spanish IRPF brackets
income_tax = 0
irpf_breakdown = []
income_tax_label = 'Income Tax (IRPF)'
if module_manager:
tax_override = module_manager.calculate_income_tax({
'taxable_income': taxable_income,
'settings': app_settings,
'base_currency': base_currency,
'currency_symbol': base_currency_symbol,
})
if tax_override:
income_tax = tax_override['income_tax']
irpf_breakdown = tax_override.get('irpf_breakdown', [])
income_tax_label = tax_override.get('label', 'Income Tax')
if not income_tax and not irpf_breakdown and taxable_income > 0:
# Default: Spanish IRPF progressive brackets
brackets = [
(12450, 0.19, '€0 - €12,450'),
(20200, 0.24, '€12,450 - €20,200'),
(35200, 0.30, '€20,200 - €35,200'),
(60000, 0.37, '€35,200 - €60,000'),
(float('inf'), 0.45, '€60,000+'),
]
prev_limit = 0
for limit, rate, label in brackets:
if taxable_income <= prev_limit:
break
amount = min(taxable_income, limit) - prev_limit
tax = amount * rate
income_tax += tax
active = taxable_income <= limit
irpf_breakdown.append({
'bracket': label, 'rate': rate * 100,
'amount': amount, 'tax': tax, 'active': active,
})
prev_limit = limit
# Total tax obligations = IRPF + module contributions (VAT, SS, etc.)
total_tax_obligations = income_tax + module_tax_total
tax_breakdown = {
'current_year': current_year,
'income': current_year_income,
'taxable_income': taxable_income,
'income_tax': income_tax,
'income_tax_label': income_tax_label,
'irpf_breakdown': irpf_breakdown,
'summary_columns': module_summary_columns,
'breakdown_rows': module_breakdown_rows,
'notes': module_notes,
'total_obligations': total_tax_obligations
}
# Sort years in descending order
sorted_years = sorted(invoices_by_year.keys(), reverse=True)
# Get public holidays from Nager.Date API
holidays = []
try:
import requests
from datetime import datetime
current_year = datetime.now().year
country_code = app_settings.country_code if app_settings and hasattr(app_settings, 'country_code') and app_settings.country_code else 'ES'
response = requests.get(f'https://date.nager.at/api/v3/PublicHolidays/{current_year}/{country_code}', timeout=3)
if response.status_code == 200:
all_holidays = response.json()
today_date = datetime.now().date()
upcoming = [h for h in all_holidays if datetime.strptime(h['date'], '%Y-%m-%d').date() >= today_date]
holidays = upcoming[:3]
except Exception:
logger.exception("Failed to fetch public holidays from Nager.Date API")
# Tax deadlines for Spanish Autónomo
from datetime import date, timedelta
tax_deadlines = _get_upcoming_tax_deadlines()
# Collect module dashboard panels
module_panels = []
if module_manager:
module_panels = module_manager.get_dashboard_panels()
module_panels.sort(key=lambda p: p.get('order', 50))
return render_template('dashboard.html',
invoices_by_year=invoices_by_year,
sorted_years=sorted_years,
quarter_totals=quarter_totals,
year_totals=year_totals,
totals=totals,
stats=stats,
tax_breakdown=tax_breakdown,
exchange_rates=exchange_rates,
tracked_currencies=tracked_currencies,
base_currency=base_currency,
base_currency_symbol=base_currency_symbol,
tax_rate_pct=tax_rate * 100,
current_date=today,
holidays=holidays,
tax_deadlines=tax_deadlines,
settings=app_settings,
module_panels=module_panels)
@app.route('/invoices')
@login_required
def index():
from sqlalchemy import select
status_filter = request.args.get('status', '')
client_filter = request.args.get('client', '')
invoice_number_filter = request.args.get('invoice_number', '')
date_from = request.args.get('date_from', '')
date_to = request.args.get('date_to', '')
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 20, type=int)
sort_by = request.args.get('sort_by', 'invoice_date')
sort_order = request.args.get('sort_order', 'desc')
# Build select statement
stmt = select(Invoice).where(Invoice.id != None)
if status_filter:
stmt = stmt.where(Invoice.status == status_filter)
if client_filter:
stmt = stmt.where(Invoice.client_name.ilike(f'%{client_filter}%'))
if invoice_number_filter:
stmt = stmt.where(Invoice.invoice_number.ilike(f'%{invoice_number_filter}%'))
if date_from:
stmt = stmt.where(Invoice.invoice_date >= datetime.strptime(date_from, '%Y-%m-%d').date())
if date_to:
stmt = stmt.where(Invoice.invoice_date <= datetime.strptime(date_to, '%Y-%m-%d').date())
# Apply sorting
sort_column = getattr(Invoice, sort_by, Invoice.invoice_date)
if sort_order == 'asc':
stmt = stmt.order_by(sort_column.asc())
else: