EliramShemesh commited on
Commit
dd4d56d
·
verified ·
1 Parent(s): 9b64783

ci: deploy backend from e25d34fe948a1a7bde1bfd0f80ba5f829c2ffaa0

Browse files
Files changed (4) hide show
  1. import_bank_transactions.py +296 -0
  2. import_via_api.py +196 -0
  3. main.py +111 -0
  4. models.py +2 -2
import_bank_transactions.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Import bank transactions from CSV/table format to local SQLite database.
4
+
5
+ Usage:
6
+ python import_bank_transactions.py
7
+
8
+ The script will:
9
+ 1. Parse the transaction data
10
+ 2. Map categories to existing ones (or create if needed)
11
+ 3. Map payment methods
12
+ 4. Insert transactions into database
13
+ """
14
+
15
+ import os
16
+ import sys
17
+ import sqlite3
18
+ from datetime import datetime
19
+
20
+ # Transaction data from user
21
+ TRANSACTIONS_DATA = """
22
+ 2024-04-08 2026-04-10 שטראוס מים בע"מ דלק, חשמל וגז 125 debit 6000 ILS תשלומים 6893 Credit Card - Discount תשלום 24 מתוך 48
23
+ 2025-10-20 2026-04-10 נטע עמית עיצוב תכשיטים שונות 101.44 debit 913 ILS תשלומים 6893 Credit Card - Discount תשלום 6 מתוך 9
24
+ 2026-02-28 2026-04-10 NETFLIX.COM LOS GATOS NL שירותי תקשורת 54.9 debit 54.9 ILS דחוי חודש 6893 Credit Card - Discount חיוב עסקת חו"ל בש"ח
25
+ 2026-03-11 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 3.16 debit 3.16 ILS רגילה 7945 Credit Card - Discount
26
+ 2026-03-12 2026-04-10 חוות נוקדי רופין בע"מ מזון וצריכה 34 debit 34 ILS רגילה 7945 Credit Card - Discount
27
+ 2026-03-19 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 3.18 debit 3.18 ILS רגילה 7945 Credit Card - Discount
28
+ 2026-03-19 2026-04-10 משק אורבך מזון וצריכה 20 debit 20 ILS רגילה 7945 Credit Card - Discount
29
+ 2026-03-19 2026-04-10 חוות נוקדי רופין בע"מ מזון וצריכה 14 debit 14 ILS רגילה 6893 Credit Card - Discount
30
+ 2026-03-19 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 3.17 debit 3.17 ILS רגילה 7945 Credit Card - Discount
31
+ 2026-03-23 2026-04-10 סעוד הראל -כללית רפואה ובתי מרקחת 59.6 debit 59.6 ILS רגילה 6893 Credit Card - Discount הוראת קבע
32
+ 2026-03-23 2026-04-10 שרותי בריאות כללית הו"ק רפואה ובתי מרקחת 104.39 debit 104.39 ILS רגילה 6893 Credit Card - Discount הוראת קבע
33
+ 2026-03-24 2026-04-10 רמי לוי שיווק השקמה תקשור שירותי תקשורת 90.77 debit 90.77 ILS רגילה 7945 Credit Card - Discount הוראת קבע
34
+ 2026-03-25 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 3.17 debit 3.17 ILS רגילה 7945 Credit Card - Discount
35
+ 2026-03-25 2026-04-10 פיס מנויים פנאי, בידור וספורט 60 debit 60 ILS רגילה 7945 Credit Card - Discount הוראת קבע
36
+ 2026-03-26 2026-04-10 כביש 6 חוצה צפון בע"מ תחבורה ורכבים 9.96 debit 9.96 ILS רגילה 6893 Credit Card - Discount הוראת קבע
37
+ 2026-03-29 2026-04-10 שמן זית אסי עמק המעיינות שונות 245 debit 245 ILS רגילה 6893 Credit Card - Discount
38
+ 2026-04-01 2026-04-01 העברה דיגיטל 1250 debit 1250 ILS Bank Account - Leumi 151154 העברה אל: פנינה גלזנר 10-816-063520922 שכר דירה 7035.18
39
+ 2026-04-01 2026-04-01 לאומי למשכנת-י 2463.51 debit 2463.51 ILS Bank Account - Leumi 771 9535.18
40
+ 2026-04-01 2026-04-01 הע. אינטרנט 1250 debit 1250 ILS Bank Account - Leumi 151260 העברה אל: חנה אורן 20-439-000194434 שכר דירה 8285.18
41
+ 2026-04-02 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 639.72 debit 639.72 ILS רגילה 7945 Credit Card - Discount
42
+ 2026-04-03 2026-04-03 ישראכרט בע"מ-י 230.49 debit 230.49 ILS Bank Account - Leumi 20543 6804.69
43
+ 2026-04-05 2026-04-05 העברת משכורת 21435 credit 21435 ILS Bank Account - Leumi 99012 העברה מאת: הפועלים 12-584-000133340 משכורת 28239.69
44
+ 2026-04-05 2026-04-05 הק בורסה קנ. 330.12 debit 330.12 ILS Bank Account - Leumi 231980 27909.57
45
+ 2026-04-06 2026-04-10 שרותי בריאות כללית הו"ק רפואה ובתי מרקחת 30 debit 30 ILS רגילה 6893 Credit Card - Discount הוראת קבע
46
+ 2026-04-07 2026-04-07 מכירת ני"ע 19974.87 credit 19974.87 ILS Bank Account - Leumi 231980 שם נייר ערך: מגדל כסשק לאקונ ,MIGDAL MNMRFIL 47884.44
47
+ 2026-04-07 2026-04-10 לולי גלידה מזון וצריכה 19 debit 19 ILS רגילה 6893 Credit Card - Discount
48
+ 2026-04-07 2026-04-10 פיס פלוס -תו נטען פנאי, בידור וספורט 225 debit 225 ILS רגילה 7945 Credit Card - Discount
49
+ 2026-04-07 2026-04-10 הטבות פיס פ. פנאי, בידור וספורט 550 debit 550 ILS רגילה 7945 Credit Card - Discount
50
+ 2026-04-10 2026-04-10 ישראכרט בע"מ-י 3552.87 debit 3552.87 ILS Bank Account - Leumi 20543 44331.57
51
+ 2026-04-10 2026-04-10 לאומי ויזה 1635.34 debit 1635.34 ILS Bank Account - Leumi 917945 33381.74
52
+ 2026-04-10 2026-04-10 פרימיום אקספ-י 8551.2 debit 8551.2 ILS Bank Account - Leumi 26000 35780.37
53
+ 2026-04-10 2026-04-10 מקס איט פיננ-י 763.29 debit 763.29 ILS Bank Account - Leumi 34685 35017.08
54
+ 2026-04-12 2026-04-12 העברה דיגיטל 360 debit 360 ILS Bank Account - Leumi 699143636 העברה אל: קיבוץ עין הנציב 20-439-000305465 סתימה אלירם שמש 33021.74
55
+ """
56
+
57
+ # Category mapping from bank categories to existing app categories
58
+ CATEGORY_MAP = {
59
+ 'דלק, חשמל וגז': 'בית', # Utilities go to Home
60
+ 'שונות': 'שונות', # Will create if doesn't exist
61
+ 'שירותי תקשורת': 'תקשורת',
62
+ 'מזון וצריכה': 'מזון',
63
+ 'רפואה ובתי מרקחת': 'בריאות',
64
+ 'פנאי, בידור וספורט': 'פנאי ובידור',
65
+ 'תחבורה ורכבים': 'תחבורה',
66
+ '': 'שונות', # Empty category
67
+ }
68
+
69
+ # Payment method mapping
70
+ PAYMENT_METHOD_MAP = {
71
+ 'Credit Card - Discount': 'כרטיס אשראי',
72
+ 'Bank Account - Leumi': 'העברה בנקאית',
73
+ }
74
+
75
+ def parse_amount(amount_str):
76
+ """Parse amount string to float."""
77
+ if not amount_str:
78
+ return 0.0
79
+ return float(amount_str.replace(',', ''))
80
+
81
+ def parse_transactions():
82
+ """Parse the transaction data."""
83
+ transactions = []
84
+ lines = TRANSACTIONS_DATA.strip().split('\n')
85
+
86
+ for line in lines:
87
+ if not line.strip():
88
+ continue
89
+
90
+ parts = line.split('\t')
91
+ if len(parts) < 11:
92
+ print(f"Skipping malformed line: {line[:50]}...")
93
+ continue
94
+
95
+ # Map fields
96
+ tx = {
97
+ 'transaction_date': parts[0],
98
+ 'charge_date': parts[1],
99
+ 'merchant': parts[2].strip(),
100
+ 'category': parts[3].strip() if len(parts) > 3 else '',
101
+ 'amount': parse_amount(parts[4]),
102
+ 'direction': parts[5], # debit or credit
103
+ 'original_amount': parts[6],
104
+ 'original_currency': parts[7],
105
+ 'transaction_type': parts[8] if len(parts) > 8 else '',
106
+ 'card_last4': parts[9] if len(parts) > 9 else '',
107
+ 'source': parts[10] if len(parts) > 10 else '',
108
+ 'reference': parts[11] if len(parts) > 11 else '',
109
+ 'notes': parts[12] if len(parts) > 12 else '',
110
+ 'balance': parse_amount(parts[13]) if len(parts) > 13 else 0,
111
+ }
112
+ transactions.append(tx)
113
+
114
+ return transactions
115
+
116
+ def get_or_create_category(conn, category_name, is_expense=True):
117
+ """Get existing category or create new one."""
118
+ cur = conn.cursor()
119
+ # First try exact match
120
+ cur.execute('SELECT id FROM category WHERE name = ?', (category_name,))
121
+ row = cur.fetchone()
122
+ if row:
123
+ return row[0]
124
+
125
+ # Create new category
126
+ category_type = 'EXPENSE' if is_expense else 'INCOME'
127
+ cur.execute(
128
+ 'INSERT INTO category (name, type, icon, color) VALUES (?, ?, ?, ?)',
129
+ (category_name, category_type, '📦', '#666666')
130
+ )
131
+ conn.commit()
132
+ new_id = cur.lastrowid
133
+ print(f" Created new category: {category_name} (ID: {new_id})")
134
+ return new_id
135
+
136
+ def get_payment_method_id(conn, source_name):
137
+ """Map bank source to payment method ID."""
138
+ pm_name = PAYMENT_METHOD_MAP.get(source_name, 'מזומן') # Default to cash
139
+
140
+ cur = conn.cursor()
141
+ cur.execute('SELECT id FROM paymentmethod WHERE name = ?', (pm_name,))
142
+ row = cur.fetchone()
143
+ if row:
144
+ return row[0]
145
+
146
+ # Return default (cash)
147
+ return 1
148
+
149
+ def get_default_user_id(conn):
150
+ """Get first user ID."""
151
+ cur = conn.cursor()
152
+ cur.execute('SELECT id FROM user LIMIT 1')
153
+ row = cur.fetchone()
154
+ return row[0] if row else 1
155
+
156
+ def transaction_exists(conn, amount, date, user_id, notes):
157
+ """Check if transaction already exists."""
158
+ cur = conn.cursor()
159
+ cur.execute('''
160
+ SELECT id FROM "transaction"
161
+ WHERE amount = ? AND date = ? AND user_id = ?
162
+ AND (notes = ? OR (? IS NULL AND notes IS NULL))
163
+ ''', (amount, date, user_id, notes, notes))
164
+ return cur.fetchone() is not None
165
+
166
+ def insert_transaction(conn, data):
167
+ """Insert a transaction."""
168
+ cur = conn.cursor()
169
+ cur.execute('''
170
+ INSERT INTO "transaction"
171
+ (amount, type, category_id, payment_method_id, user_id, date, notes, payee,
172
+ sub_category_id, is_installment, installment_number, total_installments)
173
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?)
174
+ ''', (
175
+ data['amount'], data['type'], data['category_id'], data['pm_id'],
176
+ data['user_id'], data['date'], data['notes'], data['payee'],
177
+ data['is_installment'], data['inst_num'], data['total_inst']
178
+ ))
179
+ return cur.lastrowid
180
+
181
+ def count_transactions(conn):
182
+ """Count total transactions."""
183
+ cur = conn.cursor()
184
+ cur.execute('SELECT COUNT(*) FROM "transaction"')
185
+ return cur.fetchone()[0]
186
+
187
+ def import_transactions():
188
+ """Import transactions into database."""
189
+ db_path = os.path.join(os.path.dirname(__file__), "database.db")
190
+ if not os.path.exists(db_path):
191
+ print(f"Local database not found at: {db_path}")
192
+ sys.exit(1)
193
+
194
+ print(f"Connecting to: {db_path}\n")
195
+
196
+ conn = sqlite3.connect(db_path)
197
+
198
+ try:
199
+ transactions = parse_transactions()
200
+ print(f"Parsed {len(transactions)} transactions from data\n")
201
+
202
+ # Get default user
203
+ user_id = get_default_user_id(conn)
204
+ print(f"Using user ID: {user_id}\n")
205
+
206
+ # Cache categories and payment methods
207
+ category_cache = {}
208
+ pm_cache = {}
209
+
210
+ imported = 0
211
+ skipped = 0
212
+
213
+ print("Importing transactions...")
214
+ print("-" * 60)
215
+
216
+ for tx in transactions:
217
+ # Determine transaction type
218
+ is_expense = tx['direction'] == 'debit'
219
+ tx_type = 'expense' if is_expense else 'income'
220
+
221
+ # Map category
222
+ bank_category = tx['category']
223
+ app_category = CATEGORY_MAP.get(bank_category, bank_category)
224
+
225
+ if app_category not in category_cache:
226
+ category_cache[app_category] = get_or_create_category(conn, app_category, is_expense)
227
+ category_id = category_cache[app_category]
228
+
229
+ # Map payment method
230
+ source = tx['source']
231
+ if source not in pm_cache:
232
+ pm_cache[source] = get_payment_method_id(conn, source)
233
+ pm_id = pm_cache[source]
234
+
235
+ # Build notes
236
+ notes_parts = []
237
+ if tx['notes']:
238
+ notes_parts.append(tx['notes'])
239
+ if tx['transaction_type'] and tx['transaction_type'] != 'רגילה':
240
+ notes_parts.append(f"סוג: {tx['transaction_type']}")
241
+ if tx['card_last4']:
242
+ notes_parts.append(f"כרטיס: ****{tx['card_last4']}")
243
+ if tx['reference']:
244
+ notes_parts.append(f"אסמכתא: {tx['reference']}")
245
+
246
+ notes = ' | '.join(notes_parts) if notes_parts else None
247
+
248
+ # Check if transaction already exists
249
+ if transaction_exists(conn, tx['amount'], tx['transaction_date'], user_id, notes):
250
+ print(f" ⚠ SKIP: {tx['merchant'][:30]} ₪{tx['amount']} (duplicate)")
251
+ skipped += 1
252
+ continue
253
+
254
+ # Insert transaction
255
+ insert_transaction(conn, {
256
+ 'amount': tx['amount'],
257
+ 'type': tx_type,
258
+ 'category_id': category_id,
259
+ 'pm_id': pm_id,
260
+ 'user_id': user_id,
261
+ 'date': tx['transaction_date'],
262
+ 'notes': notes,
263
+ 'payee': tx['merchant'][:100], # Truncate if too long
264
+ 'is_installment': 'תשלומים' in tx['transaction_type'],
265
+ 'inst_num': None,
266
+ 'total_inst': None
267
+ })
268
+
269
+ print(f" ✓ {tx['merchant'][:30]:30} ₪{tx['amount']:>8} ({app_category})")
270
+ imported += 1
271
+
272
+ # Commit all transactions to database
273
+ conn.commit()
274
+
275
+ print("-" * 60)
276
+ print(f"\n✓ IMPORT COMPLETE")
277
+ print(f" Imported: {imported}")
278
+ print(f" Skipped (duplicates): {skipped}")
279
+ print(f"\nTotal transactions in database: {count_transactions(conn)}")
280
+
281
+ except Exception as e:
282
+ print(f"\nERROR: {e}")
283
+ import traceback
284
+ traceback.print_exc()
285
+ sys.exit(1)
286
+ finally:
287
+ conn.close()
288
+
289
+ if __name__ == "__main__":
290
+ try:
291
+ import_transactions()
292
+ except Exception as e:
293
+ print(f"\nERROR: {e}")
294
+ import traceback
295
+ traceback.print_exc()
296
+ sys.exit(1)
import_via_api.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Import bank transactions via API endpoint.
4
+ This uses the proper API instead of direct DB injection.
5
+
6
+ Usage:
7
+ python import_via_api.py [local|prod]
8
+
9
+ Requirements:
10
+ pip install requests python-dotenv
11
+ """
12
+
13
+ import os
14
+ import sys
15
+ import json
16
+
17
+ # Check dependencies
18
+ try:
19
+ import requests
20
+ from dotenv import load_dotenv
21
+ except ImportError as e:
22
+ print("="*60)
23
+ print("MISSING DEPENDENCIES")
24
+ print("="*60)
25
+ print(f"\nError: {e}")
26
+ print("\nPlease install required packages:")
27
+ print(" pip install requests python-dotenv")
28
+ print("="*60)
29
+ sys.exit(1)
30
+
31
+ # Transaction data from user (same as before)
32
+ TRANSACTIONS_DATA = """
33
+ 2024-04-08 2026-04-10 שטראוס מים בע"מ דלק, חשמל וגז 125 debit 6000 ILS תשלומים 6893 Credit Card - Discount תשלום 24 מתוך 48
34
+ 2025-10-20 2026-04-10 נטע עמית עיצוב תכשיטים שונות 101.44 debit 913 ILS תשלומים 6893 Credit Card - Discount תשלום 6 מתוך 9
35
+ 2026-02-28 2026-04-10 NETFLIX.COM LOS GATOS NL שירותי תקשורת 54.9 debit 54.9 ILS דחוי חודש 6893 Credit Card - Discount חיוב עסקת חו"ל בש"ח
36
+ 2026-03-11 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 3.16 debit 3.16 ILS רגילה 7945 Credit Card - Discount
37
+ 2026-03-12 2026-04-10 חוות נוקדי רופין בע"מ מזון וצריכה 34 debit 34 ILS רגילה 7945 Credit Card - Discount
38
+ 2026-03-19 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 3.18 debit 3.18 ILS רגילה 7945 Credit Card - Discount
39
+ 2026-03-19 2026-04-10 משק אורבך מזון וצריכה 20 debit 20 ILS רגילה 7945 Credit Card - Discount
40
+ 2026-03-19 2026-04-10 חוות נוקדי רופין בע"מ מזון וצריכה 14 debit 14 ILS רגילה 6893 Credit Card - Discount
41
+ 2026-03-19 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 3.17 debit 3.17 ILS רגילה 7945 Credit Card - Discount
42
+ 2026-03-23 2026-04-10 סעוד הראל -כללית רפואה ובתי מרקחת 59.6 debit 59.6 ILS רגילה 6893 Credit Card - Discount הוראת קבע
43
+ 2026-03-23 2026-04-10 שרותי בריאות כללית הו"ק רפואה ובתי מרקחת 104.39 debit 104.39 ILS רגילה 6893 Credit Card - Discount הוראת קבע
44
+ 2026-03-24 2026-04-10 רמי לוי שיווק השקמה תקשור שירותי תקשורת 90.77 debit 90.77 ILS רגילה 7945 Credit Card - Discount הוראת קבע
45
+ 2026-03-25 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 3.17 debit 3.17 ILS רגילה 7945 Credit Card - Discount
46
+ 2026-03-25 2026-04-10 פיס מנויים פנאי, בידור וספורט 60 debit 60 ILS רגילה 7945 Credit Card - Discount הוראת קבע
47
+ 2026-03-26 2026-04-10 כביש 6 חוצה צפון בע"מ תחבורה ורכבים 9.96 debit 9.96 ILS רגילה 6893 Credit Card - Discount הוראת קבע
48
+ 2026-03-29 2026-04-10 שמן זית אסי עמק המעיינות שונות 245 debit 245 ILS רגילה 6893 Credit Card - Discount
49
+ 2026-04-01 2026-04-01 העברה דיגיטל 1250 debit 1250 ILS Bank Account - Leumi 151154 העברה אל: פנינה גלזנר 10-816-063520922 שכר דירה 7035.18
50
+ 2026-04-01 2026-04-01 לאומי למשכנת-י 2463.51 debit 2463.51 ILS Bank Account - Leumi 771 9535.18
51
+ 2026-04-01 2026-04-01 הע. אינטרנט 1250 debit 1250 ILS Bank Account - Leumi 151260 העברה אל: חנה אורן 20-439-000194434 שכר דירה 8285.18
52
+ 2026-04-02 2026-04-10 בלינק פינטק פלטפורמה להשק שונות 639.72 debit 639.72 ILS רגילה 7945 Credit Card - Discount
53
+ 2026-04-03 2026-04-03 ישראכרט בע"מ-י 230.49 debit 230.49 ILS Bank Account - Leumi 20543 6804.69
54
+ 2026-04-05 2026-04-05 העברת משכורת 21435 credit 21435 ILS Bank Account - Leumi 99012 העברה מאת: הפועלים 12-584-000133340 משכורת 28239.69
55
+ 2026-04-05 2026-04-05 הק בורסה קנ. 330.12 debit 330.12 ILS Bank Account - Leumi 231980 27909.57
56
+ 2026-04-06 2026-04-10 שרותי בריאות כללית הו"ק רפואה ובתי מרקחת 30 debit 30 ILS רגילה 6893 Credit Card - Discount הוראת קבע
57
+ 2026-04-07 2026-04-07 מכירת ני"ע 19974.87 credit 19974.87 ILS Bank Account - Leumi 231980 שם נייר ערך: מגדל כסשק לאקונ ,MIGDAL MNMRFIL 47884.44
58
+ 2026-04-07 2026-04-10 לולי גלידה מזון וצריכה 19 debit 19 ILS רגילה 6893 Credit Card - Discount
59
+ 2026-04-07 2026-04-10 פיס פלוס -תו נטען פנאי, בידור וספורט 225 debit 225 ILS רגילה 7945 Credit Card - Discount
60
+ 2026-04-07 2026-04-10 הטבות פיס פ. פנאי, בידור וספורט 550 debit 550 ILS רגילה 7945 Credit Card - Discount
61
+ 2026-04-10 2026-04-10 ישראכרט בע"מ-י 3552.87 debit 3552.87 ILS Bank Account - Leumi 20543 44331.57
62
+ 2026-04-10 2026-04-10 לאומי ויזה 1635.34 debit 1635.34 ILS Bank Account - Leumi 917945 33381.74
63
+ 2026-04-10 2026-04-10 פרימיום אקספ-י 8551.2 debit 8551.2 ILS Bank Account - Leumi 26000 35780.37
64
+ 2026-04-10 2026-04-10 מקס איט פיננ-י 763.29 debit 763.29 ILS Bank Account - Leumi 34685 35017.08
65
+ 2026-04-12 2026-04-12 העברה דיגיטל 360 debit 360 ILS Bank Account - Leumi 699143636 העברה אל: קיבוץ עין הנציב 20-439-000305465 סתימה אלירם שמש 33021.74
66
+ """
67
+
68
+ def parse_amount(amount_str):
69
+ """Parse amount string to float."""
70
+ if not amount_str:
71
+ return 0.0
72
+ return float(amount_str.replace(',', ''))
73
+
74
+ def parse_transactions():
75
+ """Parse the transaction data."""
76
+ transactions = []
77
+ lines = TRANSACTIONS_DATA.strip().split('\n')
78
+
79
+ for line in lines:
80
+ if not line.strip():
81
+ continue
82
+
83
+ parts = line.split('\t')
84
+ if len(parts) < 11:
85
+ print(f"Skipping malformed line: {line[:50]}...")
86
+ continue
87
+
88
+ tx = {
89
+ 'transaction_date': parts[0],
90
+ 'charge_date': parts[1],
91
+ 'merchant': parts[2].strip(),
92
+ 'category': parts[3].strip() if len(parts) > 3 else '',
93
+ 'amount': parse_amount(parts[4]),
94
+ 'direction': parts[5], # debit or credit
95
+ 'original_amount': parts[6],
96
+ 'original_currency': parts[7],
97
+ 'transaction_type': parts[8] if len(parts) > 8 else '',
98
+ 'card_last4': parts[9] if len(parts) > 9 else '',
99
+ 'source': parts[10] if len(parts) > 10 else '',
100
+ 'reference': parts[11] if len(parts) > 11 else '',
101
+ 'notes': parts[12] if len(parts) > 12 else '',
102
+ }
103
+ transactions.append(tx)
104
+
105
+ return transactions
106
+
107
+ def login(base_url, username, password):
108
+ """Login and get JWT token."""
109
+ response = requests.post(
110
+ f"{base_url}/token",
111
+ data={"username": username, "password": password}
112
+ )
113
+ if response.status_code == 200:
114
+ return response.json()["access_token"]
115
+ else:
116
+ print(f"Login failed: {response.status_code}")
117
+ print(response.text)
118
+ return None
119
+
120
+ def import_via_api(base_url, token, transactions):
121
+ """Send transactions to API."""
122
+ headers = {"Authorization": f"Bearer {token}"}
123
+
124
+ response = requests.post(
125
+ f"{base_url}/transactions/import",
126
+ headers=headers,
127
+ json={"transactions": transactions}
128
+ )
129
+
130
+ if response.status_code == 200:
131
+ return response.json()
132
+ else:
133
+ print(f"Import failed: {response.status_code}")
134
+ print(response.text)
135
+ return None
136
+
137
+ def main():
138
+ # Determine environment
139
+ env = sys.argv[1] if len(sys.argv) > 1 else "local"
140
+
141
+ if env == "local":
142
+ base_url = "http://localhost:8000"
143
+ env_file = ".env.local"
144
+ elif env == "prod":
145
+ base_url = "https://your-huggingface-space-url" # Update this
146
+ env_file = ".env.remote"
147
+ else:
148
+ print(f"Unknown environment: {env}")
149
+ print("Usage: python import_via_api.py [local|prod]")
150
+ sys.exit(1)
151
+
152
+ # Load credentials
153
+ env_path = os.path.join(os.path.dirname(__file__), env_file)
154
+ if os.path.exists(env_path):
155
+ load_dotenv(env_path)
156
+
157
+ # Get credentials (set these in your .env file or prompt)
158
+ username = os.getenv("IMPORT_USERNAME", "eliram")
159
+ password = os.getenv("IMPORT_PASSWORD")
160
+
161
+ if not password:
162
+ password = input(f"Password for {username}: ")
163
+
164
+ print(f"\nConnecting to {env} environment...")
165
+ print(f"Base URL: {base_url}\n")
166
+
167
+ # Parse transactions
168
+ transactions = parse_transactions()
169
+ print(f"Parsed {len(transactions)} transactions\n")
170
+
171
+ # Login
172
+ print(f"Logging in as {username}...")
173
+ token = login(base_url, username, password)
174
+ if not token:
175
+ sys.exit(1)
176
+ print("✓ Logged in successfully\n")
177
+
178
+ # Import
179
+ print("Importing transactions via API...")
180
+ result = import_via_api(base_url, token, transactions)
181
+
182
+ if result:
183
+ print("\n" + "="*50)
184
+ print("IMPORT RESULTS")
185
+ print("="*50)
186
+ print(f"Total: {result['total']}")
187
+ print(f"Imported: {result['imported']}")
188
+ print(f"Skipped (duplicates): {result['skipped']}")
189
+ if result['errors']:
190
+ print(f"\nErrors ({len(result['errors'])}):")
191
+ for err in result['errors'][:5]:
192
+ print(f" - {err}")
193
+ print("="*50)
194
+
195
+ if __name__ == "__main__":
196
+ main()
main.py CHANGED
@@ -462,6 +462,117 @@ def create_transaction(transaction: Transaction, session: Session = Depends(get_
462
  if isinstance(e, HTTPException):
463
  raise e
464
  raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  @app.get("/transactions/installments")
466
  def get_installment_plans(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
467
  return session.exec(
 
462
  if isinstance(e, HTTPException):
463
  raise e
464
  raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
465
+
466
+ # Import transactions from bank data
467
+ @app.post("/transactions/import")
468
+ def import_transactions(
469
+ data: dict,
470
+ session: Session = Depends(get_session),
471
+ current_user: User = Depends(get_current_user)
472
+ ):
473
+ """Import multiple transactions from bank export data."""
474
+ transactions = data.get("transactions", [])
475
+ imported = 0
476
+ skipped = 0
477
+ errors = []
478
+
479
+ # Category mapping from bank to app
480
+ category_map = {
481
+ 'דלק, חשמל וגז': 'בית',
482
+ 'שונות': 'שונות',
483
+ 'שירותי תקשורת': 'תקשורת',
484
+ 'מזון וצריכה': 'מזון',
485
+ 'רפואה ובתי מרקחת': 'בריאות',
486
+ 'פנאי, בידור וספורט': 'פנאי ובידור',
487
+ 'תחבורה ורכבים': 'תחבורה',
488
+ '': 'שונות',
489
+ }
490
+
491
+ for tx_data in transactions:
492
+ try:
493
+ # Map category
494
+ bank_cat = tx_data.get("category", "")
495
+ app_category = category_map.get(bank_cat, bank_cat)
496
+
497
+ # Find or create category
498
+ category = session.exec(
499
+ select(Category).where(Category.name == app_category)
500
+ ).first()
501
+
502
+ if not category:
503
+ # Create new category
504
+ is_expense = tx_data.get("direction") == "debit"
505
+ category = Category(
506
+ name=app_category,
507
+ type="EXPENSE" if is_expense else "INCOME",
508
+ icon="📦",
509
+ color="#666666"
510
+ )
511
+ session.add(category)
512
+ session.commit()
513
+ session.refresh(category)
514
+
515
+ # Map payment method
516
+ pm_name = "כרטיס אשראי" if "Credit Card" in tx_data.get("source", "") else "העברה בנקאית"
517
+ pm = session.exec(select(PaymentMethod).where(PaymentMethod.name == pm_name)).first()
518
+ pm_id = pm.id if pm else 1
519
+
520
+ # Build notes
521
+ notes_parts = []
522
+ if tx_data.get("notes"):
523
+ notes_parts.append(tx_data["notes"])
524
+ if tx_data.get("transaction_type") and tx_data["transaction_type"] != "רגילה":
525
+ notes_parts.append(f"סוג: {tx_data['transaction_type']}")
526
+ if tx_data.get("card_last4"):
527
+ notes_parts.append(f"כרטיס: ****{tx_data['card_last4']}")
528
+ if tx_data.get("reference"):
529
+ notes_parts.append(f"אסמכתא: {tx_data['reference']}")
530
+
531
+ notes = " | ".join(notes_parts) if notes_parts else None
532
+
533
+ # Check for duplicate
534
+ existing = session.exec(
535
+ select(Transaction).where(
536
+ Transaction.amount == tx_data["amount"],
537
+ Transaction.date == tx_data["transaction_date"],
538
+ Transaction.user_id == current_user.id
539
+ )
540
+ ).first()
541
+
542
+ if existing:
543
+ skipped += 1
544
+ continue
545
+
546
+ # Create transaction
547
+ is_expense = tx_data.get("direction") == "debit"
548
+ tx = Transaction(
549
+ amount=tx_data["amount"],
550
+ type="expense" if is_expense else "income",
551
+ category_id=category.id,
552
+ payment_method_id=pm_id,
553
+ user_id=current_user.id,
554
+ date=tx_data["transaction_date"],
555
+ notes=notes,
556
+ payee=tx_data.get("merchant", "")[:100],
557
+ is_installment="תשלומים" in tx_data.get("transaction_type", ""),
558
+ installment_number=None,
559
+ total_installments=None
560
+ )
561
+ session.add(tx)
562
+ imported += 1
563
+
564
+ except Exception as e:
565
+ errors.append(f"Error importing {tx_data.get('merchant', 'unknown')}: {str(e)}")
566
+
567
+ session.commit()
568
+
569
+ return {
570
+ "imported": imported,
571
+ "skipped": skipped,
572
+ "errors": errors,
573
+ "total": len(transactions)
574
+ }
575
+
576
  @app.get("/transactions/installments")
577
  def get_installment_plans(session: Session = Depends(get_session), current_user: User = Depends(get_current_user)):
578
  return session.exec(
models.py CHANGED
@@ -4,8 +4,8 @@ from typing import Optional, List
4
  from sqlmodel import SQLModel, Field, Relationship
5
 
6
  class TransactionType(str, Enum):
7
- EXPENSE = "expense"
8
- INCOME = "income"
9
 
10
  class User(SQLModel, table=True):
11
  id: Optional[int] = Field(default=None, primary_key=True)
 
4
  from sqlmodel import SQLModel, Field, Relationship
5
 
6
  class TransactionType(str, Enum):
7
+ EXPENSE = "EXPENSE"
8
+ INCOME = "INCOME"
9
 
10
  class User(SQLModel, table=True):
11
  id: Optional[int] = Field(default=None, primary_key=True)