fix(verifayda): format nested Fayda address objects into strings

This commit is contained in:
ghost2023
2026-08-02 00:11:39 +03:00
parent 6af63717ea
commit aaf0aa3c92
6 changed files with 173 additions and 8 deletions

View File

@@ -0,0 +1,81 @@
import { MigrationInterface, QueryRunner } from "typeorm";
/**
* A normalizeUserInfo bug in VerifaydaService read the raw `address#en` /
* `address#am` claim objects (e.g. `{ "zone#en": "...", "region#en": "...",
* "woreda#en": "..." }`) straight through as if they were strings, so any
* company verified before the fix has `attributes.ownerAddress` /
* `poaAddress` stored as that raw object instead of a formatted string —
* which crashes the portal when it tries to render it as text.
*
* Reformats every affected row's ownerAddress/poaAddress into
* "woreda, zone, region" (falling back to whatever #en fields are present,
* in that preferred order, then any leftover fields), mirroring
* VerifaydaService.formatFaydaAddress. Only touches rows where the field is
* still a jsonb object, so it's idempotent and a no-op once repaired.
*/
export class FixFaydaAddressShape3150000000000 implements MigrationInterface {
name = "FixFaydaAddressShape3150000000000";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE OR REPLACE FUNCTION pg_temp.format_fayda_address(addr jsonb)
RETURNS text AS $$
DECLARE
field_order text[] := ARRAY['houseNumber','kebele','woreda','city','subCity','zone','region','postalCode','country'];
f text;
v text;
parts text[] := '{}';
used_keys text[] := '{}';
kv record;
BEGIN
IF addr IS NULL OR jsonb_typeof(addr) != 'object' THEN
RETURN NULL;
END IF;
FOREACH f IN ARRAY field_order LOOP
v := addr ->> (f || '#en');
IF v IS NOT NULL AND trim(v) != '' THEN
parts := array_append(parts, trim(v));
used_keys := array_append(used_keys, f || '#en');
END IF;
END LOOP;
FOR kv IN SELECT * FROM jsonb_each_text(addr) LOOP
IF kv.key LIKE '%#en' AND NOT (kv.key = ANY(used_keys))
AND kv.value IS NOT NULL AND trim(kv.value) != '' THEN
parts := array_append(parts, trim(kv.value));
END IF;
END LOOP;
IF array_length(parts, 1) IS NULL THEN
RETURN NULL;
END IF;
RETURN array_to_string(parts, ', ');
END;
$$ LANGUAGE plpgsql;
UPDATE freight.companies
SET attributes = jsonb_set(
attributes,
'{ownerAddress}',
to_jsonb(pg_temp.format_fayda_address(attributes -> 'ownerAddress'))
)
WHERE jsonb_typeof(attributes -> 'ownerAddress') = 'object';
UPDATE freight.companies
SET attributes = jsonb_set(
attributes,
'{poaAddress}',
to_jsonb(pg_temp.format_fayda_address(attributes -> 'poaAddress'))
)
WHERE jsonb_typeof(attributes -> 'poaAddress') = 'object';
DROP FUNCTION pg_temp.format_fayda_address(jsonb);
`);
}
public async down(): Promise<void> {
// Data repair — not reversible (the original malformed shape isn't worth restoring).
}
}