-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2632 lines (2191 loc) · 94.5 KB
/
app.py
File metadata and controls
2632 lines (2191 loc) · 94.5 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
from __future__ import annotations
import csv
import io
import logging
import os
import re
import secrets
import sqlite3
import sys
import threading
from collections.abc import Iterable
from contextlib import closing
from datetime import datetime, timedelta
from functools import wraps
from pathlib import Path
from typing import Any
from flask import Flask, Response, flash, g, has_app_context, redirect, render_template, request, send_file, session, url_for
from werkzeug.security import check_password_hash, generate_password_hash
from core.access_control import VALID_ROLES, has_permission
try:
from openpyxl import Workbook
except Exception:
Workbook = None
try:
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
except Exception:
A4 = None
pdfmetrics = None
TTFont = None
canvas = None
try:
from waitress import serve as waitress_serve
except Exception:
waitress_serve = None
SOURCE_DIR = Path(__file__).resolve().parent
IS_FROZEN = getattr(sys, 'frozen', False)
BASE_DIR = Path(getattr(sys, '_MEIPASS', SOURCE_DIR)).resolve() if IS_FROZEN else SOURCE_DIR
def resolve_data_dir() -> Path:
if not IS_FROZEN:
return SOURCE_DIR
explicit = (os.getenv('INFINANCE_DATA_DIR') or '').strip()
if explicit:
return Path(explicit).expanduser().resolve()
local_app_data = (os.getenv('LOCALAPPDATA') or '').strip()
if local_app_data:
return Path(local_app_data).resolve() / 'INFinance'
return Path(sys.executable).resolve().parent
DATA_DIR = resolve_data_dir()
DATA_DIR.mkdir(parents=True, exist_ok=True)
DATABASE = DATA_DIR / 'infinance.db'
PDF_FONT_NAME = 'INFinanceUnicode'
SECRET_FILE = DATA_DIR / '.infinance.secret'
_BOOTSTRAP_LOCK = threading.Lock()
_BOOTSTRAP_ONCE = threading.Event()
AUTHORS = [
{
'name': 'INformigados',
'role': 'Criador e desenvolvedor principal',
'github_url': 'https://github.com/informigados',
'github_display': 'github.com/informigados',
'image': 'images/authors/informigados.webp',
},
{
'name': 'Alex Brito',
'role': 'Co-desenvolvedor',
'github_url': 'https://github.com/AlexBritoDEV',
'github_display': 'github.com/AlexBritoDEV',
'image': 'images/authors/alex-brito-dev.webp',
},
]
PUBLIC_ENDPOINTS = {
'static',
'login',
'favicon_legacy',
}
POST_LOGIN_ENDPOINTS = {
'dashboard',
'about',
'company',
'clients',
'services',
'transactions',
'expenses',
'simulator',
'das_advanced',
'monthly_report',
'users',
}
POST_LOGIN_SESSION_KEY = '_post_login_endpoint'
ADMIN_ENDPOINTS = {
'users',
'update_user_role',
'reset_user_password',
}
WRITE_METHODS = {'POST', 'PUT', 'PATCH', 'DELETE'}
WRITE_EXEMPT_ENDPOINTS = {'logout'}
CLIENTS_PER_PAGE = 12
SERVICES_PER_PAGE = 12
TRANSACTIONS_PER_PAGE = 20
EXPENSES_PER_PAGE = 20
CSRF_EXPIRED_MESSAGE = 'Sua sessão expirou ou o formulário está desatualizado. Recarregue a página e tente novamente.'
def resolve_secret_key() -> str:
env_key = os.getenv('INFINANCE_SECRET_KEY') or os.getenv('SECRET_KEY')
if env_key:
return env_key
if SECRET_FILE.exists():
file_key = SECRET_FILE.read_text(encoding='utf-8').strip()
if file_key:
return file_key
# Fallback seguro para execução local com persistência em arquivo.
generated = secrets.token_hex(32)
try:
SECRET_FILE.write_text(generated, encoding='utf-8')
except OSError as exc:
logging.getLogger(__name__).warning('Nao foi possivel persistir SECRET_FILE: %s', exc)
return generated
def resolve_session_cookie_secure() -> bool:
explicit = (os.getenv('INFINANCE_SESSION_COOKIE_SECURE') or '').strip().lower()
if explicit in {'1', 'true', 'yes', 'on'}:
return True
if explicit in {'0', 'false', 'no', 'off'}:
return False
host_raw = (os.getenv('INFINANCE_HOST') or os.getenv('FLASK_RUN_HOST') or '127.0.0.1').strip().lower()
host = host_raw.split(':', 1)[0]
return host not in {'127.0.0.1', 'localhost', '::1'}
app = Flask(
__name__,
template_folder=str(BASE_DIR / 'templates'),
static_folder=str(BASE_DIR / 'static'),
)
app.config['SECRET_KEY'] = resolve_secret_key()
app.config['DATABASE'] = str(DATABASE)
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['SESSION_COOKIE_SECURE'] = resolve_session_cookie_secure()
SERVICE_TYPES = {
'operacional': {'label': 'Operacional / Gestão / Suporte', 'default_rate': 0.06},
'intelectual': {'label': 'Intelectual / Desenvolvimento / Consultoria', 'default_rate': 0.155},
'personalizado': {'label': 'Personalizado', 'default_rate': 0.0},
}
CHANNELS = {
'PJ': 'Pessoa Jurídica',
'PF': 'Pessoa Física',
}
TRANSACTION_STATUS = {
'recebido': 'Recebido',
'a_receber': 'A receber',
'parcial': 'Parcial',
}
EXPENSE_CATEGORIES = {
'impostos': 'Impostos e Taxas',
'ferramentas': 'Ferramentas e Software',
'operacional': 'Operacional',
'marketing': 'Marketing',
'financeiro': 'Financeiro',
'outros': 'Outros',
}
ANNEX_OPTIONS = {
'I': 'Anexo I',
'II': 'Anexo II',
'III': 'Anexo III',
'IV': 'Anexo IV',
'V': 'Anexo V',
'III_V': 'Anexo III ou V (Fator R)',
}
DAS_BRACKETS = {
'I': [
{'limit': 180000.0, 'nominal': 0.04, 'deduction': 0.0},
{'limit': 360000.0, 'nominal': 0.073, 'deduction': 5940.0},
{'limit': 720000.0, 'nominal': 0.095, 'deduction': 13860.0},
{'limit': 1800000.0, 'nominal': 0.107, 'deduction': 22500.0},
{'limit': 3600000.0, 'nominal': 0.143, 'deduction': 87300.0},
{'limit': 4800000.0, 'nominal': 0.19, 'deduction': 378000.0},
],
'II': [
{'limit': 180000.0, 'nominal': 0.045, 'deduction': 0.0},
{'limit': 360000.0, 'nominal': 0.078, 'deduction': 5940.0},
{'limit': 720000.0, 'nominal': 0.10, 'deduction': 13860.0},
{'limit': 1800000.0, 'nominal': 0.112, 'deduction': 22500.0},
{'limit': 3600000.0, 'nominal': 0.147, 'deduction': 85500.0},
{'limit': 4800000.0, 'nominal': 0.30, 'deduction': 720000.0},
],
'III': [
{'limit': 180000.0, 'nominal': 0.06, 'deduction': 0.0},
{'limit': 360000.0, 'nominal': 0.112, 'deduction': 9360.0},
{'limit': 720000.0, 'nominal': 0.135, 'deduction': 17640.0},
{'limit': 1800000.0, 'nominal': 0.16, 'deduction': 35640.0},
{'limit': 3600000.0, 'nominal': 0.21, 'deduction': 125640.0},
{'limit': 4800000.0, 'nominal': 0.33, 'deduction': 648000.0},
],
'IV': [
{'limit': 180000.0, 'nominal': 0.045, 'deduction': 0.0},
{'limit': 360000.0, 'nominal': 0.09, 'deduction': 8100.0},
{'limit': 720000.0, 'nominal': 0.102, 'deduction': 12420.0},
{'limit': 1800000.0, 'nominal': 0.14, 'deduction': 39780.0},
{'limit': 3600000.0, 'nominal': 0.22, 'deduction': 183780.0},
{'limit': 4800000.0, 'nominal': 0.33, 'deduction': 828000.0},
],
'V': [
{'limit': 180000.0, 'nominal': 0.155, 'deduction': 0.0},
{'limit': 360000.0, 'nominal': 0.18, 'deduction': 4500.0},
{'limit': 720000.0, 'nominal': 0.195, 'deduction': 9900.0},
{'limit': 1800000.0, 'nominal': 0.205, 'deduction': 17100.0},
{'limit': 3600000.0, 'nominal': 0.23, 'deduction': 62100.0},
{'limit': 4800000.0, 'nominal': 0.305, 'deduction': 540000.0},
],
}
ALLOWED_SCHEMA_ALTERS: dict[str, dict[str, str]] = {
'transactions': {
'status': "TEXT NOT NULL DEFAULT 'recebido'",
'invoice_number': 'TEXT',
'invoice_description': 'TEXT',
'expected_pf_tax': 'REAL NOT NULL DEFAULT 0',
},
'services': {
'cnae_description': 'TEXT',
'annex': "TEXT NOT NULL DEFAULT 'III'",
'factor_r_applicable': 'INTEGER NOT NULL DEFAULT 1',
},
}
def get_db() -> sqlite3.Connection:
if 'db' not in g:
g.db = sqlite3.connect(app.config['DATABASE'])
g.db.row_factory = sqlite3.Row
g.db.execute('PRAGMA foreign_keys = ON')
g.db.execute('PRAGMA journal_mode = WAL')
g.db.execute('PRAGMA synchronous = NORMAL')
return g.db
@app.teardown_appcontext
def close_db(exception: Exception | None) -> None:
db = g.pop('db', None)
if db is not None:
db.close()
def ensure_column(cur: sqlite3.Cursor, table: str, column: str, ddl: str) -> None:
table_rules = ALLOWED_SCHEMA_ALTERS.get(table)
if table_rules is None or table_rules.get(column) != ddl:
raise ValueError(f'Alteração de schema não permitida para {table}.{column}.')
if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', table) or not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', column):
raise ValueError('Identificador de schema inválido.')
columns = [row['name'] for row in cur.execute(f'PRAGMA table_info({table})').fetchall()]
if column not in columns:
cur.execute(f'ALTER TABLE {table} ADD COLUMN {column} {ddl}')
def init_db() -> None:
if not has_app_context():
with app.app_context():
init_db()
return
db = get_db()
with closing(db.cursor()) as cur:
cur.execute('PRAGMA journal_mode = WAL')
cur.execute('PRAGMA synchronous = NORMAL')
cur.executescript(
'''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'viewer',
must_change_password INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
last_login_at TEXT
);
CREATE TABLE IF NOT EXISTS clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
person_type TEXT NOT NULL,
notes TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS services (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
service_type TEXT NOT NULL,
tax_rate REAL NOT NULL,
cnae TEXT,
cnae_description TEXT,
annex TEXT NOT NULL DEFAULT 'III',
factor_r_applicable INTEGER NOT NULL DEFAULT 1,
description_template TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
client_id INTEGER NOT NULL,
service_id INTEGER NOT NULL,
amount REAL NOT NULL,
channel TEXT NOT NULL,
invoice_issued INTEGER NOT NULL DEFAULT 0,
invoice_number TEXT,
invoice_description TEXT,
expected_pf_tax REAL NOT NULL DEFAULT 0,
date_received TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'recebido',
notes TEXT,
created_at TEXT NOT NULL,
FOREIGN KEY (client_id) REFERENCES clients(id),
FOREIGN KEY (service_id) REFERENCES services(id)
);
CREATE TABLE IF NOT EXISTS expenses (
id INTEGER PRIMARY KEY AUTOINCREMENT,
description TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'outros',
amount REAL NOT NULL,
date_incurred TEXT NOT NULL,
is_fixed INTEGER NOT NULL DEFAULT 0,
notes TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS company_settings (
id INTEGER PRIMARY KEY CHECK (id = 1),
company_name TEXT NOT NULL DEFAULT 'INFinance Company',
legal_name TEXT,
tax_regime TEXT NOT NULL DEFAULT 'Simples Nacional',
employees_count INTEGER NOT NULL DEFAULT 1,
payroll_monthly REAL NOT NULL DEFAULT 0,
prolabore_monthly REAL NOT NULL DEFAULT 0,
notes TEXT,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_transactions_date ON transactions(date_received);
CREATE INDEX IF NOT EXISTS idx_transactions_client_id ON transactions(client_id);
CREATE INDEX IF NOT EXISTS idx_transactions_service_id ON transactions(service_id);
CREATE INDEX IF NOT EXISTS idx_expenses_date ON expenses(date_incurred);
'''
)
ensure_column(cur, 'transactions', 'status', "TEXT NOT NULL DEFAULT 'recebido'")
ensure_column(cur, 'transactions', 'invoice_number', 'TEXT')
ensure_column(cur, 'transactions', 'invoice_description', 'TEXT')
ensure_column(cur, 'transactions', 'expected_pf_tax', 'REAL NOT NULL DEFAULT 0')
ensure_column(cur, 'services', 'cnae_description', 'TEXT')
ensure_column(cur, 'services', 'annex', "TEXT NOT NULL DEFAULT 'III'")
ensure_column(cur, 'services', 'factor_r_applicable', 'INTEGER NOT NULL DEFAULT 1')
db.commit()
def seed_data() -> None:
if not has_app_context():
with app.app_context():
seed_data()
return
db = get_db()
cur = db.cursor()
user_count = cur.execute('SELECT COUNT(*) AS total FROM users').fetchone()['total']
client_count = cur.execute('SELECT COUNT(*) AS total FROM clients').fetchone()['total']
service_count = cur.execute('SELECT COUNT(*) AS total FROM services').fetchone()['total']
expense_count = cur.execute('SELECT COUNT(*) AS total FROM expenses').fetchone()['total']
company_count = cur.execute('SELECT COUNT(*) AS total FROM company_settings').fetchone()['total']
now = datetime.now().isoformat(timespec='seconds')
today = datetime.now().strftime('%Y-%m-%d')
if user_count == 0:
admin_username = (os.getenv('INFINANCE_ADMIN_USER') or 'admin').strip() or 'admin'
admin_password = (os.getenv('INFINANCE_ADMIN_PASSWORD') or 'Admin@123').strip() or 'Admin@123'
must_change_password = 0 if os.getenv('INFINANCE_ADMIN_PASSWORD') else 1
cur.execute(
'''INSERT INTO users (username, password_hash, role, must_change_password, created_at)
VALUES (?, ?, 'admin', ?, ?)''',
(admin_username, generate_password_hash(admin_password), must_change_password, now),
)
if client_count == 0:
cur.executemany(
'INSERT INTO clients (name, person_type, notes, created_at) VALUES (?, ?, ?, ?)',
[
('Cliente Exemplo PF', 'PF', 'Cliente pessoa física para testes', now),
('Cliente Exemplo PJ', 'PJ', 'Cliente pessoa jurídica para testes', now),
],
)
if service_count == 0:
cur.executemany(
'''INSERT INTO services (name, service_type, tax_rate, cnae, cnae_description, annex, factor_r_applicable, description_template, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)''',
[
(
'Gerenciamento de site',
'operacional',
0.06,
'6319-4/00',
'Portais, provedores de conteúdo e outros serviços de informação na internet',
'III',
1,
'Prestação de serviços de gerenciamento, manutenção e administração operacional de website, incluindo atualização de conteúdo, monitoramento e suporte técnico.',
now,
),
(
'Desenvolvimento web sob demanda',
'intelectual',
0.155,
'6201-5/01',
'Desenvolvimento de programas de computador sob encomenda',
'III_V',
1,
'Prestação de serviços técnicos especializados em desenvolvimento e implementação de soluções web sob demanda.',
now,
),
],
)
if expense_count == 0:
cur.executemany(
'''INSERT INTO expenses (description, category, amount, date_incurred, is_fixed, notes, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)''',
[
('Plano de hospedagem', 'ferramentas', 89.9, today, 1, 'Infra mensal', now),
('Contabilidade', 'operacional', 250.0, today, 1, 'Assessoria mensal', now),
],
)
if company_count == 0:
cur.execute(
'''INSERT INTO company_settings (
id, company_name, legal_name, tax_regime, employees_count,
payroll_monthly, prolabore_monthly, notes, updated_at
) VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?)''',
(
'Minha Empresa',
'',
'Simples Nacional',
1,
0.0,
0.0,
'Configure os dados da empresa para melhorar simulações e relatórios.',
now,
),
)
db.commit()
def fetch_all(query: str, params: tuple[Any, ...] = ()) -> list[sqlite3.Row]:
return get_db().execute(query, params).fetchall()
def fetch_one(query: str, params: tuple[Any, ...] = ()) -> sqlite3.Row | None:
return get_db().execute(query, params).fetchone()
def execute(query: str, params: tuple[Any, ...] = ()) -> sqlite3.Cursor:
db = get_db()
cursor = db.execute(query, params)
db.commit()
return cursor
def normalize_username(raw_value: str) -> str:
return (raw_value or '').strip().lower()
def get_default_system_username() -> str:
return normalize_username((os.getenv('INFINANCE_ADMIN_USER') or 'admin').strip() or 'admin')
def is_protected_system_user(user_row: sqlite3.Row | dict[str, Any] | None) -> bool:
if user_row is None:
return False
try:
user_id = int(user_row['id'])
except (TypeError, ValueError, KeyError):
user_id = 0
username = normalize_username(str(user_row.get('username', '') if isinstance(user_row, dict) else user_row['username']))
return user_id == 1 or username == get_default_system_username()
def count_users() -> int:
row = fetch_one('SELECT COUNT(*) AS total FROM users')
return int(row['total'] or 0) if row is not None else 0
def get_user_by_id(user_id: int) -> sqlite3.Row | None:
return fetch_one('SELECT * FROM users WHERE id = ?', (user_id,))
def get_user_by_username(username: str) -> sqlite3.Row | None:
return fetch_one('SELECT * FROM users WHERE username = ?', (normalize_username(username),))
def get_current_user() -> dict[str, Any] | None:
cached = g.get('current_user_cache')
if cached is not None:
return cached
user_id = session.get('user_id')
if not user_id:
g.current_user_cache = None
return None
row = get_user_by_id(int(user_id))
if row is None:
session.clear()
g.current_user_cache = None
return None
g.current_user_cache = {
'id': row['id'],
'username': row['username'],
'role': row['role'],
'must_change_password': bool(row['must_change_password']),
}
return g.current_user_cache
def queue_post_login_endpoint(endpoint: str | None) -> None:
if endpoint in POST_LOGIN_ENDPOINTS:
session[POST_LOGIN_SESSION_KEY] = endpoint
return
session.pop(POST_LOGIN_SESSION_KEY, None)
def consume_post_login_target() -> str:
endpoint = session.pop(POST_LOGIN_SESSION_KEY, None)
if endpoint in POST_LOGIN_ENDPOINTS:
return url_for(endpoint)
return url_for('dashboard')
def static_file_version(filename: str) -> str:
normalized = (filename or '').replace('\\', '/').lstrip('/')
if not normalized:
return '0'
static_root = (BASE_DIR / 'static').resolve()
candidate = (static_root / normalized).resolve()
if static_root != candidate and static_root not in candidate.parents:
return '0'
try:
return str(int(candidate.stat().st_mtime))
except OSError:
return '0'
def asset_url(filename: str) -> str:
return url_for('static', filename=filename, v=static_file_version(filename))
def sign_in_user(user_row: sqlite3.Row) -> None:
session['user_id'] = int(user_row['id'])
session['username'] = user_row['username']
session['role'] = user_row['role']
execute(
'UPDATE users SET last_login_at = ? WHERE id = ?',
(datetime.now().isoformat(timespec='seconds'), int(user_row['id'])),
)
def sign_out_user() -> None:
for key in ('user_id', 'username', 'role'):
session.pop(key, None)
def is_admin_user() -> bool:
user = get_current_user()
return has_permission(user['role'], 'admin') if user else False
def can_write_data() -> bool:
user = get_current_user()
return has_permission(user['role'], 'write') if user else False
def admin_required(view_function):
@wraps(view_function)
def wrapper(*args, **kwargs):
if not is_admin_user():
flash('Acesso restrito a administradores.', 'error')
return redirect(url_for('dashboard'))
return view_function(*args, **kwargs)
return wrapper
def safe_float(value: Any, default: float | None = None) -> float | None:
try:
return float(value)
except (TypeError, ValueError):
return default
def normalize_percent_input(raw_value: str) -> float:
normalized = str(raw_value or '').replace(',', '.').strip()
parsed = safe_float(normalized, 0.0)
if parsed is None:
return 0.0
if parsed < 0:
return 0.0
# O campo recebe percentual em escala humana: 6 => 6%.
return parsed / 100
def parse_date_or_default(raw_value: str, default: str | None = None) -> str:
value = (raw_value or '').strip()
if not value:
return default or datetime.now().strftime('%Y-%m-%d')
try:
datetime.strptime(value, '%Y-%m-%d')
return value
except ValueError:
return default or datetime.now().strftime('%Y-%m-%d')
def parse_month_or_default(raw_month: str) -> str:
month = (raw_month or '').strip()
try:
datetime.strptime(month, '%Y-%m')
return month
except ValueError:
return datetime.now().strftime('%Y-%m')
def parse_month_or_none(raw_month: str) -> str | None:
month = (raw_month or '').strip()
if not month:
return None
try:
datetime.strptime(month, '%Y-%m')
return month
except ValueError:
return None
def parse_page_or_default(raw_page: str, default: int = 1) -> int:
try:
page = int((raw_page or '').strip())
return page if page > 0 else default
except (TypeError, ValueError, AttributeError):
return default
def parse_search_term(raw_value: str, max_length: int = 80) -> str:
return (raw_value or '').strip()[:max_length]
def build_pagination(total_items: int, requested_page: int, per_page: int) -> dict[str, int | bool]:
safe_total = max(int(total_items or 0), 0)
safe_per_page = max(int(per_page or 1), 1)
total_pages = max((safe_total + safe_per_page - 1) // safe_per_page, 1)
current_page = min(max(int(requested_page or 1), 1), total_pages)
offset = (current_page - 1) * safe_per_page
start_page = max(1, current_page - 2)
end_page = min(total_pages, current_page + 2)
return {
'total_items': safe_total,
'per_page': safe_per_page,
'total_pages': total_pages,
'current_page': current_page,
'offset': offset,
'pages': list(range(start_page, end_page + 1)),
'has_prev': current_page > 1,
'has_next': current_page < total_pages,
'prev_page': current_page - 1,
'next_page': current_page + 1,
}
def month_to_date_range(month: str) -> tuple[str, str] | None:
parsed_month = parse_month_or_none(month)
if parsed_month is None:
return None
month_start = datetime.strptime(parsed_month, '%Y-%m').replace(day=1)
next_month = (month_start + timedelta(days=32)).replace(day=1)
return month_start.strftime('%Y-%m-%d'), next_month.strftime('%Y-%m-%d')
def parse_annex(raw_annex: str, default: str = 'III') -> str:
annex = (raw_annex or '').strip().upper()
if annex in ANNEX_OPTIONS:
return annex
return default
def to_bool(raw_value: Any) -> bool:
return str(raw_value).strip().lower() in {'1', 'true', 'on', 'yes', 'sim'}
def format_brl_plain(value: float) -> str:
formatted = f'{float(value):,.2f}'
return 'R$ ' + formatted.replace(',', 'X').replace('.', ',').replace('X', '.')
def get_company_settings() -> sqlite3.Row:
row = fetch_one('SELECT * FROM company_settings WHERE id = 1')
if row is not None:
return row
now = datetime.now().isoformat(timespec='seconds')
execute(
'''INSERT INTO company_settings (
id, company_name, legal_name, tax_regime, employees_count,
payroll_monthly, prolabore_monthly, notes, updated_at
) VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?)''',
('Minha Empresa', '', 'Simples Nacional', 1, 0.0, 0.0, '', now),
)
return fetch_one('SELECT * FROM company_settings WHERE id = 1')
def calculate_transaction(amount: float, channel: str, invoice_issued: bool, service_tax_rate: float, expected_pf_tax: float) -> dict[str, float]:
gross = round(max(amount, 0.0), 2)
invoice_tax = 0.0
pf_tax = 0.0
if channel == 'PJ' and invoice_issued:
invoice_tax = round(gross * max(service_tax_rate, 0.0), 2)
elif channel == 'PF':
pf_tax = round(max(expected_pf_tax, 0.0), 2)
total_tax = round(invoice_tax + pf_tax, 2)
net = round(gross - total_tax, 2)
effective_rate = round((total_tax / gross) * 100, 2) if gross > 0 else 0.0
return {
'gross': gross,
'invoice_tax': invoice_tax,
'pf_tax': pf_tax,
'total_tax': total_tax,
'net': net,
'effective_rate': effective_rate,
}
def calculate_das_advanced(
monthly_revenue: float,
rbt12: float,
payroll_12m: float,
annex_mode: str = 'III_V',
forced_annex: str | None = None,
) -> dict[str, Any]:
monthly_revenue = max(monthly_revenue, 0.0)
rbt12 = max(rbt12, 0.0)
payroll_12m = max(payroll_12m, 0.0)
if rbt12 <= 0:
return {
'error': 'Informe uma receita bruta acumulada dos últimos 12 meses (RBT12) maior que zero.',
}
if rbt12 > 4_800_000:
return {
'error': 'RBT12 acima de R$ 4.800.000,00. O cálculo simplificado aqui não cobre esse regime.',
}
if forced_annex is not None and forced_annex not in DAS_BRACKETS:
return {
'error': 'Anexo forçado inválido. Use I, II, III, IV ou V.',
}
factor_r = payroll_12m / rbt12
annex_mode = parse_annex(annex_mode, 'III_V')
if forced_annex in DAS_BRACKETS:
annex = forced_annex
uses_factor_r = forced_annex in {'III', 'V'} and annex_mode == 'III_V'
elif annex_mode == 'III_V':
annex = 'III' if factor_r >= 0.28 else 'V'
uses_factor_r = True
else:
annex = annex_mode if annex_mode in DAS_BRACKETS else 'III'
uses_factor_r = False
bracket = DAS_BRACKETS[annex][-1]
for item in DAS_BRACKETS[annex]:
if rbt12 <= item['limit']:
bracket = item
break
effective_rate = ((rbt12 * bracket['nominal']) - bracket['deduction']) / rbt12
effective_rate = max(effective_rate, 0.0)
estimated_das = monthly_revenue * effective_rate
return {
'error': None,
'annex': annex,
'monthly_revenue': monthly_revenue,
'rbt12': rbt12,
'payroll_12m': payroll_12m,
'factor_r': factor_r,
'factor_r_percent': factor_r * 100,
'annex_mode': annex_mode,
'uses_factor_r': uses_factor_r,
'nominal_rate': bracket['nominal'],
'effective_rate': effective_rate,
'deduction': bracket['deduction'],
'estimated_das': estimated_das,
'target_rate_28_gap': max((0.28 * rbt12) - payroll_12m, 0.0) if uses_factor_r else 0.0,
'bracket_limit': bracket['limit'],
}
def get_transactions_filtered(
month: str | None = None,
limit: int | None = None,
offset: int = 0,
search: str | None = None,
) -> list[dict[str, Any]]:
params: list[Any] = []
where_clauses: list[str] = []
if month:
month_range = month_to_date_range(month)
if month_range is not None:
month_start, next_month_start = month_range
where_clauses.append('t.date_received >= ? AND t.date_received < ?')
params.extend((month_start, next_month_start))
if search:
like_term = f'%{search.lower()}%'
where_clauses.append(
'('
"LOWER(c.name) LIKE ? OR "
"LOWER(s.name) LIKE ? OR "
"LOWER(COALESCE(t.invoice_number, '')) LIKE ? OR "
"LOWER(COALESCE(t.notes, '')) LIKE ?"
')'
)
params.extend((like_term, like_term, like_term, like_term))
query = '''
SELECT t.*, c.name AS client_name, c.person_type AS client_person_type,
s.name AS service_name, s.tax_rate, s.service_type, s.cnae,
s.cnae_description, s.annex AS service_annex, s.factor_r_applicable
FROM transactions t
JOIN clients c ON c.id = t.client_id
JOIN services s ON s.id = t.service_id
'''
if where_clauses:
query += ' WHERE ' + ' AND '.join(where_clauses)
query += ' ORDER BY date(t.date_received) DESC, t.id DESC'
if limit is not None and limit > 0:
query += ' LIMIT ? OFFSET ?'
params.extend((int(limit), max(int(offset), 0)))
rows = fetch_all(query, tuple(params))
rendered: list[dict[str, Any]] = []
for row in rows:
item = dict(row)
item['calc'] = calculate_transaction(
amount=row['amount'],
channel=row['channel'],
invoice_issued=bool(row['invoice_issued']),
service_tax_rate=row['tax_rate'],
expected_pf_tax=row['expected_pf_tax'],
)
rendered.append(item)
return rendered
def count_transactions_filtered(month: str | None = None, search: str | None = None) -> int:
params: list[Any] = []
where_clauses: list[str] = []
if month:
month_range = month_to_date_range(month)
if month_range is not None:
month_start, next_month_start = month_range
where_clauses.append('t.date_received >= ? AND t.date_received < ?')
params.extend((month_start, next_month_start))
if search:
like_term = f'%{search.lower()}%'
where_clauses.append(
'('
"LOWER(c.name) LIKE ? OR "
"LOWER(s.name) LIKE ? OR "
"LOWER(COALESCE(t.invoice_number, '')) LIKE ? OR "
"LOWER(COALESCE(t.notes, '')) LIKE ?"
')'
)
params.extend((like_term, like_term, like_term, like_term))
query = '''
SELECT COUNT(*) AS total
FROM transactions t
JOIN clients c ON c.id = t.client_id
JOIN services s ON s.id = t.service_id
'''
if where_clauses:
query += ' WHERE ' + ' AND '.join(where_clauses)
row = fetch_one(query, tuple(params))
return int(row['total'] or 0) if row is not None else 0
def summarize_transactions_sql(month: str | None = None) -> dict[str, float | int]:
params: list[Any] = []
where_clauses: list[str] = []
if month:
month_range = month_to_date_range(month)
if month_range is not None:
month_start, next_month_start = month_range
where_clauses.append('t.date_received >= ? AND t.date_received < ?')
params.extend((month_start, next_month_start))
query = '''
SELECT
COALESCE(SUM(t.amount), 0) AS gross_total,
COALESCE(SUM(CASE WHEN t.channel = 'PJ' AND t.invoice_issued = 1 THEN t.amount * s.tax_rate ELSE 0 END), 0) AS invoice_tax_total,
COALESCE(SUM(CASE WHEN t.channel = 'PF' THEN t.expected_pf_tax ELSE 0 END), 0) AS pf_tax_total,
COALESCE(SUM(CASE WHEN t.channel = 'PJ' THEN t.amount ELSE 0 END), 0) AS pj_total,
COALESCE(SUM(CASE WHEN t.channel = 'PF' THEN t.amount ELSE 0 END), 0) AS pf_total,
COALESCE(SUM(CASE WHEN t.invoice_issued = 1 THEN 1 ELSE 0 END), 0) AS invoice_count
FROM transactions t
JOIN services s ON s.id = t.service_id
'''
if where_clauses:
query += ' WHERE ' + ' AND '.join(where_clauses)
row = fetch_one(query, tuple(params))
if row is None:
return {
'gross_total': 0.0,
'net_total': 0.0,
'invoice_tax_total': 0.0,
'pf_tax_total': 0.0,
'total_tax_total': 0.0,
'pj_total': 0.0,
'pf_total': 0.0,
'invoice_count': 0,
}
gross_total = float(row['gross_total'] or 0.0)
invoice_tax_total = float(row['invoice_tax_total'] or 0.0)
pf_tax_total = float(row['pf_tax_total'] or 0.0)
total_tax_total = invoice_tax_total + pf_tax_total
net_total = gross_total - total_tax_total
return {
'gross_total': gross_total,
'net_total': net_total,
'invoice_tax_total': invoice_tax_total,
'pf_tax_total': pf_tax_total,
'total_tax_total': total_tax_total,
'pj_total': float(row['pj_total'] or 0.0),
'pf_total': float(row['pf_total'] or 0.0),
'invoice_count': int(row['invoice_count'] or 0),
}
def get_expenses_filtered(
month: str | None = None,