Commit 3a60b1d8 authored by chaiwat's avatar chaiwat

7/3/2565

parent 24d53a2a
......@@ -7,6 +7,7 @@ const {
callUpdateGarage,
callDeleteGarage,
callGetGarageAll,
callApproveGarage
} = require("../services/funcCallback");
const responseCode = require("../configs/responseCode");
......@@ -126,6 +127,32 @@ router.post("/update", (request, response, next) => {
}
});
// Approve
router.put("/approve", (request, response, next) => {
let data = request.body;
console.log(data)
try {
callApproveGarage(data, function (err, datas, status) {
// console.log(status)
if (status == responseCode.SUCCESS) {
response.json({
code: 200,
message: "Update garage success",
total: datas.length,
data: datas,
});
} else {
response.json({
code: 400,
message: "Update garage not success",
});
}
});
} catch (err) {
console.log(err);
}
});
// Delete Garage
router.delete("/delete", (request, response, next) => {
let data = request.body;
......
......@@ -10,9 +10,12 @@ const {
callGetSpareByDetailID,
callDeleteSpare,
callUpdateDetail,
callGetAllSpare,
} = require("../services/funcCallback");
const responseCode = require("../configs/responseCode");
const { pushMessage } = require('../services/lineApi');
const router = express.Router();
// Insert Details
......@@ -160,6 +163,30 @@ router.post("/insert-spare", async (request, response, next) => {
}
});
// Get By spare All
router.get("/getallspare", (request, response, next) => {
// let data = request.query;
// console.log("data", data);
try {
callGetAllSpare("data", function (err, datas, status) {
if (status == responseCode.SUCCESS) {
response.json({
code: 200,
message: "get data success",
data: datas,
});
} else {
response.json({
code: 500,
message: "ไม่มี data นี้อยู่ในตาราง",
data: null,
});
}
});
} catch (err) {
console.log(err);
}
});
// Get By spare GarageID
router.get("/getspare-detailid", (request, response, next) => {
......@@ -176,7 +203,7 @@ router.get("/getspare-detailid", (request, response, next) => {
} else {
response.json({
code: 500,
message: "ไม่มี garage นี้อยู่ในตาราง",
message: "ไม่มี data นี้อยู่ในตาราง",
data: null,
});
}
......@@ -217,6 +244,7 @@ router.put("/update-detail", (request, response, next) => {
try {
callUpdateDetail(data, function (err, datas, status) {
// console.log(status)
pushMessage(datas)
if (status == responseCode.SUCCESS) {
response.json({
code: 200,
......
......@@ -29,6 +29,11 @@ app.use((req, res) => {
})
})
// app.post("/webhook", (req, res) => { // <============= เพิ่มเข้ามาใหม่
// console.log('req.body =>', JSON.stringify(req.body,null,2)) //สิ่งที่ Line ส่งมา
// res.send("HTTP POST request sent to the webhook URL!")
// })
......
// import express from 'express'
const express = require("express");
const router = express.Router();
const axios = require("axios");
// import UserController from '../controllers/users/UserController'
// const ChatController = require('../controllers/chat/chatController')
// router.use('/chat', ChatController)
const responseCode = require("../configs/responseCode");
const request = require("request");
const { callRegisterMember } = require("../services/funcCallback");
router.post("/chat/webhook", async (req, res, next) => {
// console.log("Hello", req.body.events[0]);
try {
let reply_token = req.body.events[0].replyToken;
console.log("body-------------", req.body);
const postback = req.body.events[0].postback;
console.log("postback-------------", postback);
console.log("req.body source.userID => ", req.body.events[0].source.userId);
// console.log('req.body message.text => ', req.body.events[0].message.text?)
let userId = req.body.events[0].source.userId;
let messageText = req.body.events[0].message?.text || null;
// reply(reply_token)
console.log("postback before if", postback);
if (messageText !== null) {
let messageSplit = messageText.split(",");
console.log("connect succes", messageSplit[0]);
if (messageSplit.length !== 3) {
console.log("ข้อมูลไม่ครบ!!!");
//////test
reply(reply_token);
} else {
if (messageSplit[0] === "ลงทะเบียน") {
console.log("connect succes", userId);
await findUserProfile(userId).then((res) => {
if (res) {
let data = {
party: "member",
userIdLine: res.userId,
imageUrl: res.pictureUrl,
userName: res.displayName,
member_tel: messageSplit[1],
member_name: messageSplit[2],
};
// console.log("data => ", data);
callRegisterMember(data, function (err, datas, status) {
if (status == responseCode.SUCCESS) {
replyMulti(reply_token, "ลงทะเบียนสำเร็จ");
console.log("test");
} else if (status == responseCode.ERROR_DB_DUPLICATE) {
replyMulti(
reply_token,
'ลงทะเบียน "ไม่สำเร็จ" หมายเลขโทรศัพท์นี้ลงทะเบียนเเล้ว'
);
} else if (status == responseCode.SUCCESS_NO_CONTENT) {
replyMulti(
reply_token,
'ลงทะเบียน "ไม่สำเร็จ" ID Line นี้ได้มีการลงทะเบียนแล้ว'
);
} else {
replyMulti(reply_token, 'ลงทะเบียน "ไม่สำเร็จ"');
}
});
} else {
replyMulti(reply_token, 'ลงทะเบียน "ไม่สำเร็จ"');
}
});
} else if (postback != undefined) {
console.log(
"req.body.events[0].postback => ",
req.body.events[0].postback
);
console.log("data => ", req.body.events[0].postback.data);
const _postBack = postback.data.split(",");
console.log("postback => ", _postBack);
const status = _postBack[0];
const _orderId = _postBack[1];
console.log("pos", status, _orderId);
} else {
console.log("5555!!!");
//////test
reply(reply_token);
}
}
} else {
console.log("5555!!!");
console.log("messageText", messageText);
//////test
reply(reply_token);
}
// res.sendStatus(200)
} catch (err) {
next(err);
}
});
/// testttttttt
function reply(reply_token) {
let headers = {
"Content-Type": "application/json",
Authorization:
"Bearer pe35stwPZGxT24BSF7Y6aGOa7YDmKtBlMQppWrjjZvbE8WY1Z+QSiaUhanQNRsUi9H9AhtOr52TJi1dMTqlyOoJtwoCta05j+iR8WFO1rN0BOc7n7wEtc0rrM8CcohZFAwk+9OGWaOfiRnqqRlgCmgdB04t89/1O/w1cDnyilFU=",
};
let body = JSON.stringify({
replyToken: reply_token,
messages: [
{
type: "text",
text: "Repair Center ระบบจัดการร้านซ่อม สวัสดีค่ะ \n ( ไม่สามารถตอบกลับได้ )",
},
{
type: "text",
text: 'หากลูกค้าที่ต้องการลงทะเบียน ให้พิมพ์คำว่า " ลงทะเบียน,เบอร์โทรศัพท์,ชื่อ-นามสกุล " ได้เลยค่ะ',
},
{
type: "text",
text: 'ตัวอย่าง \n " ลงทะเบียน,09xxxxxxxx,สุขสม นามใจ "',
},
{
type: "sticker",
packageId: "6136",
stickerId: "10551378",
},
],
});
request.post(
{
url: "https://api.line.me/v2/bot/message/reply",
headers: headers,
body: body,
},
(err, res, body) => {
console.log("status = " + res.statusCode);
}
);
}
async function findUserProfile(userId) {
let userData;
await axios
.get(`https://api.line.me/v2/bot/profile/${userId}`, {
headers: {
Authorization:
"Bearer pe35stwPZGxT24BSF7Y6aGOa7YDmKtBlMQppWrjjZvbE8WY1Z+QSiaUhanQNRsUi9H9AhtOr52TJi1dMTqlyOoJtwoCta05j+iR8WFO1rN0BOc7n7wEtc0rrM8CcohZFAwk+9OGWaOfiRnqqRlgCmgdB04t89/1O/w1cDnyilFU=",
},
})
.then((res) => {
userData = res.data;
});
return userData;
}
function replyMulti(reply_token, reponseText) {
let headers = {
"Content-Type": "application/json",
Authorization:
"Bearer pe35stwPZGxT24BSF7Y6aGOa7YDmKtBlMQppWrjjZvbE8WY1Z+QSiaUhanQNRsUi9H9AhtOr52TJi1dMTqlyOoJtwoCta05j+iR8WFO1rN0BOc7n7wEtc0rrM8CcohZFAwk+9OGWaOfiRnqqRlgCmgdB04t89/1O/w1cDnyilFU=",
};
let body = JSON.stringify({
replyToken: reply_token,
messages: [
{
type: "text",
text: reponseText,
},
],
});
request.post(
{
url: "https://api.line.me/v2/bot/message/reply",
headers: headers,
body: body,
},
(err, res, body) => {
console.log("status = " + res.statusCode);
}
);
}
module.exports = router;
......@@ -7,6 +7,7 @@ const member = require("./member");
const garage = require("./garage");
const repairdetail = require("./repairdetail");
const report = require("./report");
const chat = require("./chat")
const middleware = require("../middlewares/authentication");
......@@ -18,6 +19,7 @@ router.get("/test", (req, res) => {
console.log("test");
});
router.use(chat)
router.use(authentication);
router.use(member);
router.use(garage);
......
......@@ -120,7 +120,7 @@ async function registerGarage(data, callback) {
data.on_time,
data.off_time,
data.tel,
data.confirmation
data.confirmation,
];
// console.log(data.address_map)
......@@ -172,7 +172,7 @@ async function registerGarage(data, callback) {
data.on_time,
data.off_time,
data.tel,
data.confirmation
data.confirmation,
],
(err, result) => {
if (err) {
......@@ -212,7 +212,7 @@ async function loginUser(data, callback) {
// console.log(results[0].password);
if (bcrypt.compareSync(data.password, results[0].password)) {
// console.log("Successful", results[0].confirmation);
if (results[0].confirmation === 'approve') {
if (results[0].confirmation === "approve") {
callback(null, results[0], responseCode.SUCCESS);
} else {
if (results[0].garageID === "admin") {
......@@ -220,12 +220,9 @@ async function loginUser(data, callback) {
callback(null, results[0], responseCode.SUCCESS_ACCEPTED);
} else {
// console.log("test", results[0].garageID);
callback(null, null, responseCode.SUCCESS_NO_APPROVE);
callback(null, null, responseCode.SUCCESS_NO_APPROVE);
}
}
} else {
// console.log("Incorrect Email and/or Password!");
callback(null, null, responseCode.SUCCESS_NO_CONTENT);
......@@ -266,10 +263,13 @@ async function loginUser(data, callback) {
// get All Garage
function getAllGarage(data, callback) {
try {
db.query(`SELECT * FROM garage WHERE confirmation = 'approve' `, function (err, rows) {
if (err) return callback(err);
callback(null, rows, responseCode.SUCCESS);
});
db.query(
`SELECT * FROM garage WHERE confirmation = 'approve' `,
function (err, rows) {
if (err) return callback(err);
callback(null, rows, responseCode.SUCCESS);
}
);
} catch (err) {
console.log(err);
}
......@@ -339,6 +339,28 @@ function updateGarage(data, callback) {
}
}
// Approve garage
function Approve(data, callback) {
let sql = `UPDATE garage SET
confirmation = "approve" WHERE garageID = "${data.garageID}"
`;
try {
// console.log(sql, data.garageID)
db.query(sql, (error, result) => {
if (error) {
// console.log("error",error);
callback(null, result, responseCode.ERROR_BAD_REQUEST);
} else {
// console.log("good");
callback(null, data, responseCode.SUCCESS);
}
});
} catch (err) {
console.log(err);
}
}
// Delete Garage
function deleteGarage(data, callback) {
// console.log(data)
......@@ -379,31 +401,31 @@ function registerMember(data, callback) {
let dateNow = today.toLocaleDateString();
values = [
data.party,
data.garageID,
data.userIdLine,
data.imageUrl,
data.userName,
data.member_tel,
data.member_name,
data.member_ads,
data.shop_register,
dateNow,
];
try {
let sql = `SELECT member_tel FROM member`;
let sql = `SELECT userIdLine FROM member`;
db.query(sql, (error, result) => {
if (error) {
console.log("===>>> Error", error);
``;
} else {
// console.log(result)
let listUID = [];
result.forEach((doc) => {
listUID.push(doc.member_tel);
listUID.push(doc.userIdLine);
});
const check = listUID.includes(data.member_tel);
// console.log(listUID)
const check = listUID.includes(data.userIdLine);
if (check === false) {
db.query(insertInto.insert_member, [values], (err, result) => {
if (err) {
return callback(err);
callback(null, values, responseCode.ERROR_DB_DUPLICATE);
console.log("Main error =>", err);
} else {
callback(null, values, responseCode.SUCCESS);
console.log("insert success");
......@@ -450,7 +472,6 @@ function getMemberByGarage(data, callback) {
}
}
// Delete Member
function deleteMember(data, callback) {
// console.log(data)
......@@ -540,6 +561,22 @@ function spareDetail(data, callback) {
}
}
// Get Spare By GarageID
function getAllSpare(data, callback) {
try {
// console.log(detailID)
let sql = `SELECT * FROM spare`;
db.query(sql, function (err, rows) {
if (err) return callback(err);
// if (err) console.log(err);
callback(null, rows, responseCode.SUCCESS);
});
} catch (err) {
console.log(err);
}
}
// Get Spare By GarageID
function getSpareByDetailID(data, callback) {
try {
......@@ -710,10 +747,30 @@ function updateDetail(data, callback) {
db.query(sql, (error, result) => {
if (error) {
// console.log("error",error);
callback(null, result, responseCode.ERROR_BAD_REQUEST);
} else {
// console.log("good");
callback(null, data, responseCode.SUCCESS);
db.query(
`SELECT a.device_type, a.car_number, a.car_province, a.brand, a.model, a.repair_date, a.status, a.price, a.status_payment, a.equipment,
b.member_tel, b.member_name, b.userIdLine, c.spare,
d.user_name, d.garage_name
FROM repairdetails AS a
INNER JOIN member AS b ON a.member_tel = b.member_tel
INNER JOIN spare AS c ON a.detailsID = c.detailsID
INNER JOIN garage AS d ON a.garageID = d.garageID
WHERE a.detailsID = "${data.detailsID}" `,
(error, result) => {
if (error) {
console.log("error", error);
} else {
if (result) {
// console.log("result", result);
callback(null, result, responseCode.SUCCESS);
}
}
}
);
}
});
} catch (err) {
......@@ -745,4 +802,6 @@ module.exports = {
deleteSpare,
updateDetail,
getMemberByGarage,
getAllSpare,
Approve,
};
......@@ -23,7 +23,9 @@ const {
deleteSpare,
updateDetail,
getMemberByGarage,
getGarageAll
getGarageAll,
getAllSpare,
Approve,
} = require("./database");
//fucntion callback Insert Garage
......@@ -119,6 +121,20 @@ async function callUpdateGarage(data, callback) {
}
}
//fucntion callback Approve Garage
async function callApproveGarage(data, callback) {
// console.log(data)
try {
Approve(data, function (err, result, status) {
// console.log('test', result)
callback(null, result, status);
});
} catch (err) {
console.log(err);
}
}
//fucntion callback Delete Garage
async function callDeleteGarage(data, callback) {
// console.log(data)
......@@ -299,6 +315,21 @@ async function callGetByDetailID(data, callback) {
}
}
//fucntion callback get Spare All
async function callGetAllSpare(data, callback) {
try {
getAllSpare(data , function (err, result, status) {
if (err || !result.length) return callback("error or no results");
result = result.map((obj) => obj);
// console.log(result)
callback(null, result, status);
});
} catch (err) {
console.log(err);
}
}
//fucntion callback get Spare by detailID
async function callGetSpareByDetailID(data, callback) {
try {
......@@ -399,5 +430,7 @@ module.exports = {
callDeleteSpare,
callUpdateDetail,
callGetMemberByGarage,
callGetGarageAll
callGetGarageAll,
callGetAllSpare,
callApproveGarage
};
const request = require("request");
const responseCode = require("../configs/responseCode");
async function pushMessage(data) {
console.log("data in pushMessage ", data[0]);
let headers = {
"Content-Type": "application/json",
Authorization:
"Bearer pe35stwPZGxT24BSF7Y6aGOa7YDmKtBlMQppWrjjZvbE8WY1Z+QSiaUhanQNRsUi9H9AhtOr52TJi1dMTqlyOoJtwoCta05j+iR8WFO1rN0BOc7n7wEtc0rrM8CcohZFAwk+9OGWaOfiRnqqRlgCmgdB04t89/1O/w1cDnyilFU=",
};
let body = JSON.stringify({
to: data[0].userIdLine,
messages: [
{
type: "text",
text: "ขออนุญาตแจ้งสถานะการซ่อมค่ะ",
weight: "bold",
},
{
type: "text",
text: `
ชื่อลูกค้า : ${data[0].member_name}\n
รหัสลูกค้า : ${data[0].member_tel}\n
ประเภทอุปกรณ์ : ${data[0].device_type}\n
ร้าน : ${data[0].garage_name}\n
รับซ่อมวันที่ : ${data[0].repair_date}\n
สถานะการซ่อม : ${data[0].status}\n
ราคาทั้งหมด : ${data[0].price}฿\n
การชำระเงิน : ${data[0].status_payment}
`,
},
{
type: "text",
text: `Repair Center ขอขอบคุณค่ะ`,
},
{
type: "sticker",
packageId: "6136",
stickerId: "10551377",
},
// {
// type: "text",
// text: `ราคาทั้งหมด ${data[0].price}฿ การชำระเงิน ${data[0].status_payment}`,
// },
// {
// type: "bubble",
// header: {
// type: "box",
// layout: "horizontal",
// contents: [
// {
// type: "text",
// text: "NEWS DIGEST",
// weight: "bold",
// size: "sm",
// color: "#AAAAAA",
// contents: []
// }
// ]
// }
// }
],
});
request.post(
{
url: "https://api.line.me/v2/bot/message/push",
headers: headers,
body: body,
},
(err, res, body) => {
console.log("status = " + res.statusCode);
}
);
}
module.exports = { pushMessage };
......@@ -27,11 +27,11 @@ module.exports = {
member: `CREATE TABLE member(
member_tel varchar(100),
garageID varchar(100),
party varchar(100),
member_name varchar(255),
member_ads varchar(255),
shop_register varchar(255),
userIdLine varchar(100),
imageUrl varchar(255),
userName varchar(100),
registration_date varchar(100),
PRIMARY KEY (member_tel)
......
......@@ -27,11 +27,11 @@ module.exports = {
insert_member: `INSERT INTO member
(
party,
garageID,
userIdLine,
imageUrl,
userName,
member_tel,
member_name,
member_ads,
shop_register,
registration_date
) VALUES (?)`,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment