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

@ -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) => { const ranksBySalaryId = salaryRanks.reduce(
(acc, r: any) => {
if (!acc[r.salaryId]) acc[r.salaryId] = []; if (!acc[r.salaryId]) acc[r.salaryId] = [];
acc[r.salaryId].push(r); acc[r.salaryId].push(r);
return acc; return acc;
}, {} as Record<number, SalaryRanks[]>); },
{} 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:
profile.amount != null && rank?.[next] != null
? Number(rank[next]) - Number(profile.amount) ? Number(rank[next]) - Number(profile.amount)
: 0, : 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
@ -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
@ -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",
false,
),
new CallAPI().GetData(
{ headers: { authorization: request } },
"/org/unauthorize/revision/latest",
false,
),
new CallAPI().PostData(
{ headers: { authorization: request } },
"/org/unauthorize/new-salary/gen",
{
page: 1, page: 1,
pageSize: 1000, pageSize: 1000,
keyword: "", keyword: "",
year: salaryPeriod.year, year: salaryPeriod.year,
period: salaryPeriod.period, period: salaryPeriod.period,
}, false), },
new CallAPI().PostData({ headers: { authorization: request } }, "/org/unauthorize/new-salary/employee/gen", { false,
),
new CallAPI().PostData(
{ headers: { authorization: request } },
"/org/unauthorize/new-salary/employee/gen",
{
page: 1, page: 1,
pageSize: 1000, pageSize: 1000,
keyword: "", keyword: "",
year: salaryPeriod.year, year: salaryPeriod.year,
period: salaryPeriod.period, period: salaryPeriod.period,
}, false), },
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(
{ headers: { authorization: request } },
"/org/unauthorize/new-salary/gen",
{
page: index, page: index,
pageSize: 1000, pageSize: 1000,
keyword: "", keyword: "",
year: salaryPeriod.year, year: salaryPeriod.year,
period: salaryPeriod.period, period: salaryPeriod.period,
}, false), },
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(
{ headers: { authorization: request } },
"/org/unauthorize/new-salary/employee/gen",
{
page: index, page: index,
pageSize: 1000, pageSize: 1000,
keyword: "", keyword: "",
year: salaryPeriod.year, year: salaryPeriod.year,
period: salaryPeriod.period, period: salaryPeriod.period,
}, false), },
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],
@ -187,21 +205,21 @@ class CheckAuth {
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,
@ -209,13 +227,13 @@ class CheckAuth {
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) {