From a41b32420aff25b7492736e525ee86fecf7063c0 Mon Sep 17 00:00:00 2001 From: Asish Kumar Date: Sat, 5 Dec 2026 05:46:57 +0530 Subject: [PATCH] feat(export): back up split expenses Export and restore left split events out, so moving to a new instance or restoring a backup lost every event, its people, expenses, payments and the links to the members' own transactions. - Export has a "Split Expenses" option, on by default. It writes split_events, split_participants, split_expenses, split_expense_shares and split_payments. Like the bank sync option, it warns that the file carries something sensitive: the events' share links, kept so the links people already have keep working after a restore. - split_transaction_links goes along only when transactions are exported too, the same way sub-transactions follow their parents, so a restore never points at transactions missing from the backup. - Restore reads the new files after users, currencies and transactions, in dependency order. Everything is matched by id, except the event's currency (by name, like DCA strategies) and the linked transaction, which is looked up across every user: restore runs as the admin, who can't see the other members' transactions. - Guests' usernames and password hashes are restored, so they can still sign in through the share link. - Attachments stay out, as transaction attachments do: they're files, not rows. --- app/apps/export_app/forms.py | 19 +++ app/apps/export_app/resources/splits.py | 92 ++++++++++++++ app/apps/export_app/tests.py | 153 ++++++++++++++++++++++++ app/apps/export_app/views.py | 32 +++++ 4 files changed, 296 insertions(+) create mode 100644 app/apps/export_app/resources/splits.py diff --git a/app/apps/export_app/forms.py b/app/apps/export_app/forms.py index b4b4e9bf..8adbd43d 100644 --- a/app/apps/export_app/forms.py +++ b/app/apps/export_app/forms.py @@ -95,6 +95,13 @@ class ExportForm(forms.Form): label=_("DCA"), initial=False, ) + splits = forms.BooleanField( + required=False, + widget=forms.CheckboxInput(attrs={"class": "checkbox"}), + label=_("Split Expenses"), + help_text=_("Includes the events' share links"), + initial=True, + ) import_profiles = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={"class": "checkbox"}), @@ -142,6 +149,18 @@ class RestoreForm(forms.Form): ) dca_strategies = forms.FileField(required=False, label=_("DCA Strategies")) dca_entries = forms.FileField(required=False, label=_("DCA Entries")) + split_events = forms.FileField(required=False, label=_("Split Events")) + split_participants = forms.FileField( + required=False, label=_("Split Participants") + ) + split_expenses = forms.FileField(required=False, label=_("Split Expenses")) + split_expense_shares = forms.FileField( + required=False, label=_("Split Expense Shares") + ) + split_payments = forms.FileField(required=False, label=_("Split Payments")) + split_transaction_links = forms.FileField( + required=False, label=_("Split Transaction Links") + ) import_profiles = forms.FileField(required=False, label=_("Import Profiles")) def __init__(self, *args, **kwargs): diff --git a/app/apps/export_app/resources/splits.py b/app/apps/export_app/resources/splits.py new file mode 100644 index 00000000..82595011 --- /dev/null +++ b/app/apps/export_app/resources/splits.py @@ -0,0 +1,92 @@ +from import_export import fields, resources +from import_export.widgets import ForeignKeyWidget + +from apps.currencies.models import Currency +from apps.export_app.resources.transactions import AnyOwnerForeignKeyWidget +from apps.export_app.widgets.numbers import UniversalDecimalWidget +from apps.splits.models import ( + SplitEvent, + SplitExpense, + SplitExpenseShare, + SplitParticipant, + SplitPayment, + SplitTransactionLink, +) +from apps.transactions.models import Transaction + + +class SplitEventResource(resources.ModelResource): + currency = fields.Field( + attribute="currency", + column_name="currency", + widget=ForeignKeyWidget(Currency, "name"), + ) + + class Meta: + model = SplitEvent + + def get_queryset(self): + return SplitEvent.objects.select_related("currency") + + +class SplitParticipantResource(resources.ModelResource): + class Meta: + model = SplitParticipant + + +class SplitExpenseResource(resources.ModelResource): + amount = fields.Field( + attribute="amount", + column_name="amount", + widget=UniversalDecimalWidget(), + ) + + class Meta: + model = SplitExpense + + +class SplitExpenseShareResource(resources.ModelResource): + amount = fields.Field( + attribute="amount", + column_name="amount", + widget=UniversalDecimalWidget(), + ) + percentage = fields.Field( + attribute="percentage", + column_name="percentage", + widget=UniversalDecimalWidget(), + ) + shares = fields.Field( + attribute="shares", + column_name="shares", + widget=UniversalDecimalWidget(), + ) + + class Meta: + model = SplitExpenseShare + + +class SplitPaymentResource(resources.ModelResource): + amount = fields.Field( + attribute="amount", + column_name="amount", + widget=UniversalDecimalWidget(), + ) + + class Meta: + model = SplitPayment + + +class SplitTransactionLinkResource(resources.ModelResource): + # By id across every user: the restoring admin can't see the others' transactions + transaction = fields.Field( + attribute="transaction", + column_name="transaction", + widget=AnyOwnerForeignKeyWidget(Transaction), + ) + + class Meta: + model = SplitTransactionLink + + def get_queryset(self): + return SplitTransactionLink.objects.select_related("transaction") diff --git a/app/apps/export_app/tests.py b/app/apps/export_app/tests.py index 5ea92e6c..0d1a30c8 100644 --- a/app/apps/export_app/tests.py +++ b/app/apps/export_app/tests.py @@ -14,6 +14,14 @@ from apps.accounts.models import Account, InvestmentClass from apps.common.middleware.thread_local import delete_current_user, write_current_user from apps.currencies.models import Currency from apps.export_app.resources.accounts import AccountResource, InvestmentClassResource +from apps.export_app.resources.splits import ( + SplitEventResource, + SplitExpenseResource, + SplitExpenseShareResource, + SplitParticipantResource, + SplitPaymentResource, + SplitTransactionLinkResource, +) from apps.export_app.resources.transactions import ( InstallmentPlanResource, RecurringTransactionResource, @@ -25,6 +33,14 @@ from apps.export_app.resources.transactions import ( TransactionResource, ) from apps.export_app.views import process_imports +from apps.splits.models import ( + SplitEvent, + SplitExpense, + SplitExpenseShare, + SplitParticipant, + SplitPayment, + SplitTransactionLink, +) from apps.transactions.models import ( InstallmentPlan, QuickTransaction, @@ -221,6 +237,143 @@ class MultiUserRestoreTests(TestCase): self.assertEqual(export_queries(), few) +class SplitBackupTests(TestCase): + """Export and restore run as the admin; split events hold several users' data.""" + + def setUp(self): + User = get_user_model() + self.admin = User.objects.create_superuser(email="admin@x.com", password="pw") + bob = User.objects.create_user(email="bob@x.com", password="pw") + usd = Currency.objects.create(code="USD", name="US Dollar", decimal_places=2) + write_current_user(bob) + self.addCleanup(delete_current_user) + account = Account.objects.create(name="Checking", currency=usd) + hotel = Transaction.objects.create( + account=account, type="EX", date=date(2030, 1, 5), amount=90, + description="Hotel", + ) + + event = SplitEvent.objects.create( + name="Beach Trip", currency=usd, creator=bob, is_archived=True + ) + bob_p = SplitParticipant.objects.create(event=event, user=bob, name="Bob") + SplitParticipant.objects.create( + event=event, user=self.admin, name="Admin", is_active=False + ) + charlie = SplitParticipant.objects.create( + event=event, name="Charlie", is_external=True + ) + charlie.set_external_password("secret", username="chaz") + + expense = SplitExpense.objects.create( + event=event, paid_by=bob_p, created_by_participant=charlie, + description="Hotel", amount=Decimal("90.00"), date=date(2030, 1, 5), + split_type=SplitExpense.SplitType.SHARES, notes="Two nights", + ) + SplitExpenseShare.objects.create( + expense=expense, participant=bob_p, amount=Decimal("60.00"), + percentage=Decimal("66.6667"), shares=Decimal("2"), + ) + SplitExpenseShare.objects.create( + expense=expense, participant=charlie, amount=Decimal("30.00"), + percentage=Decimal("33.3333"), shares=Decimal("1"), + ) + payment = SplitPayment.objects.create( + event=event, from_participant=charlie, to_participant=bob_p, + amount=Decimal("12.50"), date=date(2030, 1, 6), notes="Part of it", + ) + SplitTransactionLink.objects.create( + event=event, user=bob, transaction=hotel, + kind=SplitTransactionLink.Kind.EXPENSE, expense=expense, + ) + SplitTransactionLink.objects.create( + event=event, user=bob, transaction=hotel, + kind=SplitTransactionLink.Kind.PAYMENT_IN, payment=payment, + counterparty=charlie, + ) + # Restore runs as the admin, who can't see Bob's transactions + write_current_user(self.admin) + + def _state(self): + return [ + sorted(SplitEvent.objects.values_list( + "name", "currency__name", "creator__email", "share_token", + "allow_external_access", "is_archived", + )), + sorted(SplitParticipant.objects.values_list( + "name", "user__email", "is_external", "is_active", + "external_username", "external_password_hash", + )), + sorted(SplitExpense.objects.values_list( + "description", "paid_by__name", "created_by_participant__name", + "amount", "date", "split_type", "notes", + )), + sorted(SplitExpenseShare.objects.values_list( + "expense__description", "participant__name", "amount", "percentage", "shares" + )), + sorted(SplitPayment.objects.values_list( + "from_participant__name", "to_participant__name", "amount", "date", "notes" + )), + sorted(SplitTransactionLink.objects.values_list( + "user__email", "transaction__description", "kind", + "expense__description", "payment__notes", "counterparty__name", + )), + ] + + def test_round_trip_restores_events_and_links_to_each_users_transactions(self): + before = self._state() + backup = io.BytesIO() + with zipfile.ZipFile(backup, "w") as z: + for resource, name in ( + (TransactionResource(), "transactions"), + (SplitEventResource(), "split_events"), + (SplitParticipantResource(), "split_participants"), + (SplitExpenseResource(), "split_expenses"), + (SplitExpenseShareResource(), "split_expense_shares"), + (SplitPaymentResource(), "split_payments"), + (SplitTransactionLinkResource(), "split_transaction_links"), + ): + z.writestr(f"{name}.csv", resource.export().csv) + + SplitExpense.objects.all().delete() + SplitPayment.objects.all().delete() + SplitEvent.objects.all().delete() + Transaction.userless_all_objects.all().delete() + backup.seek(0) + process_imports(None, {"zip_file": backup}) + + self.assertEqual(self._state(), before) + # The share link and the guest's password keep working + charlie = SplitParticipant.objects.get(name="Charlie") + self.assertTrue(charlie.check_external_password("secret")) + self.assertIsNotNone(charlie.external_claimed_at) + + def _exported_files(self, data): + self.client.force_login(self.admin) + response = self.client.post(reverse("export_form"), data, HTTP_HX_REQUEST="true") + with zipfile.ZipFile(io.BytesIO(response.content)) as z: + return set(z.namelist()) + + def test_export_includes_split_expenses(self): + files = self._exported_files({"splits": "on", "transactions": "on"}) + self.assertLessEqual( + { + "split_events.csv", + "split_participants.csv", + "split_expenses.csv", + "split_expense_shares.csv", + "split_payments.csv", + "split_transaction_links.csv", + }, + files, + ) + + def test_transaction_links_are_left_out_without_transactions(self): + files = self._exported_files({"splits": "on"}) + self.assertIn("split_events.csv", files) + self.assertNotIn("split_transaction_links.csv", files) + + class ExportViewTests(TestCase): def setUp(self): self.client.force_login( diff --git a/app/apps/export_app/views.py b/app/apps/export_app/views.py index 5cab9d08..e1635623 100644 --- a/app/apps/export_app/views.py +++ b/app/apps/export_app/views.py @@ -39,6 +39,14 @@ from apps.export_app.resources.rules import ( TransactionRuleActionResource, UpdateOrCreateTransactionRuleResource, ) +from apps.export_app.resources.splits import ( + SplitEventResource, + SplitExpenseResource, + SplitExpenseShareResource, + SplitParticipantResource, + SplitPaymentResource, + SplitTransactionLinkResource, +) from apps.export_app.resources.transactions import ( TransactionResource, TransactionTagResource, @@ -188,6 +196,24 @@ def export_form(request): "dca_entries", ) ) + if form.cleaned_data.get("splits"): + exports.append((SplitEventResource().export(), "split_events")) + exports.append( + (SplitParticipantResource().export(), "split_participants") + ) + exports.append((SplitExpenseResource().export(), "split_expenses")) + exports.append( + (SplitExpenseShareResource().export(), "split_expense_shares") + ) + exports.append((SplitPaymentResource().export(), "split_payments")) + # Links point at transactions, so they go along only with them + if export_transactions: + exports.append( + ( + SplitTransactionLinkResource().export(), + "split_transaction_links", + ) + ) if export_import_profiles: exports.append((ImportProfileResource().export(), "import_profiles")) @@ -294,6 +320,12 @@ def process_imports(request, cleaned_data): ("bank_sync_accounts", BankSyncAccountResource), ("dca_strategies", DCAStrategyResource), ("dca_entries", DCAEntryResource), + ("split_events", SplitEventResource), + ("split_participants", SplitParticipantResource), + ("split_expenses", SplitExpenseResource), + ("split_expense_shares", SplitExpenseShareResource), + ("split_payments", SplitPaymentResource), + ("split_transaction_links", SplitTransactionLinkResource), ("import_profiles", ImportProfileResource), ("transaction_rules", TransactionRuleResource), ("transaction_rules_actions", TransactionRuleActionResource),