File size: 8,106 Bytes
b85875e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c4e7c0
 
 
 
 
b85875e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c4e7c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b85875e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from contextlib import contextmanager
from typing import Any, Dict, List, Optional, Sequence

import psycopg2
from psycopg2.extras import RealDictCursor

DATABASE_URL = os.environ.get("NEON_DATABASE_URL")

if not DATABASE_URL:
    raise RuntimeError(
        "Brak zmiennej NEON_DATABASE_URL. Ustaw sekret w Hugging Face lub "
        "ustaw zmienną środowiskową lokalnie."
    )



@contextmanager
def db_conn():
    conn = psycopg2.connect(DATABASE_URL, cursor_factory=RealDictCursor)
    try:
        yield conn
        conn.commit()
    except Exception:
        conn.rollback()
        raise
    finally:
        conn.close()


def fetch_one(query: str, params: Sequence[Any]) -> Optional[Dict[str, Any]]:
    with db_conn() as conn, conn.cursor() as cur:
        cur.execute(query, params)
        return cur.fetchone()


def fetch_all(query: str, params: Sequence[Any] = ()) -> List[Dict[str, Any]]:
    with db_conn() as conn, conn.cursor() as cur:
        cur.execute(query, params)
        return cur.fetchall()


def execute(query: str, params: Sequence[Any]) -> None:
    with db_conn() as conn, conn.cursor() as cur:
        cur.execute(query, params)


def create_account(login: str, email: str, password_hash: str) -> int:
    with db_conn() as conn, conn.cursor() as cur:
        cur.execute(
            """

            INSERT INTO accounts (login, password_hash)

            VALUES (%s, %s)

            RETURNING id

            """,
            (login, password_hash),
        )
        account_id = cur.fetchone()["id"]
        cur.execute(
            """

            INSERT INTO business_profiles (account_id, company_name, owner_name,

                                           address_line, postal_code, city, tax_id, bank_account)

            VALUES (%s, '', '', '', '', '', '', '')

            """,
            (account_id,),
        )
        return account_id


def update_business(account_id: int, data: Dict[str, str]) -> None:
    execute(
        """

        UPDATE business_profiles

        SET company_name = %s,

            owner_name = %s,

            address_line = %s,

            postal_code = %s,

            city = %s,

            tax_id = %s,

            bank_account = %s

        WHERE account_id = %s

        """,
        (
            data["company_name"],
            data["owner_name"],
            data["address_line"],
            data["postal_code"],
            data["city"],
            data["tax_id"],
            data["bank_account"],
            account_id,
        ),
    )



def fetch_business_logo(account_id: int) -> Optional[Dict[str, Optional[str]]]:
    row = fetch_one(
        """

        SELECT logo_mime_type, logo_data_base64

        FROM business_profiles

        WHERE account_id = %s

        """,
        (account_id,),
    )
    if not row:
        return None
    mime_type = row.get("logo_mime_type")
    data_base64 = row.get("logo_data_base64")
    if not mime_type or not data_base64:
        return None
    return {"mime_type": mime_type, "data": data_base64}


def update_business_logo(account_id: int, mime: Optional[str], data_base64: Optional[str]) -> None:
    execute(
        """

        UPDATE business_profiles

        SET logo_mime_type = %s,

            logo_data_base64 = %s

        WHERE account_id = %s

        """,
        (mime, data_base64, account_id),
    )

def upsert_client(account_id: int, payload: Dict[str, str]) -> int:
    row = fetch_one(
        """
        SELECT id FROM clients
        WHERE account_id = %s AND tax_id = %s
        """,
        (account_id, payload["tax_id"]),
    )
    if row:
        client_id = row["id"]
        execute(
            """

            UPDATE clients

            SET name = %s,

                address_line = %s,

                postal_code = %s,

                city = %s,

                phone = %s

            WHERE id = %s

            """,
            (
                payload["name"],
                payload["address_line"],
                payload["postal_code"],
                payload["city"],
                payload.get("phone"),
                client_id,
            ),
        )
        return client_id

    with db_conn() as conn, conn.cursor() as cur:
        cur.execute(
            """

            INSERT INTO clients (account_id, name, address_line, postal_code, city, tax_id, phone)

            VALUES (%s, %s, %s, %s, %s, %s, %s)

            RETURNING id

            """,
            (
                account_id,
                payload["name"],
                payload["address_line"],
                payload["postal_code"],
                payload["city"],
                payload["tax_id"],
                payload.get("phone"),
            ),
        )
        return cur.fetchone()["id"]


def search_clients(account_id: int, term: str, limit: int = 10) -> List[Dict[str, Any]]:
    query = (term or "").strip().lower()
    like = f"%{query}%"
    return fetch_all(
        """
        SELECT name, tax_id, address_line, postal_code, city, phone
        FROM clients
        WHERE account_id = %s
          AND (
            %s = '' OR
            LOWER(COALESCE(name, '')) LIKE %s OR
            LOWER(COALESCE(tax_id, '')) LIKE %s
          )
        ORDER BY LOWER(COALESCE(name, tax_id, '')) ASC
        LIMIT %s
        """,
        (account_id, query, like, like, limit),
    )


def insert_invoice(account_id: int, client_id: int, invoice: Dict[str, Any]) -> int:
    with db_conn() as conn, conn.cursor() as cur:
        cur.execute(
            """
            INSERT INTO invoices (account_id, client_id, invoice_number, issued_at,

                                  sale_date, payment_term_days, exemption_note,

                                  total_net, total_vat, total_gross)

            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)

            RETURNING id

            """,
            (
                account_id,
                client_id,
                invoice["invoice_id"],
                invoice["issued_at"],
                invoice["sale_date"],
                invoice.get("payment_term", 14),
                invoice.get("exemption_note"),
                invoice["totals"]["net"],
                invoice["totals"]["vat"],
                invoice["totals"]["gross"],
            ),
        )
        invoice_id = cur.fetchone()["id"]

        cur.executemany(
            """

            INSERT INTO invoice_items (invoice_id, line_no, name, quantity, unit,

                                       vat_code, vat_label, unit_price_net,

                                       unit_price_gross, net_total, vat_amount, gross_total)

            VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)

            """,
            [
                (
                    invoice_id,
                    idx + 1,
                    item["name"],
                    item["quantity"],
                    item.get("unit"),
                    item.get("vat_code"),
                    item.get("vat_label"),
                    item["unit_price_net"],
                    item["unit_price_gross"],
                    item["net_total"],
                    item["vat_amount"],
                    item["gross_total"],
                )
                for idx, item in enumerate(invoice["items"])
            ],
        )

        cur.executemany(
            """

            INSERT INTO invoice_vat_summary (invoice_id, vat_label, net_total, vat_total, gross_total)

            VALUES (%s, %s, %s, %s, %s)

            """,
            [
                (
                    invoice_id,
                    row["vat_label"],
                    row["net_total"],
                    row["vat_total"],
                    row["gross_total"],
                )
                for row in invoice["summary"]
            ],
        )

        return invoice_id