Wire payments UI and fix frontend tests

This commit is contained in:
2026-02-28 13:15:41 +03:00
parent f3c93f500e
commit a150b18fe7
9 changed files with 4815 additions and 5 deletions
+4
View File
@@ -3,6 +3,10 @@
## Project Goal
Build a reliable, maintainable salon booking platform with Django (backend) and React (frontend), optimized for KSA needs (phone auth, local payments) while keeping a clean path to scale.
## Coding
- Comment concisely and often as appropriate
## Current Plan (Roadmap)
### Phase 1: Core MVP Reliability
- Phone-first auth with OTP (SMS/WhatsApp), rate limits, and social login.
+4487
View File
File diff suppressed because it is too large Load Diff
+152 -2
View File
@@ -1,14 +1,33 @@
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { apiGet } from "./api/client";
import { apiGet, apiPost } from "./api/client";
import { setLocale } from "./i18n";
export default function App() {
const [salons, setSalons] = useState([]);
const [query, setQuery] = useState("");
const [status, setStatus] = useState("idle");
const [paymentBookingId, setPaymentBookingId] = useState("");
const [paymentToken, setPaymentToken] = useState(() => localStorage.getItem("auth_token") || "");
const [paymentSourceType, setPaymentSourceType] = useState("stcpay");
const [paymentSourceValue, setPaymentSourceValue] = useState("");
const [paymentCallbackUrl, setPaymentCallbackUrl] = useState("");
const [paymentStatus, setPaymentStatus] = useState("idle");
const [paymentResult, setPaymentResult] = useState(null);
const [paymentError, setPaymentError] = useState("");
const { t, i18n } = useTranslation();
const idempotencyKey = useMemo(() => {
if (typeof crypto !== "undefined" && crypto.randomUUID) {
return crypto.randomUUID();
}
return `id-${Date.now()}-${Math.random().toString(16).slice(2)}`;
}, []);
useEffect(() => {
localStorage.setItem("auth_token", paymentToken);
}, [paymentToken]);
useEffect(() => {
let ignore = false;
@@ -33,6 +52,60 @@ export default function App() {
};
}, [query]);
async function handlePaymentSubmit(event) {
event.preventDefault();
setPaymentStatus("loading");
setPaymentError("");
setPaymentResult(null);
if (!paymentBookingId) {
setPaymentStatus("error");
setPaymentError(t("payment.errors.bookingRequired"));
return;
}
const source = { type: paymentSourceType };
if (paymentSourceType === "stcpay") {
if (!paymentSourceValue) {
setPaymentStatus("error");
setPaymentError(t("payment.errors.mobileRequired"));
return;
}
source.mobile = paymentSourceValue;
}
if (paymentSourceType === "token") {
if (!paymentSourceValue) {
setPaymentStatus("error");
setPaymentError(t("payment.errors.tokenRequired"));
return;
}
source.token = paymentSourceValue;
}
const payload = {
booking_id: Number(paymentBookingId),
provider: "moyasar",
idempotency_key: idempotencyKey,
source,
};
if (paymentCallbackUrl) {
payload.callback_url = paymentCallbackUrl;
}
try {
const data = await apiPost("/payments/", payload, paymentToken);
setPaymentResult(data);
setPaymentStatus("ready");
if (data?.redirect_url) {
window.location.assign(data.redirect_url);
}
} catch (error) {
setPaymentStatus("error");
setPaymentError(error.message || t("payment.errors.generic"));
}
}
return (
<div className="page">
<header className="hero">
@@ -90,6 +163,83 @@ export default function App() {
))}
</div>
</section>
<section className="payments">
<div className="payments-header">
<div>
<h2>{t("payment.title")}</h2>
<p className="payments-subtitle">{t("payment.subtitle")}</p>
</div>
<span className="payments-badge">{t("payment.badge")}</span>
</div>
<form className="payments-form" onSubmit={handlePaymentSubmit}>
<label className="field">
<span>{t("payment.bookingId")}</span>
<input
type="number"
min="1"
value={paymentBookingId}
onChange={(event) => setPaymentBookingId(event.target.value)}
placeholder="123"
required
/>
</label>
<label className="field">
<span>{t("payment.accessToken")}</span>
<input
type="password"
value={paymentToken}
onChange={(event) => setPaymentToken(event.target.value)}
placeholder={t("payment.accessTokenPlaceholder")}
/>
</label>
<label className="field">
<span>{t("payment.sourceType")}</span>
<select
value={paymentSourceType}
onChange={(event) => setPaymentSourceType(event.target.value)}
>
<option value="stcpay">{t("payment.sources.stcpay")}</option>
<option value="token">{t("payment.sources.token")}</option>
<option value="applepay">{t("payment.sources.applepay")}</option>
</select>
</label>
<label className="field">
<span>{t("payment.sourceValue")}</span>
<input
type="text"
value={paymentSourceValue}
onChange={(event) => setPaymentSourceValue(event.target.value)}
placeholder={t("payment.sourceValuePlaceholder")}
/>
</label>
<label className="field">
<span>{t("payment.callbackUrl")}</span>
<input
type="url"
value={paymentCallbackUrl}
onChange={(event) => setPaymentCallbackUrl(event.target.value)}
placeholder="https://example.com/payments/return"
/>
</label>
<div className="payments-actions">
<button type="submit" disabled={paymentStatus === "loading"}>
{paymentStatus === "loading" ? t("payment.processing") : t("payment.payNow")}
</button>
<p className="helper">
{t("payment.idempotency")}: {idempotencyKey}
</p>
</div>
</form>
{paymentStatus === "error" && paymentError && (
<p className="error">{paymentError}</p>
)}
{paymentStatus === "ready" && paymentResult && (
<pre className="payment-result">{JSON.stringify(paymentResult, null, 2)}</pre>
)}
</section>
</div>
);
}
+10 -3
View File
@@ -1,23 +1,30 @@
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { vi } from "vitest";
import App from "./App.jsx";
import i18n from "./i18n";
vi.mock("./api/client", () => ({
apiGet: vi.fn().mockResolvedValue([]),
apiPost: vi.fn()
}));
describe("App", () => {
it("renders the hero copy", async () => {
await i18n.changeLanguage("en");
render(<App />);
expect(
screen.getByText("Find, compare, and book top salons near you.")
await screen.findByText("Find, compare, and book top salons near you.")
).toBeInTheDocument();
});
it("switches to Arabic and sets RTL direction", async () => {
await i18n.changeLanguage("en");
render(<App />);
fireEvent.click(screen.getByRole("button", { name: "العربية" }));
const arabicButton = screen.getByRole("button", { name: "العربية" });
fireEvent.click(arabicButton);
await waitFor(() => {
expect(document.documentElement.dir).toBe("rtl");
});
expect(screen.getByText("الصالونات")).toBeInTheDocument();
expect(arabicButton).toHaveClass("active");
});
});
+17
View File
@@ -18,3 +18,20 @@ export async function apiGet(path) {
});
return handleResponse(response);
}
export async function apiPost(path, body, token) {
const headers = {
"Accept-Language": getActiveLocale(),
"Content-Type": "application/json",
};
if (token) {
headers.Authorization = `Bearer ${token}`;
}
const response = await fetch(`${API_BASE}${path}`, {
method: "POST",
headers,
body: JSON.stringify(body),
});
return handleResponse(response);
}
+26
View File
@@ -19,5 +19,31 @@
"label": "اللغة",
"arabic": "العربية",
"english": "الإنجليزية"
},
"payment": {
"title": "المدفوعات (تجريبي)",
"subtitle": "إرسال عملية دفع عبر Moyasar لحجز موجود.",
"badge": "المدفوعات",
"bookingId": "رقم الحجز",
"accessToken": "رمز الوصول",
"accessTokenPlaceholder": "الصقي رمز JWT",
"sourceType": "نوع المصدر",
"sourceValue": "قيمة المصدر",
"sourceValuePlaceholder": "رقم الجوال أو الرمز",
"callbackUrl": "رابط العودة",
"payNow": "ادفع الآن",
"processing": "جارٍ المعالجة...",
"idempotency": "مفتاح التكرار",
"sources": {
"stcpay": "stc pay (جوال)",
"token": "دفع عبر رمز",
"applepay": "Apple Pay"
},
"errors": {
"bookingRequired": "رقم الحجز مطلوب.",
"mobileRequired": "رقم الجوال مطلوب لـ stc pay.",
"tokenRequired": "الرمز مطلوب للدفع عبر الرمز.",
"generic": "فشل طلب الدفع."
}
}
}
+26
View File
@@ -19,5 +19,31 @@
"label": "Language",
"arabic": "العربية",
"english": "English"
},
"payment": {
"title": "Payment (Beta)",
"subtitle": "Send a Moyasar payment for an existing booking.",
"badge": "Payments",
"bookingId": "Booking ID",
"accessToken": "Access token",
"accessTokenPlaceholder": "Paste JWT access token",
"sourceType": "Source type",
"sourceValue": "Source value",
"sourceValuePlaceholder": "Mobile number or token",
"callbackUrl": "Callback URL",
"payNow": "Pay now",
"processing": "Processing...",
"idempotency": "Idempotency key",
"sources": {
"stcpay": "stc pay (mobile)",
"token": "tokenized payment",
"applepay": "Apple Pay"
},
"errors": {
"bookingRequired": "Booking ID is required.",
"mobileRequired": "Mobile number is required for stc pay.",
"tokenRequired": "Token is required for token payments.",
"generic": "Payment request failed."
}
}
}
+92
View File
@@ -108,6 +108,98 @@ h1 {
margin-top: 48px;
}
.payments {
margin-top: 48px;
background: rgba(255, 255, 255, 0.85);
border-radius: 24px;
padding: 28px;
box-shadow: 0 18px 32px rgba(23, 23, 23, 0.08);
}
.payments-header {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
gap: 16px;
}
.payments-subtitle {
margin: 8px 0 0;
color: #5c5a5f;
}
.payments-badge {
background: #1c1b1f;
color: #fff;
padding: 6px 12px;
border-radius: 999px;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.payments-form {
margin-top: 20px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 16px;
}
.field {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 14px;
color: #3c3a3f;
}
.field input,
.field select {
padding: 10px 12px;
border-radius: 10px;
border: 1px solid #dad3ca;
font-size: 14px;
}
.payments-actions {
grid-column: 1 / -1;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 16px;
}
.payments-actions button {
padding: 10px 18px;
border-radius: 999px;
border: none;
background: #1c1b1f;
color: white;
font-weight: 600;
cursor: pointer;
}
.payments-actions button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.helper {
font-size: 13px;
color: #5c5a5f;
margin: 0;
}
.payment-result {
margin-top: 16px;
background: #f5f5f5;
border-radius: 12px;
padding: 12px;
font-size: 12px;
overflow-x: auto;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
+1
View File
@@ -9,6 +9,7 @@ export default defineConfig({
}
},
test: {
globals: true,
environment: "jsdom",
setupFiles: "./src/test/setupTests.js"
}