gaoluyang
4 天以前 98312d84f785c09574bfd5add730ea448fb0cbd5
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
<script lang="ts" setup>
import type { FinVoucherApi } from '#/api/erp/finance/voucher';
 
import { computed, nextTick, ref, watch } from 'vue';
 
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { erpPriceInputFormatter } from '@vben/utils';
 
import { Input, InputNumber, Select } from 'ant-design-vue';
 
import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
 
import { useEntryColumns } from '../data';
import AccountSelect from './account-select.vue';
 
interface EntryRow extends FinVoucherApi.VoucherEntry {
  seq: number; // 前端行标识,用于表格定位
}
 
interface Props {
  entries?: FinVoucherApi.VoucherEntry[];
  disabled?: boolean;
}
 
const props = withDefaults(defineProps<Props>(), {
  entries: () => [],
  disabled: false,
});
 
const emit = defineEmits(['update:entries']);
 
/** 分录行,seq 用于表格行定位(新增凭证时分录还没有 id) */
const tableData = ref<EntryRow[]>([]);
let seq = 0;
 
/** 把后端分录转为带 seq 的表格行 */
function toRows(entries: FinVoucherApi.VoucherEntry[]): EntryRow[] {
  return entries.map((entry) => ({ ...entry, seq: ++seq }));
}
 
/** 合计:借方、贷方、差额 */
const summaries = computed(() => {
  const debit = tableData.value.reduce(
    (sum, item) => sum + (item.debit || 0),
    0,
  );
  const credit = tableData.value.reduce(
    (sum, item) => sum + (item.credit || 0),
    0,
  );
  return { debit, credit, diff: debit - credit };
});
 
/** 是否借贷平衡 */
const isBalanced = computed(
  () => summaries.value.debit > 0 && summaries.value.diff === 0,
);
 
/** 表格配置 */
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useEntryColumns(props.disabled),
    data: tableData.value,
    minHeight: 300,
    autoResize: true,
    border: true,
    rowConfig: {
      keyField: 'seq',
      isHover: true,
    },
    pagerConfig: {
      enabled: false,
    },
    toolbarConfig: {
      enabled: false,
    },
  },
});
 
/** 监听外部传入的分录 */
watch(
  () => props.entries,
  async (entries) => {
    if (!entries) {
      return;
    }
    tableData.value = toRows(entries);
    await nextTick(); // 特殊:保证 gridApi 已经初始化
    await gridApi.grid.reloadData(tableData.value);
  },
  { immediate: true },
);
 
/** 通知父组件分录已变更 */
function emitChange() {
  const entries = tableData.value.map(({ seq: _seq, ...entry }) => entry);
  emit('update:entries', entries);
}
 
/** 修改某行数据 */
function handleRowChange(row: EntryRow) {
  const index = tableData.value.findIndex((item) => item.seq === row.seq);
  if (index === -1) {
    tableData.value.push(row);
  } else {
    tableData.value[index] = row;
  }
  emitChange();
}
 
/** 录入借方金额时清空贷方金额,反之亦然(同一行只能有一方有金额) */
function handleDebitChange(row: EntryRow) {
  if (row.debit && row.debit > 0) {
    row.credit = 0;
  }
  handleRowChange(row);
}
 
function handleCreditChange(row: EntryRow) {
  if (row.credit && row.credit > 0) {
    row.debit = 0;
  }
  handleRowChange(row);
}
 
/** 选择会计科目 */
const accountSelectRef = ref();
const editingRow = ref<EntryRow>();
 
function handleOpenAccount(row: EntryRow) {
  if (props.disabled) {
    return;
  }
  editingRow.value = row;
  accountSelectRef.value?.open();
}
 
function handleSelectAccount(subject: {
  subjectCode: string;
  subjectName: string;
}) {
  const row = editingRow.value;
  if (!row) {
    return;
  }
  row.subjectCode = subject.subjectCode;
  row.subjectName = subject.subjectName;
  handleRowChange(row);
}
 
/** 添加一行空白分录 */
function handleAdd() {
  const row: EntryRow = {
    seq: ++seq,
    subjectCode: undefined,
    subjectName: undefined,
    summary: '',
    debit: 0,
    credit: 0,
    auxiliaryType: undefined,
    auxiliaryId: '',
    auxiliaryName: '',
  };
  tableData.value.push(row);
  gridApi.grid.reloadData(tableData.value);
  emitChange();
}
 
/** 删除一行分录 */
function handleDelete(row: EntryRow) {
  const index = tableData.value.findIndex((item) => item.seq === row.seq);
  if (index !== -1) {
    tableData.value.splice(index, 1);
  }
  gridApi.grid.reloadData(tableData.value);
  emitChange();
}
 
/** 表单校验:与后端 FinVoucherServiceImpl 的校验口径保持一致 */
function validate() {
  const rows = tableData.value.filter(
    (item) => item.subjectCode || item.debit || item.credit,
  );
  if (rows.length === 0) {
    throw new Error('请至少录入一条凭证分录');
  }
  for (let i = 0; i < rows.length; i++) {
    const item = rows[i]!;
    if (!item.subjectCode) {
      throw new Error(`第 ${i + 1} 行:已录入金额但未选择会计科目`);
    }
    const debit = item.debit || 0;
    const credit = item.credit || 0;
    if (debit <= 0 && credit <= 0) {
      throw new Error(`第 ${i + 1} 行:已选择会计科目但未录入金额`);
    }
    if (debit > 0 && credit > 0) {
      throw new Error(`第 ${i + 1} 行:借方与贷方金额不能同时大于 0`);
    }
  }
  if (summaries.value.debit <= 0) {
    throw new Error('凭证借贷合计必须大于 0');
  }
  if (summaries.value.diff !== 0) {
    throw new Error(
      `凭证借贷不平衡:借方合计 ${erpPriceInputFormatter(summaries.value.debit)},` +
        `贷方合计 ${erpPriceInputFormatter(summaries.value.credit)},` +
        `差额 ${erpPriceInputFormatter(summaries.value.diff)}`,
    );
  }
}
 
defineExpose({ validate });
</script>
 
<template>
  <div>
    <Grid class="w-full">
      <template #summary="{ row }">
        <Input
          v-model:value="row.summary"
          :disabled="disabled"
          placeholder="请输入摘要"
          @change="handleRowChange(row)"
        />
      </template>
 
      <template #subject="{ row }">
        <div
          class="flex cursor-pointer items-center"
          :class="{ 'text-primary': !disabled }"
          @click="handleOpenAccount(row)"
        >
          <span v-if="row.subjectCode">
            {{ row.subjectCode }} {{ row.subjectName }}
          </span>
          <span v-else class="text-muted-foreground">请选择会计科目</span>
        </div>
      </template>
 
      <template #debit="{ row }">
        <InputNumber
          v-model:value="row.debit"
          :precision="2"
          :min="0"
          :disabled="disabled"
          class="w-full"
          placeholder="借方金额"
          @change="handleDebitChange(row)"
        />
      </template>
 
      <template #credit="{ row }">
        <InputNumber
          v-model:value="row.credit"
          :precision="2"
          :min="0"
          :disabled="disabled"
          class="w-full"
          placeholder="贷方金额"
          @change="handleCreditChange(row)"
        />
      </template>
 
      <template #auxiliaryType="{ row }">
        <Select
          v-model:value="row.auxiliaryType"
          :disabled="disabled"
          allow-clear
          class="w-full"
          placeholder="无"
          @change="handleRowChange(row)"
        >
          <Select.Option
            v-for="dict in getDictOptions(
              DICT_TYPE.FINANCE_AUXILIARY_TYPE,
              'number',
            )"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </Select.Option>
        </Select>
      </template>
 
      <template #auxiliaryName="{ row }">
        <Input
          v-model:value="row.auxiliaryName"
          :disabled="disabled"
          placeholder="请输入辅助核算对象"
          @change="handleRowChange(row)"
        />
      </template>
 
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '删除',
              type: 'link',
              danger: true,
              popConfirm: {
                title: '确认删除该分录吗?',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
 
      <template #bottom>
        <div class="mt-2 rounded border border-border bg-muted p-2">
          <div class="flex justify-between text-sm">
            <span class="font-medium text-foreground">合计:</span>
            <div class="flex space-x-4">
              <span>
                借方合计:{{ erpPriceInputFormatter(summaries.debit) }}
              </span>
              <span>
                贷方合计:{{ erpPriceInputFormatter(summaries.credit) }}
              </span>
              <span :class="isBalanced ? 'text-green-600' : 'text-red-500'">
                差额:{{ erpPriceInputFormatter(summaries.diff) }}
                {{ isBalanced ? '(借贷平衡)' : '(借贷不平衡)' }}
              </span>
            </div>
          </div>
        </div>
        <TableAction
          v-if="!disabled"
          class="mt-2 flex justify-center"
          :actions="[
            {
              label: '添加分录',
              type: 'default',
              onClick: handleAdd,
            },
          ]"
        />
      </template>
    </Grid>
 
    <!-- 会计科目选择 -->
    <AccountSelect ref="accountSelectRef" @selected="handleSelectAccount" />
  </div>
</template>
 
<style scoped>
/*
 * 借方/贷方金额列居中。
 * vxe 列的 align: 'center' 只作用于单元格,而 ant 的 InputNumber 内部 <input>
 * (.ant-input-number-input)自带 text-align: start,会把数字压回左边,导致表头居中、
 * 数字靠左的错位,所以这里连输入框内的文字一起覆盖。
 * 本组件只有这两个 InputNumber(借方、贷方),不受影响其它列。
 */
:deep(.ant-input-number .ant-input-number-input) {
  text-align: center;
}
</style>