3 天以前 1c1af9b0fc10778ae5ac13cc68fd4030affbcfe1
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
<script lang="ts" setup>
import type { ErpPurchasePlanApi } from '#/api/erp/purchase/plan';
 
import { computed, ref } from 'vue';
 
import dayjs from 'dayjs';
 
import { useVbenModal } from '@vben/common-ui';
 
import type { TableColumnsType } from 'ant-design-vue';
import { Button, DatePicker, Input, InputNumber, message, Table } from 'ant-design-vue';
 
import { useVbenForm } from '#/adapter/form';
import {
  createPurchasePlan,
  getPurchasePlan,
  getStockAlertSuggestItems,
  updatePurchasePlan,
} from '#/api/erp/purchase/plan';
import { MdmItemSelect } from '#/views/basicData/mdm/components';
import { $t } from '#/locales';
 
import type { FormType } from '../data';
import { DEMAND_SOURCE, useFormSchema } from '../data';
 
const emit = defineEmits(['success']);
const formData = ref<ErpPurchasePlanApi.PurchasePlan>();
const formType = ref<FormType>('create');
const items = ref<ErpPurchasePlanApi.PurchasePlanItem[]>([]);
const generating = ref(false); // 正在按库存预警生成建议明细
 
const getTitle = computed(() => {
  if (formType.value === 'create') {
    return $t('ui.actionTitle.create', ['采购计划']);
  } else if (formType.value === 'edit') {
    return $t('ui.actionTitle.edit', ['采购计划']);
  } else {
    return '采购计划详情';
  }
});
 
const totalCount = computed(() =>
  items.value.reduce((sum, item) => sum + (item.count || 0), 0),
);
 
const itemColumns = computed<TableColumnsType>(() => {
  const columns: TableColumnsType = [
    { title: '序号', dataIndex: 'index', width: 50, align: 'center' },
    { title: '产品', dataIndex: 'productId', minWidth: 200 },
    { title: '单位', dataIndex: 'productUnitName', width: 90, align: 'center' },
    { title: '数量', dataIndex: 'count', width: 130, align: 'right' },
    { title: '需求日期', dataIndex: 'demandTime', width: 160 },
    { title: '备注', dataIndex: 'remark', minWidth: 160 },
  ];
  if (formType.value !== 'detail') {
    columns.push({
      title: '操作',
      dataIndex: 'action',
      width: 70,
      align: 'center',
      fixed: 'right',
    });
  }
  return columns;
});
 
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    labelWidth: 120,
  },
  wrapperClass: 'grid-cols-3',
  layout: 'vertical',
  schema: useFormSchema(formType.value),
  showDefaultActions: false,
});
 
function handleAddItem() {
  items.value.push({
    productId: undefined as unknown as number,
    productName: '',
    productUnitId: undefined as unknown as number,
    productUnitName: '',
    count: 1,
    demandTime: dayjs().format('YYYY-MM-DD'),
    remark: '',
  });
}
 
function handleRemoveItem(index: number) {
  items.value.splice(index, 1);
}
 
function handleItemSelect(index: number, item: any) {
  const row = items.value[index];
  if (!row) {
    return;
  }
  row.productId = item?.id;
  row.productName = item?.name;
  row.productUnitId = item?.unitMeasureId;
  row.productUnitName = item?.unitMeasureName;
}
 
/** 按库存预警生成建议明细并回填 */
async function handleGenerateSuggest() {
  if (generating.value) {
    return;
  }
  generating.value = true;
  try {
    const suggestItems = await getStockAlertSuggestItems();
    if (!suggestItems || suggestItems.length === 0) {
      message.warning('当前没有需要补货的物料,建议采购量为空');
      return;
    }
    items.value = suggestItems.map((item) => ({ ...item }));
    await formApi.setFieldValue('demandSource', DEMAND_SOURCE.STOCK_ALERT);
    message.success(`已生成 ${suggestItems.length} 条建议明细,请核对后保存`);
  } finally {
    generating.value = false;
  }
}
 
/** 创建或更新采购计划 */
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    if (!items.value.length) {
      message.error('请至少添加一条计划明细');
      return;
    }
    if (items.value.some((item) => !item.productId || !item.count)) {
      message.error('请完善计划明细的产品与数量');
      return;
    }
    modalApi.lock();
    const data =
      (await formApi.getValues()) as ErpPurchasePlanApi.PurchasePlan;
    data.items = items.value.map((item) => ({
      productId: item.productId,
      productUnitId: item.productUnitId,
      count: item.count,
      demandTime: item.demandTime,
      remark: item.remark,
    }));
    try {
      await (formType.value === 'create'
        ? createPurchasePlan(data)
        : updatePurchasePlan(data));
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      items.value = [];
      return;
    }
    const data = modalApi.getData<{ formType: FormType; id?: number }>();
    formType.value = data.formType;
    formApi.setDisabled(formType.value === 'detail');
    formApi.updateSchema(useFormSchema(formType.value));
    if (!data || !data.id) {
      return;
    }
    modalApi.lock();
    try {
      formData.value = await getPurchasePlan(data.id);
      await formApi.setValues(formData.value);
      items.value = (formData.value.items ?? []).map((item) => ({
        ...item,
      }));
    } finally {
      modalApi.unlock();
    }
  },
});
</script>
 
<template>
  <Modal
    :title="getTitle"
    class="w-[1100px]"
    :show-confirm-button="formType !== 'detail'"
  >
    <Form class="mx-3">
      <template #items>
        <div class="mt-2">
          <div class="mb-2 flex items-center justify-between">
            <span class="text-sm font-medium text-muted-foreground">
              计划明细(共 {{ items.length }} 条,合计数量 {{ totalCount }})
            </span>
            <div v-if="formType !== 'detail'" class="flex space-x-2">
              <Button
                type="primary"
                ghost
                :loading="generating"
                @click="handleGenerateSuggest"
              >
                按库存预警生成建议明细
              </Button>
              <Button type="dashed" @click="handleAddItem">+ 添加明细</Button>
            </div>
          </div>
          <Table
            :row-key="(record, index) => record.id ?? index ?? 0"
            :columns="itemColumns"
            :data-source="items"
            :pagination="false"
            :locale="{ emptyText: '暂无明细,请添加' }"
            :scroll="{ x: 800, y: 320 }"
            size="small"
            bordered
          >
            <template #bodyCell="{ column, record, index }">
              <!-- 序号 -->
              <template v-if="column.dataIndex === 'index'">
                <span class="block text-center">{{ index + 1 }}</span>
              </template>
              <!-- 产品 -->
              <template v-else-if="column.dataIndex === 'productId'">
                <MdmItemSelect
                  v-if="formType !== 'detail'"
                  :model-value="record.productId"
                  placeholder="请选择产品"
                  @change="handleItemSelect(index, $event)"
                />
                <span v-else>{{ record.productName || '-' }}</span>
              </template>
              <!-- 单位 -->
              <template v-else-if="column.dataIndex === 'productUnitName'">
                <span>{{ record.productUnitName || '-' }}</span>
              </template>
              <!-- 数量 -->
              <template v-else-if="column.dataIndex === 'count'">
                <InputNumber
                  v-if="formType !== 'detail'"
                  v-model:value="record.count"
                  class="!w-full"
                  :min="0.01"
                  :precision="2"
                />
                <span v-else>{{ record.count }}</span>
              </template>
              <!-- 需求日期 -->
              <template v-else-if="column.dataIndex === 'demandTime'">
                <DatePicker
                  v-if="formType !== 'detail'"
                  v-model:value="record.demandTime"
                  class="!w-full"
                  value-format="YYYY-MM-DD"
                />
                <span v-else>{{ record.demandTime || '-' }}</span>
              </template>
              <!-- 备注 -->
              <template v-else-if="column.dataIndex === 'remark'">
                <Input
                  v-if="formType !== 'detail'"
                  v-model:value="record.remark"
                  placeholder="备注"
                />
                <span v-else>{{ record.remark || '-' }}</span>
              </template>
              <!-- 操作 -->
              <template v-else-if="column.dataIndex === 'action'">
                <Button type="link" danger @click="handleRemoveItem(index)">
                  删除
                </Button>
              </template>
            </template>
          </Table>
        </div>
      </template>
    </Form>
  </Modal>
</template>