إنشاء الشحنات من Google Sheets
تحوّل هذه الوصفة جدول Google Sheets إلى منشئ شحنات بالجملة. يقرأ سكربت كل صف لا يحمل رقم تتبع بعد، وينشئ الشحنة عبر الـ API، ويكتب في الصف رقم التتبع والحالة، أو رمز الخطأ ورسالته لتصحح الصف وتشغّل السكربت من جديد.
يستخدم مفتاح API بالنطاقين shipments:write وshipments:read. المفتاح يبقى في خصائص السكربت الخاصة: لا يوجد في أي خلية. أنشئ المفتاح كما في تفعيل الواجهة.
أنشئ ورقة اسمها Shipments. الصف الأول للعناوين؛ والبيانات من الصف الثاني.
| العمود | العنوان | ملاحظات |
|---|---|---|
| A | Reference | رقم طلبك. مطلوب. يصبح reference الشحنة ومفتاح منع التكرار |
| B | Merchant | معرّف التاجر أو اسم حسابه بدقة. مطلوب. عنوان التاجر الرئيسي هو الاستلام |
| C | Recipient name | مطلوب |
| D | Recipient phone | مطلوب. نسّق العمود كـ نص عادي حتى تبقى الأصفار الأولى |
| E | City | اسم عربي أو إنجليزي. مطلوب |
| F | District | اسم عربي أو إنجليزي. مطلوب |
| G | Address line | الشارع والمبنى ومعلم. مطلوب |
| H | Short address | العنوان الوطني المختصر مثل RNBA6769. نص عادي |
| I-L | Weight kg وLength cm وWidth cm وHeight cm | مطلوبة، أرقام |
| M | COD amount | اختياري، الافتراضي 0 |
| N | Description | اختياري |
| O-R | Tracking number وStatus وError code وError message | يكتبها السكربت |
الأسماء العربية مثل جده وحي البرية تعمل: اختلافات الإملاء مقبولة (الأماكن بالاسم). يرسل السكربت الدولة SA؛ غيّرها في السكربت إن شحنت إلى غيرها.
افتح Extensions ثم Apps Script والصق السكربت واحفظ، ثم اضبط ثلاث خصائص للسكربت (Project Settings): LASTMILE_API_URL وLASTMILE_API_KEY وLASTMILE_API_SECRET. أعد تحميل الجدول فتظهر قائمة LastMile. أول تشغيل يطلب منك تفويض السكربت.
/**
* Create LastMile shipments from a Google Sheet.
*
* Setup: Extensions > Apps Script, paste this file, then Project Settings > Script properties:
* LASTMILE_API_URL base address of the API, no trailing slash
* LASTMILE_API_KEY lmc_live_...
* LASTMILE_API_SECRET the secret shown once when the key was created
* The key needs the scopes shipments:write (create) and shipments:read (replays return the shipment).
*
* Sheet "Shipments", row 1 = headers, data from row 2. Format the phone and short-address columns as Plain text.
* A Reference | B Merchant | C Recipient name | D Recipient phone | E City | F District | G Address line
* H Short address | I Weight kg | J Length cm | K Width cm | L Height cm | M COD amount | N Description
* The script writes: O Tracking number | P Status | Q Error code | R Error message
*/
const SHEET_NAME = "Shipments";
const FIRST_RESULT_COLUMN = 15; // column O
function onOpen() {
SpreadsheetApp.getUi().createMenu("LastMile").addItem("Create shipments", "createShipments").addToUi();
}
function createShipments() {
const props = PropertiesService.getScriptProperties();
const api = props.getProperty("LASTMILE_API_URL") + "/api/public/v1";
const headers = {
"X-API-Key": props.getProperty("LASTMILE_API_KEY"),
"X-API-Secret": props.getProperty("LASTMILE_API_SECRET"),
"Accept-Language": "en",
};
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
const lastRow = sheet.getLastRow();
if (lastRow < 2) return;
// getDisplayValues keeps phone numbers and short addresses exactly as typed (no lost leading zero).
const rows = sheet.getRange(2, 1, lastRow - 1, 18).getDisplayValues();
rows.forEach((row, index) => {
const [reference, merchant, name, phone, city, district, addressLine, shortAddress, weight, length, width, height, cod, description] = row;
const alreadyDone = row[14]; // tracking number present
if (!reference || alreadyDone) return;
const missing = [["Merchant", merchant], ["Recipient name", name], ["Recipient phone", phone], ["City", city], ["District", district],
["Address line", addressLine], ["Weight", weight], ["Length", length], ["Width", width], ["Height", height]]
.filter(([, value]) => !String(value).trim()).map(([label]) => label);
if (missing.length) {
writeResult(sheet, index + 2, ["", "", "missing_fields", "Fill in: " + missing.join(", ")]);
return;
}
const body = {
reference: reference,
sender: { type: "merchant", merchant: merchant },
recipient: {
country: "SA",
city: city,
district: district,
addressLine: addressLine,
shortAddress: shortAddress || undefined,
name: name,
phone: phone,
},
parcel: {
weightKg: Number(weight),
lengthCm: Number(length),
widthCm: Number(width),
heightCm: Number(height),
description: description || undefined,
},
payment: { codAmount: Number(cod || 0) },
};
// One key per row, derived from the reference: running the script twice never creates a second shipment.
const idempotencyKey = ("sheet-" + reference).replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 128);
const response = send(api + "/shipments", headers, body, idempotencyKey);
const data = JSON.parse(response.getContentText() || "{}");
if (response.getResponseCode() === 201 || response.getResponseCode() === 200) {
writeResult(sheet, index + 2, [data.trackingNumber, data.statusLabelEn, "", ""]);
} else {
writeResult(sheet, index + 2, ["", "", data.code || "http_" + response.getResponseCode(), describeError(data)]);
}
});
}
/** POST with one automatic wait when the rate limit (120 requests per minute) is hit. */
function send(url, headers, body, idempotencyKey) {
const options = {
method: "post",
contentType: "application/json",
headers: Object.assign({ "Idempotency-Key": idempotencyKey }, headers),
payload: JSON.stringify(body),
muteHttpExceptions: true,
};
let response = UrlFetchApp.fetch(url, options);
if (response.getResponseCode() === 429) {
const wait = Number(response.getHeaders()["Retry-After"] || 30);
Utilities.sleep(Math.min(wait, 60) * 1000);
response = UrlFetchApp.fetch(url, options);
}
return response;
}
/** A readable message: the API text, the failing fields, or "did you mean" suggestions for places. */
function describeError(data) {
const parts = [data.message || "Request failed"];
const details = data.details || {};
if (details.errors) {
Object.keys(details.errors).forEach((field) => parts.push(field + ": " + details.errors[field].join(" ")));
}
if (details.candidates && details.candidates.length) {
parts.push("Did you mean: " + details.candidates.map((c) => c.nameAr + " / " + c.nameEn).join(", ") + "?");
}
return parts.join(" | ");
}
function writeResult(sheet, rowNumber, values) {
sheet.getRange(rowNumber, FIRST_RESULT_COLUMN, 1, 4).setValues([values]);
SpreadsheetApp.flush();
}- مفتاح منع تكرار لكل صف، مبني من المرجع (
sheet-ORD-1001). إن توقف السكربت في المنتصف أو شغّلته مرة أخرى فلا تتكرر الصفوف التي أُنشئت: يعيد الـ API الرد الأول. والصف الذي فشل يمكن تصحيحه وإعادة إرساله بالمفتاح نفسه لأن المحاولات الفاشلة لا تُحفظ. - إن غيّرت صفاً بعد نجاحه وأفرغت رقم تتبعه لإعادة إرساله، يرد الـ API بـ
409 idempotency_key_reusedلأن الجسم تغيّر. استخدم مرجعاً جديداً لشحنة جديدة. - تُكتب الأخطاء رمزاً ورسالة. أخطاء التحقق تسرد الحقول الفاشلة (
recipient.phone: ...). والمكان غير المطابق يسرد أقرب المقترحات («Did you mean: جدة / Jeddah?») لتصحح الخلية. - حد المعدل. يسمح الـ API بـ 120 طلباً في الدقيقة لكل مفتاح. عند
429ينتظر السكربتRetry-Afterويحاول مرة ثانية. وللآلاف من الصفوف شغّله على دفعات. - حد وقت Apps Script. يتوقف التشغيل بعد دقائق قليلة. السكربت يتخطى الصفوف التي لها رقم تتبع، فأعد التشغيل فقط.
- أضف عموداً للبوليصة واستدعِ
GET /shipments/{trackingNumber}/labelلحفظ ملفات PDF في Drive. - حدّث عمود Status: مرّ على الصفوف التي لها رقم تتبع واستدعِ
GET /shipments/{trackingNumber}من مشغّل يومي، أو استقبل الـ Webhooks في تطبيق ويب منشور. - أضف عمود Quote يستدعي
POST /pricing/quoteقبل الإنشاء لمراجعة الأسعار أولاً.