feat: add local auth billing and usage management
This commit is contained in:
1 parent
f642b5e71f
commit
196fdde83f
119 files changed
+15695
-2650
No files matched your search
+320
@@ -1233,3 +1233,323 @@
|
||||
- Stopped the dev server and cleared `.next` before running the production build.
|
||||
- `npm run build`: production build passed.
|
||||
- `git diff --check`: passed.
|
||||
|
||||
## Session: 2026-08-11 - Platform-Owned Account System
|
||||
|
||||
### Phase 51: Requirements Confirmed and Implementation Started
|
||||
- **Status:** complete
|
||||
- User-confirmed scope:
|
||||
- Replace external OAuth2 account authentication with platform-owned phone/password accounts.
|
||||
- Use Supabase/Postgres in production and local JSON fallback in development.
|
||||
- Support `super_admin`, `organization_admin`, and `user` roles.
|
||||
- Enforce one account per organization; no cross-organization membership or switching.
|
||||
- Preserve legacy account/history through phone-based mapping; retain usage and archive assets/tasks on deletion.
|
||||
- Keep admin-created accounts, unified login, immutable phone identifiers, administrator password initialization/reset, and user self-service password changes.
|
||||
- Limit organization admins to their own ordinary-user management and aggregate usage; they cannot access logs/system settings or grant organization-admin roles.
|
||||
- Actions taken:
|
||||
- Read the current authentication, session, permission, account-management, data-store, and Supabase schema implementation.
|
||||
- Read and activated the file-based planning workflow for this multi-phase change.
|
||||
- Added this implementation phase and captured confirmed decisions/findings in the planning files.
|
||||
- Next:
|
||||
- For deployment, run the documented one-time super-admin bootstrap against the production Supabase database, then execute the operator-provided legacy account import file.
|
||||
|
||||
### Phase 51: Implementation and Verification Complete
|
||||
- **Status:** complete
|
||||
- Implemented:
|
||||
- Added platform organization/user/migration models to `lib/types.ts`, local JSON storage, and `supabase/schema.sql`.
|
||||
- Replaced browser OAuth/password-grant login with normalized phone + scrypt password verification, signed/chunked HttpOnly platform sessions, account lockout after five failures, and IP rate limiting.
|
||||
- Added role-aware access boundaries: super administrators control global logs/settings/organizations/accounts/usage; organization administrators are limited to ordinary users and their organization aggregate usage; ordinary users retain self-service creation and password changes.
|
||||
- Added organization lifecycle APIs/UI, administrator-created account APIs/UI, reset-password flow, self-service password change, disable/delete behavior, archive reassignment, and immutable unique phone login identifiers.
|
||||
- Preserved usage events during account deletion and added legacy import/bootstrap scripts with phone/legacy-owner mappings and history reassignment.
|
||||
- Kept `/api/v1/*` and worker authentication separate from browser platform sessions.
|
||||
- Verification:
|
||||
- `tsc --noEmit`: passed.
|
||||
- `vitest run`: passed, 22 test files / 80 tests.
|
||||
- Bootstrap/import script syntax checks: passed.
|
||||
- `next build`: passed.
|
||||
- `git diff --check`: passed.
|
||||
- HTTP smoke test on a temporary local account store: super-admin login and organization creation passed; organization-admin login passed; logs returned 403 for organization admin; ordinary-user self password change and relogin passed.
|
||||
- Project is running on `http://127.0.0.1:3000`; `/api/health` and `/auth/login` both returned 200 after the final restart.
|
||||
|
||||
## Session: 2026-08-11 - Enterprise Billing
|
||||
|
||||
### Phase 53: Official Provider Price Catalog
|
||||
- **Status:** complete
|
||||
- Added an auto-seeded, editable base catalog for Bailian Wan 2.7, EvoLink GPT Image 2, Jimeng Seedream 4.6 reference pricing, and Volcengine Ark Seedance 2.0 resolution tiers.
|
||||
- Standardized all ledger amounts in CNY fen. The final user charge is `ceil(base_fen × quantity × markup)`, with the default markup set to `1.5x`.
|
||||
- Fixed EvoLink conversion at `1 USD = 7.20 CNY`; the GPT Image 2 medium/1K/no-reference estimate becomes ¥0.34 per image.
|
||||
- Added `variantKey` resolution matching and source snapshots so later price edits do not change historical task charges.
|
||||
- Added official source links and pricing-basis notes to the super-admin table and deployment/API documentation.
|
||||
- Verification: `bun run test` passed with 23 files / 82 tests; `bun x tsc --noEmit`, `bun run build`, and `git diff --check` passed.
|
||||
|
||||
### Phase 54: Billing Center Taste Redesign
|
||||
- **Status:** complete
|
||||
- Read the current super-admin billing screenshot and identified the main issue as a long, repetitive vertical stack that mixed organization balance, pricing operations, account setup, and recharge review at the same visual weight.
|
||||
- Rebuilt `components/billing-manager.tsx` around a balance-first overview, a compact ledger, a dense but scannable price catalog, and role-specific action areas. Member recharge is separated from super-admin pricing and review actions; custom pricing creation is collapsed until needed.
|
||||
- Added a restrained B2B visual system in `app/globals.css`: one green accent, dark balance hero, quiet surfaces, compact list rows, explicit form labels, focus states, loading skeletons, responsive breakpoints, and reduced-motion handling.
|
||||
- Preserved existing API behavior and price-source links while improving hierarchy and mobile stacking. Browser smoke checks confirmed the super-admin page rendered at desktop and 390px viewport widths with no horizontal overflow.
|
||||
- Verification: desktop/mobile screenshots, `bun x tsc --noEmit`, `bun run test` (23 files / 82 tests), `bun run build`, and `git diff --check` all passed.
|
||||
|
||||
### Phase 55: Tabbed Billing Operations
|
||||
- **Status:** complete
|
||||
- Replaced the continuous super-admin/member billing stack with task tabs. Super admins now switch between 概览、价格与计费、余额管理、充值审核、收款设置; members switch between 概览、线下充值、账务流水.
|
||||
- Added `/api/admin/billing/account` so super admins can configure account name, bank, account number, and recharge contact directly in the billing center. It reuses the existing settings persistence path and updates the member-facing account immediately.
|
||||
- Added `/api/admin/billing/adjustments` for super-admin manual credit/debit entries. The organization wallet remains the only balance; an optional member selection only attributes the immutable ledger entry and does not create a personal wallet.
|
||||
- Extended `/api/admin/billing` with organization members and recent ledger data. The balance tab now shows per-member net consumption and a one-click member attribution action for the adjustment form.
|
||||
- Verification: browser tab and account-editor smoke checks, 390px mobile screenshot with no horizontal overflow, `/api/admin/billing` payload smoke, `bun run test` (23 files / 83 tests), `bun x tsc --noEmit`, `bun run build`, and `git diff --check` passed.
|
||||
|
||||
### Phase 56: Billing Error Recovery
|
||||
- **Status:** complete
|
||||
- Local `GET /billing`, `/api/billing`, `/api/admin/billing`, and `/api/settings` all returned 200 under the local fallback runtime; no new billing 500 was present in `.runtime/logs/server-events.jsonl`.
|
||||
- Added actionable detection for missing or outdated Supabase billing tables/columns, safe parsing for non-JSON proxy errors, and a billing route error boundary with migration guidance.
|
||||
- Verification: `bun x tsc --noEmit`, `bun run test` (23 files / 83 tests), `bun run build`, production API smoke (all 200), production browser tab smoke, and `git diff --check` passed.
|
||||
|
||||
### Phase 57: Super-Admin Billing Blank State
|
||||
- **Status:** complete
|
||||
- Reproduced the screenshot state: an unbound super-admin received 422 from the member-oriented `/api/billing`, while `/api/admin/billing` returned 200; the component then had no `billing` payload and hid every content section.
|
||||
- Changed super-admin loading to use the platform admin payload directly and synthesize an all-organization wallet/ledger summary. Member loading still uses the organization-scoped `/api/billing` route.
|
||||
- Verification: `bun x tsc --noEmit`, `bun run test` (23 files / 83 tests), `bun run build`, and production browser smoke confirmed the five super-admin tabs and overview render.
|
||||
|
||||
### Phase 58: Parameterized Billing Rules
|
||||
- **Status:** in_progress
|
||||
- User confirmed the structured rule-matrix approach: normalize user-selected parameters, match the most specific server-side rule, expose a quote preview, and reject real jobs without a matching rule.
|
||||
- Current code only derives `resolution` as a variant and derives quantity from `duration`/`n`; the new phase will cover quality, size, aspect ratio, reference-image count, and other provider request dimensions without trusting client-side prices.
|
||||
|
||||
### Phase 58: Parameterized Billing Rules
|
||||
- **Status:** complete
|
||||
- Extended price rules with structured JSON conditions, explicit quantity sources (`request`, `image_count`, `duration`), and priorities. Existing `variantKey` resolution rules remain compatible and are translated into conditions at match time.
|
||||
- Added server-side parameter normalization for model, resolution, size, aspect ratio, quality, duration, image count, reference-image count, scale, and audio flags. Matching now prefers exact `reqKey`, then the most-specific matching conditions, then priority; unresolved ties fail as an ambiguous configuration.
|
||||
- Added `/api/billing/quote` and shared image/video preparation helpers so the preview and real submission use the same provider payload and billing matcher. Billing snapshots now include normalized parameters, conditions, quantity source, quantity, and final amount in the job quote and ledger metadata.
|
||||
- Upgraded the super-admin price editor with condition fields for resolution, size, aspect ratio, quality, scale, reference-image count, duration, quantity source, and priority. The price table displays the configured scope; legacy rules remain editable.
|
||||
- Verification: `bunx vitest run` passed with 23 files / 86 tests; `bunx tsc --noEmit`, Node-backed `next build` (32 static pages), `git diff --check`, local `/api/health` HTTP smoke (200), and unauthenticated quote-route smoke (401 as expected) passed. Browser smoke reached the login gate without a render/500 error.
|
||||
|
||||
## Session: 2026-08-11 - Task Detail Modal and Result Directory Consolidation
|
||||
|
||||
### Phase 59: Discovery and Decision Gate
|
||||
- **Status:** complete
|
||||
- Inspected the current `/assets` result page, create-page task module, generation job shape, image/video submission payloads, asset download route, and local generated-result storage.
|
||||
- Confirmed that the visible result directory and the physical generated-result storage are separate concerns.
|
||||
- Confirmed that task records already retain the prompt, input material IDs/URLs, normalized generation settings, provider/task metadata, billing state, errors, and output asset IDs needed for an in-place detail modal.
|
||||
- User confirmed that the front-end result directory should be removed from the visible product flow, that the interaction should live in the task module, and that this is a desktop-only platform.
|
||||
|
||||
### Phase 59: Task Detail Modal and Result Directory Consolidation
|
||||
- **Status:** complete
|
||||
- Removed the `结果` navigation entry and changed `/assets` into a compatibility redirect to `/create`; the asset APIs, download route, local uploads, and `.runtime/generated-results` storage remain available.
|
||||
- Added task-card click and keyboard interaction with a desktop task detail modal covering task status, duration, prompt, input elements/material previews, normalized generation parameters, provider/request metadata, billing state, errors, and output previews.
|
||||
- Added direct result download actions to completed task cards and per-output download links inside the modal. Card-level download/detail actions stop propagation so they do not reopen the modal.
|
||||
- Updated product and deployment documentation to describe the task module as the single front-end location for task details and generated-result downloads.
|
||||
- Verification: desktop browser smoke on `/create` confirmed the trimmed navigation, 17 task cards, prompt/material/parameter rendering, and download action; `bun run test` passed (23 files / 86 tests); `bun x tsc --noEmit`, `bun run build`, and `git diff --check` passed.
|
||||
- Scope note: mobile layout work was intentionally excluded per the confirmed desktop-only product requirement.
|
||||
|
||||
### Phase 60: Direct Billing Top-ups — Started
|
||||
- Confirmed the new accounting rule: remove recharge review entirely; administrators post balance directly; future self-service payment success posts automatically.
|
||||
- Located the active request/review chain in the billing manager, `/api/billing`, `/api/admin/billing`, `/api/admin/billing/recharges/[id]`, billing store/service, schema, docs, and tests.
|
||||
- Confirmed the existing administrator adjustment endpoint can remain as the direct top-up implementation.
|
||||
- Removed member recharge form/history and the super-admin review tab/metric from the billing manager; the overview now points to balance operations instead of pending requests.
|
||||
- Removed recharge request listing/creation/review routes and active store/type mappings; direct credit adjustments now use `recharge` ledger entries through `postOrganizationTopUp`, while debits remain `adjustment` entries.
|
||||
- Updated README/API/deployment documentation to describe direct administrator posting and future automatic posting after payment success.
|
||||
|
||||
### Phase 60: Direct Billing Top-ups — Complete
|
||||
- Removed the recharge request table from the active Supabase schema definition without dropping any existing deployed table; old data, if present, is no longer part of the application workflow.
|
||||
- Renamed the super-admin operation to “余额与上账”, replaced the pending-review metric with organization cumulative charges, and kept corporate account settings as a future payment configuration surface.
|
||||
- Verification passed: no stale request/review references, `bunx tsc --noEmit`, `bunx vitest run` (23 files / 86 tests), Node-backed `next build`, `git diff --check`, `/api/health` 200, unauthenticated admin billing 401, and billing page auth redirect 307.
|
||||
- The local development server is running on `http://127.0.0.1:3000` after a clean restart.
|
||||
|
||||
### Phase 61: Simplified Billing Price Controls — Started
|
||||
- User clarified that provider standard prices and parameter tiers are platform-maintained; super administrators should only adjust the markup multiplier.
|
||||
- Current UI/API surface is broader than the intended responsibility, so this phase will collapse it to a read-only catalog with multiplier-only maintenance.
|
||||
|
||||
### Phase 61: Account Directory and Password Settings Consolidation — Started
|
||||
- Read the `design-taste-frontend` skill and applied its audit-first redesign protocol to this data-heavy product surface rather than its marketing-page-only patterns.
|
||||
- Audited the current account directory in the local desktop browser and found the password form only in `/settings`, admin-only `/accounts` access, and a cramped horizontal create-account row.
|
||||
- Confirmed implementation direction: `/accounts` becomes authenticated-user accessible, self password change moves there for every role, admin organization/member APIs remain protected, and the page is rebuilt around a modern light minimalist desktop hierarchy.
|
||||
|
||||
### Phase 61: Account Directory and Password Settings Consolidation — Complete
|
||||
- Removed `AccountSecurityPanel` from `/settings` and mounted it in `/accounts`; the existing `/api/auth/password/change` contract and session refresh behavior remain unchanged.
|
||||
- Made `/accounts` available to every authenticated user. Ordinary users see identity information and self-service password change; admin sessions additionally load the existing organization/member management APIs.
|
||||
- Rebuilt the account page as a desktop-first two-column utility surface: personal security and member directory on the main column, identity, account creation, and organization controls in the rail. Added explicit status badges, avatars, skeleton loading, focus states, empty/error feedback, and restrained green accent styling.
|
||||
- Updated navigation, middleware, README, Chinese README, and deployment notes to describe the new account access model.
|
||||
- Verification: desktop browser smoke showed the password form and loaded member directory, settings no longer contained the password form, `bun run test` passed (23 files / 86 tests), `bun x tsc --noEmit`, `bun run build`, and `git diff --check` passed.
|
||||
- Errors and resolutions: a hot-reload session held an obsolete client state and left the member skeleton visible; restarting the temporary dev server restored the expected list. The first production build emitted an autoprefixer warning for `align-items: end`; all new occurrences were changed to `flex-end`, and the final build completed without that warning.
|
||||
|
||||
### Phase 62: Account Workspace Information Architecture Correction — Complete
|
||||
- User feedback identified two concrete flaws in the first redesign: the current-user summary duplicated the “登录身份” card, and the account page was still fragmented into separate floating cards.
|
||||
- Removed the duplicate account/profile panel and kept one current-user identity summary in the page header.
|
||||
- Replaced the split main/rail composition with one continuous `account-workspace`, ordered as security settings, administrator organization/member management, and the member directory. Organization creation now sits beside account creation within the same administrator section.
|
||||
- Desktop browser verification at 1280px confirmed one identity surface, zero profile-card duplicates, a single 1180px workspace, and `bodyScrollWidth === clientWidth`.
|
||||
|
||||
### Phase 61: Simplified Billing Price Controls — Complete
|
||||
- Reduced price maintenance to the intended product model: platform-owned standard cost and parameter catalog, with super-admin control limited to the markup multiplier.
|
||||
- Replaced the multi-field rule editor with a compact read-only catalog showing service/parameters, standard cost, calculated customer price, multiplier, and a single `调整倍率` action.
|
||||
- Made the admin price collection route read-only and restricted item updates to `markupMultiplier`; structural pricing fields are rejected server-side.
|
||||
- Verification passed: `bunx tsc --noEmit`, `bunx vitest run` (23 files / 86 tests), Node-backed production build, `git diff --check`, browser legacy-form/overflow checks, and clean dev-server health (`/api/health` 200).
|
||||
|
||||
### Phase 63: Parameterized Billing Catalog — Started
|
||||
- User confirmed the recommended model: list parameter tiers under each service/model with platform-owned standard rates and multiplier controls; calculate the final quote from the selected parameter combination.
|
||||
- The current implementation only has one generic EvoLink image rule based on medium / 1K / 1:1 / no reference image, so high quality currently falls through to the same price. The next implementation step is to add dimension-aware catalog data and matching without exposing structural editing in the admin UI.
|
||||
|
||||
### Phase 63: Parameterized Billing Catalog — Complete
|
||||
- Added platform-owned parameter dimensions and tiers to billing rules. EvoLink GPT Image 2 now lists quality, resolution, aspect-ratio, and reference-image tiers; video resolution variants are grouped under their service/model.
|
||||
- Quote calculation now resolves every selected parameter, multiplies standard factors, applies one highest-selected markup multiplier, and snapshots the effective standard cost plus selected tiers into the task billing record.
|
||||
- Added a multiplier-only tier PATCH path and a backfill-safe catalog seed update that preserves existing multiplier values while synchronizing platform standard metadata and parameter dimensions.
|
||||
- Updated the billing center to show grouped service cards with child parameter rates, user prices, multipliers, source notes, and one `调整倍率` action per tier. No structural editor or custom rule form is exposed.
|
||||
- Verification: `bunx tsc --noEmit`, `bunx vitest run` (23 files / 88 tests), `bun run build`, browser checks at 1280px (5 service cards / 4 EvoLink dimensions / 15 tiers / no horizontal overflow / no legacy form), `git diff --check`, and clean dev-server health.
|
||||
|
||||
### Phase 64: Inline Generation Cost Estimate — Complete
|
||||
- Applied the ui-ux-pro-max form guidance: keep labels associated with controls, provide immediate state feedback, and put the result summary at the decision point.
|
||||
- Moved the generation quote from the top action bar into a compact `本次预估消耗` card beside the engine/parameter controls. The card shows the server-resolved amount, quantity, multiplier, and matched parameter tiers.
|
||||
- Added explicit unavailable/loading states and cleared stale loading state when the prompt or required materials are removed.
|
||||
- Added container-aware layout rules for the three-rail create workbench. At 1280px and 1440px the parameter controls and cost card align in one row; at narrower center columns they stack without horizontal overflow.
|
||||
- Browser verification observed EvoLink medium/2K/1:1 at ¥2.04, high/2K/1:1 at ¥8.16, and Seedance 5 seconds at ¥7.43 in the local configured environment.
|
||||
|
||||
### Phase 65: Billing UI Alignment and Native Multiplier Dialog — Complete
|
||||
- Reworked the price-source metadata row so the source link, platform note, and service-card content share a predictable baseline and available width.
|
||||
- Shortened the estimate card heading to `预估消耗` so the live amount, quantity, multiplier, and parameter summary remain aligned beside the controls.
|
||||
- Replaced browser prompt editing with a native in-app multiplier modal that previews standard cost/current price/new price and validates `1–1000×` input.
|
||||
- Verified parameter-driven quote refresh (`¥2.04` for the tested EvoLink Image2 configuration), Escape dismissal, `bunx vitest run` (23 files / 88 tests), `bunx tsc --noEmit`, `bun run build`, `git diff --check`, and `/api/health` HTTP 200 on the restarted port 3000 server.
|
||||
|
||||
### Phase 66: Fixed EvoLink 1K Quote and User-Facing Estimate — Complete
|
||||
- Fixed the EvoLink image payload to always request the platform-approved 1K resolution; removed the obsolete configurable resolution setting and synchronized the billing catalog default to 1K.
|
||||
- Removed internal pricing metadata from the ordinary-user estimate card. It now contains only `本次预计消耗额度` and the amount/loading placeholder.
|
||||
- Verified live values in the create page: standard quality `¥0.51`, high quality `¥2.04`; no `未开始`, automatic-calculation helper, platform multiplier, tier summary, or `2K` appeared in the user-facing page.
|
||||
- Verification passed: `bunx vitest run` (23 files / 88 tests), `bunx tsc --noEmit`, `git diff --check`, and browser quote checks.
|
||||
|
||||
### Phase 67: Unified Default Billing Multiplier — Complete
|
||||
- Changed `DEFAULT_BILLING_MARKUP_MULTIPLIER` to `1.2` and applied it across all built-in image/video rules and parameter tiers.
|
||||
- Synchronized `.runtime/data/billing-state.json` so the running local catalog no longer retains `1.5×` defaults.
|
||||
- Updated billing docs and built-in quote assertions; intentional test-specific multiplier overrides remain explicit.
|
||||
|
||||
## Session: 2026-08-12 - Seedance Native Usage Settlement
|
||||
|
||||
### Phase 68: Cross-Provider Pricing Audit — Complete
|
||||
- Reconciled Bailian image/video, EvoLink image, Jimeng reference, and Ark Seedance catalog entries against the supplied provider pricing sources.
|
||||
- Confirmed the shared 1.20× platform multiplier and identified Seedance as the only active provider whose official final price depends on returned usage rather than only the submitted parameter set.
|
||||
- Obtained confirmation to implement conservative submit-time reservation plus successful-task token reconciliation.
|
||||
|
||||
### Phase 69: Seedance Native Usage Settlement — Complete
|
||||
- Added official Seedance token rate mapping by resolution and input-video presence, with a formula-based conservative estimate for the initial reservation.
|
||||
- Added provider usage extraction for both top-level and nested Seedance response shapes.
|
||||
- Added idempotent final settlement: actual lower amount refunds the difference, actual higher amount charges the difference, and missing usage keeps the reserved amount.
|
||||
- Added the 4K catalog/resolution variant and updated product/API documentation.
|
||||
- Verification passed: `bunx vitest run` (24 files / 92 tests), `bunx tsc --noEmit`, `bun run build`, and `git diff --check`.
|
||||
|
||||
### Phase 70: Unbound Account Quote Preview — Complete
|
||||
- Traced the blank quote to the super-admin account having no organization binding; the quote request was incorrectly subject to the real-charge organization gate.
|
||||
- Added a quote-only bypass for organization lookup while preserving the strict organization requirement during actual task submission and wallet charging.
|
||||
- Added a regression test for the preview/charge boundary.
|
||||
- Browser verification now shows `¥1.64` for Image2 / 9:16 / 精细. Full verification passed: Vitest 24 files / 93 tests, TypeScript, production build, local health check, and `git diff --check`.
|
||||
|
||||
## Session: 2026-08-11 - Cross-Provider Pricing Audit
|
||||
|
||||
### Phase 68: Cross-Provider Pricing Audit — In progress
|
||||
- Audited `lib/server/billing-catalog.ts`, `lib/billing.ts`, `lib/server/billing-service.ts`, the provider payload builders, the runtime billing state, and current quote outputs.
|
||||
- Confirmed Bailian image/video baselines and the one-time 1.20× markup behavior against the current official Alibaba model pages.
|
||||
- Confirmed the Ark Seedance 2.0 sample values and identified the boundary: the official source is token-based and input-video dependent, while the current catalog is a no-input-video, 16:9, five-second reference estimate expressed per second.
|
||||
- Confirmed the active UI forces Jimeng single-image output; its ¥0.20/image entry remains a documented reference baseline because the official API page does not publish a stable per-call price.
|
||||
- No implementation changes made. Next step is to present the confirmed matches and the Seedance approximation decision to the user before changing the billing model.
|
||||
|
||||
### Phase 52: Discovery and Decision Gate
|
||||
- **Status:** complete
|
||||
- Read and restored the existing planning files before starting the new multi-step phase.
|
||||
- Inspected current types, generation services, data store, account roles, usage events/reports, routes, and package scripts.
|
||||
- Confirmed current usage is analytics-only: one event per non-mock first-party job, with no wallet or monetary ledger.
|
||||
- Confirmed organization identity and role boundaries are already available for billing integration.
|
||||
- Paused implementation at the required decision gate: billing unit/settlement semantics must be confirmed before changing financial state.
|
||||
|
||||
### Phase 52: Requirements Confirmed and Implementation Started
|
||||
- **Status:** in_progress
|
||||
- User confirmed the provider-native billing unit × super-admin markup model.
|
||||
- User added the requirement to remove 高清/智能超清 (`image.upscale`) and 局部重绘 (`image.inpaint`) capabilities.
|
||||
- Current removal targets and billing integration points are recorded in `findings.md`; implementation proceeds from the existing account-system worktree without resetting unrelated changes.
|
||||
|
||||
### Phase 52: Capability Removal and Billing Core
|
||||
- **Status:** complete
|
||||
- Removed `image.inpaint` and `image.upscale` from active capability types, provider matrices, generation UI, asset edit APIs, settings assignments, usage filters, public API validation/OpenAPI, tests, environment examples, and docs.
|
||||
- Kept historical `edited`/`upscaled` asset source values readable and labeled as historical results.
|
||||
- Added billing domain types, integer-fen pricing helpers, local billing store, Supabase billing schema/RPC, organization wallet operations, price rules, recharge requests, immutable ledger entries, and idempotent job charge/refund service.
|
||||
- Integrated pre-charge into image/video submission and final-state refunds into Worker failure handling, public API cancellation, and task deletion.
|
||||
- Added `/api/billing`, `/api/admin/billing`, price-rule CRUD, and recharge review endpoints.
|
||||
|
||||
### Phase 52: Billing Integration and Verification
|
||||
- **Status:** complete
|
||||
- Added organization-scoped integer-fen wallets, idempotent charge/refund ledger entries, provider-native quantity pricing, super-admin markup snapshots, recharge requests, review flow, and optional corporate-account display/configuration.
|
||||
- Real first-party image/video jobs quote and debit before provider dispatch; pending charges are recovered by the Worker after a process interruption; final failed/expired/cancelled jobs refund once, while successful deletion never refunds.
|
||||
- Added `/billing` for members to view organization balance, personal/org consumption, ledger, and offline recharge requests; super admins manage price rules, organization wallets, recharge review, and corporate transfer account details.
|
||||
- Removed active high-resolution/upscale and inpaint capabilities, routes, editor surface, settings assignments, public API definitions, and environment keys; the legacy `/image-edit` path now redirects to normal creation and historical asset source values remain readable.
|
||||
- Verification passed: `bun run test` (23 files / 81 tests), `bun x tsc --noEmit`, `bun run build`, `bun run info`, local `/api/health` HTTP smoke, `/billing` auth redirect, and OpenAPI stale-capability scan.
|
||||
|
||||
## Session: 2026-08-12 - Organization-Only Billing Top-ups
|
||||
|
||||
### Phase 70: Organization-Only Billing Top-ups — In progress
|
||||
- User confirmed that every top-up belongs to the organization; organization administrators and employees share the organization quota, with no personal top-up ownership.
|
||||
- Located the remaining personal-attribution path in the admin adjustment route, billing adjustment form, member “归属上账” action, and local/Supabase wallet-entry serialization.
|
||||
- Scope decision: preserve account IDs on generation charges/refunds for member consumption reporting; normalize new recharge/adjustment entries to organization-only and leave historical entries untouched.
|
||||
|
||||
### Phase 70: Organization-Only Billing Top-ups — Complete
|
||||
- Removed `accountId` from the direct organization top-up service contract and admin adjustment request path.
|
||||
- Normalized local wallet entries and the Supabase `billing_post_wallet_entry` RPC so `recharge` and `adjustment` rows never receive a personal account ID; generation `charge`/`refund` rows retain actor attribution.
|
||||
- Removed the billing-center member selector, “流水归属” field, and “归属上账” buttons. Member usage remains read-only and explicitly describes shared organization quota.
|
||||
- Updated the ledger renderer, API/deployment docs, and README wording to distinguish organization balance ownership from member consumption reporting.
|
||||
- Verification passed: focused billing tests 13/13, full Vitest 24 files / 92 tests, TypeScript, production build, and reviewed-file `git diff --check`.
|
||||
|
||||
### Errors encountered
|
||||
| Error | Attempt | Resolution |
|
||||
| --- | --- | --- |
|
||||
| `npm` was not available in the shell | First test command | Loaded the workspace runtime dependencies and used the bundled Node executable directly. |
|
||||
| Bundled `pnpm test` stopped at ignored `sharp` build scripts | Second test command | Invoked Vitest and TypeScript directly through the installed workspace dependencies, avoiding an install step. |
|
||||
|
||||
## Session: 2026-08-12 - Frontend Encoding Diagnosis
|
||||
|
||||
### Phase 71: Frontend Encoding Diagnosis — Awaiting reproduction
|
||||
- Checked source bytes, HTML/CSS response headers, and served HTML for common mojibake markers; all are valid UTF-8.
|
||||
- Used `agent-browser` to render `/auth/login` and an isolated auth-disabled `/billing` preview; Chinese labels and the billing screenshot rendered normally.
|
||||
- Found two existing Next dev-server processes associated with this workspace and port 3000, which may produce stale/mixed browser state.
|
||||
- No code change was applied because the reported garbling cannot yet be reproduced. Next input needed: the affected page URL and a screenshot or the exact garbled text.
|
||||
|
||||
## Session: 2026-08-12 - Autofilled Login Submission
|
||||
|
||||
### Phase 72: Autofilled Login Submission — In progress
|
||||
- User supplied a screenshot showing phone and password visibly filled while the login action could not be activated.
|
||||
- Traced the issue to the submit button depending on React state, which is not guaranteed to update for browser/password-manager autofill.
|
||||
- Updated `components/auth-login-panel.tsx` to use named required fields and native `FormData` values at submit time; updated the focused source regression test.
|
||||
- Browser check confirmed filled credentials trigger `POST /api/auth/password`; final test/build verification remains.
|
||||
|
||||
### Phase 72: Autofilled Login Submission — Complete
|
||||
- Focused auth-panel tests passed: 2/2.
|
||||
- Full Vitest suite passed: 24 files / 92 tests.
|
||||
- TypeScript and production build passed.
|
||||
- Browser check confirmed the filled login form is clickable and sends the password-login request.
|
||||
|
||||
## Session: 2026-08-12 - Next Development Cache Recovery
|
||||
|
||||
### Phase 73: Next Development Cache Recovery — Complete
|
||||
- Confirmed `.next/server/webpack-runtime.js` referenced missing chunk `9971.js`.
|
||||
- Stopped the two duplicate Next development processes associated with this workspace.
|
||||
- Moved the corrupted `.next` directory to `.next.corrupt-20260812-1042` for recovery and started one clean dev server on `127.0.0.1:3000`.
|
||||
- Verified `/create` compiles, `/auth/login` renders, `/api/health` responds, and clicking the login form sends `/api/auth/password` without the runtime overlay.
|
||||
|
||||
### Phase 74: Dev/Production Cache Isolation — Complete
|
||||
- Changed Next output selection so development uses `.next-dev` and production uses `.next`; added `.next-dev/` to `.gitignore`.
|
||||
- Moved the partially generated `.next-dev` cache to `.next-dev.corrupt-20260812-1108` instead of deleting it, then restarted one clean server on port 3000.
|
||||
- Verified `/auth/login` renders correctly, `/api/health` returns 200, `/create` redirects to `/auth/login` when unauthenticated, and the Lucide vendor chunk is regenerated in `.next-dev`.
|
||||
- TypeScript and diff checks remain clean for the cache-isolation change.
|
||||
|
||||
### Phase 75: Local Super-Admin Credential Recovery — Complete
|
||||
- Confirmed the requested account is the local super administrator `13800138000`; the previous plaintext password was not recoverable from its server-side hash.
|
||||
- Generated a new strong password and reset it through the running admin password API, so the old password is invalidated.
|
||||
- Saved the new credential as `super-admin` in the project browser vault, then cleared the browser cookies and verified the saved profile logs in automatically to `/create` with super-admin navigation.
|
||||
|
||||
## Session: 2026-08-12 - Quota Guard and Super-Admin Billing Exemption
|
||||
|
||||
### Phase 76: Quota Guard and Super-Admin Billing Exemption — In progress
|
||||
- User confirmed the recommended boundary: ordinary users are blocked by insufficient shared organization balance; super-admins calculate and record cost but do not consume organization quota.
|
||||
- Inspected the existing quote, submission, worker, Seedance settlement, usage-record, and UI error paths. Real platform submissions already reserve before provider dispatch, and `InsufficientBalanceError` already maps to HTTP 402; implementation will preserve that boundary.
|
||||
- Planned changes: add role-aware usage context, persist `quotaExempt` on billing snapshots, bypass wallet charge/refund for super-admin jobs, keep Seedance actual-cost settlement metadata, and expose the existing balance error in the create UI.
|
||||
|
||||
### Phase 76: Quota Guard and Super-Admin Billing Exemption — Complete
|
||||
- Added `role` to platform usage context and persisted it through generation jobs so the billing service can identify super-admin generation independently of organization binding.
|
||||
- Added `quotaExempt` to quote/job billing snapshots. Super-admin quotes work without an organization; submission marks them as calculated-but-not-charged, skips wallet charge/refund entries, and Seedance still reconciles actual completion-token cost in the job snapshot. Successful usage events retain `chargedAmountFen`.
|
||||
- Kept ordinary generation strict: wallet reservation runs before provider dispatch, and insufficient balance raises the existing HTTP 402 error with `余额不足,请先充值。`; the create UI surfaces that response and labels super-admin estimates/tasks as not counted against quota.
|
||||
- Updated README/API billing semantics and added regression tests for insufficient balance, unbound super-admin image billing, super-admin Seedance settlement, usage cost recording, and ordinary unbound rejection.
|
||||
- Verification: focused billing tests 17/17, full Vitest 24 files / 96 tests, TypeScript, production build, and `git diff --check` passed.
|
||||
- The repository-local test/typecheck wrappers initially could not find `node`; reran the same checks with the bundled workspace Node runtime and they passed.
|
||||
Reference in new issue
Block a user