import { pushover } from "https://esm.town/v/harper/pushover";
import { ShopifyProductSearch } from "https://esm.town/v/harper/ShopifyProductSearch";
import { sqlite } from "https://esm.town/v/std/sqlite?v=4";
async function addProduct(id, title, url, priceAmount, priceCurrencyCode) {
console.debug("Adding product", { id, title, url, priceAmount, priceCurrencyCode });
const res = await sqlite.execute({
sql: `INSERT OR IGNORE INTO products (id, title, url, price_amount, price_currencyCode)
VALUES (:id, :title, :url, :price_amount, :price_currencyCode)`,
args: {
id,
title,
url,
price_amount: priceAmount,
price_currencyCode: priceCurrencyCode,
},
});
const productAdded = res.rowsAffected > 0;
if (productAdded) {
console.debug("Product inserted successfully.");
} else {
console.debug("Product already exists. Skipped insertion.");
}
return productAdded;
}
async function sendNewProductMessage(products) {
if (!products || products.length === 0) {
console.log("No new products to send.");
return;
}
console.log("Sending new product messages...");
const title = "New Products Posted";
let message = `${title}\n\n`;
for (const product of products) {
const { id, title, url, priceAmount, priceCurrencyCode } = product;
message += `${title} for $${priceAmount} ${priceCurrencyCode}\n${url}\n\n`;
}
await pushover({
token: Deno.env.get("PUSHOVER_TOKEN"),
user: Deno.env.get("PUSHOVER_KEY"),
title: title,
message: message,
});
}
export default async function(interval: Interval) {
const brokerId = Deno.env.get("SHOPIFY_STORE_ID");
const first = 30;
const products = await ShopifyProductSearch(brokerId, first);
if (!products) return;
try {
await sqlite.execute(`
CREATE TABLE IF NOT EXISTS products (
id TEXT PRIMARY KEY,
title TEXT,
url TEXT,
price_amount TEXT,
price_currencyCode TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
} catch (error) {
console.error("Error creating products table:", error);
return;
}
const newProducts = [];
for (const product of products) {
const { id, title, url, priceAmount, priceCurrencyCode } = product;
const result = await addProduct(id, title, url, priceAmount, priceCurrencyCode);
if (result) {
newProducts.push(product);
}
}
await sendNewProductMessage(newProducts);
console.log(`Found ${products.length} products. Inserted ${newProducts.length} products.`);
}