Waafir
هذه الصفحة ترجمة آلية في انتظار المراجعة البشرية. قد تحتوي على أخطاء.

الاستيراد المجمّع لشريط القروض عبر NDJSON غير المتزامن

توضّح هذه الوصفة تدفق الاستيعاب الأساسي لمحفظة قروض في Waafir: أرسل ملف JSON مفصولًا بأسطر جديدة (NDJSON) يحتوي صفًا واحدًا لكل كيان من كيانات شريط القروض إلى نقطة نهاية الاستيراد غير المتزامن، ثم استطلع حالة الاستيراد حتى ينتهي العامل.

متى تستخدم هذا التدفق

تدفق استيراد NDJSON غير المتزامن هو مسار الاستيعاب المعتمد لأي حجم غير ضئيل من الصفوف. وهو يتوسّع ليشمل الأحمال التاريخية المتراكمة التي تبلغ ملايين الصفوف، وهو التدفق نفسه المستخدم لعمليات الإرسال اليومية التزايدية. يستخدم دليل الوصفات استيرادًا من النوع loan في الأمثلة أدناه؛ ويقبل التدفق نفسه الأنواع borrower وscheduled_repayment وactual_payment وcollateral وcollateral_valuation — غيّر الحقل kind وبنية الصف، ويبقى كل ما عدا ذلك مطابقًا.

بنية التدفق

ثمة ثلاث خطوات يجب أن تنفّذها شيفرتك، وخطوة واحدة ينفّذها ملفك بينها:

  1. POST /api/v1/monitoring/loan/imports — صرّح بما أنت على وشك رفعه (النوع، واسم الملف، والحجم). تتضمن الاستجابة عنوان رفع ومعرّف الاستيراد.
  2. نفّذ PUT لمحتوى NDJSON إلى عنوان الرفع — يُخزَّن ملفك كما أُرسل، دون تغيير.
  3. POST /api/v1/monitoring/loan/imports/{id}/commit — أبلغ Waafir بانتهاء الرفع. ينتقل الاستيراد من pending_upload إلى queued، ويبدأ العامل معالجة الدفعات.
  4. GET /api/v1/monitoring/loan/imports/{id} — استطلع إلى أن تصبح قيمة status إحدى القيم succeeded أو partial أو failed أو cancelled.

الوصفة

# curl — bulk import flow (loan kind)
set -euo pipefail

PAT="${WAAFIR_PAT}"
BASE_URL="${WAAFIR_BASE_URL:-https://app.waafir.io}"
NDJSON_FILE="loans-2026-05-22.ndjson"

# Step 1 — start the import and capture the upload URL + import ID.
START=$(curl -fsS -X POST "${BASE_URL}/api/v1/monitoring/loan/imports" \
  -H "Authorization: Bearer ${PAT}" \
  -H "Content-Type: application/json" \
  -d "$(cat <<JSON
{
  "kind": "loan",
  "filename": "${NDJSON_FILE}",
  "sizeBytes": $(stat -c%s "${NDJSON_FILE}")
}
JSON
)")

IMPORT_ID=$(echo "$START" | jq -r .importId)
UPLOAD_URL=$(echo "$START" | jq -r .uploadUrl)

# Step 2 — PUT the NDJSON body to the upload URL. The `headers` field
# on the start response carries the headers the upload URL was signed
# with — apply them all, or the upload is rejected with a signature
# mismatch. At minimum `Content-Type: application/x-ndjson`.
HEADER_ARGS=$(echo "$START" | jq -r '.headers | to_entries[] | "-H \"\(.key): \(.value)\""')
eval curl -fsS -X PUT --data-binary @"\"${NDJSON_FILE}\"" $HEADER_ARGS "\"${UPLOAD_URL}\""

# Step 3 — commit so the worker enqueues the import.
curl -fsS -X POST "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}/commit" \
  -H "Authorization: Bearer ${PAT}"

# Step 4 — poll status until it reaches a terminal value.
while :; do
  STATUS=$(curl -fsS "${BASE_URL}/api/v1/monitoring/loan/imports/${IMPORT_ID}" \
    -H "Authorization: Bearer ${PAT}" | jq -r .status)
  echo "import ${IMPORT_ID}: ${STATUS}"
  case "${STATUS}" in
    succeeded|partial|failed|cancelled) break ;;
  esac
  sleep 5
done
// TypeScript — bulk import flow (loan kind)
import { readFileSync, statSync } from "node:fs";

const PAT = process.env.WAAFIR_PAT!;
const BASE_URL = process.env.WAAFIR_BASE_URL ?? "https://app.waafir.io";
const NDJSON_FILE = "loans-2026-05-22.ndjson";

const headers = { Authorization: `Bearer ${PAT}`, "Content-Type": "application/json" };

// Step 1 — start the import.
const startRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports`, {
    method: "POST",
    headers,
    body: JSON.stringify({
        kind: "loan",
        filename: NDJSON_FILE,
        sizeBytes: statSync(NDJSON_FILE).size,
    }),
});
if (!startRes.ok) throw new Error(`start failed: ${startRes.status} ${await startRes.text()}`);
const { importId, uploadUrl, headers: uploadHeaders } = (await startRes.json()) as {
    importId: string;
    uploadUrl: string;
    headers: Record<string, string>;
};

// Step 2 — PUT the NDJSON body to the upload URL with the headers
// the URL was signed against. Skipping them gets the upload
// rejected with a signature mismatch.
const putRes = await fetch(uploadUrl, {
    method: "PUT",
    headers: uploadHeaders,
    body: readFileSync(NDJSON_FILE),
});
if (!putRes.ok) throw new Error(`upload failed: ${putRes.status}`);

// Step 3 — commit.
const commitRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports/${importId}/commit`, {
    method: "POST",
    headers: { Authorization: `Bearer ${PAT}` },
});
if (!commitRes.ok) throw new Error(`commit failed: ${commitRes.status} ${await commitRes.text()}`);

// Step 4 — poll.
const TERMINAL = new Set(["succeeded", "partial", "failed", "cancelled"]);
while (true) {
    const statusRes = await fetch(`${BASE_URL}/api/v1/monitoring/loan/imports/${importId}`, {
        headers: { Authorization: `Bearer ${PAT}` },
    });
    const body = (await statusRes.json()) as { status: string };
    console.log(`import ${importId}: ${body.status}`);
    if (TERMINAL.has(body.status)) break;
    await new Promise((r) => setTimeout(r, 5_000));
}
# python — bulk import flow (loan kind)
import os
import time
import requests
from pathlib import Path

PAT = os.environ["WAAFIR_PAT"]
BASE_URL = os.environ.get("WAAFIR_BASE_URL", "https://app.waafir.io")
NDJSON_FILE = Path("loans-2026-05-22.ndjson")

headers = {"Authorization": f"Bearer {PAT}", "Content-Type": "application/json"}

# Step 1 — start the import.
start = requests.post(
    f"{BASE_URL}/api/v1/monitoring/loan/imports",
    headers=headers,
    json={
        "kind": "loan",
        "filename": NDJSON_FILE.name,
        "sizeBytes": NDJSON_FILE.stat().st_size,
    },
    timeout=30,
)
start.raise_for_status()
payload = start.json()
import_id = payload["importId"]
upload_url = payload["uploadUrl"]
upload_headers = payload["headers"]  # signed-into the URL; must be sent on PUT

# Step 2 — PUT the NDJSON body to the upload URL with the headers
# the URL was signed against. Skipping them gets the upload
# rejected with a signature mismatch.
with NDJSON_FILE.open("rb") as fh:
    put = requests.put(upload_url, data=fh, headers=upload_headers, timeout=300)
    put.raise_for_status()

# Step 3 — commit.
commit = requests.post(
    f"{BASE_URL}/api/v1/monitoring/loan/imports/{import_id}/commit",
    headers={"Authorization": f"Bearer {PAT}"},
    timeout=30,
)
commit.raise_for_status()

# Step 4 — poll.
terminal = {"succeeded", "partial", "failed", "cancelled"}
while True:
    status = requests.get(
        f"{BASE_URL}/api/v1/monitoring/loan/imports/{import_id}",
        headers={"Authorization": f"Bearer {PAT}"},
        timeout=30,
    ).json()
    print(f"import {import_id}: {status['status']}")
    if status["status"] in terminal:
        break
    time.sleep(5)

ما يجب التحقق منه

عندما تبلغ status القيمة succeeded، يكون كل صف في ملف NDJSON قد وصل كصف حيّ. وتعرض الاستجابة أيضًا rowCountProcessed وrowCountSucceeded وrowCountFailed؛ وفي التشغيل النظيف يساوي عدد الصفوف الناجحة عدد صفوف ملفك.

عندما تبلغ status القيمة partial، تكون بعض الصفوف قد وصلت وبعضها لم يصل. انتقل إلى وصفة فحص الإخفاق الجزئي لتصفّح الأخطاء لكل صف وتقرير ما إذا كنت ستصلح الصفوف المخالفة وتعيد إرسالها، أم تقبل النتيجة الجزئية.

تعني الحالة failed أنه لم يصل أي صف. يحمل الحقل errorSummary.samples حمولات الأخطاء العشرة الأولى؛ ويمكن الاستعلام عن البقية عبر نقطة نهاية الأخطاء المقسّمة إلى صفحات الموضّحة في وصفة الإخفاق الجزئي.