JEISA-WEBAPP/pocketbase/pb_hooks/main.pb.js
2025-09-10 14:18:27 +02:00

77 lines
No EOL
3.6 KiB
JavaScript

/// <reference path="../pb_data/types.d.ts" />
onRecordAfterCreateRequest((e) => {
if (e.collection.name !== "book_out_records") {
return;
}
// It's generally safer to use onRecordAfterCreateSuccess to ensure the record is actually persisted
// However, for immediate feedback or if you need to modify the response, onRecordAfterCreateRequest can be used.
// For this example, we'll use onRecordAfterCreateSuccess to ensure data consistency.
// The actual email sending logic will be in onRecordAfterCreateSuccess.
// This hook is just to demonstrate where you might intercept the request.
}, "book_out_records");
onRecordAfterCreateSuccess((e) => {
if (e.collection.name !== "book_out_records") {
return;
}
const record = e.record;
// Fetch related customer and item details
$app.dao().findRecordById("customers", record.get("customer"))
.then((customer) => {
return $app.dao().findRecordById("stock_items", record.get("items"))
.then((item) => {
const customerName = customer.get("comapny_name");
const itemName = item.get("name");
const itemSku = item.get("sku");
const quantity = record.get("quantity");
const dateBookedOut = new Date(record.get("date_booked_out")).toLocaleString();
// Define the recipient email (e.g., an admin email or the customer's email if available)
// IMPORTANT: Replace 'your-admin-email@example.com' with your actual admin email or a dynamic customer email
const recipientEmail = 'your-admin-email@example.com';
const message = new MailerMessage({
from: {
address: $app.settings().meta.senderAddress,
name: $app.settings().meta.senderName,
},
to: [{address: recipientEmail}],
subject: `Stock Booked Out: ${itemName} (${itemSku})`,
html: `
<p>Dear Admin,</p>
<p>The following item has been booked out:</p>
<ul>
<li><strong>Customer:</strong> ${customerName}</li>
<li><strong>Item Name:</strong> ${itemName}</li>
<li><strong>SKU:</strong> ${itemSku}</li>
<li><strong>Quantity:</strong> ${quantity}</li>
<li><strong>Date Booked Out:</strong> ${dateBookedOut}</li>
</ul>
<p>Thank you.</p>
`,
text: `
Dear Admin,
The following item has been booked out:
Customer: ${customerName}
Item Name: ${itemName}
SKU: ${itemSku}
Quantity: ${quantity}
Date Booked Out: ${dateBookedOut}
Thank you.
`,
});
return $app.newMailClient().send(message);
});
})
.then(() => {
console.log("Book-out notification email sent successfully!");
})
.catch((err) => {
console.error("Failed to send book-out notification email:", err);
});
}, "book_out_records");