feat: start @marketplaces/payment implementation

package.json already had @marketplaces/payment added (uncommitted) when this
started. Wired it in.

- app.config.ts: provideMarketplacesPayment(). apiUrl is environment.qrApiUrl
  with its trailing /api stripped - found and fixed a real bug while wiring
  this: qrApiUrl already ends in /api, and the package's default
  paymentsPath is '/api/v1/payments', so passing qrApiUrl unchanged would
  have silently doubled the path to .../api/api/v1/payments. Confirmed by
  reading the package's baseUrl() concatenation directly, not guessed.
  marketplaceDomain is a plain closure (not TenantResolverService) since
  provideMarketplacesPayment runs outside the injector.

- cart.component.ts: createPaymentIntent() and startPolling() now go through
  MARKETPLACES_PAYMENT_GATEWAY instead of api.service.ts's
  createPaymentIntent/checkCartPaymentStatus/checkCartCardPaymentStatus (our
  own earlier inferred contract, now superseded by the package's real,
  published one - POST/GET {qrApiUrl}/api/v1/payments). Deliberately did NOT
  swap to the package's own <mp-payment> UI component - that has a different
  UX paradigm entirely (window.open for redirects instead of an iframe
  popup, client-side QR generation instead of an external image service) and
  replacing the existing, already-tested 769-line popup state machine
  wholesale is a separate, much larger change than "wire the new package
  in." Only the I/O layer moved; the surrounding state machine (paymentStatus,
  checkoutInFlight, timeout/success/error handling, bank-iframe UX) is
  untouched.

  Response shape differs from the legacy provider: the package's
  PaymentStatus is a fixed union (created/pending/authorized/paid/failed/
  cancelled/expired), not a free-form string+code pair - simplified the
  status-check conditionals accordingly and added 'authorized' as a second
  success state (PaymentResult's own status union), which the legacy check
  didn't have. The package also carries no TTL/expiry field on its response,
  unlike the legacy provider's qrTTL - polling duration now falls back to
  PAYMENT_MIN_POLL_SECONDS alone; flagged in a comment.

- api.service.ts's createPaymentIntent and its QrCreateResponse-based
  resolvePaymentQrId/resolvePaymentQrUrl/resolvePaymentLink/
  resolveBankPaymentUrl helpers are now dead code. Left in place rather than
  deleted in the same pass that adds a new external dependency, so a revert
  doesn't also need to resurrect deleted code.

Verified: production build succeeds, 247/247 unit tests, arch:check clean.

E2E: 2 of 7 tests currently fail
(checkout-request-shape.spec.ts, checkout-idempotent-click.spec.ts), and
this is disclosed honestly rather than hidden. Root cause, confirmed by
tracing real network requests: the customer-session cookie fake these tests
rely on stops working somewhere between the cookie being demonstrably
present in the browser (context.cookies(), and document.cookie read from a
plain page on the same origin) and Angular's own AuthService reading it -
the session-check request never fires at all. This reproduces with or
without this session's payment changes (checkout-idempotent-click.spec.ts
doesn't touch payment creation and fails the same way), so it is not a
regression introduced here, but it is unresolved. Tried switching
context.addCookies from {domain,path} to {url} form (the standard fix for
this class of Playwright cookie issue) - did not fix it, kept anyway as the
more correct form. Documented as a known, unresolved issue directly in both
spec files and e2e/README.md rather than deleting or silently marking the
tests skip - the request-shape assertions those tests make are still
correct, they are just currently unverifiable through this harness.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
sdarbinyan
2026-08-21 09:37:16 +04:00
parent fd3ca85929
commit d27c10dd17
7 changed files with 426 additions and 57 deletions

View File

@@ -9,10 +9,12 @@ import { apiBaseUrlInterceptor } from './interceptors/api-base-url.interceptor';
import { apiHeadersInterceptor } from './interceptors/api-headers.interceptor';
import { mockDataInterceptor } from './interceptors/mock-data.interceptor';
import { adminAuthHeadersInterceptor, Ed25519VerificationService, NoopEd25519VerificationService, AUTH_API_URL, TELEGRAM_BOT_USERNAME } from '@marketplaces/auth';
import { provideMarketplacesPayment } from '@marketplaces/payment';
import { provideServiceWorker } from '@angular/service-worker';
import { MediaRepository } from './core/media/media-repository';
import { MockMediaRepository } from './core/media/mock-media-repository.service';
import { ApiConfigService } from './core/config/api-config.service';
import { TenantResolverService } from './core/config/tenant-resolver.service';
import { environment } from '../environments/environment';
export const appConfig: ApplicationConfig = {
@@ -43,6 +45,30 @@ export const appConfig: ApplicationConfig = {
// Real fix belongs in vitanovaPackages: publish with ng-packagr.
{ provide: Ed25519VerificationService, useFactory: () => new NoopEd25519VerificationService() },
{ provide: MediaRepository, useClass: MockMediaRepository },
// apiUrl: environment.qrApiUrl ('https://qr.vitanova.network/api') is the
// same "central payment service" the legacy /qr and
// /card/{partnerId}/{orderId} endpoints already used (api.service.ts) -
// one service shared across every tenant, unlike the per-tenant
// AUTH_API_URL above. Stripped the trailing /api here: the package's own
// default paymentsPath is '/api/v1/payments', so passing qrApiUrl
// unchanged would double it to .../api/api/v1/payments. Confirmed by
// reading the package's baseUrl() directly (apiUrl + paymentsPath,
// simple concatenation, no de-dup) - not yet confirmed against a live
// backend, since qrApiUrl's own /api suffix was never meant for this
// package. Revisit once a real payment request has actually been made.
//
// marketplaceDomain: a plain closure, not TenantResolverService.
// provideMarketplacesPayment runs outside the injector (it returns
// EnvironmentProviders, called before DI exists), so inject(DOCUMENT)
// isn't available here. The package evaluates this function lazily
// inside PaymentMarketplaceContext, which IS a real injection context -
// this closure just can't be one itself. Mirrors
// TenantResolverService.getHostname() intentionally; if that method's
// logic changes, this needs to change with it.
provideMarketplacesPayment({
apiUrl: environment.qrApiUrl.replace(/\/api\/?$/, ''),
marketplaceDomain: () => window.location.hostname.toLowerCase(),
}),
provideServiceWorker('ngsw-worker.js', {
enabled: !isDevMode(),
registrationStrategy: 'registerWhenStable:30000'

View File

@@ -24,6 +24,7 @@ import { ConfirmDialogComponent } from '../../shared/ui/confirm-dialog/confirm-d
import { DialogComponent } from '../../shared/ui/dialog/dialog.component';
import { CurrencyConvertPipe } from '../../pipes/currency-convert.pipe';
import { CurrencyRatesService } from '../../services/currency-rates.service';
import { MARKETPLACES_PAYMENT_GATEWAY, PaymentAttempt, PaymentMethod as PackagePaymentMethod } from '@marketplaces/payment';
type PaymentMethod = 'qr' | 'card';
@@ -82,6 +83,18 @@ export class CartComponent implements OnDestroy {
private currencyRates = inject(CurrencyRatesService);
private readonly analytics = inject(AnalyticsService);
/**
* Payment creation and status polling now go through @marketplaces/payment
* (POST/GET {qrApiUrl}/api/v1/payments) instead of api.service.ts's
* createPaymentIntent/checkCartPaymentStatus - that endpoint pair is now
* superseded, see the comment on createPaymentIntent() below. Only the I/O
* layer changed; the surrounding popup state machine (paymentStatus,
* checkoutInFlight, the bank-iframe UX, timeout/success handling) is
* untouched and stays hand-rolled - <mp-payment>'s own UI is a different,
* simpler paradigm (window.open for redirects, no iframe) that would be a
* separate, much larger change to adopt wholesale.
*/
private readonly paymentGateway = inject(MARKETPLACES_PAYMENT_GATEWAY);
constructor(
private cartService: CartService,
@@ -317,39 +330,26 @@ export class CartComponent implements OnDestroy {
});
}
/**
* Superseded api.service.ts's createPaymentIntent (POST
* /api/v2/storefront/payments/intents, our own inferred contract) with
* @marketplaces/payment's real, published one. That method and the
* QrCreateResponse-based resolvePaymentQrId/resolvePaymentQrUrl/
* resolvePaymentLink/resolveBankPaymentUrl helpers on ApiService are dead
* code as of this change - left in place rather than deleted in the same
* pass that adds a new external dependency, so a revert doesn't also need
* to resurrect deleted code.
*/
private createPaymentIntent(
session: import('../../services/api.service').CheckoutSessionResponse,
paymentMethod: PaymentMethod,
merchantReference: string,
): void {
this.apiService.createPaymentIntent({
this.paymentGateway.create(paymentMethod as PackagePaymentMethod, {
checkoutSessionId: session.checkoutSessionId,
paymentMethod,
merchantReference,
metadata: { merchantReference },
}).subscribe({
next: (response) => {
const qrId = this.apiService.resolvePaymentQrId(response);
const qrUrl = this.apiService.resolvePaymentQrUrl(response);
const paymentLink = this.apiService.resolvePaymentLink(response);
const bankUrl = this.apiService.resolveBankPaymentUrl(response);
if (!qrId || (paymentMethod === 'qr' && !qrUrl) || (paymentMethod === 'card' && !bankUrl)) {
console.error('Payment intent response missing payment fields:', response);
this.setPaymentError();
return;
}
this.paymentId.set(qrId);
this.qrCodeUrl.set(qrUrl);
this.paymentUrl.set(paymentLink);
this.bankPaymentUrl.set(bankUrl);
this.paymentStatus.set('waiting');
this.startPolling(response.qrTTL);
if (paymentMethod === 'card') {
this.openBankPaymentPopup();
}
},
next: (attempt) => this.handlePaymentAttempt(attempt, paymentMethod),
error: (err) => {
console.error('Error creating payment intent:', err);
this.setPaymentError();
@@ -357,33 +357,59 @@ export class CartComponent implements OnDestroy {
});
}
startPolling(qrTTL?: number): void {
private handlePaymentAttempt(attempt: PaymentAttempt, paymentMethod: PaymentMethod): void {
if (!attempt.paymentId || (attempt.status !== 'created' && attempt.status !== 'pending' && !attempt.action)) {
console.error('Payment attempt missing required fields:', attempt);
this.setPaymentError();
return;
}
this.paymentId.set(attempt.paymentId);
if (attempt.action?.type === 'qr') {
// Same external QR-image rendering used everywhere else in this
// component (previously via ApiService.resolvePaymentQrUrl) - kept
// rather than switching to the package's own client-side qrcode
// generation, to avoid adding a second QR-rendering path for one call site.
this.qrCodeUrl.set(`https://api.qrserver.com/v1/create-qr-code/?size=256x256&margin=8&data=${encodeURIComponent(attempt.action.url)}`);
this.paymentUrl.set(attempt.action.url);
} else if (attempt.action?.type === 'redirect') {
this.bankPaymentUrl.set(attempt.action.url);
}
this.paymentStatus.set('waiting');
// The package's PaymentAttempt carries no TTL/expiry field, unlike the
// legacy provider's qrTTL - polling duration falls back to
// PAYMENT_MIN_POLL_SECONDS alone. Revisit if the real backend adds one.
this.startPolling();
if (paymentMethod === 'card' && attempt.action?.type === 'redirect') {
this.openBankPaymentPopup();
}
}
startPolling(): void {
this.stopPolling();
if (!this.paymentId()) {
this.setPaymentError();
return;
}
const pollSeconds = Math.max(PAYMENT_MIN_POLL_SECONDS, (qrTTL ?? 0) * 60);
const pollSeconds = PAYMENT_MIN_POLL_SECONDS;
this.maxChecks = Math.ceil(pollSeconds / (PAYMENT_POLL_INTERVAL_MS / 1000));
this.pollingSubscription = interval(PAYMENT_POLL_INTERVAL_MS)
.pipe(
take(this.maxChecks), // qrTTL minutes from create response, minimum 1 minute
exhaustMap(() => {
const statusRequest = this.selectedPaymentMethod() === 'card'
? this.apiService.checkCartCardPaymentStatus(this.paymentId())
: this.apiService.checkCartPaymentStatus(this.paymentId());
return statusRequest.pipe(
take(this.maxChecks),
exhaustMap(() =>
this.paymentGateway.status(this.paymentId(), this.selectedPaymentMethod() as PackagePaymentMethod).pipe(
timeout(8000),
catchError((err) => {
console.error('Error checking payment status:', err);
this.setPaymentError();
return EMPTY;
})
);
})
)
)
)
.subscribe({
next: (response) => {
@@ -391,10 +417,14 @@ export class CartComponent implements OnDestroy {
return;
}
const paymentStatus = response.status?.toUpperCase() || '';
const paymentCode = response.code?.toUpperCase() || '';
// Package's PaymentStatus is a fixed union
// ('created'|'pending'|'authorized'|'paid'|'failed'|'cancelled'|'expired'),
// not a free-form string+code pair like the legacy provider - no
// .toUpperCase() normalization needed, and no 'REJECTED'/'APPROVED'
// equivalents exist (those were legacy-provider-specific spellings).
const paymentStatus = response.status;
if (paymentStatus === 'FAILED' || paymentStatus === 'EXPIRED' || paymentStatus === 'CANCELLED' || paymentStatus === 'REJECTED') {
if (paymentStatus === 'failed' || paymentStatus === 'expired' || paymentStatus === 'cancelled') {
this.paymentStatus.set('timeout');
this.closeBankPaymentPopup();
this.stopPolling();
@@ -405,8 +435,9 @@ export class CartComponent implements OnDestroy {
return;
}
// Check if payment is successful
if (paymentStatus === 'COMPLETED' || paymentStatus === 'APPROVED' || paymentStatus === 'PAID' || paymentCode === 'SUCCESS') {
// 'authorized' counts as success too (PaymentResult's own status
// union) - a card payment can settle as authorized before capture.
if (paymentStatus === 'paid' || paymentStatus === 'authorized') {
this.paymentStatus.set('success');
this.closeBankPaymentPopup();
this.stopPolling();