AttendanceModal.vue
29.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
<template>
<div>
<BasicForm @register="registerForm" />
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch, computed, onMounted, onUnmounted } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './attendance.data';
import { defHttp } from '/@/utils/http/axios';
export default defineComponent({
name: 'AttendanceForm',
components: { BasicForm },
props: {
record: {
type: Object,
default: () => ({}),
},
isUpdate: {
type: Boolean,
default: false,
},
dateTime:{
type: String,
default:''
}
},
setup(props, { emit }) {
const rowId = ref('');
const attendanceOptions = ref<any[]>([]);
const modifiedFormSchema = ref<any[]>([...formSchema]);
// 存储原始考勤组数据,方便通过ID查找详细信息
const attendanceData = ref<any[]>([]);
const dateTime = ref(props.dateTime || '');
// 存储当前表单数据的引用
const formData = ref<any>({});
// 更新上月存休字段,添加或移除警告样式
function updateLastMonthField(showWarning) {
// 获取当前记录的审核状态和字段权限信息
const currentRecord = props.record || {};
const attendanceStatus = currentRecord.attendanceStatus;
const fieldPermissions = currentRecord.userOldAttendanceFieldVO || {};
// 判断lastMonthLeaveDays字段是否应该被禁用
let shouldDisableByPermission = false;
if (attendanceStatus === 10) {
const fieldKey = getFieldPermissionKey('lastMonthLeaveDays');
if (fieldKey && fieldPermissions[fieldKey] === 'LOCKED') {
shouldDisableByPermission = true;
}
}
const updatedSchema = modifiedFormSchema.value.map(item => {
if (item.field === 'lastMonthLeaveDays') {
// 保存原有的onChange处理器
const originalOnChange = item.componentProps?.onChange;
if (showWarning) {
return {
...item,
required: true,
componentProps: {
placeholder: '上月数据没配置或未审核,请手动输入上月存休数据',
style: {
borderColor: '#ff4d4f',
background: '#fff2f0'
},
disabled: shouldDisableByPermission,
onChange: (value) => {
calculateTotalLeaveDays(value, 'lastMonthLeaveDays');
setTimeout(() => {
formData.value = getFieldsValue() || {};
}, 0);
if (typeof originalOnChange === 'function') {
originalOnChange(value);
}
}
}
};
} else {
return {
...item,
componentProps: {
disabled: shouldDisableByPermission,
onChange: (value) => {
calculateTotalLeaveDays(value, 'lastMonthLeaveDays');
setTimeout(() => {
formData.value = getFieldsValue() || {};
}, 0);
if (typeof originalOnChange === 'function') {
originalOnChange(value);
}
}
}
};
}
}
return item;
});
modifiedFormSchema.value = updatedSchema;
}
// 获取考勤组数据
async function getAttendanceOptions() {
try {
const [year, month] = dateTime.value.split('-');
// const relationName = +month < 10 ? +month + 1 : +month;
const relationName = +month;
const res = await defHttp.post<any>({
url: '/order/erp/system_setting/query_list',
params: {
setting_type: [61, 62, 63, 64],
setting_value: year,
relation_name: relationName,
}
});
if (Array.isArray(res)) {
// 存储原始数据
attendanceData.value = res;
// 按settingType和settingValue分组处理数据
const groupedData: Record<number, Record<string, any[]>> = {
61: {},
62: {},
63: {},
64: {}
};
// 按年份分组
const yearGroups: Record<string, { label: string, options: any[] }> = {};
// 清空选项
attendanceOptions.value = [];
// 分组处理数据
res.forEach(item => {
const type = item.settingType;
const value = item.settingValue;
if (type >= 61 && type <= 64 && value) {
if (!groupedData[type][value]) {
groupedData[type][value] = [];
}
groupedData[type][value].push(item);
}
});
// 为每个分组创建选项
Object.entries(groupedData).forEach(([typeStr, valueGroups]) => {
const type = parseInt(typeStr);
const baseLabel = getAttendanceLabel(type);
Object.entries(valueGroups).forEach(([value, items]) => {
if (items.length > 0) {
const ids = items.map(item => item.id);
// 创建选项,值格式为 "type:value"
const optionValue = `${type}:${value}`;
const optionLabel = `${baseLabel}(${value})`;
// 按年份分组
if (!yearGroups[value]) {
yearGroups[value] = {
label: `${value}年`,
options: []
};
}
yearGroups[value].options.push({
label: optionLabel,
value: optionValue,
ids: ids
});
// 同时保存到扁平数组中,方便后续查找
attendanceOptions.value.push({
value: optionValue,
label: optionLabel,
ids: ids
});
}
});
});
// 将年份分组转为数组,并按年份降序排序
const yearGroupsArray = Object.entries(yearGroups).map(([year, group]) => {
// 按考勤类型排序选项
const sortedOptions = group.options.sort((a, b) => {
const typeA = parseInt(a.value.split(':')[0]);
const typeB = parseInt(b.value.split(':')[0]);
return typeA - typeB;
});
return {
...group,
options: sortedOptions
};
}).sort((a, b) => {
const yearA = a.label.replace('年', '');
const yearB = b.label.replace('年', '');
return yearB.localeCompare(yearA); // 降序排序,新年份在前
});
// 更新表单架构,将monthlyAttendanceName字段改为分组下拉选择
updateFormSchema(yearGroupsArray);
}
} catch (error) {
console.error('获取考勤组数据失败:', error);
}
}
// 获取考勤组标签
function getAttendanceLabel(type: number) {
switch (type) {
case 61:
return '9小时双休';
case 62:
return '9小时大小周';
case 63:
return '8小时双休';
case 64:
return '8.5小时大小周';
default:
return '未知考勤组';
}
}
// 计算累计存休
function calculateTotalLeaveDays(newFieldValue: any = null, fieldName: string | null = null) {
// 获取当前表单值
let values = formData.value || {};
// 如果传入了新值和字段名,则使用新值覆盖原有值进行计算
if (newFieldValue !== null && fieldName !== null) {
values = { ...values, [fieldName]: newFieldValue };
}
// 获取相关字段值,如果不存在则默认为0
const lastMonthLeaveDays = values.lastMonthLeaveDays !== undefined ? Number(values.lastMonthLeaveDays) : 0;
const storageLeaveDays = values.storageLeaveDays !== undefined ? Number(values.storageLeaveDays) : 0;
const compensatoryLeaveDays = values.compensatoryLeaveDays !== undefined ? Number(values.compensatoryLeaveDays) : 0;
// 计算累计存休
const totalStorageLeaveDays = lastMonthLeaveDays + storageLeaveDays - compensatoryLeaveDays;
// 更新累计存休字段
setFieldsValue({
totalStorageLeaveDays
});
}
// 更新表单架构,将monthlyAttendanceName字段改为下拉选择
function updateFormSchema(yearGroupsArray: any[]) {
// 获取当前系统年月
const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1;
// 获取查询年月
let queryYear = 0;
let queryMonth = 0;
if (dateTime.value) {
const parts = dateTime.value.split('-');
queryYear = parseInt(parts[0]);
queryMonth = parseInt(parts[1]);
}
// 判断是否禁止修改
const isDisabled = (queryYear === currentYear && queryMonth === currentMonth);
// 获取当前记录的审核状态和字段权限信息
const currentRecord = props.record || {};
const attendanceStatus = currentRecord.attendanceStatus;
const fieldPermissions = currentRecord.userOldAttendanceFieldVO || {};
const updatedSchema = modifiedFormSchema.value.map(item => {
// 处理考勤组字段
if (item.field === 'monthlyAttendanceName') {
// 判断考勤组字段是否应该被禁用
let shouldDisableByPermission = false;
// 如果审核状态为10,则根据字段权限判断是否禁用
if (attendanceStatus === 10) {
const fieldKey = getFieldPermissionKey(item.field);
if (fieldKey && fieldPermissions[fieldKey] === 'LOCKED') {
shouldDisableByPermission = true;
}
}
// 最终的禁用状态:要么因为是当前年月,要么因为权限被锁定
const finalDisabled = isDisabled || shouldDisableByPermission;
return {
...item,
component: 'Select',
componentProps: {
options: yearGroupsArray,
optionGroups: true,
placeholder: finalDisabled ? (isDisabled ? '请在员工档案中配置考勤组' : '该字段已被锁定,无法编辑') : '请选择考勤组',
onChange: handleAttendanceChange,
disabled: finalDisabled,
},
};
}
// 处理存休相关字段的onChange事件
else if (['storageLeaveDays', 'compensatoryLeaveDays'].includes(item.field)) {
// 判断当前字段是否应该被禁用
let shouldDisable = false;
// 如果审核状态为10,则根据字段权限判断是否禁用
if (attendanceStatus === 10) {
const fieldKey = getFieldPermissionKey(item.field);
if (fieldKey && fieldPermissions[fieldKey] === 'LOCKED') {
shouldDisable = true;
}
}
return {
...item,
componentProps: {
...(item.componentProps || {}),
disabled: shouldDisable,
onChange: (value) => {
const fieldName = item.field;
try {
calculateTotalLeaveDays(value, fieldName);
setTimeout(() => {
formData.value = getFieldsValue() || {};
}, 0);
} catch (error) {
console.error('计算累计存休时出错:', error);
}
},
},
};
}
// 处理其他可编辑字段
else if (['attendanceDays', 'leaveDays', 'workHours'].includes(item.field)) {
// 判断当前字段是否应该被禁用
let shouldDisable = false;
// 如果审核状态为10,则根据字段权限判断是否禁用
if (attendanceStatus === 10) {
const fieldKey = getFieldPermissionKey(item.field);
if (fieldKey && fieldPermissions[fieldKey] === 'LOCKED') {
shouldDisable = true;
}
}
return {
...item,
componentProps: {
...(item.componentProps || {}),
disabled: shouldDisable,
},
};
}
// 处理累计存休字段(只读)
else if (item.field === 'totalStorageLeaveDays') {
return {
...item,
componentProps: {
...(item.componentProps || {}),
disabled: true,
},
};
}
return item;
});
modifiedFormSchema.value = updatedSchema;
resetFields();
// 如果有记录数据,重新设置表单值
if (props.record && Object.keys(props.record).length > 0) {
setFormValues(props.record);
}
}
// 获取字段权限对应的key
function getFieldPermissionKey(fieldName: string): string | null {
const fieldMapping: Record<string, string> = {
'attendanceDays': 'attendanceDays',
'leaveDays': 'leaveDays',
'compensatoryLeaveDays': 'compensatoryLeaveDays',
'storageLeaveDays': 'storageLeaveDays',
'lastMonthLeaveDays': 'lastMonthLeaveDays',
'totalStorageLeaveDays': 'totalStorageLeaveDays',
'workHours': 'workHours',
'monthlyAttendanceName': 'monthlyAttendance'
};
return fieldMapping[fieldName] || null;
}
// 尝试解析 relationValue 字符串
function tryParseRelationValue(relationValue: string) {
try {
if (!relationValue) return null;
const parsedData = JSON.parse(relationValue);
return parsedData;
} catch (error) {
console.error('解析 relationValue 失败:', error);
return null;
}
}
// 处理考勤组选择变更
function handleAttendanceChange(value: string) {
// 获取当前系统年月
const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1;
// 获取查询年月
let queryYear = 0;
let queryMonth = 0;
if (dateTime.value) {
const parts = dateTime.value.split('-');
queryYear = parseInt(parts[0]);
queryMonth = parseInt(parts[1]);
}
// 判断是否禁止修改
const isDisabled = (queryYear === currentYear && queryMonth === currentMonth);
// 如果是当前年份,禁止修改
if (isDisabled) {
console.warn('当前年份考勤组不可修改');
return;
}
// 非当前年份,允许修改
if (value) {
const selectedOption = attendanceOptions.value.find(opt => opt.value === value);
if (selectedOption) {
// 设置考勤组名称和ID
setFieldsValue({
monthlyAttendanceName: selectedOption.label,
monthlyAttendanceIds: selectedOption.ids,
monthlyAttendanceId: selectedOption.ids && selectedOption.ids.length > 0 ? selectedOption.ids[0] : undefined
});
// 查找考勤组数据中的 relationValue 并解析
if (selectedOption.ids && selectedOption.ids.length > 0) {
const attendanceId = selectedOption.ids[0];
const attendanceItem = attendanceData.value.find(item => item.id === attendanceId);
if (attendanceItem && attendanceItem.relationValue) {
const parsedData = tryParseRelationValue(attendanceItem.relationValue);
if (parsedData) {
const updateValues: Record<string, any> = {};
if (parsedData.payDay !== undefined) {
updateValues.payDay = parsedData.payDay;
}
if (parsedData.monthlyWorkingDay !== undefined) {
updateValues.monthlyWorkingDay = parsedData.monthlyWorkingDay;
}
if (Object.keys(updateValues).length > 0) {
setFieldsValue(updateValues);
}
}
}
}
}
}
}
const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
labelWidth: 100,
baseColProps: { span: 24 },
schemas: computed(() => modifiedFormSchema.value),
showActionButtonGroup: false,
});
// 更新表单值并触发计算
function setFormValues(record: any) {
if (!record) return;
// 如果有考勤组名称,尝试找到匹配的选项
if (record.monthlyAttendanceName) {
const matchingOption = attendanceOptions.value.find(opt =>
opt.label === record.monthlyAttendanceName
);
if (matchingOption) {
// 如果找到匹配选项,设置值为选项的value
record.monthlyAttendanceName = matchingOption.value;
}
}
// 检查是否有上月存休数据,没有则显示警告
const hasLastMonthData = record.lastMonthLeaveDays !== undefined && record.lastMonthLeaveDays !== null;
updateLastMonthField(!hasLastMonthData);
setFieldsValue({
...record,
});
// 更新formData引用
formData.value = record;
// 计算累计存休
try {
calculateTotalLeaveDays();
} catch (error) {
console.error('初始计算累计存休时出错:', error);
}
}
// 监听props变化,更新表单数据
watch(
() => props.record,
(record) => {
if (record && Object.keys(record).length > 0) {
resetFields();
rowId.value = record.id || '';
// 编辑模式下只获取考勤组数据,不再获取上月存休数据
if (props.isUpdate && record.userId) {
getAttendanceOptions();
}
// 设置表单值
setFormValues(record);
} else {
resetFields();
// 新建模式,显示警告样式
updateLastMonthField(true);
}
},
{ immediate: true, deep: true }
);
// 监听dateTime属性变化
watch(
() => props.dateTime,
(newVal) => {
if (newVal) {
dateTime.value = newVal;
// 当日期变化时,重新获取考勤组数据
getAttendanceOptions();
}
},
{ immediate: true }
);
// 添加监听表单字段变化的逻辑
const watchStopHandle = ref<any>(null);
onMounted(() => {
// 在组件挂载后再设置监听,避免过早访问
watchStopHandle.value = watch(
() => {
const values = getFieldsValue();
return values ? [
values.lastMonthLeaveDays,
values.storageLeaveDays,
values.compensatoryLeaveDays
] : [];
},
(newValues, oldValues) => {
// 只在初始化和通过其他方式修改值时执行
// 不要与onChange事件产生冲突
if (newValues && newValues.length === 3 &&
(newValues[0] !== oldValues?.[0] ||
newValues[1] !== oldValues?.[1] ||
newValues[2] !== oldValues?.[2])) {
// 更新formData引用
formData.value = getFieldsValue() || {};
// 计算累计存休,但不传递特定字段的新值
try {
calculateTotalLeaveDays();
} catch (error) {
console.error('监听字段变化时计算累计存休出错:', error);
}
}
},
{ deep: true }
);
});
// 组件卸载时清除监听
onUnmounted(() => {
if (watchStopHandle.value) {
watchStopHandle.value();
}
});
// 提供给父组件调用的保存方法
async function handleSave() {
try {
// 获取当前系统年份
const currentYear = new Date().getFullYear();
// 获取查询年份
const queryYear = dateTime.value ? parseInt(dateTime.value.split('-')[0]) : 0;
// 如果是当前年份且考勤组有变更,进行警告
const isCurrentYear = queryYear === currentYear;
const hasAttendanceId = props.isUpdate && props.record && props.record.monthlyAttendanceId !== undefined;
let finalValues = null;
if (isCurrentYear && hasAttendanceId) {
try {
const values = await validate();
// 如果尝试修改了考勤组,使用原始值覆盖
const attendanceIdChanged = values.monthlyAttendanceId !== props.record.monthlyAttendanceId;
const attendanceIdsChanged = values.monthlyAttendanceIds && values.monthlyAttendanceIds[0] !== props.record.monthlyAttendanceId;
if (attendanceIdChanged || attendanceIdsChanged) {
console.warn('当前年份考勤组不可修改,已还原为原始值');
// 还原为原始的考勤组ID和名称
values.monthlyAttendanceId = props.record.monthlyAttendanceId;
values.monthlyAttendanceIds = props.record.monthlyAttendanceIds || [props.record.monthlyAttendanceId];
values.monthlyAttendanceName = props.record.monthlyAttendanceName;
// 更新表单值
setFieldsValue({
monthlyAttendanceId: props.record.monthlyAttendanceId,
monthlyAttendanceIds: props.record.monthlyAttendanceIds || [props.record.monthlyAttendanceId],
monthlyAttendanceName: props.record.monthlyAttendanceName
});
// 等待表单状态更新完成
await new Promise(resolve => setTimeout(resolve, 100));
}
// 确保在保存前重新计算一次累计存休
formData.value = values;
try {
calculateTotalLeaveDays();
} catch (error) {
console.error('保存前计算累计存休时出错:', error);
}
// 直接使用已验证的值,避免再次调用validate
finalValues = values;
} catch (validateError) {
console.error('当前年份分支validate失败:', validateError);
throw validateError;
}
} else {
// 非当前年份,允许正常修改
try {
const values = await validate();
// 确保在保存前重新计算一次累计存休
if (values) {
formData.value = values;
try {
calculateTotalLeaveDays();
} catch (error) {
console.error('保存前计算累计存休时出错:', error);
}
}
finalValues = values;
} catch (validateError) {
console.error('非当前年份分支validate失败:', validateError);
throw validateError;
}
}
// 如果没有获取到最终值,则进行最后一次验证
if (!finalValues) {
try {
finalValues = await validate();
} catch (finalValidateError) {
console.error('最终validate调用失败:', finalValidateError);
throw finalValidateError;
}
}
// 类型安全检查
if (!finalValues) {
throw new Error('无法获取有效的表单数据');
}
// 确保包含用户ID
if (!finalValues.userId && props.record && props.record.userId) {
finalValues.userId = props.record.userId;
}
// 如果是更新操作,带上ID
if (props.isUpdate && rowId.value) {
finalValues.id = rowId.value;
}
// 确保包含日期信息
if (dateTime.value && !finalValues.dateTime) {
finalValues.dateTime = dateTime.value;
}
// 尝试从多个可能的来源获取考勤组ID
const possibleIds = [
finalValues.monthlyAttendanceId,
props.record?.monthlyAttendanceId,
finalValues.monthlyAttendanceIds?.[0],
props.record?.monthlyAttendanceIds?.[0],
finalValues.monthlyAttendanceSelectedId
];
// 过滤掉undefined和null,并取第一个有效的ID
const validId = possibleIds.find(id => id !== undefined && id !== null);
// 如果找到有效ID,设置到要发送的数据中
if (validId) {
finalValues.monthlyAttendanceId = validId;
}
// 移除不需要的字段
const { chineseName, nickName, ...dataToSend } = finalValues;
// 发送请求到服务器保存编辑后的数据
const result = await defHttp.post({
url: '/order/erp/users/oldAttendance/edit',
params: dataToSend
});
if (result) {
return result;
}
return dataToSend;
} catch (error) {
console.error('保存失败:', error);
// 如果是表单验证错误,输出关键信息
if (error && typeof error === 'object') {
if (error.values) {
console.error('表单值:', error.values);
}
if (error.errorFields) {
console.error('错误字段:', error.errorFields);
}
if (error.outOfDate !== undefined) {
console.error('表单是否过期:', error.outOfDate);
}
}
return Promise.reject(error);
}
}
return {
registerForm,
handleSave
};
},
});
</script>