GROperator

جارٍ التحميل…

English

إنشاء شحنة باستخدام API Key

تنشئ الشحنات بمفتاح API وسرّه يُرسلان في الترويستين X-API-Key وX-API-Secret: دون تسجيل دخول ودون رمز مستخدم. تشرح هذه الصفحة ذلك بمثال كامل: جدول Google Sheets ينشئ الشحنات بالجملة.

يحوّل السكربت الجدول إلى منشئ شحنات بالجملة. يقرأ كل صف لا يحمل رقم تتبع بعد، وينشئ الشحنة عبر الـ API، ويكتب في الصف رقم التتبع والحالة ورابط البوليصة، أو رمز الخطأ ورسالته لتصحح الصف وتشغّل السكربت من جديد.

يستخدم مفتاح API بالنطاقين shipments:write (للإنشاء) وshipments:read (لقراءة الشحنة عند الإعادة ولتنزيل البوليصة). المفتاح يبقى في خصائص السكربت الخاصة: لا يوجد في أي خلية. أنشئ المفتاح كما في تفعيل الواجهة.

أنشئ ورقة اسمها Shipments. الصف الأول للعناوين؛ والبيانات من الصف الثاني. يجد السكربت كل عمود من نص عنوانه (حالة الأحرف لا تهم)، فلا يهم ترتيب الأعمدة. ويمكن ترك الأعمدة الاختيارية خارج الورقة.

العنوان ملاحظات
Reference رقم طلبك. مطلوب. يصبح reference الشحنة ومفتاح منع التكرار
Merchant اختياري. معرّف التاجر أو اسم حسابه بدقة. عند تعبئته تُرسل الشحنة باسم هذا التاجر ويكون عنوانه الرئيسي المحفوظ هو الاستلام
Sender name وSender phone مطلوبان عندما يكون Merchant فارغاً (مرسل خارجي لمرة واحدة). نسّق عمود الهاتف كـ نص عادي
Pickup city وPickup district وPickup address line وPickup short address مطلوبة عندما يكون Merchant فارغاً، عدا العنوان المختصر فهو مطلوب لعناوين الاستلام في السعودية. في صف التاجر، تعبئة Pickup city ترسل عنوان الاستلام هذا بدلاً من العنوان المحفوظ. نسّق عمود العنوان المختصر كـ نص عادي
Recipient name مطلوب
Recipient phone مطلوب. نسّق العمود كـ نص عادي حتى تبقى الأصفار الأولى
City اسم عربي أو إنجليزي. مطلوب
District اسم عربي أو إنجليزي. مطلوب
Address line الشارع والمبنى ومعلم. مطلوب
Short address العنوان الوطني المختصر مثل RNBA6769. مطلوب للمستلمين في السعودية. نص عادي
Weight kg وLength cm وWidth cm وHeight cm مطلوبة، أرقام
COD amount اختياري، الافتراضي 0
Description اختياري
Tracking number وStatus وError code وError message وLabel يكتبها السكربت. إن غاب عنوان منها أضافه السكربت بعد آخر عمود. Label رابط ملف PDF للبوليصة في Google Drive: افتحه للتنزيل أو الطباعة

العناوين التي يحتاجها السكربت في كل ورقة هي Reference وRecipient name وRecipient phone وCity وDistrict وAddress line وWeight kg وLength cm وWidth cm وHeight cm. إن غاب أحدها يتوقف السكربت ويخبرك بالناقص.

  • صف تاجر (Merchant معبّأ). الشحنة تتبع هذا التاجر ويستلم المندوب من عنوانه الرئيسي المحفوظ. عبّئ Pickup city وبقية أعمدة الاستلام فقط عندما يجب استلام هذه الشحنة من مكان آخر.
  • صف مرسل خارجي (Merchant فارغ). لشخص أو منشأة ليست من تجارك. تُرسل الشحنة كـ مرسل مخصص وتُسجَّل على حساب الزبائن المشترك للشركة. تحتاج اسم المرسل وهاتفه وعنوان استلام كاملاً.

لا يرسل السكربت فرعاً أبداً. يختار النظام الفرع الذي يغطي عنوان الاستلام.

الأسماء العربية مثل جده وحي البرية تعمل: اختلافات الإملاء مقبولة (الأماكن بالاسم). يرسل السكربت الدولة SA للاستلام وللمستلم؛ غيّر الثابت COUNTRY في أعلى السكربت إن شحنت إلى غيرها.

بعد إنشاء كل شحنة ينزّل السكربت بوليصتها، وهي بوليصة الشحن بمقاس 100×150 مم بصيغة PDF، ويحفظها في مجلد Google Drive اسمه LastMile labels (يُنشأ في أول تشغيل) باسم <trackingNumber>.pdf. ويوضع الرابط في عمود Label. رابط مباشر إلى الـ API لن يُفتح لأن الطلب يحتاج ترويستي المفتاح، ولذلك يحفظ السكربت الملفات في Drive. ويطلب أول تشغيل إذن Google Drive أيضاً.

إن تعذّر تنزيل البوليصة تبقى الشحنة منشأة ويُكتب الخطأ في Error code وError message بالبادئة Label:. استخدم عنصر القائمة LastMile ثم Download missing labels لجلب بوليصات كل صف له رقم تتبع وعمود Label فيه فارغ. ويشمل ذلك الجداول التي عبّأتها قبل وجود عمود Label.

افتح Extensions ثم Apps Script والصق السكربت واحفظ، ثم اضبط ثلاث خصائص للسكربت (Project Settings): LASTMILE_API_URL وLASTMILE_API_KEY وLASTMILE_API_SECRET. أعد تحميل الجدول فتظهر قائمة LastMile. أول تشغيل يطلب منك تفويض السكربت.

Apps Script
/**
 * 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 and labels). The first run also asks
 * for permission to use Google Drive: label PDFs are saved there.
 *
 * Sheet "Shipments", row 1 = headers, data from row 2. Columns are found by header text (any order, any case).
 * Format the phone and short-address columns as Plain text.
 *   Required headers: Reference, Recipient name, Recipient phone, City, District, Address line,
 *                     Weight kg, Length cm, Width cm, Height cm
 *   Optional headers: Merchant, Sender name, Sender phone, Pickup city, Pickup district, Pickup address line,
 *                     Pickup short address, Short address, COD amount, Description
 *   Written by the script (added after the last column when missing): Tracking number, Status, Error code, Error message, Label
 *   Label is a link to the shipping label PDF in the Drive folder LABEL_FOLDER.
 *
 * Two kinds of rows:
 *   Merchant filled  -> sent for that merchant; its primary saved address is the pickup. Fill Pickup city (and the
 *                       other Pickup columns) only to use a different pickup address.
 *   Merchant empty   -> one-off external sender: Sender name, Sender phone, Pickup city, Pickup district and
 *                       Pickup address line are required.
 * The script never sends a branch: the system picks the branch that covers the pickup address.
 * Menu: "Create shipments" creates shipments and saves their labels; "Download missing labels" saves labels for rows
 * that have a tracking number and an empty Label cell.
 */
const SHEET_NAME = "Shipments";
const LABEL_FOLDER = "LastMile labels";
const COUNTRY = "SA";
const REQUIRED = ["Reference", "Recipient name", "Recipient phone", "City", "District", "Address line",
  "Weight kg", "Length cm", "Width cm", "Height cm"];
const OPTIONAL = ["Merchant", "Sender name", "Sender phone", "Pickup city", "Pickup district", "Pickup address line",
  "Pickup short address", "Short address", "COD amount", "Description"];
const RESULTS = ["Tracking number", "Status", "Error code", "Error message", "Label"];

function onOpen() {
  SpreadsheetApp.getUi().createMenu("LastMile").addItem("Create shipments", "createShipments")
    .addItem("Download missing labels", "downloadMissingLabels").addToUi();
}

/** Reads the settings and the header row; stops with an alert when a required header is missing. */
function openSheet() {
  const props = PropertiesService.getScriptProperties();
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
  if (!sheet) {
    SpreadsheetApp.getUi().alert('Create a sheet named "' + SHEET_NAME + '" first.');
    return null;
  }
  const titles =sheet.getRange(1, 1, 1, Math.max(sheet.getLastColumn(), 1)).getDisplayValues()[0].map((t) => String(t).trim().toLowerCase());
  const columnOf = (title) => titles.indexOf(title.toLowerCase()); // 0-based, -1 when absent

  const absent = REQUIRED.filter((title) => columnOf(title) < 0);
  if (absent.length) {
    SpreadsheetApp.getUi().alert("Add these headers to row 1: " + absent.join(", "));
    return null;
  }

  // Result columns: append the missing ones after the last used column.
  RESULTS.forEach((title) => {
    if (columnOf(title) < 0) {
      titles.push(title.toLowerCase());
      if (titles.length > sheet.getMaxColumns()) sheet.insertColumnAfter(sheet.getMaxColumns());
      sheet.getRange(1, titles.length).setValue(title);
    }
  });

  let folder = null; // looked up once per run, created when absent
  return {
    sheet, columnOf, titles,
    api: props.getProperty("LASTMILE_API_URL") + "/api/public/v1",
    headers: {
      "X-API-Key": props.getProperty("LASTMILE_API_KEY"),
      "X-API-Secret": props.getProperty("LASTMILE_API_SECRET"),
      "Accept-Language": "en",
    },
    labelFolder: () => {
      if (!folder) {
        const found = DriveApp.getFoldersByName(LABEL_FOLDER);
        folder = found.hasNext() ? found.next() : DriveApp.createFolder(LABEL_FOLDER);
      }
      return folder;
    },
  };
}

function createShipments() {
  const ctx = openSheet();
  if (!ctx) return;
  const { sheet, columnOf, titles, api, headers } = ctx;

  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, titles.length).getDisplayValues();

  rows.forEach((row, index) => {
    const get = (title) => {
      const column = columnOf(title);
      return column < 0 ? "" : String(row[column]).trim();
    };
    if (!get("Reference") || get("Tracking number")) return;

    const merchant = get("Merchant");
    const external = !merchant;
    const needed = REQUIRED.slice(1).concat(external ? ["Sender name", "Sender phone", "Pickup city", "Pickup district", "Pickup address line"] : []);
    const missing = needed.filter((title) => !get(title));
    if (missing.length) {
      writeResult(ctx, index + 2, { code: "missing_fields", message: "Fill in: " + missing.join(", ") });
      return;
    }

    const body = {
      reference: get("Reference"),
      sender: external
        ? { type: "custom", name: get("Sender name"), phone: get("Sender phone") }
        : { type: "merchant", merchant: merchant },
      recipient: {
        country: COUNTRY,
        city: get("City"),
        district: get("District"),
        addressLine: get("Address line"),
        shortAddress: get("Short address") || undefined,
        name: get("Recipient name"),
        phone: get("Recipient phone"),
      },
      parcel: {
        weightKg: Number(get("Weight kg")),
        lengthCm: Number(get("Length cm")),
        widthCm: Number(get("Width cm")),
        heightCm: Number(get("Height cm")),
        description: get("Description") || undefined,
      },
      payment: { codAmount: Number(get("COD amount") || 0) },
    };
    // External senders always need a pickup; a merchant row sends one only to override the saved address.
    if (external || get("Pickup city")) {
      body.pickup = {
        country: COUNTRY,
        city: get("Pickup city"),
        district: get("Pickup district"),
        addressLine: get("Pickup address line"),
        shortAddress: get("Pickup short address") || undefined,
      };
    }

    // One key per row, derived from the reference: running the script twice never creates a second shipment.
    const idempotencyKey = ("sheet-" + body.reference).replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 128);
    const response = send("post", api + "/shipments", headers, body, idempotencyKey);
    const data = parseJson(response);

    if (response.getResponseCode() === 201 || response.getResponseCode() === 200) {
      // The shipment is saved first: a label problem never hides a created shipment.
      writeResult(ctx, index + 2, { tracking: data.trackingNumber, status: data.statusLabelEn });
      saveLabel(ctx, index + 2, data.trackingNumber);
    } else {
      writeResult(ctx, index + 2, { code: data.code || "http_" + response.getResponseCode(), message: describeError(data) });
    }
  });
}

/** Request with one automatic wait when the rate limit (120 requests per minute) is hit. */
function send(method, url, headers, body, idempotencyKey) {
  const options = { method: method, headers: Object.assign({}, headers), muteHttpExceptions: true };
  if (body) {
    options.contentType = "application/json";
    options.payload = JSON.stringify(body);
    options.headers["Idempotency-Key"] = idempotencyKey;
  }
  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;
}

/** Saves the label PDF in Drive (reusing a file of the same name) and writes its link to the Label cell. */
function saveLabel(ctx, rowNumber, trackingNumber) {
  const folder = ctx.labelFolder();
  const name = trackingNumber + ".pdf";
  const existing = folder.getFilesByName(name);
  if (existing.hasNext()) {
    writeResult(ctx, rowNumber, { label: existing.next().getUrl() });
    return;
  }
  const response = send("get", ctx.api + "/shipments/" + encodeURIComponent(trackingNumber) + "/label", ctx.headers);
  if (response.getResponseCode() !== 200) {
    const data = parseJson(response);
    writeResult(ctx, rowNumber, { code: data.code || "http_" + response.getResponseCode(), message: "Label: " + describeError(data) });
    return;
  }
  const file = folder.createFile(response.getBlob().setName(name));
  writeResult(ctx, rowNumber, { label: file.getUrl() });
}

/** Saves the label for every row that has a tracking number but no Label yet. */
function downloadMissingLabels() {
  const ctx = openSheet();
  if (!ctx) return;
  const { sheet, columnOf, titles } = ctx;
  const lastRow = sheet.getLastRow();
  if (lastRow < 2) return;
  const rows = sheet.getRange(2, 1, lastRow - 1, titles.length).getDisplayValues();
  rows.forEach((row, index) => {
    const tracking = String(row[columnOf("Tracking number")]).trim();
    if (tracking && !String(row[columnOf("Label")]).trim()) saveLabel(ctx, index + 2, tracking);
  });
}

/** The JSON body, or an empty object when the answer is not JSON (a proxy error page, for example). */
function parseJson(response) {
  try {
    return JSON.parse(response.getContentText() || "{}") || {};
  } catch (e) {
    return {};
  }
}

/** 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(" | ");
}

/** Writes only the result cells that are given, found by header text. A tracking number or label clears old errors. */
function writeResult(ctx, rowNumber, result) {
  const cells = { "Tracking number": result.tracking, "Status": result.status, "Error code": result.code,
    "Error message": result.message, "Label": result.label };
  if (result.code === undefined && (result.tracking !== undefined || result.label !== undefined)) {
    cells["Error code"] = "";
    cells["Error message"] = "";
  }
  Object.keys(cells).forEach((title) => {
    if (cells[title] !== undefined) ctx.sheet.getRange(rowNumber, ctx.columnOf(title) + 1).setValue(cells[title]);
  });
  SpreadsheetApp.flush();
}
  • مفتاح منع تكرار لكل صف، مبني من المرجع (sheet-ORD-1001). إن توقف السكربت في المنتصف أو شغّلته مرة أخرى فلا تتكرر الصفوف التي أُنشئت: يعيد الـ API الرد الأول. والصف الذي فشل يمكن تصحيحه وإعادة إرساله بالمفتاح نفسه لأن المحاولات الفاشلة لا تُحفظ.
  • إن غيّرت صفاً بعد نجاحه وأفرغت رقم تتبعه لإعادة إرساله، يرد الـ API بـ 409 idempotency_key_reused لأن الجسم تغيّر. استخدم مرجعاً جديداً لشحنة جديدة.
  • تُكتب الأخطاء رمزاً ورسالة. أخطاء التحقق تسرد الحقول الفاشلة (recipient.phone: ...). والمكان غير المطابق يسرد أقرب المقترحات («Did you mean: جدة / Jeddah?») لتصحح الخلية.
  • حد المعدل. يسمح الـ API بـ 120 طلباً في الدقيقة لكل مفتاح. عند 429 ينتظر السكربت Retry-After ويحاول مرة ثانية. وللآلاف من الصفوف شغّله على دفعات.
  • حد وقت Apps Script. يتوقف التشغيل بعد دقائق قليلة. السكربت يتخطى الصفوف التي لها رقم تتبع، فأعد التشغيل فقط.
  • حدّث عمود Status: مرّ على الصفوف التي لها رقم تتبع واستدعِ GET /shipments/{trackingNumber} من مشغّل يومي، أو استقبل الـ Webhooks في تطبيق ويب منشور.
  • أضف عمود Quote يستدعي POST /pricing/quote قبل الإنشاء لمراجعة الأسعار أولاً.