Compare commits

...

4 Commits

Author SHA1 Message Date
22b10c4bbf Phase 4 Stage 10 follow-up: restore BestieHistoryList picker for §4 curhat-lagi
The original Stage 10 plan retired chat_history_screen.dart on the
assumption that the new Chat tab Selesai sub-tab replaced it. That was
wrong: Figma has two distinct screens — `extras.jsx::SChatList` (the
Chat tab, browse-only) and `v4.jsx::BestieHistoryList` (the picker for
mermaid §4 returning-user curhat-lagi). They serve different purposes
on row tap: Selesai opens transcript, BestieHistoryList picks a past
bestie for targeted-pair.

Restoring BestieHistoryList at a new home:

- New screen `features/home/screens/bestie_history_list_screen.dart`
  matching Figma `v4.jsx::BestieHistoryList`:
    appBar title "bestie kamu sebelumnya"
    subtitle "{N} bestie yang pernah nemenin kamu"
    row: orb + "bestie {name}" + ONLINE pill + sessions count + last
         date + topic + → arrow
    row tap (online) → /payment with targetedMitraId (Stage-3 flow)
    row tap (closing-grace) → /chat/session/$id to finish goodbye
    row (offline) → dimmed, tap disabled

  Drops the per-row "curhat lagi" secondary button — the row tap IS the
  pick action now (cleaner, matches Figma).

- New route `/bestie/history` in router.dart; cleanly separated from the
  /chat/* family (which is now exclusively the Chat tab).

- BestieChoiceSheet "bestie yang udah kenal" re-pointed from /chat to
  /bestie/history.

- Stage 8 Maestro flow `08_returning_targeted.yaml` updated to assert
  the new screen title + tap the row by name (uses output.MITRA_NAME
  from the seed_history_session script).

- TECH_DEBT entry retired (curhat-lagi entry point restored). New
  TECH_DEBT entry tracks the still-pending wire-up of the Bestie
  Offline Popup variant for offline-row tap per mermaid §4.

flutter analyze clean (one pre-existing widget_test scaffolding error
unrelated to Stage 10).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 21:26:57 +08:00
1908e98012 Phase 4 Stage 10 Maestro: 09_chat_tab.yaml + seed-pending-payment endpoint
Closes the Stage 10 acceptance criterion §10.11 #13 (Maestro coverage).

- New dev-only `POST /internal/_test/seed-pending-payment` — inserts a
  payment_sessions row in `pending` status with expires_at 20m out, so
  the Pembayaran sub-tab has a deterministic row to render. Body
  accepts { phone, isExtension?, amount?, durationMinutes?, mode? }.
  Gated on NODE_ENV != 'production' like the other test routes.

- New Maestro helper script `seed_pending_payment.js` mirrors the
  existing seed_history_session pattern.

- New flow `09_chat_tab.yaml`:
    cold-start onboarding → home (returning view) →
    seed completed session + seed pending payment →
    tap "💬 chat" bottom-nav → lands on /chat/aktif via redirect →
    assert "aktif" / "pembayaran" / "selesai" pills + empty-state copy →
    tap pembayaran → assert "menunggu pembayaran sesi" + "bayar Rp..." →
    tap selesai → assert "X menit" duration row → tap row → assert
    "Transkrip Chat" appbar → back → still on /chat/selesai.

  Maestro parsed the YAML cleanly and started executing against the
  device; full run requires backend + online mitra in dev DB (same
  pre-reqs as flows 03/05/06/08).

- TECH_DEBT entry: Stage 10 retired the standalone bestie-history list
  screen, which means (a) the "curhat lagi" targeted-payment entry
  point has no UI affordance anywhere in the app — its plumbing in
  payment_notifier / payment_screen is now orphaned, and (b) the
  Stage 8 flow `08_returning_targeted.yaml` will fail at
  `assertVisible: "Riwayat Chat"` because it expects the deleted
  screen. Three fix paths listed in the entry for product to pick.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:24:50 +08:00
e3ea1d793e Phase 4 Stage 10 client_app: Chat tab UI (3 sub-tabs + retire bestie_history)
Flutter half of Stage 10 — the new Chat tab landing in the bottom nav.
The CTA target swaps from /chat/history to /chat, which redirects into
/chat/aktif. Three sibling routes under a single ShellRoute share a
header + sub-tab pills + the existing HaloTabBar footer:

  /chat/aktif        — the current active session (0 or 1 row)
  /chat/pembayaran   — pending initial + extension payments
  /chat/selesai      — past sessions, cursor-paginated infinite scroll

URL is the source of truth for the active sub-tab so deep links, back
stack, and Maestro all agree on state.

New feature dir `lib/features/chat_tab/`:
- providers/pending_payments_provider.dart — FutureProvider against the
  Stage-10 backend endpoint, plus pendingPaymentsCountProvider for the
  red-dot derivative
- providers/selesai_history_provider.dart — AsyncNotifier over
  GET /api/client/chat/history; tracks accumulated items + next_cursor +
  hasMore; loadMore() and refresh()
- widgets/chat_row.dart — generic row used by all 3 sub-tabs, with
  optional PaymentAmountChip / DurationChip / 📞 Call indicator
- widgets/sub_tab_pill.dart — pill with active underline + optional
  numeric badge (null hides; matches Selesai's no-badge rule)
- screens/chat_tab_shell.dart — ShellRoute scaffold + ChatSubTab enum
- screens/{aktif,pembayaran,selesai}_view.dart — the three sub-tab bodies

Router (`router.dart`):
- /chat → redirect → /chat/aktif
- ShellRoute hosts /chat/aktif, /chat/pembayaran, /chat/selesai
- /chat/history retired; /chat/history/:sessionId → /chat/transcript/:sessionId
- ChatHistoryScreen import + file deleted

HaloTabBar (`features/home/widgets/halo_tab_bar.dart` — new in the
working tree from Stage 9 sweep): now a ConsumerWidget. Chat tab goes
to /chat. Red dot renders when pendingPaymentsCountProvider > 0.

Inbound call-site updates:
- bestie_choice_sheet.dart: /chat/history → /chat
- home_screen.dart history-row tap: /chat/history/:id → /chat/transcript/:id

This commit also carries the larger Stage 9 sweep + ESP-removal + USP
gate edits that were already staged in the working tree on
`home_screen.dart` and `router.dart` from the prior session.

flutter analyze: clean except for the pre-existing scaffold
test/widget_test.dart MyApp reference (unrelated, present on master).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:14:22 +08:00
350b92f1f3 Phase 4 Stage 10 backend: Chat-tab feeds (pending payments + cursor history)
Backend half of Stage 10 — the new Chat tab in the customer app that
replaces /chat/history with a 3-sub-tab list (Aktif / Pembayaran /
Selesai).

- New GET /api/client/payment-sessions/pending — returns the customer's
  pending initial + extension payment sessions. Filter is status='pending'
  AND expires_at > NOW(). Mitra info comes from session_extensions →
  chat_sessions for extension rows, payment_sessions.targeted_mitra_id
  for targeted-curhat-lagi initial rows. TTL reuses the existing
  payment_session_timeout_minutes app_config row (default 20m) — no new
  config row needed since payment is still mocked.

- getCustomerHistory migrated from offset (page/limit) to cursor
  pagination. Cursor is base64url(`<endedAtIso>|<id>`) with id-tiebreak
  in ORDER BY so rows with identical timestamps don't duplicate or skip
  across pages. SELECT now JOINs payment_sessions to surface `mode`
  (chat/call) for the Selesai-row voice-call pill.

- requirement/flow_customer.mermaid.md: new §7 Chat Tab subgraph + Figma
  cross-ref entry for SChatList.

- requirement/phase4-customer-flow-plan.md: Stage 10 plan section. Also
  carries forward earlier uncommitted "Post-Stage-8 corrections" notes
  from the Stage 9 sweep (boot path / SHome1st / onboarding fixes).

Tests: +7 for getCustomerPendingPayments (initial null mitra,
targeted-mitra fill, extension-via-session JOIN, mixed-newest-first,
expired excluded, non-pending excluded, customer scoping). +10 for
cursor history (empty, exact-fit, multi-page walk, same-timestamp
tiebreak, limit clamp, customer scoping, CLOSING+COMPLETED only).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 20:04:58 +08:00
27 changed files with 3534 additions and 564 deletions

105
TECH_DEBT.md Normal file
View File

@@ -0,0 +1,105 @@
# Tech Debt
Running list of known shortcuts, deferred hardening, and "good enough for now"
decisions that need follow-up before they bite us in production.
Format: `[date]` short title, then enough context for someone (or future-you)
to act on it without re-deriving the discussion.
---
## Backend
### `[2026-05-11]` Public `GET /api/public/bestie/available` needs rate limiting before prod
**File:** `backend/src/routes/public/public.bestie-availability.routes.js`
**Decision:** The endpoint was made unauthenticated by business requirement —
SHome1st renders before any JWT exists, and the CTA must reflect global mitra
availability so users see whether bestie is online before committing to
onboarding. Response is intentionally a single boolean (no count, no IDs).
**Why it's debt:** No auth + no rate limit. The 10s in-memory cache bounds DB
load, but a single attacker can still hammer the endpoint to:
- run sustained traffic against the public listener (DoS surface)
- scrape `available` over time to infer mitra online/offline patterns (weak
information leak — only "is anyone online", but still a signal)
**Mitigation before prod:**
- Per-IP rate limit (suggested: ~30 req/min/IP, headroom over the legitimate
5s client poll cadence = 12 req/min/IP).
- Implement via `@fastify/rate-limit` plugin so other public endpoints can
share the policy as we add them under `/api/public/*`.
- Verify Cloud Run / NLB preserves real client IP and that
`request.ip` reflects it (Fastify already has `trustProxy: true`).
**Not required:** auth, captcha, or removing the count from
`/api/client/mitra-availability` (that route stays authed for CC/debug).
---
## Client app
### `[2026-05-11]` Social-login (Google / Apple) has no entry point after S3a rewrite
**Files:** `client_app/lib/features/auth/screens/register_screen.dart` (no longer renders them); `client_app/lib/core/auth/auth_providers_provider.dart` (still wired).
**Decision:** `RegisterScreen` was rewritten to match Figma `S3Phone` 1:1
(step-dots + name greeting + privacy card + tanpa-verif ghost link). Figma
S3a shows no Google/Apple buttons, so they were removed from this screen.
**Why it's debt:** Google/Apple buttons used to render here when the
`authProvidersProvider` flags were enabled. Today both flags are `false`
(creds pending — see `Phase 3.4 Status` memory), so nothing visible is
missing. But the moment `/api/shared/auth-providers` flips either flag,
the buttons have nowhere to live.
**Fix-when-creds-arrive:**
- Decide where Google/Apple buttons belong (likely a dedicated login screen
reachable from the SHome1st "masuk →" banner), or whether to bring them
back to S3a as Figma-friendly tiles above the phone input.
- `loginGoogle` / `loginApple` on `authProvider` are still intact, so the
wiring is one button widget away.
### `[2026-05-12]` Stage 10 — Bestie Offline Popup variant not wired on BestieHistoryList
**File:** `client_app/lib/features/home/screens/bestie_history_list_screen.dart`
**Decision:** Stage 10 follow-up restored `BestieHistoryList` as a separate
picker screen (per mermaid §4) and made offline rows un-tappable (dimmed).
Mermaid §4 actually calls for a **Bestie Offline Popup (returning variant)**
to surface when the user picks an offline bestie — with options "cari bestie
lain" and "tanya admin".
**Why it's debt:** Today the offline row is just disabled. The user gets no
explicit prompt to redirect them into the blast flow or to contact admin.
**Fix:** wire `BestieOfflinePopup` with `variant='returning'` on offline-row
tap. The popup widget already exists from Stage 8 (Tanya Admin sheet ships
with the wiring); just needs to be triggered here.
### `[2026-05-12]` S5 ESP screen retired from spec — code still ships it
**Files:** `client_app/lib/features/onboarding/` (S5ESP screen + nav wiring);
`screens/onboarding.jsx::S5ESP` (Figma reference still in handoff); any
`espSelectionProvider` / `espSkippedProvider` Riverpod state.
**Decision:** Business removed the ESP multi-select step from the customer
flow on 2026-05-12. Both verified and anonymous branches now go from
`VerifChoiceSheet` straight to the `usp_seen?` gate. See
`requirement/flow_customer.mermaid.md` §2.
**Why it's debt:** Stage 2 (commit `2645bcd`) shipped the ESP screen and its
state providers. The screen is still reachable in the current build. The
mermaid spec is the source of truth — the code has drifted behind by one
business decision.
**Fix:**
- Delete the ESP screen widget and its route registration.
- Remove `espSelectionProvider` / `espSkippedProvider` and any nav step that
routes through ESP.
- Wire `VerifChoiceSheet → USPGate → (USP screen | skip → next)` directly.
- Drop the "ESP is decorative only" memory (it's now superseded by removal).
- Keep `screens/onboarding.jsx::S5ESP` in the Figma handoff folder — it's
history, not active design.

View File

@@ -245,4 +245,45 @@ export const internalTestRoutes = async (fastify) => {
` `
return { ok: true, session_id: session.id, mitra_id: mitra.id, mitra_name: mitra.display_name } return { ok: true, session_id: session.id, mitra_id: mitra.id, mitra_name: mitra.display_name }
}) })
// Seed a payment_sessions row in `pending` status for the customer linked
// to `phone`, with expires_at safely in the future. Used by Maestro Stage
// 10 flow (09_chat_tab.yaml) to populate the Pembayaran sub-tab without
// walking the multi-screen S6 paywall → method → duration → method flow.
//
// Body: { phone, isExtension?, amount?, durationMinutes?, mode? }
// - isExtension: defaults false (initial-session payment)
// - amount: defaults 5000 IDR
// - durationMinutes: defaults 15
// - mode: 'chat' (default) | 'call'
fastify.post('/seed-pending-payment', async (request, reply) => {
const phone = request.body?.phone
if (!phone) {
return reply.code(400).send({ error: 'phone required in body' })
}
const isExtension = request.body?.isExtension === true
const amount = Number.isFinite(request.body?.amount) ? request.body.amount : 5000
const durationMinutes = Number.isFinite(request.body?.durationMinutes)
? request.body.durationMinutes
: 15
const mode = request.body?.mode === 'call' ? 'call' : 'chat'
const [customer] = await sql`
SELECT id FROM customers WHERE phone = ${phone} LIMIT 1
`
if (!customer) {
return reply.code(404).send({ error: 'no_customer_for_phone', phone })
}
const [row] = await sql`
INSERT INTO payment_sessions (
customer_id, amount, duration_minutes, is_first_session_discount,
is_extension, status, mode, expires_at
) VALUES (
${customer.id}, ${amount}, ${durationMinutes}, false,
${isExtension}, 'pending', ${mode}, NOW() + INTERVAL '20 minutes'
)
RETURNING id, customer_id, amount, is_extension, status, expires_at
`
return { ok: true, payment_id: row.id, ...row }
})
} }

View File

@@ -201,12 +201,13 @@ export const clientChatRoutes = async (app) => {
return reply.send({ success: true, data: extension }) return reply.send({ success: true, data: extension })
}) })
// Chat history // Phase 4 Stage 10 — Chat Tab Selesai feed. Cursor-paginated; old `page`
// param removed. Response shape: { items, next_cursor, has_more }.
app.get('/history', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => { app.get('/history', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const { page, limit } = request.query const { cursor, limit } = request.query
const history = await getCustomerHistory(request.customer.id, { const history = await getCustomerHistory(request.customer.id, {
page: page ? parseInt(page) : 1, cursor: cursor ?? null,
limit: limit ? parseInt(limit) : 20, limit: limit ? parseInt(limit, 10) : 20,
}) })
return reply.send({ success: true, data: history }) return reply.send({ success: true, data: history })
}) })

View File

@@ -5,6 +5,7 @@ import {
confirmPaymentSession, confirmPaymentSession,
abandonPaymentSession, abandonPaymentSession,
getPaymentSession, getPaymentSession,
getCustomerPendingPayments,
} from '../../services/payment.service.js' } from '../../services/payment.service.js'
import { import {
isCustomerEligibleForFirstSessionDiscount, isCustomerEligibleForFirstSessionDiscount,
@@ -172,6 +173,13 @@ export const clientPaymentRoutes = async (app) => {
}) })
}) })
// Phase 4 Stage 10 — Chat Tab Pembayaran feed. Static path; registered
// before `/:id` so find-my-way matches this and not the wildcard.
app.get('/pending', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const data = await getCustomerPendingPayments(request.customer.id)
return reply.send({ success: true, data })
})
app.get('/:id', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => { app.get('/:id', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const session = await getPaymentSession(request.params.id) const session = await getPaymentSession(request.params.id)
if (!session) { if (!session) {

View File

@@ -304,3 +304,41 @@ export const getPaymentSession = async (id) => {
` `
return row || null return row || null
} }
/**
* Phase 4 Stage 10 — Chat Tab Pembayaran feed.
*
* Returns the customer's pending payment sessions (initial + extension) that
* haven't paid AND haven't expired. The `expires_at > NOW()` filter is
* defensive: the background sweeper flips stale pending rows to `expired`,
* but rows can be stale between sweeps, so we filter inline too.
*
* Extension rows resolve mitra info via session_extensions → chat_sessions →
* mitras. Initial rows fall back to `payment_sessions.targeted_mitra_id`
* (set for targeted "Curhat lagi" flows); for general-blast initial rows
* the mitra is unknown until pairing succeeds, so mitra fields are null.
*/
export const getCustomerPendingPayments = async (customerId) => {
const items = await sql`
SELECT
ps.id,
ps.is_extension,
ps.amount,
ps.duration_minutes,
ps.mode,
ps.created_at,
ps.expires_at,
COALESCE(ext_m.id, tgt_m.id) AS mitra_id,
COALESCE(ext_m.display_name, tgt_m.display_name) AS mitra_display_name
FROM payment_sessions ps
LEFT JOIN session_extensions se ON se.payment_session_id = ps.id
LEFT JOIN chat_sessions cs ON cs.id = se.session_id
LEFT JOIN mitras ext_m ON ext_m.id = cs.mitra_id
LEFT JOIN mitras tgt_m ON tgt_m.id = ps.targeted_mitra_id
WHERE ps.customer_id = ${customerId}
AND ps.status = ${PaymentSessionStatus.PENDING}
AND ps.expires_at > NOW()
ORDER BY ps.created_at DESC
`
return { items, total: items.length }
}

View File

@@ -204,31 +204,87 @@ export const getActiveSessionsByMitraWithUnread = async (mitraId) => {
return sessions return sessions
} }
export const getCustomerHistory = async (customerId, { page = 1, limit = 20 } = {}) => { /**
const offset = (page - 1) * limit * Phase 4 Stage 10 — Selesai sub-tab uses cursor pagination on this endpoint.
const items = await sql` *
* Cursor is a base64-encoded `<isoTimestamp>|<id>` of the last row's
* `COALESCE(ended_at, created_at)` and `id`. The next page reads strictly
* older rows, breaking ties on `id` so adjacent rows with the same timestamp
* don't duplicate or skip across pages.
*/
const encodeHistoryCursor = (row) => {
const ts = (row.ended_at ?? row.created_at).toISOString
? (row.ended_at ?? row.created_at).toISOString()
: new Date(row.ended_at ?? row.created_at).toISOString()
return Buffer.from(`${ts}|${row.id}`, 'utf8').toString('base64url')
}
const decodeHistoryCursor = (cursor) => {
if (!cursor) return null
try {
const decoded = Buffer.from(cursor, 'base64url').toString('utf8')
const [ts, id] = decoded.split('|')
if (!ts || !id) return null
return { ts, id }
} catch {
return null
}
}
export const getCustomerHistory = async (customerId, { cursor = null, limit = 20 } = {}) => {
const cap = Math.min(Math.max(parseInt(limit, 10) || 20, 1), 50)
const decoded = decodeHistoryCursor(cursor)
// Fetch one extra to determine has_more without a second query
const fetch = cap + 1
const items = decoded
? await sql`
SELECT cs.id, cs.mitra_id, cs.status, cs.topic_sensitivity, cs.topics, cs.created_at, cs.paired_at, cs.ended_at, SELECT cs.id, cs.mitra_id, cs.status, cs.topic_sensitivity, cs.topics, cs.created_at, cs.paired_at, cs.ended_at,
cs.duration_minutes, cs.price, cs.is_first_session_discount, cs.extended_minutes, cs.duration_minutes, cs.price, cs.is_first_session_discount, cs.extended_minutes,
ps.mode AS mode,
m.display_name AS mitra_display_name, m.display_name AS mitra_display_name,
COALESCE(mos.is_online, false) AS mitra_is_online, COALESCE(mos.is_online, false) AS mitra_is_online,
(SELECT message FROM session_closures WHERE session_id = cs.id AND user_type = ${UserType.MITRA} LIMIT 1) AS mitra_closure_message, (SELECT message FROM session_closures WHERE session_id = cs.id AND user_type = ${UserType.MITRA} LIMIT 1) AS mitra_closure_message,
(SELECT message FROM session_closures WHERE session_id = cs.id AND user_type = ${UserType.CUSTOMER} LIMIT 1) AS customer_closure_message, (SELECT message FROM session_closures WHERE session_id = cs.id AND user_type = ${UserType.CUSTOMER} LIMIT 1) AS customer_closure_message,
(SELECT COUNT(*) FROM chat_sessions x (SELECT COUNT(*)::int FROM chat_sessions x
WHERE x.customer_id = ${customerId} AND x.mitra_id = cs.mitra_id WHERE x.customer_id = ${customerId} AND x.mitra_id = cs.mitra_id
AND x.status IN (${SessionStatus.COMPLETED}, ${SessionStatus.CLOSING})) AS sessions_count AND x.status IN (${SessionStatus.COMPLETED}, ${SessionStatus.CLOSING})) AS sessions_count
FROM chat_sessions cs FROM chat_sessions cs
LEFT JOIN mitras m ON m.id = cs.mitra_id LEFT JOIN mitras m ON m.id = cs.mitra_id
LEFT JOIN mitra_online_status mos ON mos.mitra_id = cs.mitra_id LEFT JOIN mitra_online_status mos ON mos.mitra_id = cs.mitra_id
LEFT JOIN payment_sessions ps ON ps.id = cs.payment_session_id
WHERE cs.customer_id = ${customerId} WHERE cs.customer_id = ${customerId}
AND cs.status IN (${SessionStatus.COMPLETED}, ${SessionStatus.CLOSING}) AND cs.status IN (${SessionStatus.COMPLETED}, ${SessionStatus.CLOSING})
ORDER BY COALESCE(cs.ended_at, cs.created_at) DESC AND (
LIMIT ${limit} OFFSET ${offset} COALESCE(cs.ended_at, cs.created_at) < ${decoded.ts}::timestamptz
OR (COALESCE(cs.ended_at, cs.created_at) = ${decoded.ts}::timestamptz AND cs.id < ${decoded.id})
)
ORDER BY COALESCE(cs.ended_at, cs.created_at) DESC, cs.id DESC
LIMIT ${fetch}
` `
const [{ count }] = await sql` : await sql`
SELECT COUNT(*) FROM chat_sessions WHERE customer_id = ${customerId} SELECT cs.id, cs.mitra_id, cs.status, cs.topic_sensitivity, cs.topics, cs.created_at, cs.paired_at, cs.ended_at,
AND status IN (${SessionStatus.COMPLETED}, ${SessionStatus.CLOSING}) cs.duration_minutes, cs.price, cs.is_first_session_discount, cs.extended_minutes,
ps.mode AS mode,
m.display_name AS mitra_display_name,
COALESCE(mos.is_online, false) AS mitra_is_online,
(SELECT message FROM session_closures WHERE session_id = cs.id AND user_type = ${UserType.MITRA} LIMIT 1) AS mitra_closure_message,
(SELECT message FROM session_closures WHERE session_id = cs.id AND user_type = ${UserType.CUSTOMER} LIMIT 1) AS customer_closure_message,
(SELECT COUNT(*)::int FROM chat_sessions x
WHERE x.customer_id = ${customerId} AND x.mitra_id = cs.mitra_id
AND x.status IN (${SessionStatus.COMPLETED}, ${SessionStatus.CLOSING})) AS sessions_count
FROM chat_sessions cs
LEFT JOIN mitras m ON m.id = cs.mitra_id
LEFT JOIN mitra_online_status mos ON mos.mitra_id = cs.mitra_id
LEFT JOIN payment_sessions ps ON ps.id = cs.payment_session_id
WHERE cs.customer_id = ${customerId}
AND cs.status IN (${SessionStatus.COMPLETED}, ${SessionStatus.CLOSING})
ORDER BY COALESCE(cs.ended_at, cs.created_at) DESC, cs.id DESC
LIMIT ${fetch}
` `
return { items, total: Number(count), page, limit } const hasMore = items.length > cap
const page = hasMore ? items.slice(0, cap) : items
const nextCursor = hasMore ? encodeHistoryCursor(page[page.length - 1]) : null
return { items: page, next_cursor: nextCursor, has_more: hasMore }
} }
export const getMitraHistory = async (mitraId, { page = 1, limit = 20 } = {}) => { export const getMitraHistory = async (mitraId, { page = 1, limit = 20 } = {}) => {

View File

@@ -3,10 +3,11 @@ import {
createPaymentSession, createPaymentSession,
confirmPaymentSession, confirmPaymentSession,
getPaymentSession, getPaymentSession,
getCustomerPendingPayments,
} from '../../src/services/payment.service.js' } from '../../src/services/payment.service.js'
import { PaymentSessionStatus } from '../../src/constants.js' import { PaymentSessionStatus, SessionStatus } from '../../src/constants.js'
import { resetDb, resetAppConfig } from '../helpers/db.js' import { resetDb, resetAppConfig, db } from '../helpers/db.js'
import { createCustomer } from '../helpers/fixtures.js' import { createCustomer, createMitra } from '../helpers/fixtures.js'
describe('payment.service', () => { describe('payment.service', () => {
let customer let customer
@@ -83,4 +84,167 @@ describe('payment.service', () => {
expect(reloaded.status).toBe(PaymentSessionStatus.PENDING) expect(reloaded.status).toBe(PaymentSessionStatus.PENDING)
expect(reloaded.confirmed_at).toBeNull() expect(reloaded.confirmed_at).toBeNull()
}) })
// Phase 4 Stage 10 — Chat Tab Pembayaran feed.
describe('getCustomerPendingPayments', () => {
it('returns empty when customer has no payments', async () => {
const result = await getCustomerPendingPayments(customer.id)
expect(result.items).toEqual([])
expect(result.total).toBe(0)
})
it('returns pending initial-session payment with null mitra info', async () => {
const pay = await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 5000,
})
const result = await getCustomerPendingPayments(customer.id)
expect(result.total).toBe(1)
expect(result.items[0]).toMatchObject({
id: pay.id,
is_extension: false,
amount: 5000,
duration_minutes: 15,
mode: 'chat',
mitra_id: null,
mitra_display_name: null,
})
})
it('fills mitra info from targeted_mitra_id for targeted initial payments', async () => {
const mitra = await createMitra({ callName: 'kak Dimas' })
await createPaymentSession({
customerId: customer.id,
durationMinutes: 30,
amount: 10000,
targetedMitraId: mitra.id,
})
const result = await getCustomerPendingPayments(customer.id)
expect(result.total).toBe(1)
expect(result.items[0].mitra_id).toBe(mitra.id)
expect(result.items[0].mitra_display_name).toBe('kak Dimas')
})
it('fills mitra info via session_extensions → chat_sessions for extension payments', async () => {
const sql = db()
const mitra = await createMitra({ callName: 'kak Sari' })
// The initial chat session this extension belongs to.
const [chatSession] = await sql`
INSERT INTO chat_sessions (customer_id, mitra_id, status, duration_minutes)
VALUES (${customer.id}, ${mitra.id}, ${SessionStatus.ACTIVE}, 12)
RETURNING id
`
const extPay = await createPaymentSession({
customerId: customer.id,
durationMinutes: 10,
amount: 2500,
isExtension: true,
})
await sql`
INSERT INTO session_extensions (
session_id, requested_duration_minutes, requested_price, status, payment_session_id
)
VALUES (${chatSession.id}, 10, 2500, 'pending', ${extPay.id})
`
const result = await getCustomerPendingPayments(customer.id)
expect(result.total).toBe(1)
expect(result.items[0]).toMatchObject({
id: extPay.id,
is_extension: true,
amount: 2500,
mitra_id: mitra.id,
mitra_display_name: 'kak Sari',
})
})
it('orders newest first and returns mixed initial + extension rows', async () => {
const sql = db()
const mitra = await createMitra({ callName: 'kak Sari' })
// Initial first
const initial = await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 5000,
})
// Then extension (newer)
const [chatSession] = await sql`
INSERT INTO chat_sessions (customer_id, mitra_id, status, duration_minutes)
VALUES (${customer.id}, ${mitra.id}, ${SessionStatus.ACTIVE}, 12)
RETURNING id
`
const extension = await createPaymentSession({
customerId: customer.id,
durationMinutes: 10,
amount: 2500,
isExtension: true,
})
await sql`
INSERT INTO session_extensions (session_id, requested_duration_minutes, requested_price, status, payment_session_id)
VALUES (${chatSession.id}, 10, 2500, 'pending', ${extension.id})
`
const result = await getCustomerPendingPayments(customer.id)
expect(result.total).toBe(2)
// Newest first
expect(result.items[0].id).toBe(extension.id)
expect(result.items[1].id).toBe(initial.id)
})
it('excludes expired pending rows (defensive filter on expires_at)', async () => {
const sql = db()
const pay = await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 5000,
})
// Manually move expires_at into the past — leaves status pending so this
// simulates the gap between TTL expiry and the next sweep tick.
await sql`
UPDATE payment_sessions
SET expires_at = NOW() - INTERVAL '1 second'
WHERE id = ${pay.id}
`
const result = await getCustomerPendingPayments(customer.id)
expect(result.total).toBe(0)
})
it('excludes non-pending statuses', async () => {
const pay = await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 5000,
})
await confirmPaymentSession(pay.id, customer.id) // → confirmed
const result = await getCustomerPendingPayments(customer.id)
expect(result.total).toBe(0)
})
it('scopes by customer — does not leak other customers payments', async () => {
await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 5000,
})
await createPaymentSession({
customerId: otherCustomer.id,
durationMinutes: 30,
amount: 10000,
})
const result = await getCustomerPendingPayments(customer.id)
expect(result.total).toBe(1)
expect(result.items[0].amount).toBe(5000)
})
})
}) })

View File

@@ -0,0 +1,167 @@
import { describe, it, expect, beforeAll, beforeEach } from 'vitest'
import { getCustomerHistory } from '../../src/services/session.service.js'
import { SessionStatus } from '../../src/constants.js'
import { resetDb, resetAppConfig, db } from '../helpers/db.js'
import { createCustomer, createMitra } from '../helpers/fixtures.js'
// Phase 4 Stage 10 — Chat Tab Selesai feed uses cursor pagination.
// Cursor is base64url(`<endedAtIso>|<id>`); response is { items, next_cursor, has_more }.
describe('session.service.getCustomerHistory (cursor paginated)', () => {
let customer
let mitra
beforeAll(async () => {
await resetAppConfig()
})
beforeEach(async () => {
await resetDb()
customer = await createCustomer({ callName: 'Alice' })
mitra = await createMitra({ callName: 'kak Sari' })
})
// Seed N completed sessions ended at deterministically spaced times.
// i=0 is the OLDEST, i=N-1 is the NEWEST.
const seedCompleted = async (count) => {
const sql = db()
const now = Date.now()
const ids = []
for (let i = 0; i < count; i++) {
const endedAt = new Date(now - (count - i) * 60_000) // 1 min apart
const [row] = await sql`
INSERT INTO chat_sessions (
customer_id, mitra_id, status, duration_minutes, price, ended_at, created_at
)
VALUES (
${customer.id}, ${mitra.id}, ${SessionStatus.COMPLETED}, 12, 5000,
${endedAt}, ${endedAt}
)
RETURNING id
`
ids.push(row.id)
}
return ids
}
it('returns empty + has_more=false when there is no history', async () => {
const result = await getCustomerHistory(customer.id, { limit: 10 })
expect(result.items).toEqual([])
expect(result.has_more).toBe(false)
expect(result.next_cursor).toBeNull()
})
it('returns all items + has_more=false when count <= limit', async () => {
await seedCompleted(5)
const result = await getCustomerHistory(customer.id, { limit: 10 })
expect(result.items).toHaveLength(5)
expect(result.has_more).toBe(false)
expect(result.next_cursor).toBeNull()
})
it('first page returns `limit` items, has_more=true, and a usable cursor', async () => {
await seedCompleted(7)
const page1 = await getCustomerHistory(customer.id, { limit: 3 })
expect(page1.items).toHaveLength(3)
expect(page1.has_more).toBe(true)
expect(page1.next_cursor).toBeTruthy()
})
it('walks across pages without duplicates or skips', async () => {
const seeded = await seedCompleted(7) // ids[0]=oldest .. ids[6]=newest
const collected = []
let cursor = null
do {
const page = await getCustomerHistory(customer.id, { cursor, limit: 3 })
collected.push(...page.items.map((r) => r.id))
cursor = page.next_cursor
if (!page.has_more) break
} while (cursor)
// Newest → oldest = reverse of seeded
expect(collected).toEqual([...seeded].reverse())
// No duplicates
expect(new Set(collected).size).toBe(collected.length)
})
it('orders by ended_at DESC with id DESC tiebreak (no gaps for same-timestamp rows)', async () => {
const sql = db()
const sameTime = new Date()
// Insert 3 rows with the EXACT same ended_at — only id distinguishes them.
const ids = []
for (let i = 0; i < 3; i++) {
const [row] = await sql`
INSERT INTO chat_sessions (
customer_id, mitra_id, status, duration_minutes, price, ended_at, created_at
)
VALUES (
${customer.id}, ${mitra.id}, ${SessionStatus.COMPLETED}, 12, 5000,
${sameTime}, ${sameTime}
)
RETURNING id
`
ids.push(row.id)
}
// Page through them 1 at a time.
const collected = []
let cursor = null
for (let i = 0; i < 5; i++) {
const page = await getCustomerHistory(customer.id, { cursor, limit: 1 })
collected.push(...page.items.map((r) => r.id))
cursor = page.next_cursor
if (!page.has_more) break
}
expect(collected).toHaveLength(3)
expect(new Set(collected).size).toBe(3)
})
it('clamps limit to 50 max', async () => {
await seedCompleted(60)
const result = await getCustomerHistory(customer.id, { limit: 999 })
expect(result.items.length).toBeLessThanOrEqual(50)
})
it('scopes by customer — does not leak other customers history', async () => {
const other = await createCustomer({ callName: 'Bob' })
const sql = db()
await sql`
INSERT INTO chat_sessions (customer_id, mitra_id, status, duration_minutes, price, ended_at)
VALUES (${customer.id}, ${mitra.id}, ${SessionStatus.COMPLETED}, 12, 5000, NOW())
`
await sql`
INSERT INTO chat_sessions (customer_id, mitra_id, status, duration_minutes, price, ended_at)
VALUES (${other.id}, ${mitra.id}, ${SessionStatus.COMPLETED}, 12, 5000, NOW())
`
const result = await getCustomerHistory(customer.id, { limit: 20 })
expect(result.items).toHaveLength(1)
})
it('includes CLOSING status (grace period) alongside COMPLETED', async () => {
const sql = db()
await sql`
INSERT INTO chat_sessions (customer_id, mitra_id, status, duration_minutes, price, ended_at)
VALUES (${customer.id}, ${mitra.id}, ${SessionStatus.CLOSING}, 12, 5000, NOW())
`
await sql`
INSERT INTO chat_sessions (customer_id, mitra_id, status, duration_minutes, price, ended_at)
VALUES (${customer.id}, ${mitra.id}, ${SessionStatus.COMPLETED}, 12, 5000, NOW())
`
const result = await getCustomerHistory(customer.id, { limit: 20 })
expect(result.items).toHaveLength(2)
})
it('excludes ACTIVE / PENDING_PAYMENT / EXTENDING', async () => {
const sql = db()
for (const status of [SessionStatus.ACTIVE, SessionStatus.PENDING_PAYMENT, SessionStatus.EXTENDING]) {
await sql`
INSERT INTO chat_sessions (customer_id, mitra_id, status, duration_minutes, price)
VALUES (${customer.id}, ${mitra.id}, ${status}, 12, 5000)
`
}
const result = await getCustomerHistory(customer.id, { limit: 20 })
expect(result.items).toHaveLength(0)
})
})

View File

@@ -114,18 +114,19 @@ env:
- assertVisible: "bestie yang udah kenal" - assertVisible: "bestie yang udah kenal"
- assertVisible: "bestie baru" - assertVisible: "bestie baru"
# Choose the known bestie path → history list with v4 layout. # Choose the known bestie path → BestieHistoryList picker (mermaid §4).
# Stage 10 renamed the screen + dropped the per-row "curhat lagi" button —
# the row tap itself is now the pick action.
- tapOn: "bestie yang udah kenal" - tapOn: "bestie yang udah kenal"
- extendedWaitUntil: - extendedWaitUntil:
visible: visible:
text: "Riwayat Chat" text: "bestie kamu sebelumnya"
timeout: 5000 timeout: 5000
- assertVisible: "ONLINE" - assertVisible: "ONLINE"
- assertVisible: "curhat lagi"
# Tap "curhat lagi" → /payment (legacy targeted-payment route). Verify the # Tap the seeded bestie row → /payment targeted-payment route. Verify the
# screen title; the targeted-payment flow itself is covered by Stage 5. # screen title; the targeted-payment flow itself is covered by Stage 5.
- tapOn: "curhat lagi" - tapOn: "bestie ${output.MITRA_NAME}"
- extendedWaitUntil: - extendedWaitUntil:
visible: visible:
text: "Chat lagi dengan" text: "Chat lagi dengan"

View File

@@ -0,0 +1,161 @@
# Stage 10 acceptance: Chat tab (3 sub-tabs).
#
# Flow:
# 1. Cold-start onboarding (abbreviated; mirrors 01_smoke) → home with a
# phone-verified customer so the dev seed endpoints can find them.
# 2. Seed a completed chat_sessions row → Selesai sub-tab has data.
# 3. Seed a pending payment_sessions row → Pembayaran sub-tab has data
# AND the bottom-nav chat tab should render a red dot (visual; not
# asserted because Maestro can't reliably introspect small pixel state).
# 4. Tap the "💬 chat" bottom-nav icon → /chat redirects to /chat/aktif.
# 5. Aktif sub-tab: no active session, so empty state copy shows.
# 6. Tap "pembayaran" pill → row with preview "menunggu pembayaran sesi"
# and the "bayar Rp..." chip.
# 7. Tap "selesai" pill → row with seeded mitra name. Tap the row →
# transcript screen opens.
# 8. Back → still on /chat/selesai (URL is source of truth for the sub-tab).
#
# Pre-req: client_app debug APK installed, backend reachable on
# BACKEND_INTERNAL_URL with NODE_ENV != 'production' so /internal/_test/*
# routes are registered, AND at least one mitra is online in the dev DB.
#
# Run:
# maestro test client_app/.maestro/flows/09_chat_tab.yaml
appId: com.halobestie.client.client_app
env:
TEST_PHONE: "+628155556678"
BACKEND_INTERNAL_URL: http://localhost:3001
---
# Wipe prior state for TEST_PHONE so the run is hermetic.
- runScript:
file: ../scripts/reset_phone.js
env:
TEST_PHONE: ${TEST_PHONE}
BACKEND_INTERNAL_URL: ${BACKEND_INTERNAL_URL}
- launchApp:
clearState: true
# Onboarding carousel → splash → home (1st time view).
- extendedWaitUntil:
visible:
text: "Mulai"
timeout: 15000
- tapOn:
text: "Mulai"
retryTapIfNoChange: true
# Verif choice sheet → "Lanjut sebagai Tamu" → name → phone OTP
- extendedWaitUntil:
visible:
text: "Lanjut sebagai Tamu"
timeout: 10000
- tapOn:
text: "Lanjut sebagai Tamu"
retryTapIfNoChange: true
- extendedWaitUntil:
visible:
text: "Nama panggilan"
timeout: 10000
- tapOn:
text: "Nama panggilan"
- inputText: "Maestro"
- hideKeyboard
- tapOn:
text: "Lanjut"
retryTapIfNoChange: true
- extendedWaitUntil:
visible:
text: "Verifikasi Akun"
timeout: 15000
- tapOn:
text: "Nomor HP"
- inputText: ${TEST_PHONE}
- hideKeyboard
- tapOn:
text: "Kirim OTP"
retryTapIfNoChange: true
- extendedWaitUntil:
visible:
text: "Masukkan OTP"
timeout: 15000
- runScript:
file: ../scripts/peek_otp.js
env:
TEST_PHONE: ${TEST_PHONE}
BACKEND_INTERNAL_URL: ${BACKEND_INTERNAL_URL}
- inputText: ${output.OTP}
- extendedWaitUntil:
notVisible:
text: "Masukkan OTP"
timeout: 15000
# Returning users land on SHomeReturning with "Mulai Curhat".
- extendedWaitUntil:
visible:
text: "Mulai Curhat"
timeout: 20000
# Seed a completed session → Selesai sub-tab populated.
- runScript:
file: ../scripts/seed_history_session.js
env:
TEST_PHONE: ${TEST_PHONE}
BACKEND_INTERNAL_URL: ${BACKEND_INTERNAL_URL}
# Seed a pending payment → Pembayaran sub-tab populated + red dot eligibility.
- runScript:
file: ../scripts/seed_pending_payment.js
env:
TEST_PHONE: ${TEST_PHONE}
BACKEND_INTERNAL_URL: ${BACKEND_INTERNAL_URL}
# Tap "💬 chat" in the bottom nav → /chat → redirected to /chat/aktif.
- tapOn:
text: "chat"
retryTapIfNoChange: true
- extendedWaitUntil:
visible:
text: "aktif"
timeout: 10000
# Sub-tab pills visible; the heading "chat" duplicates with the nav label
# so assert what's unique to the chat-tab shell.
- assertVisible: "aktif"
- assertVisible: "pembayaran"
- assertVisible: "selesai"
# Aktif default body: empty state since no active session was seeded.
- assertVisible: "belum ada chat di sini"
# Pembayaran sub-tab → seeded pending initial payment is visible.
- tapOn:
text: "pembayaran"
- extendedWaitUntil:
visible:
text: "menunggu pembayaran sesi"
timeout: 5000
- assertVisible:
text: "bayar Rp.*"
# Selesai sub-tab → seeded completed session is visible.
- tapOn:
text: "selesai"
- extendedWaitUntil:
visible:
text: ".* menit"
timeout: 5000
# Tap the row → opens the read-only transcript screen.
- tapOn:
text: ".* menit"
- extendedWaitUntil:
visible:
text: "Transkrip Chat"
timeout: 10000
# Back returns us to /chat/selesai (URL preserves sub-tab state).
- back
- extendedWaitUntil:
visible:
text: "selesai"
timeout: 5000
- assertVisible: "selesai"

View File

@@ -0,0 +1,21 @@
// Seed a `pending` payment_sessions row for TEST_PHONE so the Pembayaran
// sub-tab has a row to render without walking the multi-screen S6 paywall →
// method-pick → duration-pick → method flow.
//
// Hits the dev-only /internal/_test/seed-pending-payment endpoint.
const phone = TEST_PHONE
const url = BACKEND_INTERNAL_URL || 'http://localhost:3001'
const body = {
phone,
isExtension: PENDING_KIND === 'extension',
amount: PENDING_AMOUNT ? Number(PENDING_AMOUNT) : 5000,
}
const resp = http.post(`${url}/internal/_test/seed-pending-payment`, {
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
if (resp.status !== 200) {
throw new Error(`seed-pending-payment failed (${resp.status}): ${resp.body}`)
}
const data = json(resp.body)
output.PAYMENT_ID = data.payment_id

View File

@@ -1,327 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/widgets.dart';
import '../../home/providers/bestie_history_provider.dart';
/// Phase 4 Stage 8 — `BestieHistoryList`.
///
/// Renders past sessions with the v4 visual: orb + name + last-session date
/// + topic chips + sessions count + ONLINE pill (per-row, sourced from the
/// `mitra_is_online` field on the history payload).
///
/// Tapping a row routes to the targeted "Curhat lagi" payment flow when the
/// row references a known mitra; closing-state rows still drop into the
/// session screen so the user can finish the goodbye composer. Otherwise we
/// fall back to the transcript view.
class ChatHistoryScreen extends ConsumerWidget {
const ChatHistoryScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final historyAsync = ref.watch(bestieHistoryProvider);
final fullSessionsAsync = ref.watch(_rawHistoryProvider);
return Scaffold(
backgroundColor: HaloTokens.bg,
appBar: AppBar(
backgroundColor: HaloTokens.bg,
foregroundColor: HaloTokens.ink,
elevation: 0,
title: const Text(
'Riwayat Chat',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontWeight: FontWeight.w700,
),
),
),
body: historyAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (_, __) => const Center(
child: Text(
'gagal memuat riwayat. tarik untuk muat ulang.',
style: TextStyle(fontFamily: HaloTokens.fontBody),
),
),
data: (items) {
if (items.isEmpty) {
return const Center(
child: Text(
'Belum ada riwayat chat',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
color: HaloTokens.inkSoft,
),
),
);
}
return RefreshIndicator(
onRefresh: () async {
ref.invalidate(bestieHistoryProvider);
ref.invalidate(_rawHistoryProvider);
await ref.read(bestieHistoryProvider.future);
},
child: ListView.separated(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s16,
vertical: HaloSpacing.s12,
),
itemCount: items.length,
separatorBuilder: (_, __) => const SizedBox(height: HaloSpacing.s12),
itemBuilder: (context, index) {
final item = items[index];
final raw = fullSessionsAsync.valueOrNull?[index];
final isClosing = raw?['status'] == SessionStatus.closing;
return _BestieRow(
item: item,
isClosing: isClosing,
onTap: () {
if (isClosing && raw != null) {
context.push(
'/chat/session/${item.sessionId}',
extra: item.mitraName,
);
return;
}
context.push('/chat/history/${item.sessionId}');
},
onCurhatLagi: item.mitraId == null || isClosing
? null
: () => context.push('/payment', extra: <String, dynamic>{
'targetedMitraId': item.mitraId,
'mitraName': item.mitraName,
'topicSensitivity': TopicSensitivity.regular,
}),
);
},
),
);
},
),
);
}
}
/// Raw history payload — used to read fields the v4 `BestieHistoryItem`
/// model doesn't surface (currently `status`, for the closing-row branch).
final _rawHistoryProvider = FutureProvider<List<Map<String, dynamic>>>((ref) async {
final api = ref.read(apiClientProvider);
final response = await api.get('/api/client/chat/history');
return ((response['data']['items'] as List?) ?? const []).cast<Map<String, dynamic>>();
});
class _BestieRow extends StatelessWidget {
final BestieHistoryItem item;
final bool isClosing;
final VoidCallback onTap;
final VoidCallback? onCurhatLagi;
const _BestieRow({
required this.item,
required this.isClosing,
required this.onTap,
required this.onCurhatLagi,
});
@override
Widget build(BuildContext context) {
return Material(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
child: InkWell(
onTap: onTap,
borderRadius: HaloRadius.lg,
child: Padding(
padding: const EdgeInsets.all(HaloSpacing.s16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
HaloOrb(
size: 56,
seed: (item.mitraId ?? item.mitraName).hashCode,
label: item.mitraName,
),
const SizedBox(width: HaloSpacing.s12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Flexible(
child: Text(
item.mitraName,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 16,
fontWeight: FontWeight.w700,
color: HaloTokens.ink,
),
),
),
if (item.mitraIsOnline) ...[
const SizedBox(width: HaloSpacing.s8),
const _OnlinePill(),
],
if (isClosing) ...[
const SizedBox(width: HaloSpacing.s8),
const _ClosingBadge(),
],
],
),
const SizedBox(height: 2),
Text(
[
if (item.endedAt != null) _formatDate(item.endedAt!),
'${item.sessionsCount} sesi',
].join(' · '),
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 12.5,
color: HaloTokens.inkSoft,
),
),
],
),
),
],
),
if (item.topics.isNotEmpty) ...[
const SizedBox(height: HaloSpacing.s12),
Wrap(
spacing: HaloSpacing.s8,
runSpacing: HaloSpacing.s8,
children: item.topics
.take(3)
.map((t) => _TopicPill(label: t))
.toList(),
),
],
if (onCurhatLagi != null) ...[
const SizedBox(height: HaloSpacing.s12),
Align(
alignment: Alignment.centerRight,
child: HaloButton(
label: 'curhat lagi',
size: HaloButtonSize.sm,
variant: HaloButtonVariant.secondary,
onPressed: onCurhatLagi,
),
),
],
],
),
),
),
);
}
String _formatDate(DateTime d) =>
'${d.day.toString().padLeft(2, '0')}/${d.month.toString().padLeft(2, '0')}/${d.year}';
}
class _OnlinePill extends StatelessWidget {
const _OnlinePill();
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: HaloTokens.success.withAlpha(36),
borderRadius: BorderRadius.circular(999),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
_Dot(color: HaloTokens.success),
SizedBox(width: 4),
Text(
'ONLINE',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontWeight: FontWeight.w700,
letterSpacing: 0.6,
color: HaloTokens.success,
),
),
],
),
);
}
}
class _Dot extends StatelessWidget {
final Color color;
const _Dot({required this.color});
@override
Widget build(BuildContext context) {
return Container(
width: 6,
height: 6,
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
);
}
}
class _TopicPill extends StatelessWidget {
final String label;
const _TopicPill({required this.label});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s12,
vertical: 4,
),
decoration: BoxDecoration(
color: HaloTokens.brandSofter,
borderRadius: BorderRadius.circular(999),
),
child: Text(
label,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 11.5,
fontWeight: FontWeight.w600,
color: HaloTokens.brandDark,
),
),
);
}
}
class _ClosingBadge extends StatelessWidget {
const _ClosingBadge();
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: HaloTokens.accentSoft,
borderRadius: BorderRadius.circular(999),
),
child: const Text(
'Belum ditutup',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontWeight: FontWeight.w600,
color: HaloTokens.brandDark,
),
),
);
}
}

View File

@@ -0,0 +1,105 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/auth/auth_notifier.dart';
/// One row in the Chat Tab > Pembayaran sub-tab.
///
/// Mirrors the response of `GET /api/client/payment-sessions/pending`. A row
/// is either an initial-session payment (`isExtension == false`) — for which
/// mitra info is only present in the targeted "Curhat lagi" flow — or an
/// extension payment (`isExtension == true`) — mitra info resolved by the
/// backend via session_extensions → chat_sessions.
class PendingPaymentItem {
final String id;
final bool isExtension;
final int amount;
final int durationMinutes;
final String mode;
final DateTime createdAt;
final DateTime expiresAt;
final String? mitraId;
final String? mitraDisplayName;
const PendingPaymentItem({
required this.id,
required this.isExtension,
required this.amount,
required this.durationMinutes,
required this.mode,
required this.createdAt,
required this.expiresAt,
required this.mitraId,
required this.mitraDisplayName,
});
factory PendingPaymentItem.fromJson(Map<String, dynamic> json) {
return PendingPaymentItem(
id: json['id'] as String,
isExtension: json['is_extension'] as bool? ?? false,
amount: switch (json['amount']) {
num n => n.toInt(),
String s => int.tryParse(s) ?? 0,
_ => 0,
},
durationMinutes: switch (json['duration_minutes']) {
num n => n.toInt(),
String s => int.tryParse(s) ?? 0,
_ => 0,
},
mode: json['mode'] as String? ?? 'chat',
createdAt: DateTime.parse(json['created_at'] as String).toLocal(),
expiresAt: DateTime.parse(json['expires_at'] as String).toLocal(),
mitraId: json['mitra_id'] as String?,
mitraDisplayName: json['mitra_display_name'] as String?,
);
}
}
class PendingPaymentsData {
final List<PendingPaymentItem> items;
final int total;
const PendingPaymentsData({required this.items, required this.total});
static const empty = PendingPaymentsData(items: [], total: 0);
}
/// Customer-scoped pending payment sessions. Returns `empty` when the caller
/// has no auth identity — keeps SHome1st + the chat tab from issuing a 401.
///
/// Drives both the Pembayaran sub-tab list and the bottom-nav red dot via the
/// `pendingPaymentsCountProvider` derivative below.
final pendingPaymentsProvider =
FutureProvider<PendingPaymentsData>((ref) async {
final customerId = ref.watch(authProvider.select((s) {
final data = s.valueOrNull;
return switch (data) {
AuthAuthenticatedData d => d.profile['id'] as String?,
AuthAnonymousData d => d.customerId,
_ => null,
};
}));
if (customerId == null) return PendingPaymentsData.empty;
final api = ref.read(apiClientProvider);
final response =
await api.get('/api/client/payment-sessions/pending');
final data = response['data'] as Map<String, dynamic>? ?? const {};
final items = (data['items'] as List<dynamic>? ?? [])
.cast<Map<String, dynamic>>()
.map(PendingPaymentItem.fromJson)
.toList();
return PendingPaymentsData(
items: items,
total: switch (data['total']) {
num n => n.toInt(),
String s => int.tryParse(s) ?? items.length,
_ => items.length,
},
);
});
/// Lightweight derived count — feeds the bottom-nav red dot + the Pembayaran
/// sub-tab pill badge. Returns 0 while the underlying provider is loading or
/// has errored, so the badge never flickers from a transient state.
final pendingPaymentsCountProvider = Provider<int>((ref) {
final async = ref.watch(pendingPaymentsProvider);
return async.valueOrNull?.total ?? 0;
});

View File

@@ -0,0 +1,172 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/auth/auth_notifier.dart';
/// One row in the Chat Tab > Selesai sub-tab.
///
/// Closed-session details that survive into history: who, when, how long,
/// what closing message was left. The factory tolerates the same number /
/// string ambiguity bestieHistoryProvider already handles (postgres.js
/// stringifies bigint counts).
class SelesaiHistoryItem {
final String sessionId;
final String? mitraId;
final String mitraName;
final DateTime? endedAt;
final int? durationMinutes;
final String mode;
final String? mitraClosureMessage;
final String? customerClosureMessage;
final int sessionsCount;
final bool mitraIsOnline;
const SelesaiHistoryItem({
required this.sessionId,
required this.mitraId,
required this.mitraName,
required this.endedAt,
required this.durationMinutes,
required this.mode,
required this.mitraClosureMessage,
required this.customerClosureMessage,
required this.sessionsCount,
required this.mitraIsOnline,
});
factory SelesaiHistoryItem.fromJson(Map<String, dynamic> json) {
final endedAtRaw = json['ended_at'];
final createdAtRaw = json['created_at'];
return SelesaiHistoryItem(
sessionId: json['id'] as String,
mitraId: json['mitra_id'] as String?,
mitraName: json['mitra_display_name'] as String? ?? 'Bestie',
endedAt: endedAtRaw is String
? DateTime.tryParse(endedAtRaw)?.toLocal()
: (createdAtRaw is String
? DateTime.tryParse(createdAtRaw)?.toLocal()
: null),
durationMinutes: switch (json['duration_minutes']) {
num n => n.toInt(),
String s => int.tryParse(s),
_ => null,
},
mode: json['mode'] as String? ?? 'chat',
mitraClosureMessage: json['mitra_closure_message'] as String?,
customerClosureMessage: json['customer_closure_message'] as String?,
sessionsCount: switch (json['sessions_count']) {
num n => n.toInt(),
String s => int.tryParse(s) ?? 1,
_ => 1,
},
mitraIsOnline: json['mitra_is_online'] as bool? ?? false,
);
}
/// Preview shown in the row: prefer the mitra's closing message (closer to
/// the partner's voice), fall back to the customer's, then to a generic
/// "selesai" placeholder so empty rows still render.
String get previewText =>
(mitraClosureMessage?.trim().isNotEmpty == true
? mitraClosureMessage
: (customerClosureMessage?.trim().isNotEmpty == true
? customerClosureMessage
: 'sesi selesai'))!;
}
/// Persistent paginated state — accumulated items + cursor + flags.
class SelesaiHistoryState {
final List<SelesaiHistoryItem> items;
final String? nextCursor;
final bool hasMore;
final bool loadingMore;
const SelesaiHistoryState({
this.items = const [],
this.nextCursor,
this.hasMore = false,
this.loadingMore = false,
});
SelesaiHistoryState copyWith({
List<SelesaiHistoryItem>? items,
String? nextCursor,
bool? hasMore,
bool? loadingMore,
bool clearCursor = false,
}) =>
SelesaiHistoryState(
items: items ?? this.items,
nextCursor: clearCursor ? null : (nextCursor ?? this.nextCursor),
hasMore: hasMore ?? this.hasMore,
loadingMore: loadingMore ?? this.loadingMore,
);
}
/// Cursor-paginated Selesai history. First fetch returns the freshest 20 rows;
/// `loadMore` appends the next page. Customer-scoped — switching account
/// resets the list automatically because the build re-runs.
class SelesaiHistoryNotifier
extends AsyncNotifier<SelesaiHistoryState> {
static const _pageLimit = 20;
@override
Future<SelesaiHistoryState> build() async {
final customerId = ref.watch(authProvider.select((s) {
final data = s.valueOrNull;
return switch (data) {
AuthAuthenticatedData d => d.profile['id'] as String?,
AuthAnonymousData d => d.customerId,
_ => null,
};
}));
if (customerId == null) return const SelesaiHistoryState();
return await _fetchPage(cursor: null);
}
Future<SelesaiHistoryState> _fetchPage({String? cursor}) async {
final api = ref.read(apiClientProvider);
final url = cursor == null
? '/api/client/chat/history?limit=$_pageLimit'
: '/api/client/chat/history?limit=$_pageLimit&cursor=${Uri.encodeQueryComponent(cursor)}';
final response = await api.get(url);
final data = response['data'] as Map<String, dynamic>? ?? const {};
final items = (data['items'] as List<dynamic>? ?? [])
.cast<Map<String, dynamic>>()
.map(SelesaiHistoryItem.fromJson)
.toList();
final existing = cursor == null ? <SelesaiHistoryItem>[] : (state.valueOrNull?.items ?? const []);
return SelesaiHistoryState(
items: [...existing, ...items],
nextCursor: data['next_cursor'] as String?,
hasMore: data['has_more'] as bool? ?? false,
);
}
/// Append the next page if any. No-op when already loading or no cursor.
Future<void> loadMore() async {
final current = state.valueOrNull;
if (current == null || !current.hasMore || current.loadingMore) return;
state = AsyncData(current.copyWith(loadingMore: true));
try {
final next = await _fetchPage(cursor: current.nextCursor);
state = AsyncData(next);
} catch (e, st) {
state = AsyncError(e, st);
}
}
/// Pull-to-refresh: drop the cursor and re-fetch from the top.
Future<void> refresh() async {
state = const AsyncLoading();
try {
state = AsyncData(await _fetchPage(cursor: null));
} catch (e, st) {
state = AsyncError(e, st);
}
}
}
final selesaiHistoryProvider =
AsyncNotifierProvider<SelesaiHistoryNotifier, SelesaiHistoryState>(
SelesaiHistoryNotifier.new,
);

View File

@@ -0,0 +1,111 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/active_session_notifier.dart';
import '../../../core/theme/halo_tokens.dart';
import '../widgets/chat_row.dart';
/// Chat-Tab > aktif sub-tab.
///
/// Always renders 0 or 1 row — backend caps the customer to one active
/// session. Row stays visible while the user is inside the live chat room
/// (per §10.6 decision 1: aktif represents state, not navigation).
class AktifView extends ConsumerWidget {
const AktifView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final async = ref.watch(activeSessionProvider);
return RefreshIndicator(
onRefresh: () => ref.read(activeSessionProvider.notifier).refresh(),
color: HaloTokens.brand,
child: async.when(
loading: () => const _Loading(),
error: (e, _) => _Error(message: e.toString()),
data: (data) {
if (!data.hasSession) return const _Empty();
final session = data.session!;
final mitraName =
(session['mitra_display_name'] as String?) ?? 'Bestie';
return ListView(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s12,
),
children: [
ChatRow(
seed: mitraName.codeUnits.fold<int>(0, (a, b) => a + b),
name: mitraName,
preview: _previewFor(data.unreadCount),
isLive: true,
isCall: (session['mode'] as String?) == 'call',
onTap: () {
final sessionId = session['id'] as String?;
if (sessionId == null) return;
context.push('/chat/session/$sessionId',
extra: {'mitraName': mitraName});
},
),
],
);
},
),
);
}
String _previewFor(int unread) =>
unread > 0 ? '$unread pesan baru' : 'lagi ngobrol nih';
}
class _Empty extends StatelessWidget {
const _Empty();
@override
Widget build(BuildContext context) => const _CenteredMessage(
text: 'belum ada chat di sini',
);
}
class _Loading extends StatelessWidget {
const _Loading();
@override
Widget build(BuildContext context) => const Center(
child: CircularProgressIndicator(color: HaloTokens.brand),
);
}
class _Error extends StatelessWidget {
final String message;
const _Error({required this.message});
@override
Widget build(BuildContext context) =>
_CenteredMessage(text: 'gagal memuat: $message');
}
class _CenteredMessage extends StatelessWidget {
final String text;
const _CenteredMessage({required this.text});
@override
Widget build(BuildContext context) {
// Wrap in a scroll view so RefreshIndicator works even on empty state.
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s64,
),
child: Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
),
),
],
);
}
}

View File

@@ -0,0 +1,139 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/active_session_notifier.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../home/widgets/halo_tab_bar.dart';
import '../providers/pending_payments_provider.dart';
import '../widgets/sub_tab_pill.dart';
/// Phase 4 Stage 10 — host scaffold for the Chat tab.
///
/// Wraps the three sub-tab views (`/chat/aktif`, `/chat/pembayaran`,
/// `/chat/selesai`) via `ShellRoute`. The header + sub-tab pills + bottom
/// `HaloTabBar` stay constant while only the body swaps.
class ChatTabShell extends ConsumerWidget {
final Widget child;
final ChatSubTab active;
const ChatTabShell({
super.key,
required this.child,
required this.active,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final activeSession = ref.watch(activeSessionProvider).valueOrNull;
final unreadCount =
activeSession?.hasSession == true ? activeSession!.unreadCount : 0;
final pendingCount = ref.watch(pendingPaymentsCountProvider);
return Scaffold(
backgroundColor: HaloTokens.bg,
body: SafeArea(
bottom: false,
child: Column(
children: [
const _Heading(),
_SubTabBar(
active: active,
aktifBadge: unreadCount,
pembayaranBadge: pendingCount,
),
Expanded(child: child),
const HaloTabBar(active: 'chat'),
],
),
),
);
}
}
enum ChatSubTab {
aktif('/chat/aktif', 'aktif'),
pembayaran('/chat/pembayaran', 'pembayaran'),
selesai('/chat/selesai', 'selesai');
final String path;
final String label;
const ChatSubTab(this.path, this.label);
}
class _Heading extends StatelessWidget {
const _Heading();
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s20,
HaloSpacing.s24,
HaloSpacing.s12,
),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'chat',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 26,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
letterSpacing: -0.52,
),
),
),
);
}
}
class _SubTabBar extends StatelessWidget {
final ChatSubTab active;
final int aktifBadge;
final int pembayaranBadge;
const _SubTabBar({
required this.active,
required this.aktifBadge,
required this.pembayaranBadge,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: HaloSpacing.s16),
decoration: const BoxDecoration(
border: Border(bottom: BorderSide(color: HaloTokens.border)),
),
child: Row(
children: [
SubTabPill(
label: 'aktif',
active: active == ChatSubTab.aktif,
badgeCount: aktifBadge,
onTap: () => _navigate(context, ChatSubTab.aktif),
),
SubTabPill(
label: 'pembayaran',
active: active == ChatSubTab.pembayaran,
badgeCount: pembayaranBadge,
onTap: () => _navigate(context, ChatSubTab.pembayaran),
),
SubTabPill(
label: 'selesai',
active: active == ChatSubTab.selesai,
badgeCount: null,
onTap: () => _navigate(context, ChatSubTab.selesai),
),
],
),
);
}
void _navigate(BuildContext context, ChatSubTab target) {
if (target == active) return;
context.go(target.path);
}
}

View File

@@ -0,0 +1,103 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/theme/halo_tokens.dart';
import '../providers/pending_payments_provider.dart';
import '../widgets/chat_row.dart';
/// Chat-Tab > pembayaran sub-tab.
///
/// Lists pending initial + extension payments. Row tap resumes the
/// waiting-payment screen for that payment session.
class PembayaranView extends ConsumerWidget {
const PembayaranView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final async = ref.watch(pendingPaymentsProvider);
return RefreshIndicator(
onRefresh: () => ref.refresh(pendingPaymentsProvider.future),
color: HaloTokens.brand,
child: async.when(
loading: () => const _Loading(),
error: (e, _) => _CenteredMessage(text: 'gagal memuat: $e'),
data: (data) {
if (data.items.isEmpty) {
return const _CenteredMessage(
text: 'belum ada pembayaran tertunda',
);
}
return ListView.builder(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s12,
),
itemCount: data.items.length,
itemBuilder: (_, i) {
final item = data.items[i];
final name = item.mitraDisplayName ?? 'Bestie';
return ChatRow(
seed: name.codeUnits.fold<int>(0, (a, b) => a + b),
name: name,
preview: item.isExtension
? 'menunggu pembayaran perpanjangan'
: 'menunggu pembayaran sesi',
trailing: _relativeTime(item.createdAt),
chips: [PaymentAmountChip(amount: item.amount)],
isCall: item.mode == 'call',
onTap: () => context.push('/payment/waiting/${item.id}'),
);
},
);
},
),
);
}
}
/// Loose "2 mnt lalu" formatter — enough for the row trailing label without
/// dragging in `intl`. Mirrors the Figma copy style.
String _relativeTime(DateTime when) {
final delta = DateTime.now().difference(when);
if (delta.inSeconds < 60) return 'baru aja';
if (delta.inMinutes < 60) return '${delta.inMinutes} mnt lalu';
if (delta.inHours < 24) return '${delta.inHours} jam lalu';
if (delta.inDays < 7) return '${delta.inDays} hari lalu';
return '${(delta.inDays / 7).floor()} mgg lalu';
}
class _Loading extends StatelessWidget {
const _Loading();
@override
Widget build(BuildContext context) => const Center(
child: CircularProgressIndicator(color: HaloTokens.brand),
);
}
class _CenteredMessage extends StatelessWidget {
final String text;
const _CenteredMessage({required this.text});
@override
Widget build(BuildContext context) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s64,
),
child: Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
),
),
],
);
}
}

View File

@@ -0,0 +1,148 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/theme/halo_tokens.dart';
import '../providers/selesai_history_provider.dart';
import '../widgets/chat_row.dart';
/// Chat-Tab > selesai sub-tab.
///
/// Cursor-paginated past sessions. Tap → read-only transcript at
/// `/chat/transcript/:sessionId` (renamed from the retired /chat/history/:id).
class SelesaiView extends ConsumerStatefulWidget {
const SelesaiView({super.key});
@override
ConsumerState<SelesaiView> createState() => _SelesaiViewState();
}
class _SelesaiViewState extends ConsumerState<SelesaiView> {
final _scroll = ScrollController();
@override
void initState() {
super.initState();
_scroll.addListener(_onScroll);
}
@override
void dispose() {
_scroll.removeListener(_onScroll);
_scroll.dispose();
super.dispose();
}
void _onScroll() {
// Trigger load-more when within ~400px of the bottom. The notifier no-ops
// if there's no cursor or another fetch is in flight.
if (!_scroll.hasClients) return;
final remaining = _scroll.position.maxScrollExtent - _scroll.position.pixels;
if (remaining < 400) {
ref.read(selesaiHistoryProvider.notifier).loadMore();
}
}
@override
Widget build(BuildContext context) {
final async = ref.watch(selesaiHistoryProvider);
return RefreshIndicator(
onRefresh: () => ref.read(selesaiHistoryProvider.notifier).refresh(),
color: HaloTokens.brand,
child: async.when(
loading: () => const _Loading(),
error: (e, _) => _CenteredMessage(text: 'gagal memuat: $e'),
data: (state) {
if (state.items.isEmpty) {
return const _CenteredMessage(text: 'belum ada riwayat curhat');
}
return ListView.builder(
controller: _scroll,
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s12,
),
itemCount: state.items.length + (state.hasMore ? 1 : 0),
itemBuilder: (_, i) {
if (i >= state.items.length) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: HaloSpacing.s16),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: HaloTokens.brand,
),
),
),
);
}
final item = state.items[i];
return ChatRow(
seed: item.mitraName.codeUnits.fold<int>(0, (a, b) => a + b),
name: item.mitraName,
preview: item.previewText,
trailing: item.endedAt == null
? null
: _relativeTime(item.endedAt!),
chips: [
if (item.durationMinutes != null)
DurationChip(minutes: item.durationMinutes!),
],
isCall: item.mode == 'call',
onTap: () =>
context.push('/chat/transcript/${item.sessionId}'),
);
},
);
},
),
);
}
}
String _relativeTime(DateTime when) {
final delta = DateTime.now().difference(when);
if (delta.inSeconds < 60) return 'baru aja';
if (delta.inMinutes < 60) return '${delta.inMinutes} mnt lalu';
if (delta.inHours < 24) return '${delta.inHours} jam lalu';
if (delta.inDays < 7) return '${delta.inDays} hari lalu';
return '${(delta.inDays / 7).floor()} mgg lalu';
}
class _Loading extends StatelessWidget {
const _Loading();
@override
Widget build(BuildContext context) => const Center(
child: CircularProgressIndicator(color: HaloTokens.brand),
);
}
class _CenteredMessage extends StatelessWidget {
final String text;
const _CenteredMessage({required this.text});
@override
Widget build(BuildContext context) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s64,
),
child: Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
),
),
],
);
}
}

View File

@@ -0,0 +1,266 @@
import 'package:flutter/material.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/widgets.dart';
/// Generic row used by all three Chat-Tab sub-tabs (aktif / pembayaran /
/// selesai). The owning sub-tab supplies the right-side trailing widget and
/// any chips below the preview so this widget stays presentation-only.
///
/// Visual reference: `requirement/Figma/screens/extras.jsx::SChatList` rows.
class ChatRow extends StatelessWidget {
final int seed;
final String name;
final String preview;
final bool isLive;
final String? trailing;
final List<Widget> chips;
final bool isCall;
final VoidCallback? onTap;
const ChatRow({
super.key,
required this.seed,
required this.name,
required this.preview,
this.isLive = false,
this.trailing,
this.chips = const [],
this.isCall = false,
this.onTap,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Material(
color: HaloTokens.surface,
borderRadius: BorderRadius.circular(14),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(14),
child: Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14),
border: Border.all(color: HaloTokens.border),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_Avatar(seed: seed, isLive: isLive),
const SizedBox(width: 12),
Expanded(child: _Body(
name: name,
preview: preview,
trailing: trailing,
isLive: isLive,
isCall: isCall,
chips: chips,
)),
],
),
),
),
),
);
}
}
class _Avatar extends StatelessWidget {
final int seed;
final bool isLive;
const _Avatar({required this.seed, required this.isLive});
@override
Widget build(BuildContext context) {
return SizedBox(
width: 44,
height: 44,
child: Stack(
clipBehavior: Clip.none,
children: [
HaloOrb(seed: seed, size: 44),
if (isLive)
Positioned(
right: -2,
bottom: -2,
child: Container(
width: 14,
height: 14,
decoration: BoxDecoration(
color: HaloTokens.success,
shape: BoxShape.circle,
border: Border.all(color: HaloTokens.surface, width: 2.5),
),
),
),
],
),
);
}
}
class _Body extends StatelessWidget {
final String name;
final String preview;
final String? trailing;
final bool isLive;
final bool isCall;
final List<Widget> chips;
const _Body({
required this.name,
required this.preview,
required this.trailing,
required this.isLive,
required this.isCall,
required this.chips,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: [
Expanded(
child: Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 14,
fontWeight: FontWeight.w600,
color: HaloTokens.ink,
),
),
),
if (trailing != null || isLive)
Text(
isLive ? '● live' : (trailing ?? ''),
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10.5,
fontWeight: isLive ? FontWeight.w600 : FontWeight.w400,
color: isLive ? HaloTokens.success : HaloTokens.inkMuted,
),
),
],
),
const SizedBox(height: 2),
Text(
preview,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 12,
color: HaloTokens.inkSoft,
height: 1.4,
),
),
if (isCall || chips.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Wrap(
spacing: 6,
runSpacing: 4,
children: [
if (isCall) const _CallChip(),
...chips,
],
),
),
],
);
}
}
/// Voice-call indicator. Stage 6.0 introduced the header pill for the in-call
/// screen; this is its row-level companion in the Chat tab.
class _CallChip extends StatelessWidget {
const _CallChip();
@override
Widget build(BuildContext context) => const _Chip(
text: '📞 Call',
textColor: HaloTokens.brandDark,
background: HaloTokens.brandSoft,
);
}
/// Amber chip used on Pembayaran rows: `bayar Rp X.XXX`.
class PaymentAmountChip extends StatelessWidget {
final int amount;
const PaymentAmountChip({super.key, required this.amount});
@override
Widget build(BuildContext context) => _Chip(
text: 'bayar ${_formatRupiah(amount)}',
textColor: const Color(0xFFA8410E),
background: const Color(0xFFFFF0E5),
);
}
/// Subtle duration suffix on Selesai rows: `X menit`.
class DurationChip extends StatelessWidget {
final int minutes;
const DurationChip({super.key, required this.minutes});
@override
Widget build(BuildContext context) => Text(
'$minutes menit',
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10.5,
color: HaloTokens.inkMuted,
),
);
}
class _Chip extends StatelessWidget {
final String text;
final Color textColor;
final Color background;
const _Chip({
required this.text,
required this.textColor,
required this.background,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: background,
borderRadius: BorderRadius.circular(6),
),
child: Text(
text,
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10.5,
fontWeight: FontWeight.w600,
color: textColor,
),
),
);
}
}
String _formatRupiah(int amount) {
// Locale-agnostic, no intl dep. Render with `.` group separators per id_ID.
final s = amount.toString();
final buf = StringBuffer();
for (int i = 0; i < s.length; i++) {
if (i != 0 && (s.length - i) % 3 == 0) buf.write('.');
buf.write(s[i]);
}
return 'Rp${buf.toString()}';
}

View File

@@ -0,0 +1,92 @@
import 'package:flutter/material.dart';
import '../../../core/theme/halo_tokens.dart';
/// One of the three sub-tab buttons across the top of the Chat tab.
///
/// Active state uses the brand color for the label + an underline; an
/// optional `badgeCount` renders the numeric pill next to the label.
/// `null` or `0` hides the pill (per Selesai's no-badge rule).
class SubTabPill extends StatelessWidget {
final String label;
final bool active;
final int? badgeCount;
final VoidCallback onTap;
const SubTabPill({
super.key,
required this.label,
required this.active,
required this.onTap,
this.badgeCount,
});
@override
Widget build(BuildContext context) {
final color = active ? HaloTokens.brandDark : HaloTokens.inkSoft;
final showBadge = badgeCount != null && badgeCount! > 0;
return Expanded(
child: InkWell(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 4),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: active ? HaloTokens.brand : Colors.transparent,
width: 2,
),
),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
label,
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
fontWeight: active ? FontWeight.w700 : FontWeight.w500,
color: color,
),
),
if (showBadge) ...[
const SizedBox(width: 6),
_CountBadge(count: badgeCount!, active: active),
],
],
),
),
),
);
}
}
class _CountBadge extends StatelessWidget {
final int count;
final bool active;
const _CountBadge({required this.count, required this.active});
@override
Widget build(BuildContext context) {
return Container(
constraints: const BoxConstraints(minWidth: 18),
height: 18,
padding: const EdgeInsets.symmetric(horizontal: 6),
alignment: Alignment.center,
decoration: BoxDecoration(
color: active ? HaloTokens.brand : HaloTokens.brandSoft,
borderRadius: BorderRadius.circular(9),
),
child: Text(
'$count',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontWeight: FontWeight.w700,
color: active ? Colors.white : HaloTokens.brandDark,
),
),
);
}
}

View File

@@ -8,18 +8,21 @@ import '../../core/notifications/notif_permission.dart';
import '../../core/theme/halo_tokens.dart'; import '../../core/theme/halo_tokens.dart';
import 'providers/bestie_history_provider.dart'; import 'providers/bestie_history_provider.dart';
import 'widgets/bestie_choice_sheet.dart'; import 'widgets/bestie_choice_sheet.dart';
import 'widgets/halo_tab_bar.dart';
/// Session-only dismiss flag for the "notif denied" banner. Resets on cold /// Session-only dismiss flag for the "notif denied" banner. Resets on cold
/// restart by design — `StateProvider` lives in memory only. /// restart by design — `StateProvider` lives in memory only.
final homeNotifBannerDismissedProvider = StateProvider<bool>((_) => false); final homeNotifBannerDismissedProvider = StateProvider<bool>((_) => false);
/// Home screen. /// Home screen — Phase 4 redesign.
/// ///
/// 1. The "Mulai Curhat" CTA is gated on real-time mitra availability /// Renders one of two variants depending on auth state, mirroring the Figma
/// (polling owned by the [mitraAvailabilityProvider]). Polling is paused /// `SHome1st` / `SHomeReturning` components named in
/// on background and resumed on foreground via [WidgetsBindingObserver]. /// `requirement/flow_customer.mermaid.md` §1:
/// 2. Tapping the enabled CTA pushes `/payment` so the customer must confirm /// - `AuthInitialData` (no JWT) → SHome1st: top login-recover banner +
/// a payment session before any blast fires. /// `aku mau curhat` CTA + empty curhatan card.
/// - `AuthAnonymousData` / `AuthAuthenticatedData` → SHomeReturning:
/// `halo, {name}` greeting + `curhat sama bestie baru` CTA + history list.
class HomeScreen extends ConsumerStatefulWidget { class HomeScreen extends ConsumerStatefulWidget {
const HomeScreen({super.key}); const HomeScreen({super.key});
@@ -32,17 +35,19 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
void initState() { void initState() {
super.initState(); super.initState();
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
// Kick the availability poll on once the first frame settles. Doing it
// here (rather than in build) avoids re-firing on every rebuild.
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return; if (!mounted) return;
ref.read(mitraAvailabilityProvider.notifier).setActive(true); ref.read(mitraAvailabilityProvider.notifier).setActive(true);
// Re-fetch history every time we re-enter /home. Covers post-chat
// return via thank_you_screen's `context.go('/home')`, where the
// home widget is freshly constructed and we want the just-completed
// session reflected without requiring pull-to-refresh.
ref.invalidate(bestieHistoryProvider);
}); });
} }
@override @override
void dispose() { void dispose() {
// Stop polling when leaving home.
ref.read(mitraAvailabilityProvider.notifier).setActive(false); ref.read(mitraAvailabilityProvider.notifier).setActive(false);
WidgetsBinding.instance.removeObserver(this); WidgetsBinding.instance.removeObserver(this);
super.dispose(); super.dispose();
@@ -52,24 +57,17 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
void didChangeAppLifecycleState(AppLifecycleState state) { void didChangeAppLifecycleState(AppLifecycleState state) {
final notifier = ref.read(mitraAvailabilityProvider.notifier); final notifier = ref.read(mitraAvailabilityProvider.notifier);
if (state == AppLifecycleState.resumed) { if (state == AppLifecycleState.resumed) {
// Re-fetch in case a session ended/started while backgrounded.
ref.read(activeSessionProvider.notifier).refresh(); ref.read(activeSessionProvider.notifier).refresh();
ref.invalidate(bestieHistoryProvider);
notifier.setActive(true); notifier.setActive(true);
} else if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) { } else if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) {
notifier.setActive(false); notifier.setActive(false);
} }
} }
Future<void> _onStartChatPressed(BuildContext context) async { /// CTA path for SHomeReturning. Returning users get the bestie-choice sheet
// Phase 4 Stage 2 removes the home-screen topic sensitivity prompt; the /// when they have prior history, otherwise jump to the new-payment shell.
// ESP picks collected during onboarding feed the same column server-side Future<void> _onCurhatBestieBaruPressed(BuildContext context) async {
// (info-only — no longer drives matching). Mitras still flip
// `topic_sensitivity` mid-session via the AppBar toggle.
//
// Phase 4 Stage 8: returning users get the bestie-choice sheet first; new
// users skip straight to the multi-screen payment shell. We fetch the
// history-has-items flag on-tap so a stale cache from logout/login doesn't
// mis-route. On error (e.g. offline), fall back to the new-user path.
bool hasHistory; bool hasHistory;
try { try {
hasHistory = await ref.read(bestieHistoryHasItemsProvider.future); hasHistory = await ref.read(bestieHistoryHasItemsProvider.future);
@@ -84,12 +82,279 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
context.push('/payment/entry'); context.push('/payment/entry');
} }
/// CTA path for SHome1st. Per mermaid §2, fresh users hit S2 Nama first
/// (the call-sign check); display_name_screen kicks off `loginAnonymous`
/// and pushes into the verif-choice sheet.
void _onAkuMauCurhatPressed(BuildContext context) {
context.push('/auth/display-name');
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final authState = ref.watch(authProvider); final authState = ref.watch(authProvider);
final authData = authState.valueOrNull; final authData = authState.valueOrNull;
// SHomeReturning needs a real session; everything else (AuthInitialData,
// AsyncError, transient OTP states) renders SHome1st with the login
// banner so an unauthenticated user is never shown the returning view.
final isReturning =
authData is AuthAuthenticatedData || authData is AuthAnonymousData;
final isFresh = !isReturning;
return Scaffold(
backgroundColor: HaloTokens.bg,
body: SafeArea(
bottom: false,
child: Column(
children: [
const _NotifDeniedBanner(),
Expanded(
child: RefreshIndicator(
onRefresh: () async {
await Future.wait([
ref.read(activeSessionProvider.notifier).refresh(),
ref.read(mitraAvailabilityProvider.notifier).refresh(),
ref.refresh(bestieHistoryProvider.future),
]);
},
child: isFresh
? _SHome1stView(onCTA: () => _onAkuMauCurhatPressed(context))
: _SHomeReturningView(
onCTA: () => _onCurhatBestieBaruPressed(context),
),
),
),
const HaloTabBar(active: 'home'),
],
),
),
);
}
}
// ─── SHome1st ──────────────────────────────────────────────────────────────
class _SHome1stView extends ConsumerWidget {
final VoidCallback onCTA;
const _SHome1stView({required this.onCTA});
@override
Widget build(BuildContext context, WidgetRef ref) {
final availabilityAsync = ref.watch(mitraAvailabilityProvider);
final mitraAvailable = availabilityAsync.valueOrNull ?? false;
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: EdgeInsets.zero,
children: [
const _LoginRecoverBanner(),
Padding(
padding: const EdgeInsets.fromLTRB(28, 24, 28, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const _GreetingHaloOnly(),
const SizedBox(height: 4),
const _GreetingSubtitle(),
const SizedBox(height: 32),
_PrimaryCTA(
label: 'aku mau curhat',
enabled: mitraAvailable,
onPressed: onCTA,
),
if (!mitraAvailable) ...[
const SizedBox(height: 12),
const Text(
'belum ada bestie tersedia',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
),
],
const SizedBox(height: 28),
const _SectionLabel('curhatan sebelumnya'),
const SizedBox(height: 10),
const _HistoryEmptyCard(),
],
),
),
],
);
}
}
class _LoginRecoverBanner extends StatelessWidget {
const _LoginRecoverBanner();
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Material(
color: HaloTokens.brandSofter,
borderRadius: HaloRadius.md,
child: InkWell(
borderRadius: HaloRadius.md,
onTap: () => context.push('/auth/register'),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration(
borderRadius: HaloRadius.md,
border: Border.all(color: HaloTokens.brand.withValues(alpha: 0.2)),
),
child: Row(
children: [
Container(
width: 32,
height: 32,
decoration: const BoxDecoration(
color: HaloTokens.brand,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
alignment: Alignment.center,
child: const Text('👋', style: TextStyle(fontSize: 15)),
),
const SizedBox(width: 10),
const Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'udah pernah pakai HaloBestie?',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
height: 1.3,
),
),
SizedBox(height: 1),
Text(
'login buat lanjutin obrolan & history kamu',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 11,
color: HaloTokens.inkSoft,
height: 1.3,
),
),
],
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: HaloTokens.surface,
borderRadius: const BorderRadius.all(Radius.circular(8)),
border: Border.all(color: HaloTokens.brand.withValues(alpha: 0.33)),
),
child: const Text(
'masuk →',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: HaloTokens.brand,
),
),
),
],
),
),
),
),
);
}
}
class _GreetingHaloOnly extends StatelessWidget {
const _GreetingHaloOnly();
@override
Widget build(BuildContext context) {
return const Text(
'halo,',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 32,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
height: 1.15,
letterSpacing: -0.64,
),
);
}
}
class _GreetingSubtitle extends StatelessWidget {
const _GreetingSubtitle();
@override
Widget build(BuildContext context) {
return ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 290),
child: const Text(
'lagi ngerasa gimana hari ini? bestie akan nemenin kamu kok 🤍',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 14.5,
color: HaloTokens.inkSoft,
height: 1.55,
),
),
);
}
}
class _HistoryEmptyCard extends StatelessWidget {
const _HistoryEmptyCard();
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
decoration: BoxDecoration(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
border: Border.all(
color: HaloTokens.border,
width: 1,
style: BorderStyle.solid, // Flutter has no built-in dashed border;
// a CustomPainter could draw dashes — visual parity is close enough
// for v1 (border color + radius match Figma exactly).
),
),
alignment: Alignment.center,
child: const Text(
'belum ada curhatan. mulai aja, bestie udah siap 🌷',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
),
);
}
}
// ─── SHomeReturning ────────────────────────────────────────────────────────
class _SHomeReturningView extends ConsumerWidget {
final VoidCallback onCTA;
const _SHomeReturningView({required this.onCTA});
@override
Widget build(BuildContext context, WidgetRef ref) {
final authData = ref.watch(authProvider).valueOrNull;
final activeSessionAsync = ref.watch(activeSessionProvider); final activeSessionAsync = ref.watch(activeSessionProvider);
final availabilityAsync = ref.watch(mitraAvailabilityProvider); final availabilityAsync = ref.watch(mitraAvailabilityProvider);
final historyAsync = ref.watch(bestieHistoryProvider);
final mitraAvailable = availabilityAsync.valueOrNull ?? false;
final displayName = switch (authData) { final displayName = switch (authData) {
AuthAuthenticatedData d => d.profile['display_name'] as String? ?? '', AuthAuthenticatedData d => d.profile['display_name'] as String? ?? '',
@@ -97,57 +362,22 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
_ => '', _ => '',
}; };
// Poll-failure / loading both default to "no bestie available" (greyed-out). return ListView(
// Never optimistically enable.
final mitraAvailable = availabilityAsync.valueOrNull ?? false;
return Scaffold(
appBar: AppBar(
title: const Text('Halo Bestie'),
actions: [
IconButton(
icon: const Icon(Icons.history),
onPressed: () => context.push('/chat/history'),
),
IconButton(
icon: const Icon(Icons.logout),
onPressed: () => ref.read(authProvider.notifier).logout(),
),
],
),
body: RefreshIndicator(
onRefresh: () async {
// Pull-to-refresh kicks both the active-session and availability polls.
await Future.wait([
ref.read(activeSessionProvider.notifier).refresh(),
ref.read(mitraAvailabilityProvider.notifier).refresh(),
]);
},
child: ListView(
// Force-scroll so RefreshIndicator can fire even on a short body.
physics: const AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
padding: EdgeInsets.zero, padding: const EdgeInsets.fromLTRB(24, 32, 24, 16),
children: [ children: [
const _NotifDeniedBanner(), _GreetingHaloName(name: displayName),
const Padding( const SizedBox(height: 4),
padding: EdgeInsets.symmetric(horizontal: 32), const _GreetingSubtitle(),
child: SizedBox(height: 32), const SizedBox(height: 24),
), activeSessionAsync.when(
Center(child: Text('Halo, $displayName!', style: const TextStyle(fontSize: 24))), loading: () => const Center(child: CircularProgressIndicator()),
const SizedBox(height: 32), error: (_, __) => _PrimaryCTA(
Center( label: 'curhat sama bestie baru',
child: activeSessionAsync.when(
loading: () => const CircularProgressIndicator(),
error: (_, __) => _StartChatButton(
enabled: mitraAvailable, enabled: mitraAvailable,
onPressed: () => _onStartChatPressed(context), onPressed: onCTA,
), ),
data: (snapshot) { data: (snapshot) {
// Hide the "Sesi Aktif" CTA when the session is in `closing`
// — the conversation is over, only the goodbye composer
// remains. Backend auto-completes such sessions after a
// grace period; until then the user shouldn't be invited
// back into them from home.
final status = snapshot.session?['status'] as String?; final status = snapshot.session?['status'] as String?;
final isCurhatable = snapshot.hasSession && status != 'closing'; final isCurhatable = snapshot.hasSession && status != 'closing';
if (isCurhatable) { if (isCurhatable) {
@@ -157,48 +387,280 @@ class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObse
onTap: () { onTap: () {
final sessionId = snapshot.sessionId; final sessionId = snapshot.sessionId;
if (sessionId == null) return; if (sessionId == null) return;
context.push('/chat/session/$sessionId', extra: snapshot.mitraName); context.push('/chat/session/$sessionId',
extra: snapshot.mitraName);
}, },
); );
} }
return _StartChatButton( return _PrimaryCTA(
label: 'curhat sama bestie baru',
enabled: mitraAvailable, enabled: mitraAvailable,
onPressed: () => _onStartChatPressed(context), onPressed: onCTA,
); );
}, },
), ),
if (!mitraAvailable) ...[
const SizedBox(height: 12),
const Text(
'belum ada bestie tersedia',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
), ),
], ],
const SizedBox(height: 28),
const _SectionLabel('curhatan sebelumnya'),
const SizedBox(height: 10),
historyAsync.when(
loading: () => const Padding(
padding: EdgeInsets.symmetric(vertical: 24),
child: Center(child: CircularProgressIndicator()),
), ),
error: (_, __) => const _HistoryEmptyCard(),
data: (items) {
if (items.isEmpty) return const _HistoryEmptyCard();
return Column(
children: [
for (var i = 0; i < items.length; i++) ...[
_HistoryItemTile(item: items[i], seed: i + 1),
if (i < items.length - 1) const SizedBox(height: 10),
],
],
);
},
),
],
);
}
}
class _GreetingHaloName extends StatelessWidget {
final String name;
const _GreetingHaloName({required this.name});
@override
Widget build(BuildContext context) {
final shown = name.trim().isEmpty ? 'kamu' : name;
return Text.rich(
TextSpan(
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 32,
fontWeight: FontWeight.w700,
height: 1.15,
letterSpacing: -0.64,
),
children: [
const TextSpan(
text: 'halo, ',
style: TextStyle(color: HaloTokens.brandDark),
),
TextSpan(
text: shown,
style: const TextStyle(color: HaloTokens.brand),
),
],
), ),
); );
} }
} }
class _StartChatButton extends StatelessWidget { class _HistoryItemTile extends StatelessWidget {
final bool enabled; final BestieHistoryItem item;
final VoidCallback onPressed; final int seed;
const _StartChatButton({required this.enabled, required this.onPressed}); const _HistoryItemTile({required this.item, required this.seed});
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Column( final relative = _relativeWhen(item.endedAt);
final topicLine = item.topics.isEmpty ? '' : '"${item.topics.first}"';
return Material(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
child: InkWell(
borderRadius: HaloRadius.lg,
onTap: () => context.push('/chat/transcript/${item.sessionId}'),
child: Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
borderRadius: HaloRadius.lg,
border: Border.all(color: HaloTokens.border),
),
child: Row(
children: [ children: [
const SizedBox(height: 16), _OrbPlaceholder(seed: seed),
ElevatedButton( const SizedBox(width: 12),
style: ElevatedButton.styleFrom( Expanded(
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 16), child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(
child: Text(
item.mitraName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 14,
fontWeight: FontWeight.w600,
color: HaloTokens.ink,
), ),
onPressed: enabled ? onPressed : null,
child: const Text('Mulai Curhat', style: TextStyle(fontSize: 18)),
), ),
const SizedBox(height: 12), ),
if (!enabled) const SizedBox(width: 6),
Text( Text(
'Belum ada bestie tersedia', relative,
style: TextStyle(fontSize: 14, color: Colors.grey.shade600), style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10.5,
color: HaloTokens.inkMuted,
),
), ),
], ],
),
if (topicLine.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
topicLine,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 12,
color: HaloTokens.inkSoft,
height: 1.4,
),
),
],
if (item.endedAt != null) ...[
const SizedBox(height: 4),
const Text(
'sesi habis · tap untuk lanjutin curhat',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontStyle: FontStyle.italic,
color: HaloTokens.inkMuted,
),
),
],
],
),
),
],
),
),
),
);
}
static String _relativeWhen(DateTime? when) {
if (when == null) return '';
final diff = DateTime.now().difference(when);
if (diff.inDays >= 7) return '${(diff.inDays / 7).floor()} mgg lalu';
if (diff.inDays >= 1) return '${diff.inDays} hari lalu';
if (diff.inHours >= 1) return '${diff.inHours} jam lalu';
if (diff.inMinutes >= 1) return '${diff.inMinutes} mnt lalu';
return 'baru saja';
}
}
/// Placeholder for the Figma `HBOrb` gradient component. v1 ships as a
/// solid-color disc keyed off `seed`; a real animated orb is a follow-up.
class _OrbPlaceholder extends StatelessWidget {
final int seed;
const _OrbPlaceholder({required this.seed});
@override
Widget build(BuildContext context) {
const palette = [
HaloTokens.brand,
HaloTokens.lilac,
HaloTokens.mint,
HaloTokens.accent,
];
final color = palette[seed % palette.length];
return Container(
width: 42,
height: 42,
decoration: BoxDecoration(
gradient: RadialGradient(
colors: [color.withValues(alpha: 0.95), color.withValues(alpha: 0.55)],
),
shape: BoxShape.circle,
),
);
}
}
// ─── Shared ────────────────────────────────────────────────────────────────
class _SectionLabel extends StatelessWidget {
final String text;
const _SectionLabel(this.text);
@override
Widget build(BuildContext context) {
return Text(
text,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 11.5,
fontWeight: FontWeight.w600,
color: HaloTokens.inkMuted,
letterSpacing: 0.69,
),
);
}
}
class _PrimaryCTA extends StatelessWidget {
final String label;
final bool enabled;
final VoidCallback onPressed;
const _PrimaryCTA({
required this.label,
required this.enabled,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity,
child: DecoratedBox(
decoration: BoxDecoration(
borderRadius: HaloRadius.xl,
boxShadow: enabled ? HaloShadows.button : const [],
),
child: Material(
color: enabled ? HaloTokens.brand : HaloTokens.brandSofter,
borderRadius: HaloRadius.xl,
child: InkWell(
borderRadius: HaloRadius.xl,
onTap: enabled ? onPressed : null,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 18),
child: Center(
child: Text(
label,
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 15,
fontWeight: FontWeight.w600,
color: enabled ? Colors.white : HaloTokens.inkMuted,
),
),
),
),
),
),
),
); );
} }
} }
@@ -216,11 +678,14 @@ class _ActiveSessionCard extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Card( return Material(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
elevation: 2, elevation: 2,
shadowColor: HaloTokens.brand.withValues(alpha: 0.2),
child: InkWell( child: InkWell(
onTap: onTap, onTap: onTap,
borderRadius: BorderRadius.circular(12), borderRadius: HaloRadius.lg,
child: Padding( child: Padding(
padding: const EdgeInsets.all(20), padding: const EdgeInsets.all(20),
child: Row( child: Row(
@@ -229,7 +694,7 @@ class _ActiveSessionCard extends StatelessWidget {
isLabelVisible: unreadCount > 0, isLabelVisible: unreadCount > 0,
label: Text('$unreadCount'), label: Text('$unreadCount'),
child: const CircleAvatar( child: const CircleAvatar(
backgroundColor: Colors.green, backgroundColor: HaloTokens.success,
child: Icon(Icons.chat, color: Colors.white), child: Icon(Icons.chat, color: Colors.white),
), ),
), ),
@@ -239,18 +704,27 @@ class _ActiveSessionCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
const Text( const Text(
'Sesi Aktif', 'sesi aktif',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 16,
fontWeight: FontWeight.w700,
color: HaloTokens.ink,
),
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
Text( Text(
'Sedang curhat dengan $mitraName', 'sedang curhat dengan $mitraName',
style: const TextStyle(fontSize: 14, color: Colors.grey), style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 14,
color: HaloTokens.inkSoft,
),
), ),
], ],
), ),
), ),
const Icon(Icons.chevron_right), const Icon(Icons.chevron_right, color: HaloTokens.inkMuted),
], ],
), ),
), ),
@@ -260,8 +734,8 @@ class _ActiveSessionCard extends StatelessWidget {
} }
/// Above-the-fold amber banner shown when notif permission is denied. Tap /// Above-the-fold amber banner shown when notif permission is denied. Tap
/// "nyalain" → opens app settings; tap the close icon → hides for the /// "nyalain" → opens app settings; tap close → hides for the in-memory
/// in-memory session only (cold restart re-shows it). /// session (cold restart re-shows it).
class _NotifDeniedBanner extends ConsumerWidget { class _NotifDeniedBanner extends ConsumerWidget {
const _NotifDeniedBanner(); const _NotifDeniedBanner();
@@ -331,3 +805,4 @@ class _NotifDeniedBanner extends ConsumerWidget {
); );
} }
} }

View File

@@ -0,0 +1,325 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/widgets.dart';
import '../providers/bestie_history_provider.dart';
/// `BestieHistoryList` — the picker for the returning-user "curhat lagi"
/// flow (mermaid §4). Visual reference: `screens/v4.jsx::BestieHistoryList`.
///
/// Reached from `BestieChoiceSheet` → "bestie yang udah kenal". Row tap =
/// pick a past bestie → targeted-pair payment flow. Transcript browsing
/// lives in the Chat-tab Selesai sub-tab, not here.
///
/// Row interaction rules:
/// - mitra_is_online + status != closing → tap targets `/payment` with
/// `targetedMitraId`, which jumps into the Stage-3.x payment flow and,
/// once confirmed, the Stage-5 targeted-wait overlay.
/// - status == closing → tap drops into the chat session screen so the
/// user can finish the goodbye composer (one-time grace path).
/// - mitra_is_online == false → row is dimmed and tap is disabled. Mermaid
/// §4 calls for a Bestie Offline Popup variant here, deferred until
/// OfflinePopup gets its returning-user copy.
class BestieHistoryListScreen extends ConsumerWidget {
const BestieHistoryListScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final historyAsync = ref.watch(bestieHistoryProvider);
final rawAsync = ref.watch(_rawHistoryProvider);
return Scaffold(
backgroundColor: HaloTokens.bg,
appBar: AppBar(
backgroundColor: HaloTokens.bg,
foregroundColor: HaloTokens.brandDark,
elevation: 0,
title: const Text(
'bestie kamu sebelumnya',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 20,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
),
),
),
body: historyAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (_, __) => const Center(
child: Text(
'gagal memuat riwayat. tarik untuk muat ulang.',
style: TextStyle(fontFamily: HaloTokens.fontBody),
),
),
data: (items) {
if (items.isEmpty) {
return const Center(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: HaloSpacing.s24),
child: Text(
'belum ada bestie sebelumnya. coba bestie baru dulu ya.',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: HaloTokens.fontBody,
color: HaloTokens.inkSoft,
),
),
),
);
}
return RefreshIndicator(
onRefresh: () async {
ref.invalidate(bestieHistoryProvider);
ref.invalidate(_rawHistoryProvider);
await ref.read(bestieHistoryProvider.future);
},
child: ListView.separated(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s12,
),
itemCount: items.length + 1,
separatorBuilder: (_, __) =>
const SizedBox(height: HaloSpacing.s12),
itemBuilder: (context, index) {
if (index == 0) {
return Padding(
padding: const EdgeInsets.only(
bottom: HaloSpacing.s8,
left: 2,
),
child: Text(
'${items.length} bestie yang pernah nemenin kamu',
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkSoft,
),
),
);
}
final item = items[index - 1];
final raw = rawAsync.valueOrNull?[index - 1];
final isClosing = raw?['status'] == SessionStatus.closing;
return _BestieRow(
item: item,
isClosing: isClosing,
onPick: () {
if (isClosing) {
context.push(
'/chat/session/${item.sessionId}',
extra: item.mitraName,
);
return;
}
if (item.mitraId == null) return;
context.push('/payment', extra: <String, dynamic>{
'targetedMitraId': item.mitraId,
'mitraName': item.mitraName,
'topicSensitivity': TopicSensitivity.regular,
});
},
);
},
),
);
},
),
);
}
}
/// Raw history payload — used to read fields the v4 `BestieHistoryItem`
/// model doesn't surface (currently `status`, for the closing-row branch).
final _rawHistoryProvider =
FutureProvider<List<Map<String, dynamic>>>((ref) async {
final api = ref.read(apiClientProvider);
final response = await api.get('/api/client/chat/history');
return ((response['data']['items'] as List?) ?? const [])
.cast<Map<String, dynamic>>();
});
class _BestieRow extends StatelessWidget {
final BestieHistoryItem item;
final bool isClosing;
final VoidCallback onPick;
const _BestieRow({
required this.item,
required this.isClosing,
required this.onPick,
});
@override
Widget build(BuildContext context) {
final canPick = item.mitraIsOnline && !isClosing && item.mitraId != null;
return Material(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
child: InkWell(
onTap: canPick ? onPick : null,
borderRadius: HaloRadius.lg,
child: Opacity(
opacity: canPick ? 1.0 : 0.55,
child: Padding(
padding: const EdgeInsets.all(HaloSpacing.s16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
HaloOrb(
size: 56,
seed: (item.mitraId ?? item.mitraName).hashCode,
label: item.mitraName,
),
const SizedBox(width: HaloSpacing.s12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Flexible(
child: Text(
'bestie ${item.mitraName}',
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 15,
fontWeight: FontWeight.w700,
color: HaloTokens.ink,
),
),
),
if (item.mitraIsOnline) ...[
const SizedBox(width: HaloSpacing.s8),
const _OnlinePill(),
],
if (isClosing) ...[
const SizedBox(width: HaloSpacing.s8),
const _ClosingBadge(),
],
],
),
const SizedBox(height: 2),
Text(
[
'${item.sessionsCount}× sesi',
if (item.endedAt != null)
'terakhir ${_formatDate(item.endedAt!)}',
].join(' · '),
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 12,
color: HaloTokens.inkSoft,
),
),
if (item.topics.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
'"${item.topics.first}"',
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 11.5,
fontStyle: FontStyle.italic,
color: HaloTokens.inkMuted,
),
),
],
],
),
),
const SizedBox(width: HaloSpacing.s8),
Text(
'',
style: TextStyle(
fontSize: 16,
color: canPick ? HaloTokens.brand : HaloTokens.inkMuted,
),
),
],
),
),
),
),
);
}
String _formatDate(DateTime d) =>
'${d.day.toString().padLeft(2, '0')}/${d.month.toString().padLeft(2, '0')}/${d.year}';
}
class _OnlinePill extends StatelessWidget {
const _OnlinePill();
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: HaloTokens.success.withAlpha(36),
borderRadius: BorderRadius.circular(999),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
_Dot(color: HaloTokens.success),
SizedBox(width: 4),
Text(
'ONLINE',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontWeight: FontWeight.w700,
letterSpacing: 0.6,
color: HaloTokens.success,
),
),
],
),
);
}
}
class _Dot extends StatelessWidget {
final Color color;
const _Dot({required this.color});
@override
Widget build(BuildContext context) {
return Container(
width: 6,
height: 6,
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
);
}
}
class _ClosingBadge extends StatelessWidget {
const _ClosingBadge();
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: HaloTokens.accentSoft,
borderRadius: BorderRadius.circular(999),
),
child: const Text(
'Belum ditutup',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontWeight: FontWeight.w600,
color: HaloTokens.brandDark,
),
),
);
}
}

View File

@@ -51,7 +51,7 @@ class BestieChoiceSheet extends StatelessWidget {
icon: Icons.favorite_outline, icon: Icons.favorite_outline,
onTap: () { onTap: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
context.push('/chat/history'); context.push('/bestie/history');
}, },
), ),
const SizedBox(height: HaloSpacing.s12), const SizedBox(height: HaloSpacing.s12),

View File

@@ -0,0 +1,161 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../chat_tab/providers/pending_payments_provider.dart';
/// 4-tab bottom bar mirroring Figma `HBTabBar` (home / chat / kamu / premium SOON).
///
/// Phase 4 §1 wires home + chat + kamu. `premium` is intentionally
/// no-op + SOON-tagged. Each tab uses `context.go` so tapping a tab from any
/// non-tab screen resets the back-stack — preventing nav-stack growth as the
/// user bounces between tabs.
///
/// Stage 10: the `chat` tab now lands on `/chat` (which redirects into the
/// `aktif` sub-tab) and renders a red dot when any Pembayaran row is pending.
class HaloTabBar extends ConsumerWidget {
/// One of `home`, `chat`, `kamu`, `premium`.
final String active;
const HaloTabBar({super.key, required this.active});
@override
Widget build(BuildContext context, WidgetRef ref) {
final pendingCount = ref.watch(pendingPaymentsCountProvider);
return Container(
decoration: const BoxDecoration(
color: HaloTokens.surface,
border: Border(top: BorderSide(color: HaloTokens.border)),
),
padding: EdgeInsets.fromLTRB(
HaloSpacing.s16,
HaloSpacing.s8,
HaloSpacing.s16,
MediaQuery.of(context).padding.bottom + HaloSpacing.s8,
),
child: Row(
children: [
_TabItem(
icon: '🏠',
label: 'home',
active: active == 'home',
onTap: () => context.go('/home'),
),
_TabItem(
icon: '💬',
label: 'chat',
active: active == 'chat',
showDot: pendingCount > 0,
onTap: () => context.go('/chat'),
),
_TabItem(
icon: '👤',
label: 'kamu',
active: active == 'kamu',
onTap: () => context.go('/profile'),
),
_TabItem(
icon: '',
label: 'premium',
active: active == 'premium',
soon: true,
onTap: () {},
),
],
),
);
}
}
class _TabItem extends StatelessWidget {
final String icon;
final String label;
final bool active;
final bool soon;
final bool showDot;
final VoidCallback onTap;
const _TabItem({
required this.icon,
required this.label,
required this.active,
required this.onTap,
this.soon = false,
this.showDot = false,
});
@override
Widget build(BuildContext context) {
final color = active ? HaloTokens.brand : HaloTokens.inkMuted;
final opacity = soon ? 0.5 : 1.0;
return Expanded(
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Stack(
clipBehavior: Clip.none,
alignment: Alignment.center,
children: [
Column(
mainAxisSize: MainAxisSize.min,
children: [
Opacity(
opacity: opacity,
child: Text(icon, style: const TextStyle(fontSize: 22)),
),
const SizedBox(height: 2),
Opacity(
opacity: opacity,
child: Text(
label,
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontWeight: active ? FontWeight.w600 : FontWeight.w400,
color: color,
),
),
),
],
),
if (soon)
Positioned(
top: -2,
right: 4,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
decoration: const BoxDecoration(
color: HaloTokens.accent,
borderRadius: BorderRadius.all(Radius.circular(6)),
),
child: const Text(
'SOON',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 8,
fontWeight: FontWeight.w700,
color: Colors.white,
letterSpacing: 0.32,
),
),
),
),
if (showDot && !soon)
Positioned(
top: 2,
right: 18,
child: Container(
width: 8,
height: 8,
decoration: const BoxDecoration(
color: HaloTokens.danger,
shape: BoxShape.circle,
),
),
),
],
),
),
),
);
}
}

View File

@@ -2,25 +2,28 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart'; import 'package:go_router/go_router.dart';
import 'core/auth/auth_notifier.dart'; import 'core/auth/auth_notifier.dart';
import 'features/auth/screens/welcome_screen.dart';
import 'features/auth/screens/display_name_screen.dart'; import 'features/auth/screens/display_name_screen.dart';
import 'features/auth/screens/register_screen.dart'; import 'features/auth/screens/register_screen.dart';
import 'features/auth/screens/otp_screen.dart'; import 'features/auth/screens/otp_screen.dart';
import 'features/auth/screens/force_register_screen.dart'; import 'features/auth/screens/force_register_screen.dart';
import 'features/auth/screens/set_display_name_screen.dart'; import 'features/auth/screens/set_display_name_screen.dart';
import 'features/onboarding/onboarding_screen.dart'; import 'features/onboarding/onboarding_screen.dart';
import 'features/onboarding/screens/esp_screen.dart';
import 'features/onboarding/screens/notif_gate_screen.dart'; import 'features/onboarding/screens/notif_gate_screen.dart';
import 'features/onboarding/screens/usp_screen.dart'; import 'features/onboarding/screens/usp_screen.dart';
import 'features/splash/splash_screen.dart'; import 'features/splash/splash_screen.dart';
import 'features/home/home_screen.dart'; import 'features/home/home_screen.dart';
import 'features/home/screens/bestie_history_list_screen.dart';
import 'features/profile/profile_screen.dart';
import 'core/constants.dart'; import 'core/constants.dart';
import 'features/chat/screens/searching_screen.dart'; import 'features/chat/screens/searching_screen.dart';
import 'features/chat/screens/bestie_found_screen.dart'; import 'features/chat/screens/bestie_found_screen.dart';
import 'features/chat/screens/no_bestie_screen.dart'; import 'features/chat/screens/no_bestie_screen.dart';
import 'features/chat/screens/chat_screen.dart'; import 'features/chat/screens/chat_screen.dart';
import 'features/chat/screens/chat_history_screen.dart';
import 'features/chat/screens/chat_transcript_screen.dart'; import 'features/chat/screens/chat_transcript_screen.dart';
import 'features/chat_tab/screens/chat_tab_shell.dart';
import 'features/chat_tab/screens/aktif_view.dart';
import 'features/chat_tab/screens/pembayaran_view.dart';
import 'features/chat_tab/screens/selesai_view.dart';
import 'features/chat/screens/targeted_waiting_screen.dart'; import 'features/chat/screens/targeted_waiting_screen.dart';
import 'features/chat/screens/thank_you_screen.dart'; import 'features/chat/screens/thank_you_screen.dart';
import 'features/payment/screens/payment_screen.dart'; import 'features/payment/screens/payment_screen.dart';
@@ -69,8 +72,7 @@ GoRouter buildRouter(Ref ref) {
final authState = ref.read(authProvider); final authState = ref.read(authProvider);
final isSplash = state.matchedLocation == '/splash'; final isSplash = state.matchedLocation == '/splash';
final isOnboarding = state.matchedLocation == '/onboarding'; final isOnboarding = state.matchedLocation == '/onboarding';
final isAuthRoute = state.matchedLocation.startsWith('/auth') || final isAuthRoute = state.matchedLocation.startsWith('/auth');
state.matchedLocation == '/welcome';
// Phase 4 onboarding flow (Verif Choice → ESP → USP) — must transit // Phase 4 onboarding flow (Verif Choice → ESP → USP) — must transit
// freely while authState is AuthAnonymousData so the router doesn't // freely while authState is AuthAnonymousData so the router doesn't
// boot the user back to /home before they finish onboarding. // boot the user back to /home before they finish onboarding.
@@ -89,14 +91,15 @@ GoRouter buildRouter(Ref ref) {
return isOnboarding ? null : '/onboarding'; return isOnboarding ? null : '/onboarding';
} }
if (isOnboarding) { if (isOnboarding) {
return '/welcome'; return '/home';
} }
final data = authState.valueOrNull; final data = authState.valueOrNull;
if (data == null) { if (data == null) {
// Error state — show login // Error state — drop onto Home; SHome1st variant handles the
if (!isAuthRoute && !isSplash) return '/welcome'; // unauthenticated render (login banner overlay).
if (isSplash) return '/welcome'; if (!isAuthRoute && !isSplash) return '/home';
if (isSplash) return '/home';
return null; return null;
} }
@@ -106,19 +109,22 @@ GoRouter buildRouter(Ref ref) {
// intentionally pushes into /onboarding/* after loginAnonymous. // intentionally pushes into /onboarding/* after loginAnonymous.
if (isOnboardingFlow) return null; if (isOnboardingFlow) return null;
// While AuthAnonymousData, the user may legitimately be mid-flow on // While AuthAnonymousData, the user may legitimately be mid-flow on
// /welcome (initial entry) → /auth/display-name (push) → about to // /home → /auth/display-name (push) → about to open the Verif Choice
// open the Verif Choice Sheet. When refreshListenable fires after // Sheet. When refreshListenable fires after loginAnonymous resolves,
// loginAnonymous resolves, GoRouter re-evaluates the *bottom* of the // GoRouter re-evaluates the bottom of the navigation stack — without
// navigation stack (/welcome) which would otherwise redirect to // this carve-out an /auth/* push would be torn down before the sheet
// /home and tear the stack down before the sheet can open. Allow // can open. Allow any auth route to stay put under AuthAnonymousData.
// any auth route to stay put under AuthAnonymousData.
if (data is AuthAnonymousData && isAuthRoute) return null; if (data is AuthAnonymousData && isAuthRoute) return null;
return (isSplash || isAuthRoute) ? '/home' : null; return (isSplash || isAuthRoute) ? '/home' : null;
} }
if (data is AuthNeedsDisplayNameData) return '/auth/set-name'; if (data is AuthNeedsDisplayNameData) return '/auth/set-name';
if (data is AuthForceRegisterData) return '/auth/force-register'; if (data is AuthForceRegisterData) return '/auth/force-register';
if (!isAuthRoute && !isSplash) return '/welcome'; // Phase 4: per flow_customer.mermaid §1, fresh / unauthenticated users
if (isSplash) return '/welcome'; // land on Home directly — the login panel is an overlay on Home, not a
// separate /welcome screen. The Home1st login-panel overlay itself is
// still a follow-up (audit: Home1st 🟡).
if (!isAuthRoute && !isSplash) return '/home';
if (isSplash) return '/home';
return null; return null;
}, },
routes: [ routes: [
@@ -126,26 +132,19 @@ GoRouter buildRouter(Ref ref) {
GoRoute(path: '/_theme_preview', builder: (_, __) => const ThemePreviewScreen()), GoRoute(path: '/_theme_preview', builder: (_, __) => const ThemePreviewScreen()),
GoRoute(path: '/splash', builder: (_, __) => const SplashScreen()), GoRoute(path: '/splash', builder: (_, __) => const SplashScreen()),
GoRoute(path: '/onboarding', builder: (_, __) => const OnboardingScreen()), GoRoute(path: '/onboarding', builder: (_, __) => const OnboardingScreen()),
GoRoute(path: '/welcome', builder: (_, __) => const WelcomeScreen()),
GoRoute(path: '/auth/display-name', builder: (_, __) => const DisplayNameScreen()), GoRoute(path: '/auth/display-name', builder: (_, __) => const DisplayNameScreen()),
GoRoute(path: '/auth/register', builder: (_, __) => const RegisterScreen()), GoRoute(path: '/auth/register', builder: (_, __) => const RegisterScreen()),
GoRoute(path: '/auth/otp', builder: (context, state) => OtpScreen(phone: state.extra as String)), GoRoute(path: '/auth/otp', builder: (context, state) => OtpScreen(phone: state.extra as String)),
GoRoute(path: '/auth/set-name', builder: (_, __) => const SetDisplayNameScreen()), GoRoute(path: '/auth/set-name', builder: (_, __) => const SetDisplayNameScreen()),
GoRoute(path: '/auth/force-register', builder: (_, __) => const ForceRegisterScreen()), GoRoute(path: '/auth/force-register', builder: (_, __) => const ForceRegisterScreen()),
// Phase 4 onboarding sub-flow (Stage 2). Verified vs anonymous branch // Phase 4 onboarding sub-flow (Stage 2; updated 2026-05-12 — ESP retired,
// share ESP + USP screens; the parent path drives the post-USP fork. // USP is now a one-time gate, see `usp_seen_provider.dart`). Verified vs
GoRoute( // anonymous branches share the USP screen; the parent path drives the
path: '/onboarding/verif/esp', // post-USP fork.
builder: (_, __) => const EspScreen(verified: true),
),
GoRoute( GoRoute(
path: '/onboarding/verif/usp', path: '/onboarding/verif/usp',
builder: (_, __) => const UspScreen(verified: true), builder: (_, __) => const UspScreen(verified: true),
), ),
GoRoute(
path: '/onboarding/anon/esp',
builder: (_, __) => const EspScreen(verified: false),
),
GoRoute( GoRoute(
path: '/onboarding/anon/usp', path: '/onboarding/anon/usp',
builder: (_, __) => const UspScreen(verified: false), builder: (_, __) => const UspScreen(verified: false),
@@ -166,6 +165,7 @@ GoRouter buildRouter(Ref ref) {
redirect: (_, __) => '/payment/method-pick', redirect: (_, __) => '/payment/method-pick',
), ),
GoRoute(path: '/home', builder: (_, __) => const HomeScreen()), GoRoute(path: '/home', builder: (_, __) => const HomeScreen()),
GoRoute(path: '/profile', builder: (_, __) => const ProfileScreen()),
GoRoute(path: '/payment', builder: (context, state) { GoRoute(path: '/payment', builder: (context, state) {
// Legacy Phase 3.7 single-screen payment. Still reachable from // Legacy Phase 3.7 single-screen payment. Still reachable from
// - Home "Mulai Curhat" CTA → no extras (general blast follows confirm) // - Home "Mulai Curhat" CTA → no extras (general blast follows confirm)
@@ -232,10 +232,38 @@ GoRouter buildRouter(Ref ref) {
); );
}), }),
GoRoute(path: '/chat/thank-you', builder: (_, __) => const ThankYouScreen()), GoRoute(path: '/chat/thank-you', builder: (_, __) => const ThankYouScreen()),
GoRoute(path: '/chat/history', builder: (_, __) => const ChatHistoryScreen()), // Phase 4 Stage 10 — Chat tab with 3 sub-tabs. The bare `/chat` entry
GoRoute(path: '/chat/history/:sessionId', builder: (context, state) { // redirects into the default `aktif` sub-tab so tap-on-bottom-nav lands
// on a deterministic URL.
GoRoute(path: '/chat', redirect: (_, __) => '/chat/aktif'),
ShellRoute(
builder: (context, state, child) {
final active = switch (state.uri.path) {
'/chat/pembayaran' => ChatSubTab.pembayaran,
'/chat/selesai' => ChatSubTab.selesai,
_ => ChatSubTab.aktif,
};
return ChatTabShell(active: active, child: child);
},
routes: [
GoRoute(path: '/chat/aktif', builder: (_, __) => const AktifView()),
GoRoute(
path: '/chat/pembayaran',
builder: (_, __) => const PembayaranView()),
GoRoute(
path: '/chat/selesai', builder: (_, __) => const SelesaiView()),
],
),
GoRoute(path: '/chat/transcript/:sessionId', builder: (context, state) {
return ChatTranscriptScreen(sessionId: state.pathParameters['sessionId']!); return ChatTranscriptScreen(sessionId: state.pathParameters['sessionId']!);
}), }),
// Returning-user `curhat lagi` picker (mermaid §4). Reached from
// BestieChoiceSheet → "bestie yang udah kenal". Tap row → targeted-pair
// payment. Separate from the Chat tab (which is browse-only).
GoRoute(
path: '/bestie/history',
builder: (_, __) => const BestieHistoryListScreen(),
),
], ],
); );
} }

View File

@@ -19,11 +19,11 @@ the Figma handoff naming (`S1`, `S6`, `S10`, …); see `Figma/handoff/png/` for
```mermaid ```mermaid
flowchart TD flowchart TD
S1["S1 · Splash 🟢"] --> Home{"JWT session?"} S1["S1 · Splash 🟢"] --> Home{"JWT session?"}
Home -->|"no"| Home1st["Home (1st time)<br/>+ login panel 🟡"] Home -->|"no"| Home1st["Home (1st time)<br/>+ login panel 🟢"]
Home -->|"yes"| HomeRet["Home (returning)<br/>+ profile panel 🟢"] Home -->|"yes"| HomeRet["Home (returning)<br/>+ profile panel 🟢"]
Home1st --> NotifCheck{"OS notif allowed?"} Home1st --> NotifCheck{"OS notif allowed?"}
HomeRet --> NotifCheck HomeRet --> NotifCheck
NotifCheck -->|"no"| HomeBanner["Home + notif banner 🔴"] NotifCheck -->|"no"| HomeBanner["Home + notif banner 🟢"]
NotifCheck -->|"yes"| HomeReady["Home (ready) 🟢"] NotifCheck -->|"yes"| HomeReady["Home (ready) 🟢"]
HomeBanner --> HomeReady HomeBanner --> HomeReady
@@ -33,8 +33,6 @@ flowchart TD
classDef missing fill:#ffe5e5,stroke:#c44979 classDef missing fill:#ffe5e5,stroke:#c44979
classDef partial fill:#fff4d6,stroke:#c69b3f classDef partial fill:#fff4d6,stroke:#c69b3f
class HomeBanner missing
class Home1st partial
``` ```
--- ---
@@ -46,45 +44,92 @@ flowchart TD
Start["from Home — 'aku mau curhat' 🟢"] --> NameCheck{"call_sign exists?"} Start["from Home — 'aku mau curhat' 🟢"] --> NameCheck{"call_sign exists?"}
NameCheck -->|"no"| S2["S2 · Pengisian Nama 🟢"] NameCheck -->|"no"| S2["S2 · Pengisian Nama 🟢"]
NameCheck -->|"yes"| VerifChoice NameCheck -->|"yes"| VerifChoice
S2 --> VerifChoice["Verif vs Anon Choice Sheet<br/>(VerifChoiceSheet) 🔴"] S2 --> VerifChoice["Verif vs Anon Choice Sheet<br/>(VerifChoiceSheet) 🟢"]
VerifChoice -->|"verif WA · Rp2k"| ESPa["S5 · ESP screening<br/>(multi-select chips) 🟡"] VerifChoice -->|"verif WA · Rp2k"| USPGateA{"usp_seen flag? 🔴"}
VerifChoice -->|"tanpa verif · Rp5k+"| ESPb["S5 · ESP screening 🟡"] VerifChoice -->|"tanpa verif · Rp5k+"| USPGateB{"usp_seen flag? 🔴"}
%% Verified path %% Verified path
ESPa --> USPa["S5b · USP screen 🔴"] USPGateA -->|"no · first-timer"| USPa["S5b · USP screen 🟢"]
USPa --> S3a["S3a · WhatsApp input 🟡 (6→4 digit)"] USPGateA -->|"yes · skip"| S3a
USPa --> S3a["S3a · WhatsApp input 🟢"]
S3a --> S3b["S3b · OTP 4-digit 🟡"] S3a --> S3b["S3b · OTP 4-digit 🟡"]
S3b --> OTPok{"OTP ok?"} S3b --> OTPok{"OTP ok?"}
OTPok -->|"too many retries"| OTPBlock["OTP Blocked Popup 🔴<br/>→ fallback to Anon"] OTPok -->|"too many retries"| OTPBlock["OTP Blocked Popup 🟢<br/>→ fallback to Anon"]
OTPBlock --> ESPb OTPBlock --> USPGateB
OTPok -->|"verified"| S6["S6 · Paywall Rp2.000<br/>(12 menit, sekali seumur hidup) 🟡"] OTPok -->|"verified"| UserLookup{"user found in DB?<br/>(phone match) 🔴"}
UserLookup -->|"no · brand-new"| S6["S6 · Paywall Rp2.000<br/>(12 menit, sekali seumur hidup) 🟢"]
UserLookup -->|"yes · existing account"| LoadCallSign["Load stored call_sign<br/>→ overwrite local call_sign 🔴"]
LoadCallSign --> TransactedCheck{"has_transacted flag? 🔴"}
TransactedCheck -->|"no · never paid"| S6
TransactedCheck -->|"yes · returning verified"| PickMethod
S6 --> Pay S6 --> Pay
%% Anonymous path %% Anonymous path
ESPb --> USPb["S5b · USP screen 🔴"] USPGateB -->|"no · first-timer"| USPb["S5b · USP screen 🟢"]
USPb --> PickMethod["Pilih cara curhat<br/>(chat / voice call) 🔴"] USPGateB -->|"yes · skip"| PickMethod
PickMethod --> PickDuration["Pemilihan harga<br/>(5 durations, full screen) 🟡"] USPb --> PickMethod["Pilih cara curhat<br/>(chat / voice call) 🟢"]
PickDuration --> PayMethod["Cara bayar (QRIS-first) 🔴"] PickMethod --> PickDuration["Pemilihan harga<br/>(5 durations, full screen) 🟢"]
PickDuration --> PayMethod["Cara bayar (QRIS-first) 🟢"]
PayMethod --> Pay PayMethod --> Pay
%% Shared payment exit %% Shared payment exit
Pay["Xendit checkout<br/>(QRIS / e-wallet) 🔴"] --> WaitPay["Waiting Payment<br/>(20-min QRIS clock) 🔴"] Pay["Xendit checkout<br/>(QRIS / e-wallet) 🟡"] --> WaitPay["Waiting Payment<br/>(20-min QRIS clock) 🟢"]
WaitPay --> PayStat{"payment status"} WaitPay --> PayStat{"payment status"}
PayStat -->|"timeout 20 min"| PayExpired["Pembayaran expired 🔴<br/>→ retry"] PayStat -->|"timeout 20 min"| PayExpired["Pembayaran expired 🟢<br/>→ retry"]
PayExpired --> Pay PayExpired --> Pay
PayStat -->|"paid"| NotifGate PayStat -->|"paid"| NotifGate
classDef missing fill:#ffe5e5,stroke:#c44979 classDef missing fill:#ffe5e5,stroke:#c44979
classDef partial fill:#fff4d6,stroke:#c69b3f classDef partial fill:#fff4d6,stroke:#c69b3f
class VerifChoice,USPa,USPb,PickMethod,PayMethod,Pay,WaitPay,PayExpired,OTPBlock missing class UserLookup,LoadCallSign,TransactedCheck,USPGateA,USPGateB missing
class ESPa,ESPb,S3a,S3b,S6,PickDuration partial class S3b,Pay partial
``` ```
> **ESP screening removed (2026-05-12):** the S5 ESP multi-select chip
> screen is retired from the spec. Both verified and anonymous branches
> now go from `VerifChoiceSheet` straight to the `usp_seen?` gate. Any
> ESP code still in `client_app` is now tech debt to retire — see
> `TECH_DEBT.md`.
>
> **S5b USP is one-time-only (2026-05-12):** the USP screen now shows at
> most once per user. Gating is driven by a `usp_seen` flag that lives in
> two places:
> - **Local (SharedPreferences):** the runtime gate. Set to `true` when the
> user dismisses the USP screen for the first time. Survives across
> sessions on the same device.
> - **DB (`customers.usp_seen` column 🔴):** the cross-device source of truth.
> Written when the user account is created (post-OTP, after JWT issuance
> and `users` row insert) if local flag is already true, OR on any
> subsequent USP dismissal once an account exists. Read on login/relogin
> and hydrated back into local. "True wins" — if either side says seen,
> the gate is closed.
>
> Anonymous users with no account only have the local flag; if they later
> upgrade to verified, account creation propagates the local flag to DB.
> Returning verified users on a fresh device will see USP at most once on
> that device (DB hydrate happens on login, after USP gate fires pre-OTP).
> Business has accepted this edge case.
>
> **Anchor mismatch:** flow_customer.md numbers ESP/USP under > **Anchor mismatch:** flow_customer.md numbers ESP/USP under
> `5.1.2 Verification request (OTP)` for both branches, but Figma puts > `5.1.2 Verification request (OTP)` for both branches, but Figma puts
> `VerifChoiceSheet` *before* ESP. The mermaid above follows Figma; reconcile in > `VerifChoiceSheet` *before* ESP. The mermaid above follows Figma; reconcile in
> phase4 spec. > phase4 spec.
>
> **Post-OTP account lookup (added 2026-05-11):** the verified path is not
> always "new user". After a successful OTP, the backend looks up the phone
> number; if a row exists, the app overwrites the freshly-typed call_sign with
> the stored one. Then `has_transacted` decides routing:
> - `false` → S6 Paywall (Rp2.000 first-session) — user has an account but
> never converted.
> - `true` → jump straight into `PickMethod` (the regular chat/voice +
> duration + payment flow). USPb is already skipped because USPGateA
> already evaluated pre-OTP on the verified branch.
>
> `has_transacted` is the persistent flag on the users table that flips the
> first-time pricing off forever. Backend phone-lookup behaviour already
> exists (see Phase 1 auto-link via phone); the app-side reconciliation +
> `has_transacted` plumbing is the new work.
--- ---
@@ -92,13 +137,13 @@ flowchart TD
```mermaid ```mermaid
flowchart TD flowchart TD
NotifGate["Notif Gate Screen 🔴<br/>(Aktifkan / Nanti Saja)"] --> NotifBranch{"OS allowed?"} NotifGate["Notif Gate Screen 🟢<br/>(Aktifkan / Nanti Saja)"] --> NotifBranch{"OS allowed?"}
NotifBranch -->|"no + ask"| EnableNotif["OS settings deeplink"] --> SoftPrompt NotifBranch -->|"no + ask"| EnableNotif["OS settings deeplink"] --> SoftPrompt
NotifBranch -->|"yes / skipped"| SoftPrompt NotifBranch -->|"yes / skipped"| SoftPrompt
SoftPrompt["S7 · Soft-prompt<br/>(consent + warmup, CTA 'Aku ngerti, Lanjut') 🟡"] --> Blast SoftPrompt["S7 · Soft-prompt<br/>(consent + warmup, CTA 'Aku ngerti, Lanjut') 🟡"] --> Blast
Blast["Blast pair request<br/>S7 · Searching state 🟡"] --> BlastTimer{"5-min timer"} Blast["Blast pair request<br/>S7 · Searching state 🟢"] --> BlastTimer{"5-min timer"}
BlastTimer -->|"matched"| S9["S9 · Match Found<br/>(bestie name, age, hobi) 🟡"] BlastTimer -->|"matched"| S9["S9 · Match Found<br/>(bestie name, age, hobi) 🟡"]
BlastTimer -->|"timeout"| S7Timeout["S7 · Timeout 5 menit 🔴<br/>CTA 'Coba Cari Lagi'<br/>ghost CTA 'Coba cari lagi nanti' → Home"] BlastTimer -->|"timeout"| S7Timeout["S7 · Timeout 5 menit 🟢<br/>CTA 'Coba Cari Lagi'<br/>ghost CTA 'Coba cari lagi nanti' → Home"]
S7Timeout -->|"retry"| Blast S7Timeout -->|"retry"| Blast
S7Timeout -->|"home"| HomeRet S7Timeout -->|"home"| HomeRet
S9 --> S10 S9 --> S10
@@ -107,8 +152,7 @@ flowchart TD
classDef missing fill:#ffe5e5,stroke:#c44979 classDef missing fill:#ffe5e5,stroke:#c44979
classDef partial fill:#fff4d6,stroke:#c69b3f classDef partial fill:#fff4d6,stroke:#c69b3f
class NotifGate,S7Timeout missing class SoftPrompt,S9 partial
class SoftPrompt,Blast,S9 partial
``` ```
--- ---
@@ -117,7 +161,7 @@ flowchart TD
```mermaid ```mermaid
flowchart TD flowchart TD
CTA["'curhat sama bestie baru' 🟢"] --> Choice["Bestie Choice Sheet<br/>(BestieChoiceSheet) 🔴"] CTA["'curhat sama bestie baru' 🟢"] --> Choice["Bestie Choice Sheet<br/>(BestieChoiceSheet) 🟢"]
Choice -->|"bestie yang udah kenal"| HistList["Bestie History List<br/>(BestieHistoryList) 🟢"] Choice -->|"bestie yang udah kenal"| HistList["Bestie History List<br/>(BestieHistoryList) 🟢"]
Choice -->|"bestie baru"| BlastFlow["→ S7 Soft-prompt + Blast<br/>(see diagram 3)"] Choice -->|"bestie baru"| BlastFlow["→ S7 Soft-prompt + Blast<br/>(see diagram 3)"]
@@ -125,16 +169,14 @@ flowchart TD
PickBestie --> CheckOnline{"bestie online?"} PickBestie --> CheckOnline{"bestie online?"}
CheckOnline -->|"no"| OfflinePopup["Bestie Offline Popup<br/>(returning variant) 🟢"] CheckOnline -->|"no"| OfflinePopup["Bestie Offline Popup<br/>(returning variant) 🟢"]
OfflinePopup -->|"cari bestie lain"| BlastFlow OfflinePopup -->|"cari bestie lain"| BlastFlow
OfflinePopup -->|"tanya admin"| AdminSheet["Sheet · tanya admin<br/>(WA / Telegram) 🔴"] OfflinePopup -->|"tanya admin"| AdminSheet["Sheet · tanya admin<br/>(WA / Telegram) 🟢"]
CheckOnline -->|"yes"| Targeted["Request targeted pair<br/>'Menunggu bestie tertentu' 🟡<br/>(20s countdown overlay)"] CheckOnline -->|"yes"| Targeted["Request targeted pair<br/>'Menunggu bestie tertentu' 🟢<br/>(20s countdown overlay)"]
Targeted --> TargetedRes{"mitra answers?"} Targeted --> TargetedRes{"mitra answers?"}
TargetedRes -->|"accept"| S10["→ S10 Chat Room"] TargetedRes -->|"accept"| S10["→ S10 Chat Room"]
TargetedRes -->|"reject / timeout"| OfflinePopup TargetedRes -->|"reject / timeout"| OfflinePopup
classDef missing fill:#ffe5e5,stroke:#c44979 classDef missing fill:#ffe5e5,stroke:#c44979
classDef partial fill:#fff4d6,stroke:#c69b3f classDef partial fill:#fff4d6,stroke:#c69b3f
class Choice,AdminSheet missing
class Targeted partial
``` ```
--- ---
@@ -143,21 +185,21 @@ flowchart TD
```mermaid ```mermaid
flowchart TD flowchart TD
Enter["enter S10 · Chat Room<br/>(WebSocket open, timer running) 🟡"] --> T3{"3-minutes-left tick"} Enter["enter S10 · Chat Room<br/>(WebSocket open, timer running) 🟢"] --> T3{"3-minutes-left tick"}
T3 -->|"fired"| Snackbar["S10 · Snackbar reminder<br/>'sisa 3 menit lagi ya' 🔴"] T3 -->|"fired"| Snackbar["S10 · Snackbar reminder<br/>'sisa 3 menit lagi ya' 🟢"]
Snackbar --> T2 Snackbar --> T2
T3 -->|"not yet"| T2{"2-minutes-left tick"} T3 -->|"not yet"| T2{"2-minutes-left tick"}
T2 -->|"fired"| LowTime["S10 · Last 2 Minutes<br/>(timer turns danger color) 🔴"] T2 -->|"fired"| LowTime["S10 · Last 2 Minutes<br/>(timer turns danger color) 🟢"]
LowTime --> Expire LowTime --> Expire
T2 -->|"not yet"| Expire{"timer hits 0"} T2 -->|"not yet"| Expire{"timer hits 0"}
Expire -->|"fired"| ExpiredBanner["S10 · Floating Expired Banner<br/>'habis nih... mau lanjutin?' 🔴"] Expire -->|"fired"| ExpiredBanner["S10 · Floating Expired Banner<br/>'habis nih... mau lanjutin?' 🟢"]
ExpiredBanner --> CTAExt{"perpanjang CTA?"} ExpiredBanner --> CTAExt{"perpanjang CTA?"}
CTAExt -->|"yes"| TimeUp CTAExt -->|"yes"| TimeUp
CTAExt -->|"close / ignore"| EndFlow["→ end-session flow"] CTAExt -->|"close / ignore"| EndFlow["→ end-session flow"]
Expire -->|"not yet · user taps perpanjang"| TimeUp Expire -->|"not yet · user taps perpanjang"| TimeUp
TimeUp["Time-up Bottom Sheet<br/>(5 durations · chat/call toggle) 🟡"] TimeUp["Time-up Bottom Sheet<br/>(5 durations · chat/call toggle) 🟢"]
TimeUp -->|"perpanjang"| AskMitra["Targeted re-pay request<br/>(same mitra, no blast) 🔴"] TimeUp -->|"perpanjang"| AskMitra["Targeted re-pay request<br/>(same mitra, no blast) 🟢"]
TimeUp -->|"cukup, akhiri sesi"| EndFlow TimeUp -->|"cukup, akhiri sesi"| EndFlow
AskMitra --> MitraRes{"mitra approves?"} AskMitra --> MitraRes{"mitra approves?"}
@@ -166,8 +208,6 @@ flowchart TD
classDef missing fill:#ffe5e5,stroke:#c44979 classDef missing fill:#ffe5e5,stroke:#c44979
classDef partial fill:#fff4d6,stroke:#c69b3f classDef partial fill:#fff4d6,stroke:#c69b3f
class Snackbar,LowTime,ExpiredBanner,AskMitra missing
class Enter,TimeUp partial
``` ```
--- ---
@@ -176,11 +216,11 @@ flowchart TD
```mermaid ```mermaid
flowchart TD flowchart TD
EndStart["End-session entry<br/>(from S10 or Time-up sheet 'Cukup, Akhiri')"] --> Confirm1["Popup · Konfirmasi Akhiri (1)<br/>'beneran udah cukup?' 🟡"] EndStart["End-session entry<br/>(from S10 or Time-up sheet 'Cukup, Akhiri')"] --> Confirm1["Popup · Konfirmasi Akhiri (1)<br/>'beneran udah cukup?' 🟢"]
Confirm1 -->|"Gak Jadi, Balik"| TimeUp["Time-up Bottom Sheet 🟡"] Confirm1 -->|"Gak Jadi, Balik"| TimeUp["Time-up Bottom Sheet 🟢"]
Confirm1 -->|"Lanjut Akhiri"| Confirm2["Popup · Konfirmasi Akhiri (2)<br/>'mau tinggalin pesan penutup?' 🔴"] Confirm1 -->|"Lanjut Akhiri"| Confirm2["Popup · Konfirmasi Akhiri (2)<br/>'mau tinggalin pesan penutup?' 🟢"]
Confirm2 -->|"Tulis Pesan Penutup"| ClosingSheet["Pesan Penutup Bottom Sheet<br/>(textarea) 🟡"] Confirm2 -->|"Tulis Pesan Penutup"| ClosingSheet["Pesan Penutup Bottom Sheet<br/>(textarea) 🟢"]
Confirm2 -->|"Lewati Saja"| ThankYou Confirm2 -->|"Lewati Saja"| ThankYou
ClosingSheet -->|"Kirim & Akhiri"| MitraReceipt{"mitra rejects close?"} ClosingSheet -->|"Kirim & Akhiri"| MitraReceipt{"mitra rejects close?"}
@@ -188,16 +228,54 @@ flowchart TD
MitraReceipt -->|"no"| ThankYou MitraReceipt -->|"no"| ThankYou
MitraReceipt -->|"yes (rare)"| OfflinePopup["Bestie Offline Popup 🟢"] MitraReceipt -->|"yes (rare)"| OfflinePopup["Bestie Offline Popup 🟢"]
ThankYou["S11 · Terima Kasih Udah Cerita 🔴"] --> Home["→ Home (returning) 🟢"] ThankYou["S11 · Terima Kasih Udah Cerita 🟢"] --> Home["→ Home (returning) 🟢"]
classDef missing fill:#ffe5e5,stroke:#c44979 classDef missing fill:#ffe5e5,stroke:#c44979
classDef partial fill:#fff4d6,stroke:#c69b3f classDef partial fill:#fff4d6,stroke:#c69b3f
class Confirm2,ThankYou missing
class Confirm1,ClosingSheet,TimeUp partial
``` ```
--- ---
## 7. Chat Tab (3 sub-tabs) — Phase 4 Stage 10
```mermaid
flowchart TD
HomeTabBar["HaloTabBar · tap '💬 chat'"] --> ChatRedirect["/chat redirect 🟡"]
ChatRedirect --> Aktif["/chat/aktif · sub-tab 🟡"]
Aktif -->|"tap pill 'pembayaran'"| Pembayaran["/chat/pembayaran · sub-tab 🟡"]
Aktif -->|"tap pill 'selesai'"| Selesai["/chat/selesai · sub-tab 🟡"]
Pembayaran -->|"tap pill 'aktif'"| Aktif
Pembayaran -->|"tap pill 'selesai'"| Selesai
Selesai -->|"tap pill 'aktif'"| Aktif
Selesai -->|"tap pill 'pembayaran'"| Pembayaran
Aktif -->|"empty"| AktifEmpty["empty state · 'belum ada chat di sini' 🟡"]
Pembayaran -->|"empty"| PembayaranEmpty["empty state · 'belum ada pembayaran tertunda' 🟡"]
Selesai -->|"empty"| SelesaiEmpty["empty state · 'belum ada riwayat curhat' 🟡"]
Aktif -->|"tap active session row"| ChatRoom["S10 · Chat Room 🟢"]
Pembayaran -->|"tap pending payment row"| WaitingPayment["S7 · Waiting Payment 🟢"]
Selesai -->|"tap past session row"| Transcript["Read-only transcript /chat/transcript/:id 🟢"]
classDef missing fill:#ffe5e5,stroke:#c44979
classDef partial fill:#fff4d6,stroke:#c69b3f
class ChatRedirect,Aktif,Pembayaran,Selesai,AktifEmpty,PembayaranEmpty,SelesaiEmpty partial
```
**Data sources**
- Aktif → existing `GET /api/client/chat/session/active-with-unread` (0 or 1 row)
- Pembayaran → new `GET /api/client/payment-sessions/pending` (filters `status='pending' AND expires_at > NOW()`)
- Selesai → existing `GET /api/client/history`, migrated to cursor pagination (`{ items, next_cursor, has_more }`)
**Badges**
- Bottom-nav `chat` tab → red dot when Pembayaran `total > 0`
- `aktif` sub-tab pill → numeric badge from `unread_count`
- `pembayaran` sub-tab pill → numeric badge from `total`
- `selesai` sub-tab pill → no badge
---
## Cross-reference: Figma → flow_customer.md ## Cross-reference: Figma → flow_customer.md
| Figma artifact (file) | Source | flow_customer.md ref | | Figma artifact (file) | Source | flow_customer.md ref |
@@ -207,8 +285,8 @@ flowchart TD
| Notif banner on home | `screens/v3.jsx::HBNotifBanner` | §4.1 | | Notif banner on home | `screens/v3.jsx::HBNotifBanner` | §4.1 |
| S2 Nama | `screens/onboarding.jsx::S2Name` (and v4 variant) | §5.1.1 | | S2 Nama | `screens/onboarding.jsx::S2Name` (and v4 variant) | §5.1.1 |
| `VerifChoiceSheet` | `screens/v4.jsx::VerifChoiceSheet` | implied between §5.1.1 ↔ §5.1.2 | | `VerifChoiceSheet` | `screens/v4.jsx::VerifChoiceSheet` | implied between §5.1.1 ↔ §5.1.2 |
| S5 ESP screening | `screens/onboarding.jsx::S5ESP` | §5.1.2.1.1 / §5.1.2.2.1 | | ~~S5 ESP screening~~ | ~~`screens/onboarding.jsx::S5ESP`~~ | **retired 2026-05-12** — code is tech debt |
| S5b USP | `screens/onboarding.jsx::S5USP` | §5.1.2.1.2 / §5.1.2.2.2 | | S5b USP (one-time) | `screens/onboarding.jsx::S5USP` | §5.1.2.1.2 / §5.1.2.2.2 — gated by `usp_seen` |
| S3a WA / S3b OTP | `screens/onboarding.jsx::S3Phone` (+ `screens/v4.jsx::S3OTPV4`) | §5.1.2.1.3-4 | | S3a WA / S3b OTP | `screens/onboarding.jsx::S3Phone` (+ `screens/v4.jsx::S3OTPV4`) | §5.1.2.1.3-4 |
| `OTPBlockedPopup` | `screens/v4.jsx::OTPBlockedPopup` | (gap — not in flow doc) | | `OTPBlockedPopup` | `screens/v4.jsx::OTPBlockedPopup` | (gap — not in flow doc) |
| S6 Paywall Rp2k | `screens/onboarding.jsx::S6Paywall` | §5.1.2.1.5 | | S6 Paywall Rp2k | `screens/onboarding.jsx::S6Paywall` | §5.1.2.1.5 |
@@ -234,6 +312,7 @@ flowchart TD
| Confirm akhiri (2 popups) | `screens/v3.jsx::HBConfirmEndPopup` (step 1 + 2) | §5.8.2.1 / §5.8.2.1.1 | | Confirm akhiri (2 popups) | `screens/v3.jsx::HBConfirmEndPopup` (step 1 + 2) | §5.8.2.1 / §5.8.2.1.1 |
| Closing Message Sheet | `screens/extras.jsx::SClosingSheet` | §5.8.2.1.1.1 | | Closing Message Sheet | `screens/extras.jsx::SClosingSheet` | §5.8.2.1.1.1 |
| S11 Thank-you | `screens/session.jsx::S11Post` | §5.8.2.1.1.1.1 | | S11 Thank-you | `screens/session.jsx::S11Post` | §5.8.2.1.1.1.1 |
| Chat Tab (3 sub-tabs) | `screens/extras.jsx::SChatList` | §7 |
Anything Figma describes that flow_customer.md doesn't mention is captured as a Anything Figma describes that flow_customer.md doesn't mention is captured as a
gap in `phase4-customer-flow.md` (next-phase doc). gap in `phase4-customer-flow.md` (next-phase doc).

View File

@@ -4,8 +4,8 @@
> on master (commits `4ada7c9` through `862fc35`, plus the pre-Phase-4 > on master (commits `4ada7c9` through `862fc35`, plus the pre-Phase-4
> `4680c36` OTP test infrastructure). `flutter analyze` clean across > `4680c36` OTP test infrastructure). `flutter analyze` clean across
> both apps; backend Vitest 15/15. **Stage 9 (test sweep) is > both apps; backend Vitest 15/15. **Stage 9 (test sweep) is
> operator-driven and pending** — see `project_resume_next.md` in > operator-driven and in progress** — see "Post-Stage-8 corrections"
> agent memory for the run-list and known TODOs. > below for fixes applied during the visual sweep.
> See [phase4-customer-flow.md](phase4-customer-flow.md) for the PRD, > See [phase4-customer-flow.md](phase4-customer-flow.md) for the PRD,
> [flow_customer.md](flow_customer.md) for the source-of-truth flow, > [flow_customer.md](flow_customer.md) for the source-of-truth flow,
@@ -791,6 +791,74 @@ Tapping launches `url_launcher` with the deeplink. No webview.
--- ---
# Post-Stage-8 corrections (2026-05-10, uncommitted)
The first visual sweep of the live app caught that the boot path was still
on Phase 1 plumbing — Splash → `/welcome` (Phase 1 social/phone picker) →
forms — instead of the mermaid §1 contract: **Splash → Home (1st time / returning)**.
The new home variants (`SHome1st`, `SHomeReturning`) had not been built;
`home_screen.dart` was the Phase 1 placeholder with a Material AppBar +
"Mulai Curhat" button.
Fixes applied in the working tree (not yet committed):
## C.1 `/welcome` retired
- Route + `WelcomeScreen` import + `welcome_screen.dart` file all removed.
- Router redirects (formerly pointing at `/welcome` for `AuthInitialData`,
`AsyncError`, and post-onboarding-carousel cases) now point at `/home`.
- The router carve-out comment that referenced `/welcome` as the bottom of
the navigation stack updated to reference `/home`.
- **Stage 2.6 of this plan is stale**: it described editing
`welcome_screen.dart` to read `authProvidersProvider`; that screen no
longer exists. The `authProvidersProvider` itself is preserved and is
now consumed only at the phone-OTP / future login-recovery surfaces.
## C.2 `home_screen.dart` rewritten to Figma §1 spec
- Renders `SHome1st` (`screens/v3.jsx::SHome1st`) for unauthenticated users
(any state that isn't `AuthAuthenticatedData` / `AuthAnonymousData`).
- Renders `SHomeReturning` (`SHomeReturning`) for authenticated /
anonymous users.
- Components: login-recover banner, "halo," / "halo, {name}" greeting
(brand-colored name on returning), `aku mau curhat` / `curhat sama
bestie baru` primary CTA, "curhatan sebelumnya" history section (live
data via `bestieHistoryProvider`), bottom 4-tab `HBTabBar` footer
(home / chat / kamu / premium SOON — only home + chat wired).
- `_NotifDeniedBanner` (Stage 4) preserved at the top.
- `_ActiveSessionCard` preserved on SHomeReturning so a user mid-session
can rejoin (not in Figma §1 but a hard UX requirement).
- Material `AppBar` removed — the Figma layout has none. Logout will land
on the `kamu` tab when that's built.
## C.3 Onboarding carousel destination fixed
- `OnboardingScreen._finish()` now navigates to `/home` instead of
`/welcome`. The 3-page intro carousel (`Langsung Curhat / 100% Anonim /
Bestie yang Relevan`) itself is kept for now — it is **not in the
mermaid §1**, but the operator chose minimum-touch correction. Full
retirement (delete `OnboardingScreen` + `onboardingDoneProvider` + the
`/onboarding` route + the gate at the top of `router.dart`) is a
follow-up.
## C.4 Defensive variant gate
- `HomeScreen` now treats anything that is *not* `AuthAuthenticatedData`
or `AuthAnonymousData` as "fresh" → renders `SHome1st`. This avoids the
unauthenticated-but-erroring user seeing `halo, kamu` (the returning
view) for a brief moment.
## C.5 Open gap — Login flow not in mermaid
`SHome1st`'s `masuk →` banner button currently routes to `/auth/register`
(phone-OTP entry). This is an interpretation, not a spec: the mermaid (and
Figma `SHome1st`'s `onLogin` callback) doesn't define the login destination.
**The mermaid needs a Login flow diagram** added — destinations from the
`masuk →` banner, OTP success → `AuthAuthenticatedData` → SHomeReturning.
Tracked in agent memory as `project_phase4_login_flow_gap.md`.
---
# Stage 9 — Test Sweep # Stage 9 — Test Sweep
## 9.1 Maestro flows ## 9.1 Maestro flows
@@ -819,6 +887,268 @@ endpoints).
--- ---
# Stage 10 — Chat Tab (3 sub-tabs)
> Added 2026-05-12 after design review. Figma source: `SChatList` in
> [requirement/Figma/screens/extras.jsx](Figma/screens/extras.jsx) (line 22+).
> Not yet in `flow_customer.mermaid.md` — §10.8 adds it.
## 10.1 Scope & goal
Replace the existing `/chat/history` destination (a flat list of closed sessions
backed by `bestie_history_provider`) with a new **Chat tab** screen that
contains three sub-tabs:
| Sub-tab | Contents | Tap behavior |
|---|---|---|
| `aktif` | The user's single ongoing session (0 or 1 item) | Resume the live chat room |
| `pembayaran` | Pending initial-session + extension payments | Resume the Xendit payment flow |
| `selesai` | Past sessions (status `COMPLETED` + `CLOSING`) — cursor-paginated 20/page | Open read-only transcript |
The chat icon in `HaloTabBar` already exists and points to `/chat/history`
only its **destination** changes. Bottom-nav structure is unchanged.
`bestie_history` (screen + provider) is **retired** in this stage.
## 10.2 Figma source
- `SChatList` — list layout, sub-tab pill counters, per-item visuals
- `S_pembayaran_kedaluwarsa` (same file, ~line 600) — expired-payment full
screen. **Copy says 20 menit**, see §10.6.
- Item visuals: `HBOrb` (avatar) + optional green `success`-color live dot;
name (`who`) bold; preview text muted; right-aligned timestamp
(`● live` when active); below-preview chips:
- `bayar Rp X.XXX` chip (amber) on `pembayaran` items
- `X menit` duration suffix on `selesai` items
## 10.3 Routes & navigation (client_app)
Each sub-tab gets its **own path** so deep links, back stack, and Maestro
tests all agree on the active tab (URL is the source of truth):
| Path | Sub-tab |
|---|---|
| `/chat` | Redirect → `/chat/aktif` |
| `/chat/aktif` | Aktif (default landing) |
| `/chat/pembayaran` | Pembayaran |
| `/chat/selesai` | Selesai |
Implementation: a single `ShellRoute` (or a shared scaffold widget passed
the active tab id) so the three paths render the same chrome (heading,
sub-tab pills, bottom `HaloTabBar`) with only the list body swapping.
Tapping a sub-tab pill calls `context.go('/chat/<id>')`.
Renames + cleanup:
- `HaloTabBar` `chat` tab `onTap`: `/chat/history``/chat` (which then
redirects to `/chat/aktif`).
- Old `/chat/history` route + `bestie_history_screen.dart` +
`bestie_history_provider.dart` deleted.
- `/chat/history/:sessionId` (read-only transcript) renamed to
**`/chat/transcript/:sessionId`** so no route lives under the retired
`/chat/history` parent. All inbound `context.push('/chat/history/...')`
updated.
Bottom-nav red-dot tap behavior: the chat tab still calls
`context.go('/chat')` (no special-case for the red dot). The user lands on
the default `aktif` tab. FCM payment-pending pushes (if/when wired) target
`/chat/pembayaran` directly.
## 10.4 Sub-tab content & item model
### aktif
- Backed by existing `/api/client/chat/session/active-with-unread` (already
wired via `activeSessionProvider`). No new endpoint.
- Always renders the active session even when the user is currently inside
the chat room (per decision §10.6 below).
- Voice-call sessions (`mode='call'`) render with a small **📞 Call** pill in
the same row (consistent with Stage 6.0 header-badge convention).
- Empty state copy: `belum ada chat di sini`.
### pembayaran
- Backed by **new** `GET /api/client/payment-sessions/pending` (§10.7).
- Two row kinds (preview copy differentiates):
- Initial-session: `menunggu pembayaran sesi`
- Extension: `menunggu pembayaran perpanjangan`
- Amber `bayar Rp X.XXX` chip per Figma.
- Empty state: `belum ada pembayaran tertunda`.
### selesai
- Backed by existing `GET /api/client/history` — switch from offset (`page`)
to cursor pagination (§10.7) and rename param.
- Per-item: `mins` (duration), preview = closing message (mitra's if present,
else customer's), relative timestamp.
- Empty state: `belum ada riwayat curhat`.
## 10.5 Badges
| Surface | Trigger | Visual |
|---|---|---|
| Bottom-nav `chat` tab | `pembayaran` count > 0 | Red dot (no number) |
| `aktif` sub-tab pill | Unread message count > 0 | Numeric badge (uses existing `unread_count` from `active-with-unread`) |
| `pembayaran` sub-tab pill | Pending payment count > 0 | Numeric badge (count from `/payments/pending`) |
| `selesai` sub-tab pill | — | **No badge** (overrides the Figma count pill) |
Bottom-nav red-dot data source: piggy-back on the same
`/api/client/payment-sessions/pending` call (its `total` field). Polled when the
`HaloTabBar` host screen mounts; refreshed by riverpod invalidation when a
payment is created or completed.
## 10.6 Decisions baked in
1. **Aktif always shows the live session.** Even when the user is on the chat
screen, the row stays in `aktif` — it represents state, not navigation.
2. **Voice-call sessions live in the same list with a Call pill.** Per memory
`project_phase4_chat_ux_improvements` and Stage 6.0.
3. **Pembayaran TTL reuses existing `payment_session_timeout_minutes`.**
Payment is still mocked (per memory `project_pricing_still_mocked_3_7`);
real Xendit is not wired yet. The `app_config.payment_session_timeout_minutes`
row (default `20`) already drives `expires_at` on `payment_sessions` rows
via `createPaymentSession`. The Figma "pembayaran kedaluwarsa" 20-min copy
already matches the default — no new app_config row needed for Stage 10.
When real Xendit lands, the same value is reused for the invoice TTL.
4. **Max 1 active session.** Aligns with existing pairing constraint; no
backend change.
## 10.7 Backend changes
### 10.7.1 New: `GET /api/client/payment-sessions/pending`
Returns pending initial-session + extension payment sessions for the
authenticated customer (not yet paid, not yet expired).
Query: `payment_sessions WHERE customer_id = $1 AND status = 'pending' AND
expires_at > NOW() ORDER BY created_at DESC`. `is_extension` drives the row
kind. For extension rows, the originating `chat_sessions` row is joined for
mitra info; for initial rows, mitra info is null until pairing happens.
```
GET /api/client/payment-sessions/pending
→ 200 {
success: true,
data: {
items: [
{
id: "pay_…", // payment_sessions.id
kind: "initial" | "extension",
mitra_id: "…" | null, // populated only for extension rows
mitra_display_name: "kak Dimas" | null,
amount: 2500,
duration_minutes: 30,
mode: "chat" | "call",
created_at: "…",
expires_at: "…" // already = created_at + payment_session_timeout_minutes
}
],
total: 1 // drives the bottom-nav red dot
}
}
```
Service: `getCustomerPendingPayments(customerId)` (new fn) in
`payment.service.js`. The existing `expireStalePaymentSessions` sweeper +
inline expiry check in `confirmPaymentSession` already covers the TTL flip;
the endpoint just filters `expires_at > NOW()` defensively in case the
sweeper hasn't run yet for a stale row.
### 10.7.2 Modify: `GET /api/client/history` → cursor pagination
- Add `cursor` (opaque, base64 of `ended_at + id`) and `limit` (default 20,
max 50) query params.
- Response shape changes from `{ items, total, page, limit }` to
`{ items, next_cursor, has_more }`.
- `total` removed; if a future UI needs it, expose a separate `/count`
endpoint.
- `bestie_history_provider` is deleted along with the screen — the new
`selesai_history_provider` uses cursor pagination on this endpoint.
### 10.7.3 Reuse: `GET /api/client/chat/session/active-with-unread`
No changes. The `aktif` tab calls this directly.
### 10.7.4 No new sweeper needed
The existing `expireStalePaymentSessions` already flips
`pending → expired` past `expires_at`. The Pembayaran query filters on
`expires_at > NOW()` to handle the gap between TTL expiry and the next
sweep tick, so no additional sweeper is needed for Stage 10.
## 10.8 Mermaid flow update (`flow_customer.mermaid.md`)
Add a `subgraph chat_tab` after the home subgraph:
```
chat_tab
chat_tab.entry — tap "💬 chat" in HaloTabBar
chat_tab.aktif — active session row → resume chat
chat_tab.pembayaran — pending payment row → resume Xendit
chat_tab.selesai — past session row → transcript
chat_tab.empty.{aktif,pembayaran,selesai} — empty states
```
Edges:
- `home_* → chat_tab.entry` (from any home variant)
- `chat_tab.aktif → S10_chat_room` (existing)
- `chat_tab.pembayaran → S7_waiting_payment` (Stage 3.5)
- `chat_tab.selesai → S_transcript` (existing read-only transcript)
(Wording above is a description — final mermaid syntax added during the
implementation commit.)
## 10.9 Flutter file changes (preview)
- New: `client_app/lib/features/chat_tab/screens/chat_tab_shell.dart` — the
shared scaffold (heading + sub-tab pills + body slot) rendered by all
three sub-tab paths via `ShellRoute`.
- New: `client_app/lib/features/chat_tab/screens/{aktif_view.dart,pembayaran_view.dart,selesai_view.dart}` — the body of each sub-tab.
- New: `client_app/lib/features/chat_tab/widgets/{chat_row.dart,sub_tab_pill.dart}`
- New: `client_app/lib/features/chat_tab/providers/{pending_payments_provider.dart,selesai_history_provider.dart}`
- Delete: `client_app/lib/features/home/providers/bestie_history_provider.dart`
- Delete: `client_app/lib/features/chat/screens/bestie_history_screen.dart`
(or wherever it lives — confirm during code stage)
- Modify: `client_app/lib/features/home/widgets/halo_tab_bar.dart` — change
`/chat/history``/chat`; add red-dot rendering driven by
`pendingPaymentsProvider.total`.
- Modify: `client_app/lib/router.dart`:
- Add `/chat` (redirect → `/chat/aktif`), `/chat/aktif`, `/chat/pembayaran`,
`/chat/selesai` (wrapped in a single `ShellRoute`).
- Rename `/chat/history/:sessionId``/chat/transcript/:sessionId`.
- Remove `/chat/history`.
- Modify: any caller that does `context.push('/chat/history/$id')` for the
transcript — grep and update to `/chat/transcript/$id`.
## 10.10 Out of scope (this stage)
- **Failed-payment retry from the list.** Pembayaran only shows
not-yet-paid + not-yet-expired. Failed/expired surface via the existing
S6/S7 "pembayaran kedaluwarsa" screen on direct payment-flow re-entry, not
the list.
- **Refund / dispute states.** No row kind for these.
- **Search / filter** in `selesai`.
- **Concurrent active sessions.** Aktif is 0-or-1 by backend constraint.
- **Voice-call as separate sub-tab.** Lives in the same list with a Call pill.
## 10.11 Acceptance for Stage 10
1. Tapping `💬 chat` navigates to `/chat`, which redirects to `/chat/aktif`.
Direct navigation to `/chat/pembayaran` or `/chat/selesai` lands on the
correct tab. Tapping a sub-tab pill updates the URL accordingly.
2. With an active session: row appears in `aktif`, tap → live chat room with
composer focused. Returning to `/chat` keeps the row visible.
3. With a pending initial-session payment: row appears in `pembayaran` with
`bayar Rp X.XXX` chip; tap → Stage 3.5 waiting-payment screen.
4. With a pending extension payment: row appears in `pembayaran` with the
extension preview copy; tap → extension payment screen.
5. After 20 minutes without payment: row disappears from `pembayaran`; the
"pembayaran kedaluwarsa" screen shows on re-entry (Stage 3.6 behavior
unchanged).
6. Bottom-nav `💬 chat` shows a red dot iff `pembayaran` total > 0.
7. `aktif` sub-tab pill shows unread count when > 0.
8. `pembayaran` sub-tab pill shows pending count when > 0.
9. `selesai` sub-tab pill shows no badge regardless.
10. `selesai` scrolls past 20 items via cursor pagination without duplicates
or gaps.
11. Voice-call sessions render with the 📞 Call pill in both `aktif` and
`selesai`.
12. `/chat/history` is gone from `router.dart`; `/chat/history/:sessionId` is
renamed to `/chat/transcript/:sessionId`; no dead inbound `context.push`
references remain.
13. Maestro: new flow `09_chat_tab.yaml` covering aktif → resume,
pembayaran → payment, selesai → transcript.
14. Backend tests cover `getCustomerPendingPayments` (initial only,
extension only, mixed, expired excluded) and the new cursor-paginated
`getCustomerHistory`.
---
# Resolved Decisions (2026-05-09 — recorded from product review) # Resolved Decisions (2026-05-09 — recorded from product review)
| # | Decision | | # | Decision |