I run a research lab. I'm setting up Airtable to manage purchase requests and inventory.
I have two tables:
1. Purchase Catalog, with fields 'Item' and 'Current Stock'
2. Order Line Items, with relevant fields fields "Quantity' and 'Status'.
'Order Line Items' is a table that represent specific instances of wanting to puchase something. Purchase Catalog represents different items one would purchase. The two tables are linked.
When we received an item, I will change the status in 'Order Line Items' to 'Received', at which point, I want the field 'Quantity' (from Order Line Items) to add to the value in field 'Current Stock' (from Purchase Catalog).
I asked ChatGPT to make me a script and it looks like it would work but it's not doing anything to change 'Current Stock'. Could someone help me figure out how to do what I'm seeking?
// Define input variables
let tableLineItems = base.getTable("Order Line Items");
let tableCatalog = base.getTable("Purchase Catalog");
// Get the record ID from the automation trigger
let recordId = input.config().recordId;
// Field names
let statusField = "Status";
let quantityField = "Quantity";
let catalogLinkField = "Purchase Catalog";
let currentStockField = "Current Stock";
// Fetch the specific record from the Order Line Items table
let record = await tableLineItems.selectRecordAsync(recordId);
// Log the record details for debugging
console.log(`Record ID: ${recordId}`);
console.log(`Status: ${record.getCellValue(statusField)}`);
console.log(`Quantity: ${record.getCellValue(quantityField)}`);
console.log(`Linked Catalog Record: ${JSON.stringify(record.getCellValue(catalogLinkField))}`);
// Ensure the record exists and the status is "Received"
if (record && record.getCellValue(statusField) === "Received") {
let quantity = record.getCellValue(quantityField);
let catalogRecord = record.getCellValue(catalogLinkField);
// Check if there is a linked record in Purchase Catalog and a valid quantity
if (catalogRecord && quantity) {
let catalogRecordId = catalogRecord[0].id;
// Fetch the linked record from Purchase Catalog
let catalogRecordData = await tableCatalog.selectRecordAsync(catalogRecordId);
// Log the current stock before updating
console.log(`Current Stock before update: ${catalogRecordData.getCellValue(currentStockField)}`);
if (catalogRecordData) {
let currentStock = catalogRecordData.getCellValue(currentStockField) || 0;
// Update the Current Stock in Purchase Catalog
await tableCatalog.updateRecordAsync(catalogRecordId, {
[currentStockField]: currentStock + quantity
});
// Log the updated stock value
console.log(`Updated Stock: ${currentStock + quantity}`);
}
}
}