How can I safely map scoped API address-standardization responses back to the correct selected React rows?
15:36 09 Sep 2026

have a TypeScript/React flow where users can standardize addresses for all rows, selected rows, or all except selected rows.

When only selected rows are sent to the API, the response contains only those rows in request order. I need to safely map those standardized results back to the correct original location rows.

I also need to preserve the original address for Revert and avoid modifying rows that were not selected.

What is the best approach here: map responses using the original row indexes, use a stable location ID, or include an explicit row identifier in the API request/response?

Is there any edge case in this approach that could cause the standardized address to be applied to the wrong location?

import { describe, expect, it } from "vitest";
import type { WorkflowLocation } from "@/lib/workflow-data";
import {
  applyWorkingFromAddressGroup,
  LOCATION_ADDRESS_FIELDS,
  locationActionNeedsSelection,
  locationAddressGroupFrom,
  pruneSelectedLocationRows,
  resolveLocationActionRows,
  revertLocationAddresses,
  captureOriginalBeforeStandardize,
  standardLostAfterLocationFieldEdit,
  withLocalStandardizedLocations,
  withOriginalAddressGroup,
} from "./location-address-groups";
import { applyScrubbedLocations, type ScrubbedLocation } from "./api/clearance";

function loc(partial: Partial = {}): WorkflowLocation {
  return {
    n: 1,
    locationNumber: "1",
    buildingNumber: "1",
    address: "123 East 37th Street",
    city: "New York",
    state: "NY",
    county: "",
    zip: "10016",
    construction: "",
    year: 1940,
    sprinkler: "",
    stories: 15,
    building: 0,
    contents: 0,
    bi: 0,
    tiv: 0,
    sqFt: 0,
    images: 0,
    standardized: false,
    ...partial,
  };
}

const scrubbed: ScrubbedLocation = {
  number: 899,
  location_number: "1",
  building_number: "1",
  address: "123 East 37th Street",
  addressUser: "123 East 37th Street",
  city: "New York",
  state: "NY",
  zipcode: "10016",
  status: "success",
  scrubbedAddress: {
    FormattedStreetAddress: "123 E 37th St",
    City: "New York",
    State: "NY",
    ZipCode: "10016",
    County: "New York County",
  },
};

describe("standardLostAfterLocationFieldEdit", () => {
  it("treats address, city, state, zip, and county as geo fields", () => {
    expect([...LOCATION_ADDRESS_FIELDS].sort()).toEqual([
      "address",
      "city",
      "county",
      "state",
      "zip",
    ]);
  });

  it("clears standardized only when a geo field is edited", () => {
    for (const field of LOCATION_ADDRESS_FIELDS) {
      expect(standardLostAfterLocationFieldEdit(true, field)).toBe(true);
    }
    expect(standardLostAfterLocationFieldEdit(true, "tiv")).toBe(false);
    expect(standardLostAfterLocationFieldEdit(true, "locationNumber")).toBe(false);
    expect(standardLostAfterLocationFieldEdit(true, "year")).toBe(false);
    expect(standardLostAfterLocationFieldEdit(true, "construction")).toBe(false);
  });

  it("does not report a loss when the row was not standardized", () => {
    expect(standardLostAfterLocationFieldEdit(false, "address")).toBe(false);
    expect(standardLostAfterLocationFieldEdit(false, "city")).toBe(false);
    expect(standardLostAfterLocationFieldEdit(false, "tiv")).toBe(false);
  });
});

describe("location address groups", () => {
  it("coerces missing geo fields to empty strings", () => {
    expect(
      locationAddressGroupFrom({
        address: undefined as unknown as string,
        city: null as unknown as string,
        state: undefined as unknown as string,
        zip: null as unknown as string,
        county: undefined as unknown as string,
      }),
    ).toEqual({
      address: "",
      city: "",
      state: "",
      zip: "",
      county: "",
    });
  });

  it("snapshots working geo fields as the original group", () => {
    const original = locationAddressGroupFrom(loc());
    expect(original).toEqual({
      address: "123 East 37th Street",
      city: "New York",
      state: "NY",
      zip: "10016",
      county: "",
    });
  });

  it("adds an original group when the row does not have one", () => {
    const seeded = withOriginalAddressGroup(loc({ address: "1 First Ave" }));
    expect(seeded.original).toEqual({
      address: "1 First Ave",
      city: "New York",
      state: "NY",
      zip: "10016",
      county: "",
    });
  });

  it("does not overwrite an existing original group until Standardize", () => {
    const first = withOriginalAddressGroup(loc());
    const edited = withOriginalAddressGroup({ ...first, address: "9 Changed St" });
    expect(edited.original?.address).toBe("123 East 37th Street");
    expect(edited.original).toBe(first.original);
  });

  it("saves the edited working address when Standardize is clicked", () => {
    const seeded = withOriginalAddressGroup(loc());
    const typed = { ...seeded, address: "9 Changed St", city: "Brooklyn", standardized: false };
    const captured = captureOriginalBeforeStandardize(typed);
    expect(captured.original).toEqual({
      address: "9 Changed St",
      city: "Brooklyn",
      state: "NY",
      zip: "10016",
      county: "",
    });
  });

  it("keeps the prior original if the row is already standardized", () => {
    const captured = captureOriginalBeforeStandardize({
      ...loc({ address: "123 E 37th St", standardized: true }),
      original: locationAddressGroupFrom(loc()),
    });
    expect(captured.original?.address).toBe("123 East 37th Street");
  });

  it("snapshots current values when standardized is true but original is missing", () => {
    const captured = captureOriginalBeforeStandardize(loc({ address: "9 New St", standardized: true }));
    expect(captured.original).toEqual({
      address: "9 New St",
      city: "New York",
      state: "NY",
      zip: "10016",
      county: "",
    });
  });

  it("restores working fields from the original group", () => {
    const original = locationAddressGroupFrom(loc());
    const next = applyWorkingFromAddressGroup(loc({ address: "123 E 37th St", county: "New York County" }), original);
    expect(next.address).toBe("123 East 37th Street");
    expect(next.city).toBe("New York");
    expect(next.state).toBe("NY");
    expect(next.zip).toBe("10016");
    expect(next.county).toBe("");
  });
});

describe("resolveLocationActionRows", () => {
  it("returns every row for all", () => {
    expect(resolveLocationActionRows("all", [1], 3)).toEqual([0, 1, 2]);
    expect(locationActionNeedsSelection("all")).toBe(false);
  });

  it("returns only checked rows for selected", () => {
    expect(resolveLocationActionRows("selected", new Set([0, 2]), 4)).toEqual([0, 2]);
    expect(locationActionNeedsSelection("selected")).toBe(true);
  });

  it("returns unchecked rows for excludingSelected", () => {
    expect(resolveLocationActionRows("excludingSelected", [1], 3)).toEqual([0, 2]);
  });

  it("returns no rows when selected/excluding has an empty selection", () => {
    expect(resolveLocationActionRows("selected", [], 3)).toEqual([]);
    expect(resolveLocationActionRows("excludingSelected", [], 3)).toEqual([0, 1, 2]);
    expect(locationActionNeedsSelection("excludingSelected")).toBe(false);
  });

  it("returns an empty list when total is 0", () => {
    expect(resolveLocationActionRows("all", [0], 0)).toEqual([]);
    expect(resolveLocationActionRows("selected", new Set([0]), 0)).toEqual([]);
    expect(resolveLocationActionRows("excludingSelected", [0], 0)).toEqual([]);
  });
});

describe("applyScrubbedLocations original + scope", () => {
  it("keeps the original group and writes the scrubbed group", () => {
    const [next] = applyScrubbedLocations([loc({ id: "899" })], [scrubbed]);
    expect(next.original).toEqual({
      address: "123 East 37th Street",
      city: "New York",
      state: "NY",
      zip: "10016",
      county: "",
    });
    expect(next.address).toBe("123 E 37th St");
    expect(next.county).toBe("New York County");
    expect(next.scrubbed?.address).toBe("123 E 37th St");
    expect(next.standardized).toBe(true);
  });

  it("stores the pre-standardize edited address so Revert can restore it", () => {
    const seeded = withOriginalAddressGroup(loc({ id: "899", address: "123 East 37th Street" }));
    const typed = { ...seeded, address: "123 E 37 Street", standardized: false };
    const [next] = applyScrubbedLocations([typed], [scrubbed]);
    expect(next.original?.address).toBe("123 E 37 Street");
    expect(next.address).toBe("123 E 37th St");
    const [reverted] = revertLocationAddresses([next], [0]);
    expect(reverted.address).toBe("123 E 37 Street");
    expect(reverted.standardized).toBe(false);
  });

  it("only scrubs the requested row indexes", () => {
    const rows = [loc({ id: "899", n: 1 }), loc({ id: "900", n: 2, address: "10 Pine" })];
    const [kept, skipped] = applyScrubbedLocations(rows, [scrubbed], [0]);
    expect(kept.address).toBe("123 E 37th St");
    expect(kept.standardized).toBe(true);
    expect(skipped.address).toBe("10 Pine");
    expect(skipped.standardized).toBe(false);
  });

  it("leaves standardized false on a failed or unmatched scoped row", () => {
    const rows = [loc({ id: "899", n: 1 }), loc({ id: "900", n: 2, address: "10 Pine" })];
    const failed: ScrubbedLocation = { ...scrubbed, number: 899, status: "failure" };
    const [miss, unmatched] = applyScrubbedLocations(rows, [failed], [0, 1]);
    expect(miss.address).toBe("123 East 37th Street");
    expect(miss.standardized).toBe(false);
    expect(unmatched.address).toBe("10 Pine");
    expect(unmatched.standardized).toBe(false);
  });

  it("reads a flat standardized_address when the portal group is missing", () => {
    const [next] = applyScrubbedLocations(
      [loc({ id: "12" })],
      [
        {
          number: 12,
          address: "123 East 37th Street",
          city: "New York",
          state: "NY",
          zipcode: "10016",
          standardized_address: "123 E 37th St, New York, NY 10016",
          status: "success",
        },
      ],
    );
    expect(next.address).toBe("123 E 37th St, New York, NY 10016");
    expect(next.original?.address).toBe("123 East 37th Street");
    expect(next.standardized).toBe(true);
  });
});

describe("revertLocationAddresses", () => {
  it("falls back to current working fields when original is missing", () => {
    const [reverted] = revertLocationAddresses([loc({ address: "Only working", standardized: true })], [0]);
    expect(reverted.address).toBe("Only working");
    expect(reverted.original?.address).toBe("Only working");
    expect(reverted.standardized).toBe(false);
  });

  it("reverts all requested rows back to the original group", () => {
    const [scrubbedRow] = applyScrubbedLocations([loc({ id: "899" })], [scrubbed]);
    const [reverted] = revertLocationAddresses([scrubbedRow], [0]);
    expect(reverted.address).toBe("123 East 37th Street");
    expect(reverted.city).toBe("New York");
    expect(reverted.state).toBe("NY");
    expect(reverted.zip).toBe("10016");
    expect(reverted.county).toBe("");
    expect(reverted.standardized).toBe(false);
    expect(reverted.original?.address).toBe("123 East 37th Street");
  });

  it("leaves unselected rows standardized", () => {
    const first = applyScrubbedLocations([loc({ id: "899" })], [scrubbed])[0];
    const second = { ...first, n: 2, id: "900", address: "9 Other St" };
    const [a, b] = revertLocationAddresses([first, second], [0]);
    expect(a.standardized).toBe(false);
    expect(a.address).toBe("123 East 37th Street");
    expect(b.address).toBe("9 Other St");
    expect(b.standardized).toBe(true);
  });

  it("reverts selected and excludingSelected the same way standardize scopes rows", () => {
    const rows = [
      applyScrubbedLocations([loc({ id: "899", n: 1 })], [scrubbed])[0],
      applyScrubbedLocations([loc({ id: "899", n: 2, address: "200 West 40th Street" })], [scrubbed])[0],
      loc({ n: 3, address: "Keep me", standardized: true, original: locationAddressGroupFrom(loc({ address: "Keep me" })) }),
    ];
    const selected = revertLocationAddresses(rows, resolveLocationActionRows("selected", [1], 3));
    expect(selected[0].address).toBe("123 E 37th St");
    expect(selected[1].address).toBe("200 West 40th Street");
    expect(selected[2].address).toBe("Keep me");

    const excluding = revertLocationAddresses(rows, resolveLocationActionRows("excludingSelected", [1], 3));
    expect(excluding[0].address).toBe("123 East 37th Street");
    expect(excluding[1].address).toBe("123 E 37th St");
    expect(excluding[2].address).toBe("Keep me");
    expect(excluding[2].standardized).toBe(false);
  });
});

describe("local standardize fallback", () => {
  it("standardizes every row when no indexes are passed", () => {
    const [first, second] = withLocalStandardizedLocations([
      loc({ address: "1 Main" }),
      loc({ n: 2, address: "2 Oak" }),
    ]);
    expect(first.standardized).toBe(true);
    expect(second.standardized).toBe(true);
    expect(first.original?.address).toBe("1 Main");
    expect(second.original?.address).toBe("2 Oak");
  });

  it("keeps current city/state/zip on scoped rows and does not invent an address", () => {
    const [first, second] = withLocalStandardizedLocations(
      [loc({ city: "", state: "", zip: "" }), loc({ n: 2, address: "10 Pine", city: "Chicago", state: "IL", zip: "60601" })],
      [0],
    );
    expect(first.city).toBe("");
    expect(first.state).toBe("");
    expect(first.zip).toBe("");
    expect(first.original?.city).toBe("");
    expect(first.scrubbed?.city).toBe("");
    expect(first.standardized).toBe(true);
    expect(second.city).toBe("Chicago");
    expect(second.standardized).toBe(false);
  });
});

describe("pruneSelectedLocationRows", () => {
  it("drops the deleted index and shifts later rows", () => {
    expect([...pruneSelectedLocationRows(new Set([0, 2, 3]), 2)].sort()).toEqual([0, 2]);
  });

  it("shifts later checkboxes when the first row is deleted", () => {
    expect([...pruneSelectedLocationRows(new Set([0, 1]), 0)].sort()).toEqual([0]);
  });
});
reactjs