diff --git a/src/organizations/test_companies.py b/src/organizations/test_companies.py index 9175625..cb2f9d1 100644 --- a/src/organizations/test_companies.py +++ b/src/organizations/test_companies.py @@ -200,6 +200,25 @@ class TestCompanyDatasetService: f"{legacy_module}.{legacy_record.__class__.__name__}" ) record.legacy_pk = str(legacy_record.pk) + legacy_owner = ( + OrganizationSourceRecord.objects.filter( + legacy_model=record.legacy_model, + legacy_pk=record.legacy_pk, + ) + .exclude(pk=record.pk) + .select_related("extension") + .first() + ) + if legacy_owner is not None: + if ( + legacy_owner.source != source + or legacy_owner.extension.organization_id != organization.pk + ): + raise RuntimeError( + "Legacy parser record is already linked to another " + "organization source record" + ) + legacy_owner.delete() record.save(update_fields=["legacy_model", "legacy_pk", "updated_at"]) if source == ParserLoadLog.Source.FNS_REPORTS: cls._refresh_financial_lines( diff --git a/tests/apps/organizations/test_test_companies_commands.py b/tests/apps/organizations/test_test_companies_commands.py index 18900e7..952e54d 100644 --- a/tests/apps/organizations/test_test_companies_commands.py +++ b/tests/apps/organizations/test_test_companies_commands.py @@ -216,6 +216,34 @@ class TestCompaniesCommandsTest(TestCase): ) self.assertEqual(OrganizationSourceRecord.objects.count(), 20 * 15) + def test_create_replaces_stale_source_record_for_same_legacy_row(self): + call_command("create_test_companies", stdout=StringIO()) + + company = Organization.objects.get(name="Тестовая компания 1") + stale_record = OrganizationSourceRecord.objects.get( + extension__organization=company, + source=ParserLoadLog.Source.PROCUREMENTS, + ) + stale_record.external_id = "0373200000000000001" + stale_record.save(update_fields=["external_id"]) + + call_command("create_test_companies", stdout=StringIO()) + + canonical_record = OrganizationSourceRecord.objects.get( + extension__organization=company, + source=ParserLoadLog.Source.PROCUREMENTS, + ) + self.assertEqual( + canonical_record.external_id, + f"{TEST_RECORD_PREFIX}:01:{ParserLoadLog.Source.PROCUREMENTS}", + ) + self.assertEqual( + canonical_record.legacy_pk, + str( + ProcurementRecord.objects.get(purchase_number="0373200000000000001").pk + ), + ) + @override_settings(STATE_CORP_EXCHANGE_TOKEN=TEST_EXCHANGE_TOKEN) def test_created_source_records_are_included_in_state_corp_package(self): call_command("create_test_companies", stdout=StringIO())