Skip to content

fix(condo): DOMA-11706 use address service client for property meter import#7840

Open
abshnko wants to merge 4 commits into
mainfrom
fix/condo/DOMA-11706/fix-property-meter-import-address-resolve
Open

fix(condo): DOMA-11706 use address service client for property meter import#7840
abshnko wants to merge 4 commits into
mainfrom
fix/condo/DOMA-11706/fix-property-meter-import-address-resolve

Conversation

@abshnko

@abshnko abshnko commented Jul 10, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Improvements
    • Enhanced property/address matching when registering meter readings.
    • Address recognition now uses normalized inputs to resolve the correct property within the selected organization.
    • Reading results now include more precise outcomes when an address is unrecognized or does not correspond to a property.
  • Bug Fixes
    • Improved behavior for imported readings containing duplicate or previously unrecognized addresses.
  • Tests
    • Added Jest coverage for successful resolution, missing property within the organization, and unrecognized address handling.

…adrress resolve instead of billing PropertyResolver
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@abshnko, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 21 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1ab9828e-9eda-49f0-a43a-955f84fb728f

📥 Commits

Reviewing files that changed from the base of the PR and between 7e74f26 and 515d9ba.

📒 Files selected for processing (1)
  • apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.js
📝 Walkthrough

Walkthrough

The meter registration service now delegates address normalization and organization property matching to a shared resolver returning resolved addresses and matching properties. Tests cover recognized, organization-unmatched, and unrecognized addresses.

Changes

Property meter resolution

Layer / File(s) Summary
Address normalization and property matching
apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.js, apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.spec.js
Adds chunked address-service normalization, organization-scoped property lookup, resolution error handling, and tests for recognized, unmatched, and unrecognized addresses.
Meter registration integration
apps/condo/domains/meter/schema/RegisterPropertyMetersReadingsService.js
Replaces the previous property resolution flow with the shared resolver and adds per-reading debug logging.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Suggested labels: ✋🙂 Review please

Suggested reviewers: dkoviazin, sitozzz, vovaaxeapolla

Sequence Diagram(s)

sequenceDiagram
  participant MeterService as RegisterPropertyMetersReadingsService
  participant Resolver as resolvePropertyMeterAddressesForOrganization
  participant AddressService as addressService
  participant Property as Keystone Property
  MeterService->>Resolver: readings and organizationId
  Resolver->>AddressService: bulkSearch reading addresses
  AddressService-->>Resolver: normalized addresses and addressKeys
  Resolver->>Property: find organization properties by addressKey
  Property-->>Resolver: matching properties
  Resolver-->>MeterService: resolvedAddresses and properties
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: switching property meter import to the address service client.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/condo/DOMA-11706/fix-property-meter-import-address-resolve

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 619bdd4498

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

readings,
addressService = createInstance(),
}) {
const uniqueAddresses = [...new Set(readings.map(({ address }) => address).filter(Boolean))]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve globalId address resolution

When a caller supplies a FIAS house id through reading.addressInfo.globalId (or relies on it because address is empty/ambiguous), this helper never includes that value in the address-service lookup; it only normalizes reading.address. The previous PropertyResolver path consumed addressInfo and searched fiasId:<globalId>, so those rows now produce no addressKey and the mutation returns PROPERTY_NOT_FOUND even when the organization property exists. Include the addressInfo.globalId/fiasId: candidate when building the lookup set.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.spec.js (1)

11-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add test for the "address not recognized" case.

The resolver has three main outcomes: property matched, property not in organization, and address not recognized. Only the first two are tested. The "address not recognized" path (when bulkSearch returns no addressKey or normalizedAddress) sets propertyAddress to { error: ERRORS.ADDRESS_NOT_RECOGNIZED_VALUE } and properties to {} — this should be covered.

✨ Suggested test
test('returns address not recognized error when bulkSearch fails to normalize address', async () => {
    const address = 'г Иваново, мкр Московский, д 14А к 1'
    const addressService = {
        bulkSearch: jest.fn().mockResolvedValue({
            map: {},
            addresses: {},
        }),
    }
    find.mockResolvedValue([])

    const result = await resolvePropertyMeterAddressesForOrganization({
        organizationId: 'organization-1',
        tin: '1234567890',
        readings: [{ address }],
        addressService,
    })

    expect(result.resolvedAddresses[address].addressResolve.propertyAddress).toEqual({
        error: ERRORS.ADDRESS_NOT_RECOGNIZED_VALUE,
    })
    expect(result.resolvedAddresses[address].addressResolve.properties).toEqual({})
    expect(find).not.toHaveBeenCalled()
})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.spec.js`
around lines 11 - 97, Add a test in the
resolvePropertyMeterAddressesForOrganization suite covering bulkSearch returning
empty map and addresses results. Assert propertyAddress equals { error:
ERRORS.ADDRESS_NOT_RECOGNIZED_VALUE }, properties is {}, and find is not called
when the address cannot be recognized.

Source: Coding guidelines

apps/condo/domains/meter/schema/RegisterPropertyMetersReadingsService.js (1)

163-164: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Use a Map for property lookups inside the readings loop.

properties.find() is O(n) per reading, making the loop O(n×m). A Map<addressKey, property> built once before the loop gives O(1) lookups.

⚡ Proposed refactor
                 const meterReadingForSearchingDuplicates = await getMeterReadingsForSearchingDuplicates(readings, meters, properties, 'PropertyMeterReading')

+                const propertiesByAddressKey = new Map(properties.map(p => [p.addressKey, p]))
+
                 for (const reading of readings) {
                     const meterNumber = reading.meterNumber.trim()
                     const addressKey = get(resolvedAddresses, [reading.address, 'addressResolve', 'propertyAddress', 'addressKey'])
                     let readingSource = get(reading, 'readingSource')

                     if (isNil(readingSource)) {
                         readingSource = { id: OTHER_METER_READING_SOURCE_ID }
                     }

                     if (isEmpty(meterNumber)) {
                         resultRows.push(new GQLError(ERRORS.INVALID_METER_NUMBER, context))
                         continue
                     }

                     const dateValidationError = getDateStrValidationError(context, locale, reading)
                     if (dateValidationError) {
                         resultRows.push(dateValidationError)
                         continue
                     }

-                    const property = properties.find((p) => p.addressKey === addressKey)
+                    const property = propertiesByAddressKey.get(addressKey)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/condo/domains/meter/schema/RegisterPropertyMetersReadingsService.js`
around lines 163 - 164, Replace the repeated properties.find() lookup in the
readings loop with a Map keyed by addressKey, constructing it once before the
loop and retrieving properties via map.get(addressKey). Remove the temporary
console.log while updating the lookup logic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/condo/domains/meter/schema/RegisterPropertyMetersReadingsService.js`:
- Line 164: Remove the debug console.log statement inside the readings loop in
RegisterPropertyMetersReadingsService, ensuring no property, address, reading,
or resolvedAddresses data is emitted through unstructured logging; retain the
surrounding reading-resolution logic unchanged.

In
`@apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.js`:
- Line 66: Remove the debug console.log from
resolvePropertyMeterAddressesForOrganization before the merge; do not replace it
with unstructured logging, and use the project’s structured Pino logger only if
diagnostic output is required, avoiding sensitive address or property data.

---

Nitpick comments:
In `@apps/condo/domains/meter/schema/RegisterPropertyMetersReadingsService.js`:
- Around line 163-164: Replace the repeated properties.find() lookup in the
readings loop with a Map keyed by addressKey, constructing it once before the
loop and retrieving properties via map.get(addressKey). Remove the temporary
console.log while updating the lookup logic.

In
`@apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.spec.js`:
- Around line 11-97: Add a test in the
resolvePropertyMeterAddressesForOrganization suite covering bulkSearch returning
empty map and addresses results. Assert propertyAddress equals { error:
ERRORS.ADDRESS_NOT_RECOGNIZED_VALUE }, properties is {}, and find is not called
when the address cannot be recognized.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 32de843c-f64d-45cb-847b-7f529a8e5a4b

📥 Commits

Reviewing files that changed from the base of the PR and between 8c5e20b and 619bdd4.

📒 Files selected for processing (3)
  • apps/condo/domains/meter/schema/RegisterPropertyMetersReadingsService.js
  • apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.js
  • apps/condo/domains/meter/utils/serverSchema/resolvePropertyMeterAddressesForOrganization.spec.js

@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants