add permission brother

This commit is contained in:
kittapath 2025-12-12 01:37:27 +07:00
parent 10ae9c0d13
commit cbf5f2599d
2 changed files with 272 additions and 216 deletions

View file

@ -72,68 +72,68 @@ export class SalaryPeriodController extends Controller {
const data = { const data = {
group1id: group1id:
salaryPeriod.salaryOrgs && salaryPeriod.salaryOrgs &&
salaryPeriod.salaryOrgs.find( salaryPeriod.salaryOrgs.find(
(x) => (x) =>
x.group == "GROUP1" && x.group == "GROUP1" &&
x.rootId == body.rootId && x.rootId == body.rootId &&
x.snapshot == body.snapshot.toLocaleUpperCase(), x.snapshot == body.snapshot.toLocaleUpperCase(),
) == null ) == null
? null ? null
: salaryPeriod.salaryOrgs && : salaryPeriod.salaryOrgs &&
salaryPeriod.salaryOrgs.find( salaryPeriod.salaryOrgs.find(
(x) => (x) =>
x.group == "GROUP1" && x.group == "GROUP1" &&
x.rootId == body.rootId && x.rootId == body.rootId &&
x.snapshot == body.snapshot.toLocaleUpperCase(), x.snapshot == body.snapshot.toLocaleUpperCase(),
)?.id, )?.id,
group1IsClose: group1IsClose:
salaryPeriod.salaryOrgs && salaryPeriod.salaryOrgs &&
salaryPeriod.salaryOrgs.find( salaryPeriod.salaryOrgs.find(
(x) => (x) =>
x.group == "GROUP1" && x.group == "GROUP1" &&
x.rootId == body.rootId && x.rootId == body.rootId &&
x.snapshot == body.snapshot.toLocaleUpperCase(), x.snapshot == body.snapshot.toLocaleUpperCase(),
) == null ) == null
? null ? null
: salaryPeriod.salaryOrgs && : salaryPeriod.salaryOrgs &&
salaryPeriod.salaryOrgs.find( salaryPeriod.salaryOrgs.find(
(x) => (x) =>
x.group == "GROUP1" && x.group == "GROUP1" &&
x.rootId == body.rootId && x.rootId == body.rootId &&
x.snapshot == body.snapshot.toLocaleUpperCase(), x.snapshot == body.snapshot.toLocaleUpperCase(),
)?.isClose, )?.isClose,
group2id: group2id:
salaryPeriod.salaryOrgs && salaryPeriod.salaryOrgs &&
salaryPeriod.salaryOrgs.find( salaryPeriod.salaryOrgs.find(
(x) => (x) =>
x.group == "GROUP2" && x.group == "GROUP2" &&
x.rootId == body.rootId && x.rootId == body.rootId &&
x.snapshot == body.snapshot.toLocaleUpperCase(), x.snapshot == body.snapshot.toLocaleUpperCase(),
) == null ) == null
? null ? null
: salaryPeriod.salaryOrgs && : salaryPeriod.salaryOrgs &&
salaryPeriod.salaryOrgs.find( salaryPeriod.salaryOrgs.find(
(x) => (x) =>
x.group == "GROUP2" && x.group == "GROUP2" &&
x.rootId == body.rootId && x.rootId == body.rootId &&
x.snapshot == body.snapshot.toLocaleUpperCase(), x.snapshot == body.snapshot.toLocaleUpperCase(),
)?.id, )?.id,
group2IsClose: group2IsClose:
salaryPeriod.salaryOrgs && salaryPeriod.salaryOrgs &&
salaryPeriod.salaryOrgs.find( salaryPeriod.salaryOrgs.find(
(x) => (x) =>
x.group == "GROUP2" && x.group == "GROUP2" &&
x.rootId == body.rootId && x.rootId == body.rootId &&
x.snapshot == body.snapshot.toLocaleUpperCase(), x.snapshot == body.snapshot.toLocaleUpperCase(),
) == null ) == null
? null ? null
: salaryPeriod.salaryOrgs && : salaryPeriod.salaryOrgs &&
salaryPeriod.salaryOrgs.find( salaryPeriod.salaryOrgs.find(
(x) => (x) =>
x.group == "GROUP2" && x.group == "GROUP2" &&
x.rootId == body.rootId && x.rootId == body.rootId &&
x.snapshot == body.snapshot.toLocaleUpperCase(), x.snapshot == body.snapshot.toLocaleUpperCase(),
)?.isClose, )?.isClose,
effectiveDate: salaryPeriod.effectiveDate, effectiveDate: salaryPeriod.effectiveDate,
period: salaryPeriod.period, period: salaryPeriod.period,
}; };
@ -192,8 +192,8 @@ export class SalaryPeriodController extends Controller {
_salaryOrgGROUP2 == null _salaryOrgGROUP2 == null
? 0 ? 0
: _salaryOrgGROUP2.salaryProfiles.reduce((accumulator, object) => { : _salaryOrgGROUP2.salaryProfiles.reduce((accumulator, object) => {
return accumulator + object.amountSpecial; return accumulator + object.amountSpecial;
}, 0); }, 0);
const data = { const data = {
org: item.root, org: item.root,
total: item.total + (_salaryOrgGROUP2 == null ? 0 : _salaryOrgGROUP2.total), total: item.total + (_salaryOrgGROUP2 == null ? 0 : _salaryOrgGROUP2.total),
@ -583,9 +583,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryHalfSpecial; : salaryRanks.salaryHalfSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryHalf == null || salaryRanks.salaryHalf == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryHalf - salaryProfile.amount; : salaryRanks.salaryHalf - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -598,9 +598,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryFullSpecial; : salaryRanks.salaryFullSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryFull == null || salaryRanks.salaryFull == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryFull - salaryProfile.amount; : salaryRanks.salaryFull - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -613,9 +613,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryFullHalfSpecial; : salaryRanks.salaryFullHalfSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryFullHalf == null || salaryRanks.salaryFullHalf == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryFullHalf - salaryProfile.amount; : salaryRanks.salaryFullHalf - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -1051,9 +1051,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryHalfSpecial; : salaryRanks.salaryHalfSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryHalf == null || salaryRanks.salaryHalf == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryHalf - salaryProfile.amount; : salaryRanks.salaryHalf - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -1066,9 +1066,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryFullSpecial; : salaryRanks.salaryFullSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryFull == null || salaryRanks.salaryFull == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryFull - salaryProfile.amount; : salaryRanks.salaryFull - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -1081,9 +1081,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryFullHalfSpecial; : salaryRanks.salaryFullHalfSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryFullHalf == null || salaryRanks.salaryFullHalf == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryFullHalf - salaryProfile.amount; : salaryRanks.salaryFullHalf - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -1392,9 +1392,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryHalfSpecial; : salaryRanks.salaryHalfSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryHalf == null || salaryRanks.salaryHalf == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryHalf - salaryProfile.amount; : salaryRanks.salaryHalf - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -1407,9 +1407,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryFullSpecial; : salaryRanks.salaryFullSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryFull == null || salaryRanks.salaryFull == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryFull - salaryProfile.amount; : salaryRanks.salaryFull - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -1422,9 +1422,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryFullHalfSpecial; : salaryRanks.salaryFullHalfSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryFullHalf == null || salaryRanks.salaryFullHalf == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryFullHalf - salaryProfile.amount; : salaryRanks.salaryFullHalf - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -1543,7 +1543,7 @@ export class SalaryPeriodController extends Controller {
} }
return new HttpSuccess(); return new HttpSuccess();
} }
//NEW CHANGE TYPE-MULTI //NEW CHANGE TYPE-MULTI
@Post("newchange/type-multi") @Post("newchange/type-multi")
async newchangeTypeMulti( async newchangeTypeMulti(
@ -1573,16 +1573,19 @@ export class SalaryPeriodController extends Controller {
const salaryRanks = await this.salaryRankRepository.find(); const salaryRanks = await this.salaryRankRepository.find();
// Map lookup // Map lookup
const posTypeMap = new Map(posTypes.map(x => [x.posTypeName, x])); const posTypeMap = new Map(posTypes.map((x) => [x.posTypeName, x]));
const posLevelMap = new Map(posLevels.map(x => [`${x.posTypeId}|${x.posLevelName}`, x])); const posLevelMap = new Map(posLevels.map((x) => [`${x.posTypeId}|${x.posLevelName}`, x]));
const salaryMap = new Map( const salaryMap = new Map(
salaries.map(x => [`${x.posTypeId}|${x.posLevelId}|${x.isSpecial ? 1 : 0}`, x]), salaries.map((x) => [`${x.posTypeId}|${x.posLevelId}|${x.isSpecial ? 1 : 0}`, x]),
);
const ranksBySalaryId = salaryRanks.reduce(
(acc, r: any) => {
if (!acc[r.salaryId]) acc[r.salaryId] = [];
acc[r.salaryId].push(r);
return acc;
},
{} as Record<number, SalaryRanks[]>,
); );
const ranksBySalaryId = salaryRanks.reduce((acc, r: any) => {
if (!acc[r.salaryId]) acc[r.salaryId] = [];
acc[r.salaryId].push(r);
return acc;
}, {} as Record<number, SalaryRanks[]>);
const profilesToSave: SalaryProfile[] = []; const profilesToSave: SalaryProfile[] = [];
const orgNeedRecalc = new Set<string>(); const orgNeedRecalc = new Set<string>();
@ -1616,7 +1619,9 @@ export class SalaryPeriodController extends Controller {
const posLevel = posLevelMap.get(`${posType.id}|${profile.posLevel}`); const posLevel = posLevelMap.get(`${posType.id}|${profile.posLevel}`);
if (!posLevel) throw new HttpError(404, "ไม่พบระดับตำแหน่ง"); if (!posLevel) throw new HttpError(404, "ไม่พบระดับตำแหน่ง");
const salaryBase = salaryMap.get(`${posLevel.posTypeId}|${posLevel.id}|${profile.isSpecial ? 1 : 0}`); const salaryBase = salaryMap.get(
`${posLevel.posTypeId}|${posLevel.id}|${profile.isSpecial ? 1 : 0}`,
);
if (!salaryBase) throw new HttpError(404, "ไม่พบระดับเงินเดือน"); if (!salaryBase) throw new HttpError(404, "ไม่พบระดับเงินเดือน");
const salaryId = Number(salaryBase.id); const salaryId = Number(salaryBase.id);
@ -1643,11 +1648,12 @@ export class SalaryPeriodController extends Controller {
// --- คำนวณเงินเดือนตาม rank เดิมก่อน dynamic type adjustment --- // --- คำนวณเงินเดือนตาม rank เดิมก่อน dynamic type adjustment ---
const calc = (sp: keyof SalaryRanks, next: keyof SalaryRanks) => ({ const calc = (sp: keyof SalaryRanks, next: keyof SalaryRanks) => ({
amountSpecial: rank?.[sp] ?? 0, amountSpecial: rank?.[sp] ?? 0,
amountUse: profile.amount != null && rank?.[next] != null amountUse:
? Number(rank[next]) - Number(profile.amount) profile.amount != null && rank?.[next] != null
: 0, ? Number(rank[next]) - Number(profile.amount)
: 0,
positionSalaryAmount: rank?.[next] ?? 0, positionSalaryAmount: rank?.[next] ?? 0,
isNext: rank?.isNext ?? 0 isNext: rank?.isNext ?? 0,
}); });
// --- FULLHAFT dynamic type adjustment หลังคำนวณเงินเดือน --- // --- FULLHAFT dynamic type adjustment หลังคำนวณเงินเดือน ---
@ -1715,7 +1721,7 @@ export class SalaryPeriodController extends Controller {
// SNAP1 / APR // SNAP1 / APR
if (org.snapshot === "SNAP1" && org.salaryPeriod.period === "APR") { if (org.snapshot === "SNAP1" && org.salaryPeriod.period === "APR") {
const countFull = org.salaryProfiles.filter(p => p.type === "FULL").length; const countFull = org.salaryProfiles.filter((p) => p.type === "FULL").length;
org.total = org.salaryProfiles.length; org.total = org.salaryProfiles.length;
org.fifteenPercent = Math.floor(org.total * 0.15); org.fifteenPercent = Math.floor(org.total * 0.15);
org.quantityUsed = countFull; org.quantityUsed = countFull;
@ -1729,7 +1735,7 @@ export class SalaryPeriodController extends Controller {
org.sixPercentAmount = total * 0.06; org.sixPercentAmount = total * 0.06;
const useAmount = org.salaryProfiles const useAmount = org.salaryProfiles
.filter(p => ["HAFT", "FULL", "FULLHAFT"].includes(p.type)) .filter((p) => ["HAFT", "FULL", "FULLHAFT"].includes(p.type))
.reduce((s, p) => s + (p.amountUse ?? 0), 0); .reduce((s, p) => s + (p.amountUse ?? 0), 0);
org.useAmount = useAmount; org.useAmount = useAmount;
@ -1737,17 +1743,25 @@ export class SalaryPeriodController extends Controller {
// --- SNAP2 APR recalc --- // --- SNAP2 APR recalc ---
const salaryPeriodAPROld = await this.salaryPeriodRepository.findOne({ const salaryPeriodAPROld = await this.salaryPeriodRepository.findOne({
where: { period: "APR", year: org.salaryPeriod.year } where: { period: "APR", year: org.salaryPeriod.year },
}); });
if (salaryPeriodAPROld) { if (salaryPeriodAPROld) {
const orgSnap2Old: any = await this.salaryOrgRepository.findOne({ const orgSnap2Old: any = await this.salaryOrgRepository.findOne({
where: { salaryPeriodId: salaryPeriodAPROld.id, rootId: org.rootId, group: org.group, snapshot: "SNAP2" }, where: {
relations: ["salaryProfiles"] salaryPeriodId: salaryPeriodAPROld.id,
rootId: org.rootId,
group: org.group,
snapshot: "SNAP2",
},
relations: ["salaryProfiles"],
}); });
if (orgSnap2Old) { if (orgSnap2Old) {
const spent = orgSnap2Old.salaryProfiles.reduce((sum: number, p: any) => sum + (p.amountUse ?? 0), 0); const spent = orgSnap2Old.salaryProfiles.reduce(
(sum: number, p: any) => sum + (p.amountUse ?? 0),
0,
);
org.spentAmount = spent; org.spentAmount = spent;
org.remainingAmount = (org.sixPercentAmount - useAmount) - spent; org.remainingAmount = org.sixPercentAmount - useAmount - spent;
} }
} }
} }
@ -1763,10 +1777,6 @@ export class SalaryPeriodController extends Controller {
return new HttpSuccess(); return new HttpSuccess();
} }
/** /**
* API * API
* *
@ -1876,7 +1886,7 @@ export class SalaryPeriodController extends Controller {
_data.child1 != undefined && _data.child1 != null _data.child1 != undefined && _data.child1 != null
? _data.child1[0] != null ? _data.child1[0] != null
? `child1Id IN (:...child1)` ? `child1Id IN (:...child1)`
: `child1Id is null` : `child1Id is ${_data.privilege == "PARENT" ? "not null" : "null"}`
: "1=1", : "1=1",
{ {
child1: _data.child1, child1: _data.child1,
@ -1911,7 +1921,7 @@ export class SalaryPeriodController extends Controller {
{ {
child4: _data.child4, child4: _data.child4,
}, },
) );
if (body.sortBy) { if (body.sortBy) {
if (body.sortBy === "posExecutive") { if (body.sortBy === "posExecutive") {
@ -1919,18 +1929,16 @@ export class SalaryPeriodController extends Controller {
.orderBy(`profile.posExecutive`, body.descending ? "DESC" : "ASC") .orderBy(`profile.posExecutive`, body.descending ? "DESC" : "ASC")
.addOrderBy(`profile.positionExecutiveField`, body.descending ? "DESC" : "ASC"); .addOrderBy(`profile.positionExecutiveField`, body.descending ? "DESC" : "ASC");
} else { } else {
query = query.orderBy( query = query.orderBy(`profile.${body.sortBy}`, body.descending ? "DESC" : "ASC");
`profile.${body.sortBy}`,
body.descending ? "DESC" : "ASC"
);
} }
} else { } else {
query = query.orderBy("profile.rootOrder", "ASC") query = query
.orderBy("profile.rootOrder", "ASC")
.addOrderBy("profile.child1Order", "ASC") .addOrderBy("profile.child1Order", "ASC")
.addOrderBy("profile.child2Order", "ASC") .addOrderBy("profile.child2Order", "ASC")
.addOrderBy("profile.child3Order", "ASC") .addOrderBy("profile.child3Order", "ASC")
.addOrderBy("profile.child4Order", "ASC") .addOrderBy("profile.child4Order", "ASC")
.addOrderBy("profile.posMasterNo", "ASC") .addOrderBy("profile.posMasterNo", "ASC");
} }
const [salaryProfile, total] = await query const [salaryProfile, total] = await query
@ -2164,9 +2172,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryHalfSpecial; : salaryRanks.salaryHalfSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryHalf == null || salaryRanks.salaryHalf == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryHalf - salaryProfile.amount; : salaryRanks.salaryHalf - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -2179,9 +2187,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryFullSpecial; : salaryRanks.salaryFullSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryFull == null || salaryRanks.salaryFull == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryFull - salaryProfile.amount; : salaryRanks.salaryFull - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -2194,9 +2202,9 @@ export class SalaryPeriodController extends Controller {
: salaryRanks.salaryFullHalfSpecial; : salaryRanks.salaryFullHalfSpecial;
salaryProfile.amountUse = salaryProfile.amountUse =
salaryRanks == null || salaryRanks == null ||
salaryProfile == null || salaryProfile == null ||
salaryRanks.salaryFullHalf == null || salaryRanks.salaryFullHalf == null ||
salaryProfile.amount == null salaryProfile.amount == null
? 0 ? 0
: salaryRanks.salaryFullHalf - salaryProfile.amount; : salaryRanks.salaryFullHalf - salaryProfile.amount;
salaryProfile.positionSalaryAmount = salaryProfile.positionSalaryAmount =
@ -2759,16 +2767,14 @@ export class SalaryPeriodController extends Controller {
"salaryPeriod.status", "salaryPeriod.status",
"salaryPeriod.year", "salaryPeriod.year",
"salaryPeriod.revisionId", "salaryPeriod.revisionId",
]) ]);
if (sortBy) { if (sortBy) {
query = query.orderBy( query = query.orderBy(`salaryPeriod.${sortBy}`, descending ? "DESC" : "ASC");
`salaryPeriod.${sortBy}`,
descending ? "DESC" : "ASC"
);
} else { } else {
query = query.orderBy("salaryPeriod.year", "DESC") query = query
.addOrderBy("salaryPeriod.effectiveDate", "DESC") .orderBy("salaryPeriod.year", "DESC")
.addOrderBy("salaryPeriod.effectiveDate", "DESC");
} }
const [salaryPeriod, total] = await query const [salaryPeriod, total] = await query
@ -3018,27 +3024,27 @@ export class SalaryPeriodController extends Controller {
const [salaryProfileCount, salaryProfileEmployeeCount] = await Promise.all([ const [salaryProfileCount, salaryProfileEmployeeCount] = await Promise.all([
salaryOrgCount > 0 salaryOrgCount > 0
? AppDataSource.query( ? AppDataSource.query(
` `
SELECT COUNT(*) as count FROM salaryProfile SELECT COUNT(*) as count FROM salaryProfile
WHERE salaryOrgId IN ( WHERE salaryOrgId IN (
SELECT id FROM salaryOrg SELECT id FROM salaryOrg
WHERE salaryPeriodId = ? AND snapshot = ? WHERE salaryPeriodId = ? AND snapshot = ?
) )
`, `,
[salaryPeriod.id, snapshot], [salaryPeriod.id, snapshot],
).then((result) => result[0]?.count || 0) ).then((result) => result[0]?.count || 0)
: Promise.resolve(0), : Promise.resolve(0),
salaryOrgEmployeeCount > 0 salaryOrgEmployeeCount > 0
? AppDataSource.query( ? AppDataSource.query(
` `
SELECT COUNT(*) as count FROM salaryProfileEmployee SELECT COUNT(*) as count FROM salaryProfileEmployee
WHERE salaryOrgId IN ( WHERE salaryOrgId IN (
SELECT id FROM salaryOrgEmployee SELECT id FROM salaryOrgEmployee
WHERE salaryPeriodId = ? AND snapshot = ? WHERE salaryPeriodId = ? AND snapshot = ?
) )
`, `,
[salaryPeriod.id, snapshot], [salaryPeriod.id, snapshot],
).then((result) => result[0]?.count || 0) ).then((result) => result[0]?.count || 0)
: Promise.resolve(0), : Promise.resolve(0),
]); ]);
@ -3051,27 +3057,27 @@ export class SalaryPeriodController extends Controller {
await Promise.all([ await Promise.all([
salaryOrgCount > 0 salaryOrgCount > 0
? AppDataSource.query( ? AppDataSource.query(
` `
DELETE FROM salaryProfile DELETE FROM salaryProfile
WHERE salaryOrgId IN ( WHERE salaryOrgId IN (
SELECT id FROM salaryOrg SELECT id FROM salaryOrg
WHERE salaryPeriodId = ? AND snapshot = ? WHERE salaryPeriodId = ? AND snapshot = ?
) )
`, `,
[salaryPeriod.id, snapshot], [salaryPeriod.id, snapshot],
) )
: Promise.resolve(), : Promise.resolve(),
salaryOrgEmployeeCount > 0 salaryOrgEmployeeCount > 0
? AppDataSource.query( ? AppDataSource.query(
` `
DELETE FROM salaryProfileEmployee DELETE FROM salaryProfileEmployee
WHERE salaryOrgId IN ( WHERE salaryOrgId IN (
SELECT id FROM salaryOrgEmployee SELECT id FROM salaryOrgEmployee
WHERE salaryPeriodId = ? AND snapshot = ? WHERE salaryPeriodId = ? AND snapshot = ?
) )
`, `,
[salaryPeriod.id, snapshot], [salaryPeriod.id, snapshot],
) )
: Promise.resolve(), : Promise.resolve(),
]); ]);
@ -4047,27 +4053,27 @@ export class SalaryPeriodController extends Controller {
const [salaryProfileCount, salaryProfileEmployeeCount] = await Promise.all([ const [salaryProfileCount, salaryProfileEmployeeCount] = await Promise.all([
salaryOrgCount > 0 salaryOrgCount > 0
? AppDataSource.query( ? AppDataSource.query(
` `
SELECT COUNT(*) as count FROM salaryProfile SELECT COUNT(*) as count FROM salaryProfile
WHERE salaryOrgId IN ( WHERE salaryOrgId IN (
SELECT id FROM salaryOrg SELECT id FROM salaryOrg
WHERE salaryPeriodId = ? AND snapshot = ? WHERE salaryPeriodId = ? AND snapshot = ?
) )
`, `,
[salaryPeriod.id, snapshot], [salaryPeriod.id, snapshot],
).then((result) => result[0]?.count || 0) ).then((result) => result[0]?.count || 0)
: Promise.resolve(0), : Promise.resolve(0),
salaryOrgEmployeeCount > 0 salaryOrgEmployeeCount > 0
? AppDataSource.query( ? AppDataSource.query(
` `
SELECT COUNT(*) as count FROM salaryProfileEmployee SELECT COUNT(*) as count FROM salaryProfileEmployee
WHERE salaryOrgId IN ( WHERE salaryOrgId IN (
SELECT id FROM salaryOrgEmployee SELECT id FROM salaryOrgEmployee
WHERE salaryPeriodId = ? AND snapshot = ? WHERE salaryPeriodId = ? AND snapshot = ?
) )
`, `,
[salaryPeriod.id, snapshot], [salaryPeriod.id, snapshot],
).then((result) => result[0]?.count || 0) ).then((result) => result[0]?.count || 0)
: Promise.resolve(0), : Promise.resolve(0),
]); ]);
@ -4080,27 +4086,27 @@ export class SalaryPeriodController extends Controller {
await Promise.all([ await Promise.all([
salaryOrgCount > 0 salaryOrgCount > 0
? AppDataSource.query( ? AppDataSource.query(
` `
DELETE FROM salaryProfile DELETE FROM salaryProfile
WHERE salaryOrgId IN ( WHERE salaryOrgId IN (
SELECT id FROM salaryOrg SELECT id FROM salaryOrg
WHERE salaryPeriodId = ? AND snapshot = ? WHERE salaryPeriodId = ? AND snapshot = ?
) )
`, `,
[salaryPeriod.id, snapshot], [salaryPeriod.id, snapshot],
) )
: Promise.resolve(), : Promise.resolve(),
salaryOrgEmployeeCount > 0 salaryOrgEmployeeCount > 0
? AppDataSource.query( ? AppDataSource.query(
` `
DELETE FROM salaryProfileEmployee DELETE FROM salaryProfileEmployee
WHERE salaryOrgId IN ( WHERE salaryOrgId IN (
SELECT id FROM salaryOrgEmployee SELECT id FROM salaryOrgEmployee
WHERE salaryPeriodId = ? AND snapshot = ? WHERE salaryPeriodId = ? AND snapshot = ?
) )
`, `,
[salaryPeriod.id, snapshot], [salaryPeriod.id, snapshot],
) )
: Promise.resolve(), : Promise.resolve(),
]); ]);
@ -4152,22 +4158,40 @@ export class SalaryPeriodController extends Controller {
// Parallel loading of initial data and API calls // Parallel loading of initial data and API calls
console.time("⏱ API: Load initial data"); console.time("⏱ API: Load initial data");
const [orgs, revisionId, _orgProfiles, _orgProfileEmployees] = await Promise.all([ const [orgs, revisionId, _orgProfiles, _orgProfileEmployees] = await Promise.all([
new CallAPI().GetData({ headers: { authorization: request } }, "/org/unauthorize/active/root/id", false), new CallAPI().GetData(
new CallAPI().GetData({ headers: { authorization: request } }, "/org/unauthorize/revision/latest", false), { headers: { authorization: request } },
new CallAPI().PostData({ headers: { authorization: request } }, "/org/unauthorize/new-salary/gen", { "/org/unauthorize/active/root/id",
page: 1, false,
pageSize: 1000, ),
keyword: "", new CallAPI().GetData(
year: salaryPeriod.year, { headers: { authorization: request } },
period: salaryPeriod.period, "/org/unauthorize/revision/latest",
}, false), false,
new CallAPI().PostData({ headers: { authorization: request } }, "/org/unauthorize/new-salary/employee/gen", { ),
page: 1, new CallAPI().PostData(
pageSize: 1000, { headers: { authorization: request } },
keyword: "", "/org/unauthorize/new-salary/gen",
year: salaryPeriod.year, {
period: salaryPeriod.period, page: 1,
}, false), pageSize: 1000,
keyword: "",
year: salaryPeriod.year,
period: salaryPeriod.period,
},
false,
),
new CallAPI().PostData(
{ headers: { authorization: request } },
"/org/unauthorize/new-salary/employee/gen",
{
page: 1,
pageSize: 1000,
keyword: "",
year: salaryPeriod.year,
period: salaryPeriod.period,
},
false,
),
]); ]);
console.timeEnd("⏱ API: Load initial data"); console.timeEnd("⏱ API: Load initial data");
@ -4182,13 +4206,18 @@ export class SalaryPeriodController extends Controller {
const promises = []; const promises = [];
for (let index = 2; index <= page; index++) { for (let index = 2; index <= page; index++) {
promises.push( promises.push(
new CallAPI().PostData({ headers: { authorization: request } }, "/org/unauthorize/new-salary/gen", { new CallAPI().PostData(
page: index, { headers: { authorization: request } },
pageSize: 1000, "/org/unauthorize/new-salary/gen",
keyword: "", {
year: salaryPeriod.year, page: index,
period: salaryPeriod.period, pageSize: 1000,
}, false), keyword: "",
year: salaryPeriod.year,
period: salaryPeriod.period,
},
false,
),
); );
} }
const results = await Promise.all(promises); const results = await Promise.all(promises);
@ -4207,13 +4236,18 @@ export class SalaryPeriodController extends Controller {
const promises = []; const promises = [];
for (let index = 2; index <= page; index++) { for (let index = 2; index <= page; index++) {
promises.push( promises.push(
new CallAPI().PostData({ headers: { authorization: request } }, "/org/unauthorize/new-salary/employee/gen", { new CallAPI().PostData(
page: index, { headers: { authorization: request } },
pageSize: 1000, "/org/unauthorize/new-salary/employee/gen",
keyword: "", {
year: salaryPeriod.year, page: index,
period: salaryPeriod.period, pageSize: 1000,
}, false), keyword: "",
year: salaryPeriod.year,
period: salaryPeriod.period,
},
false,
),
); );
} }
const results = await Promise.all(promises); const results = await Promise.all(promises);
@ -4799,9 +4833,9 @@ export class SalaryPeriodController extends Controller {
_salaryOrg.remainQuota = Math.floor((_salaryOrg.salaryProfiles.length * 15) / 100); _salaryOrg.remainQuota = Math.floor((_salaryOrg.salaryProfiles.length * 15) / 100);
} }
_salaryOrg.createdUserId = "" _salaryOrg.createdUserId = "";
_salaryOrg.createdFullName = "System Administrator"; _salaryOrg.createdFullName = "System Administrator";
_salaryOrg.lastUpdateUserId = "" _salaryOrg.lastUpdateUserId = "";
_salaryOrg.lastUpdateFullName = "System Administrator"; _salaryOrg.lastUpdateFullName = "System Administrator";
_salaryOrg.createdAt = new Date(); _salaryOrg.createdAt = new Date();
_salaryOrg.lastUpdatedAt = new Date(); _salaryOrg.lastUpdatedAt = new Date();
@ -4939,7 +4973,8 @@ export class SalaryPeriodController extends Controller {
); );
let request: any = response.data.access_token; let request: any = response.data.access_token;
if (current.getDate() == 1 && current.getMonth() == 2) { //snap1 วันที่ 1 มีนา if (current.getDate() == 1 && current.getMonth() == 2) {
//snap1 วันที่ 1 มีนา
salaryPeriod = await this.salaryPeriodRepository.findOne({ salaryPeriod = await this.salaryPeriodRepository.findOne({
where: { where: {
year: current.getFullYear(), year: current.getFullYear(),
@ -4950,7 +4985,8 @@ export class SalaryPeriodController extends Controller {
if (salaryPeriod) { if (salaryPeriod) {
this.performSnapshotOperationForCronjob("SNAP1", salaryPeriod.id, request); this.performSnapshotOperationForCronjob("SNAP1", salaryPeriod.id, request);
} }
} else if (current.getDate() == 1 && current.getMonth() == 3) { //snap2 วันที่ 1 เมษา } else if (current.getDate() == 1 && current.getMonth() == 3) {
//snap2 วันที่ 1 เมษา
salaryPeriod = await this.salaryPeriodRepository.findOne({ salaryPeriod = await this.salaryPeriodRepository.findOne({
where: { where: {
year: current.getFullYear(), year: current.getFullYear(),
@ -4961,7 +4997,8 @@ export class SalaryPeriodController extends Controller {
if (salaryPeriod) { if (salaryPeriod) {
this.performSnapshotOperationForCronjob("SNAP2", salaryPeriod.id, request); this.performSnapshotOperationForCronjob("SNAP2", salaryPeriod.id, request);
} }
} else if (current.getDate() == 1 && current.getMonth() == 8) { //snap1 วันที่ 1 กันยา } else if (current.getDate() == 1 && current.getMonth() == 8) {
//snap1 วันที่ 1 กันยา
salaryPeriod = await this.salaryPeriodRepository.findOne({ salaryPeriod = await this.salaryPeriodRepository.findOne({
where: { where: {
year: current.getFullYear(), year: current.getFullYear(),
@ -4972,7 +5009,8 @@ export class SalaryPeriodController extends Controller {
if (salaryPeriod) { if (salaryPeriod) {
this.performSnapshotOperationForCronjob("SNAP1", salaryPeriod.id, request); this.performSnapshotOperationForCronjob("SNAP1", salaryPeriod.id, request);
} }
} else if (current.getDate() == 1 && current.getMonth() == 9) { //snap2 วันที่ 1 ตุลา } else if (current.getDate() == 1 && current.getMonth() == 9) {
//snap2 วันที่ 1 ตุลา
salaryPeriod = await this.salaryPeriodRepository.findOne({ salaryPeriod = await this.salaryPeriodRepository.findOne({
where: { where: {
year: current.getFullYear(), year: current.getFullYear(),

View file

@ -94,6 +94,15 @@ class CheckAuth {
child4: null, child4: null,
privilege: "ROOT", privilege: "ROOT",
}; };
} else if (privilege == "PARENT") {
data = {
root: [x.orgRootId],
child1: [null],
child2: null,
child3: null,
child4: null,
privilege: "PARENT",
};
} else if (privilege == "CHILD") { } else if (privilege == "CHILD") {
data = { data = {
root: node >= 0 ? [x.orgRootId] : null, root: node >= 0 ? [x.orgRootId] : null,
@ -103,6 +112,15 @@ class CheckAuth {
child4: node >= 4 ? [x.orgChild4Id] : null, child4: node >= 4 ? [x.orgChild4Id] : null,
privilege: "CHILD", privilege: "CHILD",
}; };
} else if (privilege == "BROTHER") {
data = {
// root: node >= 0 ? [x.orgRootId] : null,
root: node >= 0 ? [x.orgRootId] : null,
child1: node >= 2 ? [x.orgChild1Id] : null,
child2: node >= 3 ? [x.orgChild2Id] : null,
child3: node >= 4 ? [x.orgChild3Id] : null,
privilege: "BROTHER",
};
} else if (privilege == "NORMAL") { } else if (privilege == "NORMAL") {
data = { data = {
root: [x.orgRootId], root: [x.orgRootId],
@ -185,38 +203,38 @@ class CheckAuth {
} }
public async checkOrg(token: any, keycloakId: string) { public async checkOrg(token: any, keycloakId: string) {
const redisClient = await this.redis.createClient({ const redisClient = await this.redis.createClient({
host: process.env.REDIS_HOST, host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT, port: process.env.REDIS_PORT,
}) });
const getAsync = promisify(redisClient.get).bind(redisClient) const getAsync = promisify(redisClient.get).bind(redisClient);
try { try {
let reply = await getAsync("org_" + keycloakId) let reply = await getAsync("org_" + keycloakId);
if (reply != null) { if (reply != null) {
reply = JSON.parse(reply) reply = JSON.parse(reply);
} else { } else {
if (!keycloakId) throw new Error("No KeycloakId provided") if (!keycloakId) throw new Error("No KeycloakId provided");
const x = await new CallAPI().GetData( const x = await new CallAPI().GetData(
{ {
headers: { authorization: token }, headers: { authorization: token },
}, },
`/org/permission/checkOrg/${keycloakId}`, `/org/permission/checkOrg/${keycloakId}`,
false false,
) );
const data = { const data = {
orgRootId: x.orgRootId, orgRootId: x.orgRootId,
orgChild1Id: x.orgChild1Id, orgChild1Id: x.orgChild1Id,
orgChild2Id: x.orgChild2Id, orgChild2Id: x.orgChild2Id,
orgChild3Id: x.orgChild3Id, orgChild3Id: x.orgChild3Id,
orgChild4Id: x.orgChild4Id, orgChild4Id: x.orgChild4Id,
} };
return data return data;
} }
} catch (error) { } catch (error) {
console.error("Error calling API:", error) console.error("Error calling API:", error);
throw error throw error;
} }
} }
public async PermissionCreate(req: RequestWithUser, system: string) { public async PermissionCreate(req: RequestWithUser, system: string) {
return await this.Permission(req, system, "CREATE"); return await this.Permission(req, system, "CREATE");