diff --git a/day6/app.js b/day6/app.js index 97a1728..bacdb2a 100644 --- a/day6/app.js +++ b/day6/app.js @@ -1,11 +1,13 @@ -var createError = require('http-errors'); -var express = require('express'); -var path = require('path'); -var cookieParser = require('cookie-parser'); -var logger = require('morgan'); +var createError = require("http-errors"); +var express = require("express"); +var path = require("path"); +var cookieParser = require("cookie-parser"); +var logger = require("morgan"); -var indexRouter = require('./routes/index'); -var usersRouter = require('./routes/users'); +var indexRouter = require("./routes/index"); +var usersRouter = require("./routes/users"); + +require("./cronJobs/shopifyCustomerSync"); const db = require("./models"); var cors = require("cors"); @@ -13,17 +15,17 @@ var cors = require("cors"); var app = express(); app.set("db", db); // view engine setup -app.set('views', path.join(__dirname, 'views')); -app.set('view engine', 'jade'); +app.set("views", path.join(__dirname, "views")); +app.set("view engine", "jade"); app.use(cors()); -app.use(logger('dev')); +app.use(logger("dev")); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); -app.use(express.static(path.join(__dirname, 'public'))); +app.use(express.static(path.join(__dirname, "public"))); -app.use('/', indexRouter); -app.use('/users', usersRouter); +app.use("/", indexRouter); +app.use("/users", usersRouter); // catch 404 and forward to error handler app.use(function (req, res, next) { @@ -34,11 +36,11 @@ app.use(function (req, res, next) { app.use(function (err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; - res.locals.error = req.app.get('env') === 'development' ? err : {}; + res.locals.error = req.app.get("env") === "development" ? err : {}; // render the error page res.status(err.status || 500); - res.render('error'); + res.render("error"); }); module.exports = app; diff --git a/day6/bin/www b/day6/bin/www index cd1a62f..99872f2 100755 --- a/day6/bin/www +++ b/day6/bin/www @@ -4,16 +4,16 @@ * Module dependencies. */ -var app = require('../app'); -var debug = require('debug')('day-1:server'); -var http = require('http'); +var app = require("../app"); +var debug = require("debug")("day-1:server"); +var http = require("http"); /** * Get port from environment and store in Express. */ -var port = normalizePort(process.env.PORT || '3000'); -app.set('port', port); +var port = normalizePort(process.env.PORT || "3000"); +app.set("port", port); /** * Create HTTP server. @@ -26,8 +26,8 @@ var server = http.createServer(app); */ server.listen(port); -server.on('error', onError); -server.on('listening', onListening); +server.on("error", onError); +server.on("listening", onListening); /** * Normalize a port into a number, string, or false. @@ -54,22 +54,20 @@ function normalizePort(val) { */ function onError(error) { - if (error.syscall !== 'listen') { + if (error.syscall !== "listen") { throw error; } - var bind = typeof port === 'string' - ? 'Pipe ' + port - : 'Port ' + port; + var bind = typeof port === "string" ? "Pipe " + port : "Port " + port; // handle specific listen errors with friendly messages switch (error.code) { - case 'EACCES': - console.error(bind + ' requires elevated privileges'); + case "EACCES": + console.error(bind + " requires elevated privileges"); process.exit(1); break; - case 'EADDRINUSE': - console.error(bind + ' is already in use'); + case "EADDRINUSE": + console.error(bind + " is already in use"); process.exit(1); break; default: @@ -83,8 +81,7 @@ function onError(error) { function onListening() { var addr = server.address(); - var bind = typeof addr === 'string' - ? 'pipe ' + addr - : 'port ' + addr.port; - debug('Listening on ' + bind); + var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port; + debug("Listening on " + bind); + console.log("Server running on:", bind); } diff --git a/day6/cronJobs/shopifyCustomerSync.js b/day6/cronJobs/shopifyCustomerSync.js new file mode 100644 index 0000000..71720c5 --- /dev/null +++ b/day6/cronJobs/shopifyCustomerSync.js @@ -0,0 +1,80 @@ +// const { getUnFulfilledOrders } = require("../services/shopifyService"); +const { exec } = require("child_process"); +const { promisify } = require("util"); +const cron = require("node-cron"); +const { customer } = require("../models"); + +const execPromise = promisify(exec); +const API_KEY = "65c3c809c002379e3a0ea04aeaf2cf84"; +const API_PASSWORD = "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"; +const STORE = "roving-house.myshopify.com"; +const API_VERSION = "2022-01"; + +// (async () => { +// const orders = await getUnFulfilledOrders(); +// console.log(orders); +// })(); + +async function fetchShopifyCustomers() { + let nextUrl = `https://${API_KEY}:${API_PASSWORD}@${STORE}/admin/api/${API_VERSION}/customers.json?limit=250`; + const allCustomers = []; + + try { + while (nextUrl) { + const curlCommand = `curl -i -X GET "${nextUrl}"`; + const { stdout } = await execPromise(curlCommand); + + // Separate headers and body + const parts = stdout.split("\r\n\r\n"); + const rawHeaders = parts[0]; + const body = parts.slice(1).join("\r\n\r\n"); + + const response = JSON.parse(body); + if (response.customers) { + allCustomers.push(...response.customers); + } + + // console.log(response); + + // Parse pagination header + const match = rawHeaders.match(/<([^>]+)>; rel="next"/); + nextUrl = match ? match[1] : null; + } + + return allCustomers; + } catch (error) { + console.error("Error fetching customers:", error); + throw error; + } +} + +async function syncCustomers() { + try { + const shopifyCustomers = await fetchShopifyCustomers(); + console.log(`Found ${shopifyCustomers.length} customers from Shopify`); + + for (const c of shopifyCustomers) { + await customer.findOrCreate({ + where: { shopify_customer_id: c.id.toString() }, + defaults: { + shopify_customer_id: c.id.toString(), + shopify_customer_email: c.email || "", + }, + }); + console.log(`Created customer: ${c.id}`); + } + + console.log("Customer sync completed successfully"); + } catch (error) { + console.error("Customer sync failed:", error); + } +} + +// run every minute +cron.schedule("* * * * *", () => { + console.log("Running Shopify customer sync..."); + syncCustomers(); +}); + +// For manual testing +module.exports = { syncCustomers }; diff --git a/day6/models/customer.js b/day6/models/customer.js new file mode 100644 index 0000000..d8a6ff2 --- /dev/null +++ b/day6/models/customer.js @@ -0,0 +1,19 @@ +module.exports = (sequelize, DataTypes) => { + const customer = sequelize.define("customer", { + id: { + type: DataTypes.INTEGER, + primaryKey: true, + autoIncrement: true, + }, + shopify_customer_id: { + type: DataTypes.STRING, + allowNull: false, + }, + shopify_customer_email: { + type: DataTypes.STRING, + allowNull: false, + }, + }); + + return customer; +}; diff --git a/day6/models/index.js b/day6/models/index.js index 8c44682..588e131 100644 --- a/day6/models/index.js +++ b/day6/models/index.js @@ -1,4 +1,4 @@ -'use strict'; +"use strict"; /*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2020*/ /** * Sequelize File @@ -8,49 +8,63 @@ * @author Ryan Wong * */ -const fs = require('fs'); -const path = require('path'); -let Sequelize = require('sequelize'); +const fs = require("fs"); +const path = require("path"); +let Sequelize = require("sequelize"); const basename = path.basename(__filename); -const { DataTypes } = require('sequelize'); +const { DataTypes } = require("sequelize"); const config = { - DB_DATABASE: 'mysql', - DB_USERNAME: 'root', - DB_PASSWORD: 'root', - DB_ADAPTER: 'mysql', - DB_NAME: 'day_1', - DB_HOSTNAME: 'localhost', + DB_DATABASE: "mysql", + DB_USERNAME: "root", + DB_PASSWORD: process.env.DB_PASSWORD || "root", + DB_ADAPTER: "mysql", + DB_NAME: "day_6", + DB_HOSTNAME: "localhost", DB_PORT: 3306, }; let db = {}; -let sequelize = new Sequelize(config.DB_DATABASE, config.DB_USERNAME, config.DB_PASSWORD, { - dialect: config.DB_ADAPTER, - username: config.DB_USERNAME, - password: config.DB_PASSWORD, - database: config.DB_NAME, - host: config.DB_HOSTNAME, - port: config.DB_PORT, - logging: console.log, - timezone: '-04:00', - pool: { - maxConnections: 1, - minConnections: 0, - maxIdleTime: 100, - }, - define: { - timestamps: false, - underscoredAll: true, - underscored: true, - }, -}); +let sequelize = new Sequelize( + config.DB_NAME, + config.DB_USERNAME, + config.DB_PASSWORD, + { + dialect: config.DB_ADAPTER, + username: config.DB_USERNAME, + password: config.DB_PASSWORD, + database: config.DB_NAME, + host: config.DB_HOSTNAME, + port: config.DB_PORT, + logging: console.log, + timezone: "-04:00", + pool: { + maxConnections: 1, + minConnections: 0, + maxIdleTime: 100, + }, + define: { + timestamps: false, + underscoredAll: true, + underscored: true, + }, + } +); -// sequelize.sync({ force: true }); +sequelize + .sync() + .then(() => { + console.log("All tables synced successfully."); + }) + .catch((err) => { + console.error("Failed to sync tables:", err); + }); fs.readdirSync(__dirname) .filter((file) => { - return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js'; + return ( + file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js" + ); }) .forEach((file) => { var model = require(path.join(__dirname, file))(sequelize, DataTypes); @@ -66,4 +80,4 @@ Object.keys(db).forEach((modelName) => { db.sequelize = sequelize; db.Sequelize = Sequelize; -module.exports = db; \ No newline at end of file +module.exports = db; diff --git a/day6/package.json b/day6/package.json index 219c20e..e13b3b6 100644 --- a/day6/package.json +++ b/day6/package.json @@ -3,9 +3,11 @@ "version": "0.0.0", "private": true, "scripts": { - "start": "node ./bin/www" + "start": "node ./bin/www", + "dev": "node --watch --env-file=.env ./bin/www" }, "dependencies": { + "axios": "^1.10.0", "cookie-parser": "~1.4.4", "cors": "^2.8.5", "debug": "~2.6.9", @@ -14,6 +16,7 @@ "jade": "~1.11.0", "morgan": "~1.9.1", "mysql2": "^2.3.3", + "node-cron": "^4.2.1", "sequelize": "^6.15.1" } } diff --git a/day6/public/stylesheets/style.css b/day6/public/stylesheets/style.css index 9453385..d2c2024 100644 --- a/day6/public/stylesheets/style.css +++ b/day6/public/stylesheets/style.css @@ -4,5 +4,19 @@ body { } a { - color: #00B7FF; + color: #00b7ff; +} + +#results { + display: grid; + grid-template-columns: repeat(5, 1fr); + gap: 8px; +} + +.productCard { + border: 2px solid black; + border-radius: 16px; + display: flex; + flex-direction: column; + align-items: center; } diff --git a/day6/routes/index.js b/day6/routes/index.js index ecca96a..303cde8 100644 --- a/day6/routes/index.js +++ b/day6/routes/index.js @@ -1,9 +1,32 @@ -var express = require('express'); +var express = require("express"); var router = express.Router(); +const { exec } = require("child_process"); /* GET home page. */ -router.get('/', function(req, res, next) { - res.render('index', { title: 'Express' }); +router.get("/", function (req, res, next) { + res.render("index", { title: "Express" }); +}); + +router.get("/products", function (req, res, next) { + // Use curl to fetch products from Shopify + const curlCmd = `curl -X GET \"https://roving-house.myshopify.com/admin/api/2021-07/products.json\" -u 65c3c809c002379e3a0ea04aeaf2cf84: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`; + exec(curlCmd, (error, stdout, stderr) => { + if (error) { + return res.render("products", { products: [], error: error.message }); + } + let products = []; + console.log(error, stdout); + try { + const data = JSON.parse(stdout); + products = data.products || []; + } catch (e) { + return res.render("products", { + products: [], + error: "Failed to parse products", + }); + } + res.render("products", { products }); + }); }); module.exports = router; diff --git a/day6/views/products.jade b/day6/views/products.jade new file mode 100644 index 0000000..23cad7d --- /dev/null +++ b/day6/views/products.jade @@ -0,0 +1,21 @@ +extends layout + +block content + h1 Products page + div#results + if products && products.length + each product in products + .card(style="border:1px solid #ccc;padding:10px;margin:10px;display:inline-block;width:200px;") + if product.image && product.image.src + img(src=product.image.src, alt=product.title, style="width:100%;height:150px;object-fit:cover;") + else if product.images && product.images.length + img(src=product.images[0].src, alt=product.title, style="width:100%;height:150px;object-fit:cover;") + else + div(style="width:100%;height:150px;background:#eee;text-align:center;line-height:150px;") No Image + h3= product.title + if product.variants && product.variants.length + p Price: $#{product.variants[0].price} + else + p Price: N/A + else + p No products found. \ No newline at end of file