📜 2. โค้ด Google Apps Script (Code.gs) พร้อมใช้งาน
รองรับการสร้างหัวตารางอัตโนมัติ + อัปโหลดสลิปเข้า Google Drive + ตั้งชื่อไฟล์สลิปตามลำดับ เช่น "1 ธนิศา 399"
/**
* ระบบรับออเดอร์ "น้ำพริกแม่วิภา" เชื่อมต่อ Google Sheet + อัปโหลดสลิปลง Google Drive
* ตั้งชื่อไฟล์สลิปอัตโนมัติตามบรีฟ: [ลำดับ] [ชื่อลูกค้า] [ยอดโอน] เช่น "1 ธนิศา 399"
*/
const FOLDER_NAME = "Slips_น้ำพริกแม่วิภา";
const SHEET_NAME = "Orders";
function doPost(e) {
const lock = LockService.getScriptLock();
lock.tryLock(10000);
try {
const data = JSON.parse(e.postData.contents);
const ss = SpreadsheetApp.getActiveSpreadsheet();
let sheet = ss.getSheetByName(SHEET_NAME);
// สร้างชีทและหัวตารางอัตโนมัติหากยังไม่มี
if (!sheet) {
sheet = ss.insertSheet(SHEET_NAME);
sheet.appendRow([
"ลำดับ",
"เลขออเดอร์",
"วัน-เวลาที่สั่ง",
"ชื่อลูกค้าผู้สั่ง",
"เบอร์โทรศัพท์",
"ที่อยู่จัดส่ง",
"รายการสินค้าที่สั่ง",
"ยอดชำระสุทธิ (บาท)",
"วิธีชำระเงิน (โอน/COD)",
"ชื่อผู้โอน",
"ชื่อไฟล์สลิป",
"ลิงก์รูปสลิป (Google Drive)",
"หมายเหตุ",
"สถานะออเดอร์"
]);
sheet.getRange(1, 1, 1, 14).setFontWeight("bold").setBackground("#5B1906").setFontColor("#FDF7E2");
}
// คำนวณลำดับที่กรอกในชีท (แถวที่ 2 = ลำดับที่ 1)
const rowIndex = sheet.getLastRow();
const customerShortName = (data.customerName || "ลูกค้า").trim().split(" ")[0].replace(/^คุณ/, "");
const slipStandardName = rowIndex + " " + customerShortName + " " + data.totalAmount;
// อัปโหลดรูปสลิปขึ้น Google Drive (ถ้าลูกค้าแนบมา)
let slipDriveUrl = "ไม่ได้แนบสลิป / รอส่งทางไลน์";
if (data.slipBase64 && data.slipBase64.indexOf("base64,") !== -1) {
let folders = DriveApp.getFoldersByName(FOLDER_NAME);
let folder = folders.hasNext() ? folders.next() : DriveApp.createFolder(FOLDER_NAME);
const parts = data.slipBase64.split("base64,");
const contentType = parts[0].split(":")[1].split(";")[0];
const ext = contentType.indexOf("png") !== -1 ? ".png" : ".jpg";
const decoded = Utilities.base64Decode(parts[1]);
const blob = Utilities.newBlob(decoded, contentType, slipStandardName + ext);
const file = folder.createFile(blob);
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
slipDriveUrl = file.getUrl();
}
// บันทึกข้อมูลลงแถวใหม่ใน Google Sheet
sheet.appendRow([
rowIndex,
data.orderId,
new Date().toLocaleString("th-TH", { timeZone: "Asia/Bangkok" }),
data.customerName,
"'" + data.customerPhone,
data.customerAddress,
data.itemsSummary,
data.totalAmount,
data.paymentMethod,
data.payerName || data.customerName,
slipStandardName,
slipDriveUrl,
data.note || "-",
data.paymentMethod === "COD" ? "รอจัดส่ง (COD)" : "รอตรวจสอบยอดโอน"
]);
return ContentService.createTextOutput(JSON.stringify({
status: "success",
seqNumber: rowIndex,
orderId: data.orderId,
slipName: slipStandardName,
slipUrl: slipDriveUrl
})).setMimeType(ContentService.MimeType.JSON);
} catch (err) {
return ContentService.createTextOutput(JSON.stringify({
status: "error",
message: err.toString()
})).setMimeType(ContentService.MimeType.JSON);
} finally {
lock.releaseLock();
}
}