إنشاء إيصال PDF لطلب
يقدّم طلبًا، ثم يقرؤه مرة أخرى مع بيانات التسعير الكاملة، ويبني إيصالًا قابلًا للطباعة يمكن عرضه كملف PDF على جانب العميل.
ما يفعله هذا المثال:
- يقدّم طلبًا ثم يقرؤه مجددًا باستخدام Orders.getOrderByMarkerAndId()
- يُنشئ إيصالًا من منتجات الطلب ومجاميعه وطريقة الدفع
- يعرض الإيصال على شكل ملف PDF قابل للتنزيل على جانب العميل
المتطلبات المسبقة:
- قيمتا PROJECT_URL وAPP_TOKEN صالحتان لـ OneEntry API.
- مستخدم مسجل
- مخزن طلبات مهيأ بالعلامة "orders"
ملاحظات:
- عرض PDF ليس جزءًا من OneEntry SDK. استخدم أي مكتبة على جانب العميل (يظهر هنا jsPDF)؛ يوفّر SDK بيانات الطلب فقط.
- تُرجَع
totalSumكسلسلة نصية؛ حوّلها باستخدامNumber()قبل التنسيق. لا تكتب رمز العملة بشكل ثابت: نسّق القيمة باستخدامcurrencyالخاصة بالطلب، وارجع إلى رقم عادي إذا كانت فارغة. - تعالج الأمثلة الأخطاء بالحد الأدنى: فهي ترمي استثناءً عندما يُرجع الاستدعاء كائن خطأ.
- افتراضيًا (
isShell: true) يُعيد SDK كائن خطأ بدلًا من رمي استثناء، لذا تحقق من النتيجة، مثل'statusCode' in result. معisShell: falseيرمي استثناءً، وتعالج الأخطاء باستخدام try/catch. راجع الأخطاء.
وثائق المنصة:
مرجع SDK:
جربها مباشرة
شغّل هذا المثال في بيئة JS SDK التجريبية. اربط Project URL وApp Token عند الزيارة الأولى، ثم افتح:
السيناريو
1. استورد defineOneEntry وعرّف PROJECT_URL وAPP_TOKEN
import { defineOneEntry } from 'oneentry';
import type { IOrderData } from 'oneentry';
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
2. أنشئ عميل API باستخدام defineOneEntry()
const { AuthProvider, Orders } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
3. صادِق على المستخدم باستخدام AuthProvider.auth()
const authData = [
{ marker: 'email_reg', value: 'your-email' },
{ marker: 'password_reg', value: 'your-password' },
];
const user = await AuthProvider.auth('email', { authData });
console.log(user);
النتيجة:
{
"userIdentifier": "john@example.com",
"authProviderIdentifier": "email",
"accessToken": "eyJhbGciOiJIUzI1NiIsInR...pZCI6MTYsImF1dGhQ",
"refreshToken": "1745494429101-...-2834edf8"
}
4. قدّم الطلب باستخدام Orders.createOrder()
const body: IOrderData = {
formIdentifier: 'order',
paymentAccountIdentifier: 'cash',
formData: [{ type: 'string', marker: 'name', value: 'John Smith' }],
products: [{ productId: 15, quantity: 1 }],
};
const created = await Orders.createOrder('orders', body);
if ('statusCode' in created) {
throw new Error(created.message);
}
النتيجة:
{
"id": 127,
"formIdentifier": "order",
"paymentAccountIdentifier": "cash",
"formData": [
{
"type": "string",
"marker": "name",
"value": "John Smith"
}
],
"products": [
{
"productId": 15,
"quantity": 1
}
],
"currency": "USD",
"totalSum": 400,
"bonusApplied": 0,
"totalDue": 400,
"discountConfig": {
"orderDiscounts": [],
"productDiscounts": [],
"coupon": null,
"settings": {
"allowStacking": false,
"maxDiscountValue": null,
"allowGiftStacking": false,
"maxBonusPaymentPercent": null,
"minBonusAmount": null,
"minOrderAmountForBonus": null,
"giftRefundPolicy": "KEEP_GIFT"
},
"additionalDiscountsMarkers": [],
"totalRaw": 400,
"totalSumWithDiscount": 400,
"excludedGiftProductIds": [],
"bonus": {
"availableBalance": 0,
"maxBonusDiscount": 0,
"minBonusAmount": null,
"minOrderAmountForBonus": null,
"bonusApplied": 0
},
"bonusApplied": 0,
"totalDue": 400
},
"statusIdentifier": "upcoming",
"statusLocalizeInfos": {
"title": "Upcoming"
},
"createdDate": "2026-06-06T12:04:52.459Z"
}
5. اقرأ الطلب المقدَّم باستخدام Orders.getOrderByMarkerAndId()
// This returns the full order: products with titles/prices, totalSum, currency,
// payment method and status — everything the receipt needs.
const order = await Orders.getOrderByMarkerAndId('orders', created.id);
if ('statusCode' in order) {
throw new Error(order.message);
}
النتيجة:
{
"id": 127,
"storageId": 1,
"createdDate": "2026-06-06T12:04:52.459Z",
"statusIdentifier": "upcoming",
"statusLocalizeInfos": {
"title": "Upcoming"
},
"formIdentifier": "order",
"formData": [
{
"type": "string",
"marker": "name",
"value": "John Smith"
}
],
"attributeSetIdentifier": "order",
"paymentStrategy": "once",
"totalSum": "400",
"totalSumRaw": "400",
"currency": "USD",
"paymentAccountIdentifier": "cash",
"paymentAccountLocalizeInfos": {
"title": "Cash"
},
"products": [
{
"id": 15,
"title": "Orange ball",
"sku": null,
"previewImage": "[]",
"price": 400,
"quantity": 1,
"isGift": false
}
],
"paymentUrl": null,
"discountConfig": {
"orderDiscounts": [],
"productDiscounts": [],
"coupon": null,
"settings": {
"allowStacking": false,
"maxDiscountValue": null,
"allowGiftStacking": false,
"maxBonusPaymentPercent": null,
"minBonusAmount": null,
"minOrderAmountForBonus": null,
"giftRefundPolicy": "KEEP_GIFT"
},
"additionalDiscountsMarkers": [],
"totalRaw": 400,
"totalSumWithDiscount": 400,
"excludedGiftProductIds": [],
"bonus": {
"availableBalance": 0,
"maxBonusDiscount": 0,
"minBonusAmount": null,
"minOrderAmountForBonus": null,
"bonusApplied": 0
},
"bonusApplied": 0,
"totalDue": 400
},
"isPartial": false,
"isCompleted": null,
"split": {
"completed": false,
"partial": false,
"stages": [
{
"marker": "default",
"sessionId": null,
"productId": 15,
"title": "Default",
"value": 400,
"status": "planned"
}
]
}
}
6. ابنِ الإيصال من بيانات الطلب
// Format money with the order's currency; fall back to a plain number if it's empty.
const currency = order.currency || '';
const money = (v: number) =>
currency
? new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(v)
: v.toFixed(2);
// Order status is only a marker; its title is project-specific. Prefer the
// localized title from the API, then a client map, then the raw marker.
const STATUS_LABELS: Record<string, string> = {
upcoming: 'Upcoming',
};
const receipt = {
orderId: order.id,
// createdDate is an ISO string returned by the API.
date: new Date(order.createdDate).toLocaleString('en-US'),
status:
order.statusLocalizeInfos?.title ??
STATUS_LABELS[order.statusIdentifier ?? ''] ??
order.statusIdentifier,
// paymentAccountLocalizeInfos.title is the human label; fall back to the marker.
payment: order.paymentAccountLocalizeInfos?.title || order.paymentAccountIdentifier,
items: order.products.map((p) => ({
title: p.title,
quantity: p.quantity,
price: money(p.price),
lineTotal: money(p.price * p.quantity),
})),
// totalSum is a string ("400"), so convert it before formatting.
total: money(Number(order.totalSum)),
};
console.log(receipt);
النتيجة:
{
"orderId": 127,
"date": "6/6/2026, 3:04:52 PM",
"status": "Upcoming",
"payment": "Cash",
"items": [
{
"title": "Orange ball",
"quantity": 1,
"price": "$400.00",
"lineTotal": "$400.00"
}
],
"total": "$400.00"
}
7. اعرض الإيصال كملف PDF على العميل (مثلًا باستخدام jsPDF)
ثبّت jsPDF أولًا: npm install jspdf.
import { jsPDF } from 'jspdf';
const doc = new jsPDF();
doc.setFontSize(16);
doc.text(`Receipt #${receipt.orderId}`, 14, 20);
doc.setFontSize(11);
doc.text(`Date: ${receipt.date}`, 14, 30);
doc.text(`Status: ${receipt.status}`, 14, 37);
doc.text(`Payment: ${receipt.payment}`, 14, 44);
let y = 58;
receipt.items.forEach((item) => {
// Start a new page before the line runs off the bottom (A4 is 297 mm).
if (y > 280) {
doc.addPage();
y = 20;
}
doc.text(`${item.quantity} × ${item.title}`, 14, y);
doc.text(item.lineTotal, 196, y, { align: 'right' });
y += 7;
});
doc.setFontSize(13);
if (y > 272) {
doc.addPage();
y = 20;
}
doc.text(`Total: ${receipt.total}`, 196, y + 8, { align: 'right' });
doc.save(`receipt-${receipt.orderId}.pdf`);
المثال النهائي
// 1. Import defineOneEntry and define PROJECT_URL and APP_TOKEN
import { defineOneEntry } from 'oneentry';
import type { IOrderData } from 'oneentry';
import { jsPDF } from 'jspdf'; // npm install jspdf
const PROJECT_URL = 'https://your-project.oneentry.cloud';
const APP_TOKEN = 'your-app-token';
// 2. Create an API client
const { AuthProvider, Orders } = defineOneEntry(PROJECT_URL, {
token: APP_TOKEN,
});
// 3. Sign in
const authData = [
{ marker: 'email_reg', value: 'your-email' },
{ marker: 'password_reg', value: 'your-password' },
];
const user = await AuthProvider.auth('email', { authData });
console.log(user);
// 4. Place the order
const body: IOrderData = {
formIdentifier: 'order',
paymentAccountIdentifier: 'cash',
formData: [{ type: 'string', marker: 'name', value: 'John Smith' }],
products: [{ productId: 15, quantity: 1 }],
};
const created = await Orders.createOrder('orders', body);
if ('statusCode' in created) {
throw new Error(created.message);
}
// 5. Read the placed order back
// This returns the full order: products with titles/prices, totalSum, currency,
// payment method and status — everything the receipt needs.
const order = await Orders.getOrderByMarkerAndId('orders', created.id);
if ('statusCode' in order) {
throw new Error(order.message);
}
// 6. Build the receipt from the order data
// Format money with the order's currency; fall back to a plain number if it's empty.
const currency = order.currency || '';
const money = (v: number) =>
currency
? new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(v)
: v.toFixed(2);
// Order status is only a marker; its title is project-specific. Prefer the
// localized title from the API, then a client map, then the raw marker.
const STATUS_LABELS: Record<string, string> = {
upcoming: 'Upcoming',
};
const receipt = {
orderId: order.id,
// createdDate is an ISO string returned by the API.
date: new Date(order.createdDate).toLocaleString('en-US'),
status:
order.statusLocalizeInfos?.title ??
STATUS_LABELS[order.statusIdentifier ?? ''] ??
order.statusIdentifier,
// paymentAccountLocalizeInfos.title is the human label; fall back to the marker.
payment: order.paymentAccountLocalizeInfos?.title || order.paymentAccountIdentifier,
items: order.products.map((p) => ({
title: p.title,
quantity: p.quantity,
price: money(p.price),
lineTotal: money(p.price * p.quantity),
})),
// totalSum is a string ("400"), so convert it before formatting.
total: money(Number(order.totalSum)),
};
console.log(receipt);
// 7. Render the receipt as a PDF on the client
const doc = new jsPDF();
doc.setFontSize(16);
doc.text(`Receipt #${receipt.orderId}`, 14, 20);
doc.setFontSize(11);
doc.text(`Date: ${receipt.date}`, 14, 30);
doc.text(`Status: ${receipt.status}`, 14, 37);
doc.text(`Payment: ${receipt.payment}`, 14, 44);
let y = 58;
receipt.items.forEach((item) => {
// Start a new page before the line runs off the bottom (A4 is 297 mm).
if (y > 280) {
doc.addPage();
y = 20;
}
doc.text(`${item.quantity} × ${item.title}`, 14, y);
doc.text(item.lineTotal, 196, y, { align: 'right' });
y += 7;
});
doc.setFontSize(13);
if (y > 272) {
doc.addPage();
y = 20;
}
doc.text(`Total: ${receipt.total}`, 196, y + 8, { align: 'right' });
doc.save(`receipt-${receipt.orderId}.pdf`);