Skip to content

feat(notifications): persist order cancellations in history with context#602

Merged
grunch merged 3 commits into
mainfrom
feat/persist-cancellation-notifications
Jun 11, 2026
Merged

feat(notifications): persist order cancellations in history with context#602
grunch merged 3 commits into
mainfrom
feat/persist-cancellation-notifications

Conversation

@AndreaDiazCorreia

@AndreaDiazCorreia AndreaDiazCorreia commented May 22, 2026

Copy link
Copy Markdown
Member

Summary

Closes #535.

When an order is canceled due to counterparty inactivity in waiting-payment or waiting-buyer-invoice, the user previously only saw a transient SnackBar — the event never reached the notifications screen (bell icon), so they could not review what happened to the order afterwards.

This PR persists every Action.canceled event to the notification history with a context-aware message based on the order's previous status:

  • waiting-payment → "The seller did not continue the order. The order has been cancelled."
  • waiting-buyer-invoice → "The buyer did not continue the order. The order has been cancelled."
  • Other (manual cancel, pending expiry, etc.) → generic "The order has been canceled."

Changes

  • NotificationDataExtractor: new previousStatus parameter; Action.canceled no longer returns null (which previously skipped persistence) and instead emits NotificationData with previous_status in values.
  • NotificationMessageMapper.getMessageKeyWithContext: resolves the correct localization key for Action.canceled based on previous_status.
  • AbstractMostroNotifier.subscribe(): captures previousStatus = state.status before state.updateWith(msg) and forwards it through handleEvent → extractor.
  • AbstractMostroNotifier.handleEvent(): removed the now-redundant showCustomMessage('orderCanceled') call — the centralized notify() path already shows the SnackBar and persists to history.
  • OrderNotifier: forwards previousStatus in its handleEvent override and converts the pending-order-expiry showCustomMessage('orderCanceled') to a notify(Action.canceled, ...) call so it also appears in the history.
  • Localizations: added notification_order_canceled_by_seller_inactivity_message and notification_order_canceled_by_buyer_inactivity_message to en, es, it, de, fr.

Test plan

  • fvm flutter analyze → no issues (verified)
  • fvm flutter test → all tests pass (verified, 369/369)
  • Manual: take a sell order, let the seller (maker) not pay → after Action.canceled, open the notifications screen and verify the "seller did not continue" message appears
  • Manual: take a buy order, let the buyer (maker) not provide an invoice → verify the "buyer did not continue" message appears
  • Manual: create a pending order and let it expire → verify a generic cancellation entry appears in the notifications screen
  • Manual: verify a single SnackBar is shown (no duplicate) on cancellation
  • Manual: verify message is correctly localized in EN, ES, IT

Summary by CodeRabbit

  • New Features

    • Cancellation notifications are always produced and persisted; when available they include the previous order status and correctly distinguish user-initiated vs automatic cancels.
    • Notifications now use distinct messages for cancellations due to seller vs buyer inactivity.
    • Manual cancels are tracked/untracked so user-initiated and automatic expirations are handled distinctly; automatic expirations generate deterministic notification events.
  • Localization

    • Added localized messages for inactivity-based cancellations in English, German, Spanish, French, and Italian.

@coderabbitai

coderabbitai Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0c248cc8-003e-4bb0-8b3e-09e80ce8dac0

📥 Commits

Reviewing files that changed from the base of the PR and between 06163dd and 5c91953.

📒 Files selected for processing (9)
  • lib/features/notifications/utils/notification_data_extractor.dart
  • lib/features/notifications/utils/notification_message_mapper.dart
  • lib/features/order/notifiers/abstract_mostro_notifier.dart
  • lib/features/order/notifiers/order_notifier.dart
  • lib/l10n/intl_de.arb
  • lib/l10n/intl_en.arb
  • lib/l10n/intl_es.arb
  • lib/l10n/intl_fr.arb
  • lib/l10n/intl_it.arb
✅ Files skipped from review due to trivial changes (1)
  • lib/l10n/intl_fr.arb
🚧 Files skipped from review as they are similar to previous changes (8)
  • lib/l10n/intl_de.arb
  • lib/l10n/intl_es.arb
  • lib/features/notifications/utils/notification_data_extractor.dart
  • lib/l10n/intl_it.arb
  • lib/l10n/intl_en.arb
  • lib/features/notifications/utils/notification_message_mapper.dart
  • lib/features/order/notifiers/order_notifier.dart
  • lib/features/order/notifiers/abstract_mostro_notifier.dart

Walkthrough

Threads previous order status and a user-initiated-cancel flag through notifiers into NotificationDataExtractor, which now persists Action.canceled notifications (optionally adding previous_status). Message mapper and localization add keys for seller vs buyer inactivity; auto-expiration uses the centralized notify path with a stable eventId.

Changes

Order cancellation notification for inactivity detection

Layer / File(s) Summary
Status threading through notifier chain
lib/features/order/notifiers/abstract_mostro_notifier.dart, lib/features/order/notifiers/order_notifier.dart
AbstractMostroNotifier.subscribe() captures current state.status and computes/removes a user-initiated cancel flag; it forwards previousStatus and wasUserInitiatedCancel into handleEvent() (abstract and concrete).
Status-aware notification extraction and message mapping
lib/features/notifications/utils/notification_data_extractor.dart, lib/features/notifications/utils/notification_message_mapper.dart
NotificationDataExtractor.extractFromMostroMessage() signature extended with previousStatus and wasUserInitiatedCancel; Action.canceled now yields persistent NotificationData and injects previous_status when appropriate. NotificationMessageMapper.getMessageKeyWithContext() maps values['previous_status'] to new seller/buyer inactivity message keys and _resolveLocalizationKey returns the new localized strings.
Bond deletion deferral & centralized notification delivery
lib/features/order/notifiers/abstract_mostro_notifier.dart
Action.canceled path reuses the subscribe-provided wasUserInitiatedCancel for bond-cancel deletion deferral and removes the direct orderCanceled custom-notification emission, relying on the extractor/notification flow.
OrderNotifier integration and auto-expiration
lib/features/order/notifiers/order_notifier.dart
OrderNotifier.handleEvent() updated to accept/forward previousStatus and wasUserInitiatedCancel. cancelOrder() marks cancels as user-initiated and rolls back on RPC failure. Auto-expiration now calls notify(Action.canceled, values: {'previous_status': Status.pending.value}, eventId: 'auto_expire:$orderId') instead of showing a transient custom message.
Inactivity cancellation message localization
lib/l10n/intl_*.arb (de, en, es, fr, it)
Adds new localized message keys for notification_order_canceled_by_seller_inactivity_message and notification_order_canceled_by_buyer_inactivity_message.

Sequence Diagram(s)

sequenceDiagram
  participant Subscribe as AbstractMostroNotifier.subscribe()
  participant HandleEvent as AbstractMostroNotifier.handleEvent()
  participant Extractor as NotificationDataExtractor.extractFromMostroMessage()
  participant Mapper as NotificationMessageMapper.getMessageKeyWithContext()
  participant Notify as NotificationActionsProvider.notifier.notify()
  Subscribe->>HandleEvent: call with previousStatus, wasUserInitiatedCancel
  HandleEvent->>Extractor: extractFromMostroMessage(event, session, previousStatus, wasUserInitiatedCancel)
  Extractor->>Mapper: getMessageKeyWithContext(Action.canceled, values)
  Mapper->>Notify: notify(Action.canceled, NotificationData)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • MostroP2P/mobile#604: Related changes to cancellation/bond notification pipeline and user-initiated cancel semantics.
  • MostroP2P/mobile#327: Overlaps on Action.canceled handling in the notifier/notification pipeline.
  • MostroP2P/mobile#378: Modifies NotificationDataExtractor.extractFromMostroMessage(...) at the same surface.

Suggested reviewers

  • grunch
  • Catrya
  • BraCR10

Poem

🐰 I hopped through status threads tonight,
marked which cancels came from hands, not plight,
I tucked the old state in a tiny note,
so inboxes can tell who failed to float,
🥕 a rabbit's cheer for clearer notification light.

🚥 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 accurately reflects the main objective of the PR: persisting order cancellations to the notifications history with contextual information about why they were canceled.
Linked Issues check ✅ Passed All requirements from issue #535 are met: cancellations due to counterparty inactivity are persisted to notifications history with context-aware messages distinguishing seller vs. buyer inactivity.
Out of Scope Changes check ✅ Passed All changes are directly scoped to resolving issue #535: notification persistence, context-aware messaging, and supporting infrastructure; no extraneous modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/persist-cancellation-notifications

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 and usage tips.

@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: 1

🤖 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 `@lib/features/order/notifiers/order_notifier.dart`:
- Around line 187-193: The notify call in order_notifier.dart that persists
auto-expiration cancellations (using
ref.read(notificationActionsProvider.notifier) and notify with Action.canceled)
must include a stable eventId to avoid duplicate history entries; update the
notify invocation to pass a deterministic eventId (for example a string like
"auto_expire:<orderId>" or a hash based on orderId + expirationTimestamp) via
the eventId parameter so repeated emissions of the same cancellation won't
create duplicate notifications.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c2f7c680-aecf-4829-b16e-91bc188b1315

📥 Commits

Reviewing files that changed from the base of the PR and between df7490c and 0b4f402.

📒 Files selected for processing (9)
  • lib/features/notifications/utils/notification_data_extractor.dart
  • lib/features/notifications/utils/notification_message_mapper.dart
  • lib/features/order/notifiers/abstract_mostro_notifier.dart
  • lib/features/order/notifiers/order_notifier.dart
  • lib/l10n/intl_de.arb
  • lib/l10n/intl_en.arb
  • lib/l10n/intl_es.arb
  • lib/l10n/intl_fr.arb
  • lib/l10n/intl_it.arb

Comment thread lib/features/order/notifiers/order_notifier.dart Outdated

@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: 0b4f402eb9

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread lib/features/notifications/utils/notification_message_mapper.dart

@ermeme ermeme 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.

Revisión Hermes

Veredicto: NO aprobaría este PR todavía.

Hay un problema funcional: el nuevo criterio usa solo previous_status para decidir si la cancelación fue por inactividad. Eso mezcla cancelaciones manuales con expiraciones reales y puede mostrar un mensaje falso en el historial.

Necesita un discriminador más preciso antes de entrar.

Comment thread lib/features/notifications/utils/notification_message_mapper.dart

@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: 1

🤖 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 `@lib/features/order/notifiers/order_notifier.dart`:
- Around line 127-131: The code sets the user-initiated cancel flag via
AbstractMostroNotifier.markUserInitiatedCancel(orderId) before awaiting
mostroService.cancelOrder(orderId); if the async call throws the flag remains
set and later Action.canceled may be misclassified—wrap the await in a
try/catch, and in the catch call the corresponding rollback/unmark method (e.g.,
AbstractMostroNotifier.unmarkUserInitiatedCancel(orderId) or the actual method
that clears the flag) before rethrowing the error so the flag is only left set
on successful cancel.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0141b9cb-d938-47c6-ba1f-4589e8423f88

📥 Commits

Reviewing files that changed from the base of the PR and between 0b4f402 and 18e4e16.

📒 Files selected for processing (3)
  • lib/features/notifications/utils/notification_data_extractor.dart
  • lib/features/order/notifiers/abstract_mostro_notifier.dart
  • lib/features/order/notifiers/order_notifier.dart

Comment thread lib/features/order/notifiers/order_notifier.dart Outdated

@ermeme ermeme 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.

Revisión Hermes

Veredicto: todavía no lo aprobaría.

El commit arregla el caso principal, pero dejó un hueco: el flag de markUserInitiatedCancel() se setea antes de await mostroService.cancelOrder(orderId) y nunca se limpia si esa llamada falla o no llega a emitir Action.canceled. Eso deja estado colgado y puede contaminar una cancelación posterior del mismo orderId.

La solución debería limpiar el flag en un try/finally o moverlo a una estructura con expiración/caducidad.

Comment thread lib/features/order/notifiers/order_notifier.dart
ermeme[bot]
ermeme Bot previously approved these changes May 22, 2026

@ermeme ermeme 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.

Hermes review

Approved.

The previous blocker is fixed: manual cancels are now tagged separately, the fallback is generic when the cancel was user-initiated, and the failure path now rolls back the marker so it does not leak into later events. The notification history behavior is now consistent for inactivity vs manual cancellation.

mostronatorcoder[bot]
mostronatorcoder Bot previously approved these changes Jun 2, 2026

@mostronatorcoder mostronatorcoder 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.

I re-checked the current head and I do not see a remaining blocking issue.

What I specifically verified after the earlier review concerns:

  • Manual cancels are no longer misclassified as counterparty inactivity. previous_status only drives the inactivity-specific message when the cancel was not user-initiated, so waiting-payment / waiting-buyer-invoice manual cancels now correctly fall back to the generic cancellation message.
  • The user-initiated cancel marker is rolled back if mostroService.cancelOrder(orderId) throws, so it does not leak into a later unrelated Action.canceled for the same orderId.
  • Auto-expiration now goes through the centralized notify/history path with a stable eventId, which is the right way to persist the event without duplicate entries.
  • Persisting Action.canceled in notification history with contextual messaging is the right product behavior here, and the notifier/data-extractor threading is scoped to that purpose.

I would still welcome focused tests around the manual-cancel vs inactivity classification path, because this logic is stateful and easy to regress. But on the current revision I do not see a blocker that should hold merge.

Approved.

@AndreaDiazCorreia AndreaDiazCorreia force-pushed the feat/persist-cancellation-notifications branch from 2a95305 to 06163dd Compare June 9, 2026 23:21
ermeme[bot]
ermeme Bot previously approved these changes Jun 9, 2026

@ermeme ermeme 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.

Reviewed by Hermes Agent. The cancellation history flow now distinguishes manual cancels from inactivity timeouts, rolls back the user-cancel marker on failure, and deduplicates auto-expiration notifications. No blocking issues found.

…essages

- Add previousStatus parameter to notification extraction and event handling chain to differentiate cancellation reasons
- Map Action.canceled to specific messages based on previous status (waiting-payment → seller inactivity, waiting-buyer-invoice → buyer inactivity)
- Remove early return for canceled orders in NotificationDataExtractor; persist all cancellations to notification history
- Replace custom showCustomMessage calls

@ermeme ermeme 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.

Reviewed the current head. The earlier cancellation-marker blocker is resolved, and I don't see any remaining blocking issues. Approving.

@Catrya Catrya left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

tACK

@grunch grunch merged commit fbad36c into main Jun 11, 2026
2 checks passed
@grunch grunch deleted the feat/persist-cancellation-notifications branch June 11, 2026 19:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add notification screen when orders are cancelled due to counterparty inactivity

3 participants