Skip to content

Instantly share code, notes, and snippets.

@naiplawan
Created September 28, 2023 03:52
Show Gist options
  • Select an option

  • Save naiplawan/c03845cf36ce4ae42b9c7ad31413677a to your computer and use it in GitHub Desktop.

Select an option

Save naiplawan/c03845cf36ce4ae42b9c7ad31413677a to your computer and use it in GitHub Desktop.
Promotion Feature
import { Router } from "express";
import supabase from "../utils/supabase.js";
import multer from "multer";
const promotionRouter = Router();
// const multer = require("multer");
const upload = multer()
promotionRouter.get("/", async (req, res) => {
const { keyword } = req.query;
try {
const { data, error } = await supabase
.from("promotion")
.select("*")
.ilike("promotion_code", `%${keyword}%`);
if (error) {
throw error;
}
return res.json({
data,
});
} catch (error) {
res.status(500).json({
error: error.message,
});
}
});
// ดู promotion แบบเจาะจง id
promotionRouter.get("/:id", async (req, res) => {
try {
const promotionId = req.params.id;
const { data, error } = await supabase
.from("promotion")
.select("*")
.eq("promotion_id", promotionId);
if (error) {
throw error;
}
res.status(200).json({ success: true, data });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, error: "Internal Server Error" });
}
});
promotionRouter.put("/:id", async (req, res) => {
try {
const promotionId = req.params.id;
const updatedPromotionItem = {
promotion_code: req.body.promotion_code,
promotion_types: req.body.promotion_types,
promotion_quota: req.body.promotion_quota,
promotion_discount: req.body.promotion_discount,
promotion_expiry_date: req.body.promotion_expiry_date,
promotion_expiry_time: req.body.promotion_expiry_time,
};
const { data: updatedPromotionData, error: updatedPromotionError } =
await supabase
.from("promotion")
.update(updatedPromotionItem)
.eq("promotion_id", promotionId);
if (updatedPromotionError) {
console.error("Error updating service data", updatedPromotionError);
return res
.status(500)
.json({ message: "Error cannot update data to supabase" });
}
console.log("updated data", updatedPromotionData);
return res.status(200).send("Promotion is successfully updated");
} catch (error) {
console.error(error);
res.status(500).json({ success: false, error: "Internal Server Error" });
}
});
promotionRouter.post("/",upload.none(), async (req, res) => {
try {
const {
promotion_code,
promotion_types,
promotion_quota,
promotion_discount,
promotion_expiry_date,
promotion_expiry_time,
} = req.body;
console.log(req.body);
const formattedExpiryDate = new Date(req.body.promotion_expiry_date[1]);
const formattedExpiryDateAsString = formattedExpiryDate
.toISOString()
.split("T")[0];
const formattedExpiryTime = req.body.promotion_expiry_time[1];
//item
const promotionItem = {
promotion_code,
promotion_types,
promotion_quota,
promotion_expiry_date,
promotion_expiry_time,
};
// Get current date and time
const currentDateTime = new Date();
console.log(
promotion_code,
promotion_types,
promotion_quota,
promotion_discount
);
// Insert data into Supabase table
const { data, error } = await supabase.from("promotion").insert([
{
promotion_code,
promotion_types,
promotion_quota,
promotion_discount,
promotion_expiry_date: formattedExpiryDateAsString,
promotion_expiry_time: formattedExpiryTime,
promotion_created_date_time: currentDateTime,
promotion_edited_date_time: currentDateTime,
},
]);
if (error) {
throw error;
}
res.status(201).json({ success: true, data });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, error: "Internal Server Error" });
}
});
promotionRouter.delete("/:id", async (req, res) => {
try {
const promotionId = req.params.id;
const { data, error } = await supabase
.from("promotion")
.delete()
.eq("promotion_id", promotionId);
if (error) {
return res.status(500).json({ error: "ไม่สามารถลบได้" });
}
if (data && data.length === 0) {
return res
.status(404)
.json({ error: `ไม่พบรายการที่ตรงกับ ${promotionId}` });
}
return res.status(200).json({ success: true });
} catch (error) {
res.status(500).json({ success: false, error: "ไม่สามารถลบได้" });
}
});
export default promotionRouter;
// promotionRouter.put("/:id", async (req, res) => {
// try {
// const promotionId = req.params.id;
// // Extract the fields you want to update from the request body
// const {
// promotion_code,
// promotion_types,
// promotion_quota,
// promotion_discount,
// promotion_expiry_date,
// promotion_expiry_time,
// } = req.body;
// // Update the fields in the Supabase table
// const { data, error } = await supabase
// .from("promotion")
// .update({
// promotion_code,
// promotion_types,
// promotion_quota,
// promotion_discount,
// promotion_expiry_date,
// promotion_expiry_time,
// })
// .eq("promotion_id", promotionId);
// if (error) {
// throw error;
// }
// // Check if any rows were updated
// if (data && data.length === 0) {
// return res
// .status(404)
// .json({ error: `No promotion with ID ${promotionId} found.` });
// }
// return res.status(200).json({ success: true, data });
// } catch (error) {
// console.error(error);
// res.status(500).json({ success: false, error: "Internal Server Error" });
// }
// });
import { useState } from "react";
import axios from "axios";
export const usePromotion = () => {
const [promotion, setPromotion] = useState({});
const getPromotion = async (promotionCode) => {
try {
const response = await axios(`http://localhost:4000/promotion?keyword=${promotionCode}`);
const data = response.data.data[0];
setPromotion(data);
} catch (error) {
console.error("Failed to get promotions:", error);
}
};
return { promotion, getPromotion };
import { useState } from "react";
import { Input, Button } from "antd";
import { usePromotion } from "../hooks/promotion";
const PromotionMockUpPage = () => {
const [promotionCode, setPromotionCode] = useState("");
const { promotion, getPromotion } = usePromotion();
const handleApplyPromotion = () => {
console.log("handleApplyPromotion called with promotionCode:", promotionCode);
getPromotion(promotionCode);
console.log("promotion:", promotion);
};
const handleInputChange = (e) => {
console.log("handleInputChange called with value:", e.target.value);
setPromotionCode(e.target.value);
};
return (
<div className="promotion-container">
<div className="promotion">
<div className="promotion-image">
<div className="promotion-input">
<Input
id="promotion-code"
placeholder="Enter promotion code"
value={promotionCode}
onChange={handleInputChange}
/>
<Button type="primary" onClick={handleApplyPromotion}>
Apply
</Button>
<div className="promotion-total-price">
<p>Total Price</p>
<p>1000</p>
</div>
</div>
</div>
</div>
</div>
);
};
export default PromotionMockUpPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment