File size: 3,751 Bytes
5054581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const SPREADSHEET_ID = "18vKc9qAKo8htCipBXxr2Uy3zgYS_k3qlUdlAWkKMeIA";
const SHEET_NAME = "الورقة1";
const EDITABLE_HEADERS = ["الاسم", "المسمى الوظفي", "المسمى الوظيفي", "البريد الإلكتروني", "رقم التواصل"];

function doGet(e) {
  return handleRequest_(e);
}

function doPost(e) {
  return handleRequest_(e);
}

function handleRequest_(e) {
  try {
    const payload = parsePayload_(e);
    const action = String(payload.action || e.parameter.action || "read").toLowerCase();
    if (action === "read" || action === "getdata" || action === "list") {
      return json_({ ok: true, ...readSheet_() });
    }
    if (action === "update" || action === "save") {
      return json_(updateRow_(payload));
    }
    return json_({ ok: false, message: "إجراء غير معروف." });
  } catch (error) {
    return json_({ ok: false, message: error.message || String(error) });
  }
}

function parsePayload_(e) {
  if (!e) return {};
  if (e.postData && e.postData.contents) {
    try {
      return JSON.parse(e.postData.contents);
    } catch (error) {
      if (e.parameter && e.parameter.payload) {
        return JSON.parse(e.parameter.payload);
      }
    }
  }
  if (e.parameter && e.parameter.payload) {
    return JSON.parse(e.parameter.payload);
  }
  return e.parameter || {};
}

function getSheet_() {
  const spreadsheet = SpreadsheetApp.openById(SPREADSHEET_ID);
  const sheet = spreadsheet.getSheetByName(SHEET_NAME) || spreadsheet.getSheets()[0];
  if (!sheet) throw new Error("لم يتم العثور على ورقة بيانات داخل Google Sheet.");
  return sheet;
}

function readSheet_() {
  const sheet = getSheet_();
  const lastRow = sheet.getLastRow();
  const lastColumn = sheet.getLastColumn();
  if (lastRow < 1 || lastColumn < 1) {
    return { sheetName: sheet.getName(), headers: [], rows: [] };
  }
  const values = sheet.getRange(1, 1, lastRow, lastColumn).getDisplayValues();
  const headers = values[0].map((header) => String(header || "").trim());
  const rows = values.slice(1)
    .map((row, index) => {
      const item = { rowNumber: index + 2 };
      headers.forEach((header, columnIndex) => {
        if (header) item[header] = row[columnIndex] || "";
      });
      return item;
    })
    .filter((row) => headers.some((header) => header && String(row[header] || "").trim()));
  return { sheetName: sheet.getName(), headers, rows };
}

function updateRow_(payload) {
  const sheet = getSheet_();
  const data = readSheet_();
  const headers = data.headers;
  const headerIndex = {};
  headers.forEach((header, index) => {
    headerIndex[header] = index + 1;
  });

  const rowNumber = Number(payload.rowNumber || payload.rowIndex);
  if (!rowNumber || rowNumber < 2 || rowNumber > sheet.getLastRow()) {
    throw new Error("رقم الصف غير صحيح، ولن يتم إنشاء صف جديد.");
  }

  const updates = typeof payload.updates === "string" ? JSON.parse(payload.updates) : (payload.updates || {});
  const allowedColumns = Object.keys(updates).filter((header) => {
    return EDITABLE_HEADERS.indexOf(header) !== -1 && headerIndex[header];
  });
  if (!allowedColumns.length) {
    throw new Error("لا توجد أعمدة مسموح بتحديثها في الطلب.");
  }

  allowedColumns.forEach((header) => {
    sheet.getRange(rowNumber, headerIndex[header]).setValue(updates[header] || "");
  });

  return {
    ok: true,
    success: true,
    rowNumber,
    updatedHeaders: allowedColumns,
    message: "تم تحديث الصف نفسه بنجاح.",
  };
}

function json_(payload) {
  return ContentService
    .createTextOutput(JSON.stringify(payload))
    .setMimeType(ContentService.MimeType.JSON);
}