|
| 1 | +import datetime |
| 2 | +import decimal |
| 3 | + |
| 4 | +import requests |
| 5 | + |
| 6 | +from django.conf import settings |
| 7 | +from django.contrib.auth import get_user_model |
| 8 | + |
| 9 | +from thebook.bookkeeping.models import BankAccount, Category, Transaction |
| 10 | + |
| 11 | + |
| 12 | +def fetch_transactions(start_date: datetime.date, end_date: datetime.date): |
| 13 | + bank_account, _ = BankAccount.objects.get_or_create( |
| 14 | + name=settings.OPENPIX_BANK_ACCOUNT |
| 15 | + ) |
| 16 | + user = get_user_model().objects.get_or_create_automation_user() |
| 17 | + bank_account_transfer_category, _ = Category.objects.get_or_create( |
| 18 | + name="Transferência entre contas bancárias" |
| 19 | + ) |
| 20 | + |
| 21 | + response = requests.get( |
| 22 | + f"{settings.OPENPIX_API_BASE_URL}/api/v1/transaction", |
| 23 | + params={ |
| 24 | + "start": start_date.strftime("%Y-%m-%dT00:00:00Z"), |
| 25 | + "end": end_date.strftime("%Y-%m-%dT00:00:00Z"), |
| 26 | + }, |
| 27 | + headers={ |
| 28 | + "Authorization": settings.OPENPIX_APP_ID, |
| 29 | + }, |
| 30 | + ) |
| 31 | + data = response.json() |
| 32 | + |
| 33 | + transactions = jmespath("transactions", data) |
| 34 | + for transaction in transactions: |
| 35 | + transaction_type = jmespath.search("type", transaction) |
| 36 | + if transaction_type != "WITHDRAW": |
| 37 | + continue |
| 38 | + |
| 39 | + transaction_id = jmespath.search("endToEndId", transaction) |
| 40 | + transaction_date = datetime.datetime.strptime( |
| 41 | + jmespath.search("time", transaction), "%Y-%m-%dT%H:%M:%S.%fZ" |
| 42 | + ).date() |
| 43 | + transaction_amount = -1 * jmespath.search("value", transaction) / 100 |
| 44 | + |
| 45 | + utc_transaction_date = datetime.datetime.strptime( |
| 46 | + raw_date, "%Y-%m-%dT%H:%M:%SZ" |
| 47 | + ) |
| 48 | + |
| 49 | + Transaction.objects.create( |
| 50 | + reference=transaction_id, |
| 51 | + date=transaction_date, |
| 52 | + description=f"Transferência entre contas bancárias - {transaction_id}", |
| 53 | + amount=transaction_amount, |
| 54 | + bank_account=bank_account, |
| 55 | + category=bank_account_transfer_category, |
| 56 | + created_by=user, |
| 57 | + ) |
0 commit comments