day 6
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
# day 6
|
||||
|
||||
## Instructions
|
||||
|
||||
- setup project
|
||||
- clone to your github
|
||||
- Read the documentation https://sequelize.org/v7/manual/getting-started.html
|
||||
- Setup the following Models in models folder. Make sure tables made by sequelize:
|
||||
|
||||
```
|
||||
customer
|
||||
- id
|
||||
- shopify_customer_id
|
||||
- shopify_customer_email
|
||||
```
|
||||
|
||||
- make a cronjob that pulls all shopify customers and write into our database table. If customer exist, don't add again. Look at shopifyService to see how to call api. https://shopify.dev/api/admin-rest/2022-01/resources/customer#[get]/admin/api/2022-01/customers.json Use CURL version not nodeJS version
|
||||
|
||||
- Make a page /products that return webpage where you query paginated shopify products as cards with product title, price, image https://shopify.dev/api/admin-rest/2022-01/resources/product#[get]/admin/api/2022-01/products.json Use CURL version not nodeJS version
|
||||
|
||||
- Everything must be done by end of date
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
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');
|
||||
|
||||
const db = require("./models");
|
||||
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.use(cors());
|
||||
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('/', indexRouter);
|
||||
app.use('/users', usersRouter);
|
||||
|
||||
// catch 404 and forward to error handler
|
||||
app.use(function (req, res, next) {
|
||||
next(createError(404));
|
||||
});
|
||||
|
||||
// error handler
|
||||
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 : {};
|
||||
|
||||
// render the error page
|
||||
res.status(err.status || 500);
|
||||
res.render('error');
|
||||
});
|
||||
|
||||
module.exports = app;
|
||||
Executable
+90
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Module dependencies.
|
||||
*/
|
||||
|
||||
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);
|
||||
|
||||
/**
|
||||
* Create HTTP server.
|
||||
*/
|
||||
|
||||
var server = http.createServer(app);
|
||||
|
||||
/**
|
||||
* Listen on provided port, on all network interfaces.
|
||||
*/
|
||||
|
||||
server.listen(port);
|
||||
server.on('error', onError);
|
||||
server.on('listening', onListening);
|
||||
|
||||
/**
|
||||
* Normalize a port into a number, string, or false.
|
||||
*/
|
||||
|
||||
function normalizePort(val) {
|
||||
var port = parseInt(val, 10);
|
||||
|
||||
if (isNaN(port)) {
|
||||
// named pipe
|
||||
return val;
|
||||
}
|
||||
|
||||
if (port >= 0) {
|
||||
// port number
|
||||
return port;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Event listener for HTTP server "error" event.
|
||||
*/
|
||||
|
||||
function onError(error) {
|
||||
if (error.syscall !== 'listen') {
|
||||
throw error;
|
||||
}
|
||||
|
||||
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');
|
||||
process.exit(1);
|
||||
break;
|
||||
case 'EADDRINUSE':
|
||||
console.error(bind + ' is already in use');
|
||||
process.exit(1);
|
||||
break;
|
||||
default:
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Event listener for HTTP server "listening" event.
|
||||
*/
|
||||
|
||||
function onListening() {
|
||||
var addr = server.address();
|
||||
var bind = typeof addr === 'string'
|
||||
? 'pipe ' + addr
|
||||
: 'port ' + addr.port;
|
||||
debug('Listening on ' + bind);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
/*Powered By: Manaknightdigital Inc. https://manaknightdigital.com/ Year: 2020*/
|
||||
/**
|
||||
* Sequelize File
|
||||
* @copyright 2020 Manaknightdigital Inc.
|
||||
* @link https://manaknightdigital.com
|
||||
* @license Proprietary Software licensing
|
||||
* @author Ryan Wong
|
||||
*
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
let Sequelize = require('sequelize');
|
||||
const basename = path.basename(__filename);
|
||||
const config = {
|
||||
DB_DATABASE: 'mysql',
|
||||
DB_USERNAME: 'root',
|
||||
DB_PASSWORD: 'root',
|
||||
DB_ADAPTER: 'mysql',
|
||||
DB_NAME: 'day_1',
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
// sequelize.sync({ force: true });
|
||||
|
||||
fs.readdirSync(__dirname)
|
||||
.filter((file) => {
|
||||
return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
|
||||
})
|
||||
.forEach((file) => {
|
||||
var model = sequelize['import'](path.join(__dirname, file));
|
||||
db[model.name] = model;
|
||||
});
|
||||
|
||||
Object.keys(db).forEach((modelName) => {
|
||||
if (db[modelName].associate) {
|
||||
db[modelName].associate(db);
|
||||
}
|
||||
});
|
||||
|
||||
db.sequelize = sequelize;
|
||||
db.Sequelize = Sequelize;
|
||||
|
||||
module.exports = db;
|
||||
@@ -0,0 +1,26 @@
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
const location = sequelize.define(
|
||||
"location",
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.INTEGER,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
name: DataTypes.STRING,
|
||||
created_at: DataTypes.DATEONLY,
|
||||
updated_at: DataTypes.DATE,
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
freezeTableName: true,
|
||||
tableName: "location",
|
||||
},
|
||||
{
|
||||
underscoredAll: false,
|
||||
underscored: false,
|
||||
}
|
||||
);
|
||||
|
||||
return location;
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "day-1",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "node ./bin/www"
|
||||
},
|
||||
"dependencies": {
|
||||
"cookie-parser": "~1.4.4",
|
||||
"cors": "^2.8.5",
|
||||
"debug": "~2.6.9",
|
||||
"express": "~4.16.1",
|
||||
"http-errors": "~1.6.3",
|
||||
"jade": "~1.11.0",
|
||||
"morgan": "~1.9.1",
|
||||
"mysql2": "^2.3.3",
|
||||
"sequelize": "^6.15.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
body {
|
||||
padding: 50px;
|
||||
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #00B7FF;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
var express = require('express');
|
||||
var router = express.Router();
|
||||
|
||||
/* GET home page. */
|
||||
router.get('/', function(req, res, next) {
|
||||
res.render('index', { title: 'Express' });
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,9 @@
|
||||
var express = require('express');
|
||||
var router = express.Router();
|
||||
|
||||
/* GET users listing. */
|
||||
router.get('/', function(req, res, next) {
|
||||
res.send('respond with a resource');
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,166 @@
|
||||
const axios = require("axios");
|
||||
const shopifyUrl = "https://65c3c809c002379e3a0ea04aeaf2cf84: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@roving-house.myshopify.com";
|
||||
const graphQlUrl = `${shopifyUrl}/admin/api/2021-07/graphql.json`;
|
||||
|
||||
async function getUnFulfilledOrders() {
|
||||
const orders = await axios.get(`${shopifyUrl}/admin/api/2021-07/orders.json?fulfillment_status=unfulfilled&limit=250`);
|
||||
|
||||
const orderIds = orders?.data?.orders.map((order, index) => ({
|
||||
sys_index: index,
|
||||
order_id: order.id,
|
||||
customer_id: order.customer.id,
|
||||
email: order.email,
|
||||
customer_name:
|
||||
(order.customer.first_name && order.customer.first_name.length > 0 ? order.customer.first_name : "") +
|
||||
" " +
|
||||
(order.customer.last_name && order.customer.last_name.length > 0 ? order.customer.last_name : ""),
|
||||
line_items: order.line_items,
|
||||
year_month: order.created_at.split("-")[0] + "-" + order.created_at.split("-")[1],
|
||||
created_at: order.created_at.split("T")[0],
|
||||
}));
|
||||
return orderIds;
|
||||
}
|
||||
|
||||
async function getOrderSingle(orderId) {
|
||||
return await axios.get(`${shopifyUrl}/admin/api/2021-07/orders/${orderId}.json`);
|
||||
}
|
||||
|
||||
async function getOrderSingleLineItems(orderId) {
|
||||
const orderSingle = await getOrderSingle(orderId);
|
||||
return orderSingle?.data?.order?.line_items;
|
||||
}
|
||||
|
||||
async function getCustomersLastOrdersLineItems(customerId) {
|
||||
const customerSingle = await getCustomerById(customerId);
|
||||
const lastOrderId = customerSingle?.data?.customer?.last_order_id;
|
||||
return await getOrderSingleLineItems(lastOrderId);
|
||||
}
|
||||
|
||||
async function getOrderSingleCreatedAt(orderId) {
|
||||
const orderSingle = await getOrderSingle(orderId);
|
||||
return orderSingle?.data?.order?.created_at.split("T")[0];
|
||||
}
|
||||
|
||||
async function getCustomerById(customerId) {
|
||||
return await axios.get(`${shopifyUrl}/admin/api/2021-07/customers/${customerId}.json`);
|
||||
}
|
||||
|
||||
async function getCustomerLastOrderId(customerId) {
|
||||
const customerSingle = await getCustomerById(customerId);
|
||||
return customerSingle?.data?.customer?.last_order_id;
|
||||
}
|
||||
|
||||
async function getCustomerLastOrderDate(customerId) {
|
||||
const lastOrderId = await getCustomerLastOrderId(customerId);
|
||||
const orderDate = await getOrderSingleCreatedAt(lastOrderId);
|
||||
return orderDate;
|
||||
}
|
||||
|
||||
async function getProductById(productId) {
|
||||
return await axios.get(`${shopifyUrl}/admin/api/2021-07/products/${productId}.json`);
|
||||
}
|
||||
|
||||
async function getProductByTitle(title) {
|
||||
// console.log(title);
|
||||
title = JSON.stringify(title);
|
||||
// console.log(title);
|
||||
return await axios.get(`${shopifyUrl}/admin/api/2021-07/products.json?title=${title}`);
|
||||
}
|
||||
|
||||
// adds product to order by quantity of 1 and price in USD
|
||||
async function addItemToOrder(orderId, rewardVariantId, note = "Reward Item") {
|
||||
try {
|
||||
if (!rewardVariantId) {
|
||||
console.log("addItemToOrder Error: parameter->productItem must have a variantId to be added to order");
|
||||
return;
|
||||
}
|
||||
|
||||
// begin editing order
|
||||
const beginEditQuery = `mutation {
|
||||
orderEditBegin (id: "gid://shopify/Order/${orderId}"){
|
||||
calculatedOrder
|
||||
{
|
||||
id
|
||||
}
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}`;
|
||||
const beginEditResponse = await axios
|
||||
.post(graphQlUrl, {
|
||||
query: beginEditQuery,
|
||||
})
|
||||
.then((data) => data.data);
|
||||
if (beginEditResponse.data.errors && beginEditResponse.data.errors.length) {
|
||||
throw beginEditResponse.data.errors;
|
||||
}
|
||||
const calculatedOrderId = beginEditResponse.data.orderEditBegin.calculatedOrder.id;
|
||||
// add item to order mutation
|
||||
const addItemQuery = `mutation {
|
||||
orderEditAddVariant (id: "${calculatedOrderId}", variantId: "gid://shopify/ProductVariant/${rewardVariantId}", quantity: 1, allowDuplicates: false){
|
||||
calculatedLineItem {
|
||||
title
|
||||
}
|
||||
calculatedOrder {
|
||||
id
|
||||
}
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}`;
|
||||
const addItemResponse = await axios
|
||||
.post(graphQlUrl, {
|
||||
query: addItemQuery,
|
||||
})
|
||||
.then((data) => data.data);
|
||||
if (addItemResponse.data.errors && addItemResponse.data.errors.length) {
|
||||
throw addItemResponse.data.errors;
|
||||
}
|
||||
// commit response
|
||||
const commitEditQuery = `mutation {
|
||||
orderEditCommit (id: "${calculatedOrderId}", notifyCustomer: false, staffNote: "${note}") {
|
||||
order {
|
||||
id
|
||||
}
|
||||
userErrors {
|
||||
field
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
const commitResponse = await axios
|
||||
.post(graphQlUrl, {
|
||||
query: commitEditQuery,
|
||||
})
|
||||
.then((data) => data.data);
|
||||
if (commitResponse.data.errors && commitResponse.data.errors.length) {
|
||||
throw commitResponse.data.errors;
|
||||
}
|
||||
|
||||
return "ok";
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return "error";
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
shopifyUrl,
|
||||
graphQlUrl,
|
||||
addItemToOrder,
|
||||
getUnFulfilledOrders,
|
||||
getOrderSingle,
|
||||
getOrderSingleCreatedAt,
|
||||
getCustomerById,
|
||||
getCustomerLastOrderId,
|
||||
getCustomerLastOrderDate,
|
||||
getProductById,
|
||||
getProductByTitle,
|
||||
getOrderSingleLineItems,
|
||||
getCustomersLastOrdersLineItems
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
extends layout
|
||||
|
||||
block content
|
||||
h1= message
|
||||
h2= error.status
|
||||
pre #{error.stack}
|
||||
@@ -0,0 +1,5 @@
|
||||
extends layout
|
||||
|
||||
block content
|
||||
h1= title
|
||||
p Welcome to #{title}
|
||||
@@ -0,0 +1,7 @@
|
||||
doctype html
|
||||
html
|
||||
head
|
||||
title= title
|
||||
link(rel='stylesheet', href='/stylesheets/style.css')
|
||||
body
|
||||
block content
|
||||
Reference in New Issue
Block a user