Skip to content

Commit

Permalink
재고 스냅샷기능 업데이트
Browse files Browse the repository at this point in the history
  • Loading branch information
KimKyuBong committed Nov 20, 2023
1 parent 5949c77 commit 20c2bf0
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 19 deletions.
4 changes: 2 additions & 2 deletions routes/admin/adminRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { checkAdminTokens } = require("@token");
// add, remove를 insert로 통합
const insertInventoryRouter = require("./inventory/insertInventory");
const createSnapshotsRouter = require("./inventory/createSnapshots");
const stockInfoRouter = require("./inventory/stockInfo");
const stockVarianceRouter = require("./inventory/stockVariance");
const itemCheckRouter = require("./inventory/itemCheck");
const inventoryCheckRouter = require("./inventory/inventoryCheck");
const inventoryByDayRouter = require("./inventory/inventoryByDay");
Expand Down Expand Up @@ -44,7 +44,7 @@ router.use("/pwchange", pwChangeRouter);

router.use("/insertinventory", insertInventoryRouter);
router.use("/createsnapshots", createSnapshotsRouter);
router.use("/stockInfo", stockInfoRouter);
router.use("/stockVariance", stockVarianceRouter);
router.use("/itemCheck", itemCheckRouter);
router.use("/inventoryCheck", inventoryCheckRouter);
router.use("/inventoryByDay", inventoryByDayRouter);
Expand Down
File renamed without changes.
16 changes: 10 additions & 6 deletions routes/auth/adminlogin.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,18 @@ router.post("/", async (req, res) => {
const results = await executeQueryPromise(query, [email]);

if (results.length === 0) {
return res.status(401).json({ error: "이메일 또는 비밀번호가 잘못되었습니다" });
return res
.status(401)
.json({ error: "이메일 또는 비밀번호가 잘못되었습니다" });
}

const user = results[0];
const isPasswordValid = await bcrypt.compare(password, user.password);

if (!isPasswordValid) {
return res.status(401).json({ error: "이메일 또는 비밀번호가 잘못되었습니다" });
return res
.status(401)
.json({ error: "이메일 또는 비밀번호가 잘못되었습니다" });
}

if (user.is_admin !== 1) {
Expand All @@ -33,10 +37,10 @@ router.post("/", async (req, res) => {
await updateRefToken(email, refreshToken);

// 쿠키에 토큰 및 로그인 상태 저장
res.cookie('accessToken', accessToken, { httpOnly: true });
res.cookie('refreshToken', refreshToken, { httpOnly: true });
res.cookie('isAdminLoggedIn', 'true', { httpOnly: false, maxAge: 3600000 });
res.cookie('isLoggedIn', 'true', { httpOnly: false, maxAge: 3600000 });
res.cookie("accessToken", accessToken, { httpOnly: true });
res.cookie("refreshToken", refreshToken, { httpOnly: true });
res.cookie("isAdminLoggedIn", "true", { httpOnly: false });
res.cookie("isLoggedIn", "true", { httpOnly: false });

return res.status(200).json({
message: "로그인이 성공적으로 되었습니다",
Expand Down
2 changes: 1 addition & 1 deletion routes/auth/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async function handleLogin(req, res) {
res
.cookie("accessToken", accessToken, { httpOnly: true }) // httpOnly는 JavaScript를 통한 접근을 제한
.cookie("refreshToken", refreshToken, { httpOnly: true })
.cookie("isLoggedIn", "true", { httpOnly: false, maxAge: 3600000 })
.cookie("isLoggedIn", "true", { httpOnly: false })
.status(200)
.json({
message: "로그인이 성공적으로 되었습니다",
Expand Down
82 changes: 72 additions & 10 deletions utils/inventory.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,24 +278,86 @@ class InventoryService {

async createSnapshotForItem(itemId, quantity, writer_id) {
try {
const currentTimestamp = new Date().getTime(); // 현재 타임스탬프를 얻습니다.
const currentTimestamp = new Date().getTime();
console.log(currentTimestamp);
// 스냅샷 생성
await InventorySnapshots.create({
snapshotDate: currentTimestamp,
itemId: itemId,
quantity: quantity,
writer_id: writer_id,

// 이전 스냅샷 조회
const previousSnapshot = await InventorySnapshots.findOne({
where: { itemId },
order: [["snapshotDate", "DESC"]],
});

console.log(
`Snapshot created for Item ID ${itemId} at timestamp ${currentTimestamp}`,
);
if (!previousSnapshot) {
await InventorySnapshots.create({
snapshotDate: currentTimestamp,
itemId,
quantity,
writer_id,
});

console.log(
`Snapshot created for Item ID ${itemId} at timestamp ${currentTimestamp}`,
);
} else {
const previousQuantity = previousSnapshot.quantity;
const previousDate = previousSnapshot.snapshotDate;
const inventoryChange = await Inventory.findOne({
attributes: [
[sequelize.fn("SUM", sequelize.col("quantity")), "total_change"],
],
where: {
item_id: itemId,
last_updated: {
[Op.gt]: previousDate, // 가장 가까운 스냅샷 이후
[Op.lte]: currentTimestamp, // 입력받은 날짜까지
},
},
});
const diff = previousQuantity + inventoryChange.total_change - quantity;
if (diff === 0) {
console.log("No change in quantity.");
} else if (diff < 0) {
console.log(`Quantity increased by ${-diff}.`);
await InventorySnapshots.create({
snapshotDate: currentTimestamp,
itemId,
quantity: quantity,
writer_id,
});

await Inventory.create({
snapshotDate: currentTimestamp - 300000,
itemId,
quantity: diff,
writer_id,
reason: "자동생성 초과",
});
} else {
console.log(`Quantity decreased by ${diff}.`);
console.warn("Warning: Quantity decreased. Verify the data.");
await InventorySnapshots.create({
snapshotDate: currentTimestamp,
itemId,
quantity: quantity,
writer_id,
});

await Inventory.create({
snapshotDate: currentTimestamp - 300000,
itemId,
quantity: diff,
writer_id,
reason: "자동생성 손실",
});
// 여기에서 경고를 표시하거나 예외를 throw할 수 있습니다.
}
}
} catch (error) {
console.error(`Error creating snapshot: ${error.message}`);
throw error;
}
}

async createMondaySnapshot(itemID, date) {
date = convertKSTtoUTC(date);

Expand Down

0 comments on commit 20c2bf0

Please sign in to comment.