feat(mes): 新增 md item 的迁移

pull/345/head
YunaiV 2026-05-21 00:58:45 +08:00
parent 13c3028ecc
commit 6b1425d541
42 changed files with 4982 additions and 0 deletions

View File

@ -0,0 +1,2 @@
export { default as MdItemSelectDialog } from './md-item-select-dialog.vue';
export { default as MdItemSelect } from './md-item-select.vue';

View File

@ -0,0 +1,188 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesMdItemApi } from '#/api/mes/md/item';
import type { MesMdItemTypeApi } from '#/api/mes/md/item/type';
import { nextTick, ref } from 'vue';
import { CommonStatusEnum } from '@vben/constants';
import { Card, message, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getItemPage } from '#/api/mes/md/item';
import { MdItemTypeTree } from '#/views/mes/md/item/type/components';
import { useItemSelectGridColumns, useItemSelectGridFormSchema } from '../data';
defineOptions({ name: 'MdItemSelectDialog' });
const emit = defineEmits<{
selected: [rows: MesMdItemApi.Item[]];
}>();
const open = ref(false);
const multiple = ref(true);
const syncingSingleSelection = ref(false);
const selectedRows = ref<MesMdItemApi.Item[]>([]);
const selectedItemTypeId = ref<number>();
const preSelectedIds = ref<number[]>([]);
const typeTreeRef = ref<InstanceType<typeof MdItemTypeTree>>();
/** 单选模式下同步 VXE 勾选状态,避免跨页残留多选 */
async function syncSingleSelection(row?: MesMdItemApi.Item) {
syncingSingleSelection.value = true;
await nextTick();
await gridApi.grid.clearCheckboxRow();
if (row) {
await gridApi.grid.setCheckboxRow(row, true);
}
await nextTick();
syncingSingleSelection.value = false;
}
/** 处理勾选变化,单选模式只保留最后一条 */
async function handleCheckboxChange({
checked,
records,
row,
}: {
checked: boolean;
records: MesMdItemApi.Item[];
row?: MesMdItemApi.Item;
}) {
if (syncingSingleSelection.value) {
return;
}
if (!multiple.value) {
const selected = checked && row ? [row] : [];
selectedRows.value = selected;
await syncSingleSelection(selected[0]);
return;
}
selectedRows.value = records;
}
function handleCheckboxAll({ records }: { records: MesMdItemApi.Item[] }) {
if (syncingSingleSelection.value) {
return;
}
selectedRows.value = records;
}
function handleItemTypeNodeClick(row: MesMdItemTypeApi.ItemType | undefined) {
selectedItemTypeId.value = row?.id;
gridApi.query();
}
function applyPreSelection() {
if (preSelectedIds.value.length === 0) {
return;
}
const rows = gridApi.grid.getData() as MesMdItemApi.Item[];
for (const row of rows) {
if (row.id && preSelectedIds.value.includes(row.id)) {
gridApi.grid.setCheckboxRow(row, true);
if (!multiple.value) {
selectedRows.value = [row];
}
}
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useItemSelectGridFormSchema(),
},
gridOptions: {
columns: useItemSelectGridColumns(),
height: 560,
keepSource: true,
checkboxConfig: {
highlight: true,
range: true,
reserve: true,
},
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getItemPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
itemTypeId: selectedItemTypeId.value,
status: CommonStatusEnum.ENABLE,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<MesMdItemApi.Item>,
gridEvents: {
checkboxAll: handleCheckboxAll,
checkboxChange: handleCheckboxChange,
},
});
async function resetQueryState() {
selectedItemTypeId.value = undefined;
selectedRows.value = [];
typeTreeRef.value?.reset();
await gridApi.grid.clearCheckboxRow();
await gridApi.formApi.resetForm();
}
async function openModal(selectedIds?: number[], options?: { multiple?: boolean }) {
open.value = true;
multiple.value = options?.multiple ?? true;
preSelectedIds.value = selectedIds || [];
await nextTick();
await resetQueryState();
await gridApi.query();
await nextTick();
applyPreSelection();
}
async function closeModal() {
open.value = false;
await resetQueryState();
}
function handleConfirm() {
if (selectedRows.value.length === 0) {
message.warning(multiple.value ? '请至少选择一条数据' : '请选择一条数据');
return;
}
emit('selected', multiple.value ? selectedRows.value : [selectedRows.value[0]!]);
open.value = false;
}
defineExpose({ open: openModal });
</script>
<template>
<Modal
v-model:open="open"
title="物料产品选择"
width="80%"
:destroy-on-close="true"
@ok="handleConfirm"
@cancel="closeModal"
>
<div class="flex h-full w-full">
<Card class="mr-4 h-full w-1/5">
<MdItemTypeTree ref="typeTreeRef" @node-click="handleItemTypeNodeClick" />
</Card>
<div class="w-4/5">
<Grid table-title="" />
</div>
</div>
</Modal>
</template>

View File

@ -0,0 +1,132 @@
<script lang="ts" setup>
import type { MesMdItemApi } from '#/api/mes/md/item';
import { computed, ref, useAttrs, watch } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Input, Tooltip } from 'ant-design-vue';
import { getItem } from '#/api/mes/md/item';
import MdItemSelectDialog from './md-item-select-dialog.vue';
defineOptions({ name: 'MdItemSelect', inheritAttrs: false });
const props = withDefaults(
defineProps<{
allowClear?: boolean;
disabled?: boolean;
modelValue?: number;
placeholder?: string;
}>(),
{
allowClear: true,
disabled: false,
modelValue: undefined,
placeholder: '请选择产品物料',
},
);
const emit = defineEmits<{
change: [item: MesMdItemApi.Item | undefined];
'update:modelValue': [value: number | undefined];
}>();
const attrs = useAttrs();
const dialogRef = ref<InstanceType<typeof MdItemSelectDialog>>();
const hovering = ref(false);
const selectedItem = ref<MesMdItemApi.Item>();
const displayLabel = computed(() => selectedItem.value?.name ?? '');
const showClear = computed(
() => props.allowClear && !props.disabled && hovering.value && props.modelValue != null,
);
async function resolveItemById(id: number | undefined) {
if (id == null) {
selectedItem.value = undefined;
return;
}
if (selectedItem.value?.id === id) {
return;
}
try {
selectedItem.value = await getItem(id);
} catch (error) {
console.error('[MdItemSelect] resolveItemById failed:', error);
}
}
watch(
() => props.modelValue,
(value) => {
resolveItemById(value);
},
{ immediate: true },
);
function clearSelected() {
selectedItem.value = undefined;
emit('update:modelValue', undefined);
emit('change', undefined);
}
function handleClick(event: MouseEvent) {
if (props.disabled) {
return;
}
const target = event.target as HTMLElement;
if (showClear.value && target.closest('.ant-input-suffix')) {
event.stopPropagation();
clearSelected();
return;
}
const selectedIds = props.modelValue == null ? [] : [props.modelValue];
dialogRef.value?.open(selectedIds, { multiple: false });
}
function handleSelected(rows: MesMdItemApi.Item[]) {
const item = rows[0];
if (!item) {
return;
}
selectedItem.value = item;
emit('update:modelValue', item.id);
emit('change', item);
}
</script>
<template>
<div
v-bind="attrs"
class="w-full"
:class="disabled ? 'cursor-not-allowed' : 'cursor-pointer'"
@click="handleClick"
@mouseenter="hovering = true"
@mouseleave="hovering = false"
>
<Tooltip :mouse-enter-delay="0.5" :open="selectedItem ? undefined : false">
<template #title>
<div v-if="selectedItem" class="leading-6">
<div>编码{{ selectedItem.code || '-' }}</div>
<div>名称{{ selectedItem.name || '-' }}</div>
<div>规格{{ selectedItem.specification || '-' }}</div>
<div>单位{{ selectedItem.unitMeasureName || '-' }}</div>
</div>
</template>
<Input
:disabled="disabled"
:placeholder="placeholder"
:value="displayLabel"
readonly
>
<template #suffix>
<IconifyIcon
class="size-4"
:icon="showClear ? 'lucide:circle-x' : 'lucide:search'"
/>
</template>
</Input>
</Tooltip>
</div>
<MdItemSelectDialog ref="dialogRef" @selected="handleSelected" />
</template>

View File

@ -0,0 +1,474 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesMdItemApi } from '#/api/mes/md/item';
import type { MesMdProductBomApi } from '#/api/mes/md/item/productBom';
import { h, markRaw } from 'vue';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { Button } from 'ant-design-vue';
import { z } from '#/adapter/form';
import { generateAutoCode } from '#/api/mes/md/autocode/record';
import { MdItemTypeSelect } from '#/views/mes/md/item/type/components';
import { MdUnitMeasureSelect } from '#/views/mes/md/unitmeasure/components';
import { MesAutoCodeRuleCode } from '#/views/mes/utils/constants';
/** 新增/修改物料产品的表单 */
export function useFormSchema(formApi?: any): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'code',
label: '物料编码',
component: 'Input',
componentProps: {
maxLength: 64,
placeholder: '请输入物料编码',
},
rules: z.string().min(1, '物料编码不能为空').max(64),
suffix: () =>
h(
Button,
{
type: 'default',
onClick: async () => {
try {
const code = await generateAutoCode(
MesAutoCodeRuleCode.MD_ITEM_CODE,
);
await formApi?.setFieldValue('code', code);
} catch (error) {
console.error(error);
}
},
},
{ default: () => '生成' },
),
},
{
fieldName: 'name',
label: '物料名称',
component: 'Input',
componentProps: {
maxLength: 255,
placeholder: '请输入物料名称',
},
rules: z.string().min(1, '物料名称不能为空').max(255),
},
{
fieldName: 'specification',
label: '规格型号',
component: 'Input',
componentProps: {
maxLength: 255,
placeholder: '请输入规格型号',
},
},
{
fieldName: 'unitMeasureId',
label: '单位',
component: markRaw(MdUnitMeasureSelect),
componentProps: {
placeholder: '请选择计量单位',
},
rules: 'selectRequired',
},
{
fieldName: 'itemTypeId',
label: '物料分类',
component: markRaw(MdItemTypeSelect),
componentProps: {
onChange: async (itemType: any) => {
await formApi?.setFieldValue('itemOrProduct', itemType?.itemOrProduct);
},
},
rules: 'selectRequired',
},
{
fieldName: 'status',
label: '状态',
component: 'RadioGroup',
componentProps: {
buttonStyle: 'solid',
disabled: true,
optionType: 'button',
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
rules: z.number().default(CommonStatusEnum.DISABLE),
},
{
fieldName: 'highValue',
label: '高值物料',
component: 'Switch',
componentProps: {
checkedChildren: '是',
unCheckedChildren: '否',
},
rules: z.boolean().default(false),
},
{
fieldName: 'batchFlag',
label: '批次管理',
component: 'Switch',
componentProps: {
checkedChildren: '是',
unCheckedChildren: '否',
},
rules: z.boolean().default(true),
},
{
fieldName: 'safeStockFlag',
label: '安全库存',
component: 'Switch',
componentProps: {
checkedChildren: '是',
unCheckedChildren: '否',
},
rules: z.boolean().default(false),
},
{
fieldName: 'minStock',
label: '最低库存量',
component: 'InputNumber',
componentProps: {
class: '!w-full',
min: 0,
precision: 2,
},
dependencies: {
triggerFields: ['safeStockFlag'],
show: (values) => Boolean(values.safeStockFlag),
},
rules: z.number().default(0),
},
{
fieldName: 'maxStock',
label: '最高库存量',
component: 'InputNumber',
componentProps: {
class: '!w-full',
min: 0,
precision: 2,
},
dependencies: {
triggerFields: ['safeStockFlag'],
show: (values) => Boolean(values.safeStockFlag),
},
rules: z.number().default(0),
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
rows: 3,
},
formItemClass: 'col-span-3',
},
{
fieldName: 'itemOrProduct',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'code',
label: '物料编码',
component: 'Input',
componentProps: {
allowClear: true,
placeholder: '请输入物料编码',
},
},
{
fieldName: 'name',
label: '物料名称',
component: 'Input',
componentProps: {
allowClear: true,
placeholder: '请输入物料名称',
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
allowClear: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择状态',
},
},
];
}
/** 物料导入表单 */
export function useImportFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'file',
label: '物料数据',
component: 'Upload',
rules: 'required',
help: '仅允许导入 xls、xlsx 格式文件',
},
{
fieldName: 'updateSupport',
label: '是否覆盖',
component: 'Switch',
componentProps: {
checkedChildren: '是',
unCheckedChildren: '否',
},
rules: z.boolean().default(false),
help: '是否更新已经存在的物料数据',
},
];
}
/** 列表的字段 */
export function useGridColumns(
onStatusChange?: (
newStatus: number,
row: MesMdItemApi.Item,
) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions<MesMdItemApi.Item>['columns'] {
return [
{
field: 'code',
title: '物料编码',
minWidth: 160,
slots: { default: 'code' },
},
{
field: 'name',
title: '物料名称',
minWidth: 160,
},
{
field: 'specification',
title: '规格型号',
minWidth: 160,
},
{
field: 'unitMeasureName',
title: '单位',
width: 100,
align: 'center',
},
{
field: 'itemTypeName',
title: '物料分类',
minWidth: 140,
align: 'center',
},
{
field: 'itemOrProduct',
title: '物料/产品',
width: 120,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.MES_MD_ITEM_OR_PRODUCT },
},
},
{
field: 'safeStockFlag',
title: '安全库存',
width: 120,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.INFRA_BOOLEAN_STRING },
},
},
{
field: 'status',
title: '状态',
width: 120,
align: 'center',
cellRender: {
attrs: { beforeChange: onStatusChange },
name: 'CellSwitch',
props: {
checkedValue: CommonStatusEnum.ENABLE,
unCheckedValue: CommonStatusEnum.DISABLE,
},
},
},
{
field: 'createTime',
title: '创建时间',
width: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 物料选择弹窗搜索表单 */
export function useItemSelectGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'code',
label: '物料编码',
component: 'Input',
componentProps: {
allowClear: true,
placeholder: '请输入物料编码',
},
},
{
fieldName: 'name',
label: '物料名称',
component: 'Input',
componentProps: {
allowClear: true,
placeholder: '请输入物料名称',
},
},
];
}
/** 物料选择弹窗列表字段 */
export function useItemSelectGridColumns(): VxeTableGridOptions<MesMdItemApi.Item>['columns'] {
return [
{ type: 'checkbox', width: 50 },
{
field: 'code',
title: '物料编码',
width: 180,
},
{
field: 'name',
title: '物料名称',
minWidth: 160,
align: 'left',
},
{
field: 'specification',
title: '规格型号',
minWidth: 140,
align: 'left',
},
{
field: 'unitMeasureName',
title: '单位',
width: 90,
align: 'center',
},
{
field: 'itemOrProduct',
title: '物料/产品',
width: 110,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.MES_MD_ITEM_OR_PRODUCT },
},
},
{
field: 'itemTypeName',
title: '所属分类',
width: 140,
align: 'center',
},
{
field: 'createTime',
title: '创建时间',
width: 180,
formatter: 'formatDateTime',
},
];
}
/** 产品 BOM 子表字段 */
export function useProductBomGridColumns(
isReadOnly = false,
): VxeTableGridOptions<MesMdProductBomApi.ProductBom>['columns'] {
const columns: VxeTableGridOptions<MesMdProductBomApi.ProductBom>['columns'] = [
{
field: 'bomItemCode',
title: '物料编码',
minWidth: 160,
align: 'center',
},
{
field: 'bomItemName',
title: '物料名称',
minWidth: 160,
align: 'center',
},
{
field: 'bomItemSpecification',
title: '规格型号',
minWidth: 140,
align: 'center',
},
{
field: 'unitMeasureName',
title: '单位',
width: 80,
align: 'center',
},
{
field: 'itemOrProduct',
title: '物料/产品',
width: 110,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.MES_MD_ITEM_OR_PRODUCT },
},
},
{
field: 'quantity',
title: '用量比例',
width: 100,
align: 'center',
},
{
field: 'remark',
title: '备注',
minWidth: 140,
align: 'center',
},
];
if (!isReadOnly) {
columns.push({
field: 'actions',
title: '操作',
width: 120,
align: 'center',
fixed: 'right',
slots: { default: 'actions' },
});
}
return columns;
}

View File

@ -0,0 +1,233 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesMdItemApi } from '#/api/mes/md/item';
import type { MesMdItemTypeApi } from '#/api/mes/md/item/type';
import { ref } from 'vue';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictLabel } from '@vben/hooks';
import { downloadFileFromBlobPart } from '@vben/utils';
import { Button, Card, message, Modal } from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteItem,
exportItem,
getItemPage,
updateItemStatus,
} from '#/api/mes/md/item';
import { $t } from '#/locales';
import { MdItemTypeTree } from '#/views/mes/md/item/type/components';
import { PrinterLabel } from '#/views/mes/wm/barcode/components';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
import ImportForm from './modules/import-form.vue';
defineOptions({ name: 'MesMdItem' });
const selectedItemTypeId = ref<number>();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [ImportModal, importModalApi] = useVbenModal({
connectedComponent: ImportForm,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建物料 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 查看物料 */
function handleDetail(row: MesMdItemApi.Item) {
formModalApi.setData({ id: row.id, type: 'detail' }).open();
}
/** 编辑物料 */
function handleEdit(row: MesMdItemApi.Item) {
formModalApi.setData({ id: row.id, type: 'update' }).open();
}
/** 删除物料 */
async function handleDelete(row: MesMdItemApi.Item) {
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting', [row.name]),
duration: 0,
});
try {
await deleteItem(row.id!);
message.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
hideLoading();
}
}
/** 导出物料 */
async function handleExport() {
const data = await exportItem(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '物料产品.xls', source: data });
}
/** 导入物料 */
function handleImport() {
importModalApi.open();
}
/** 分类树点击 */
function handleTypeNodeClick(row: MesMdItemTypeApi.ItemType | undefined) {
selectedItemTypeId.value = row?.id;
handleRefresh();
}
/** 更新物料状态 */
async function handleStatusChange(
newStatus: number,
row: MesMdItemApi.Item,
): Promise<boolean | undefined> {
return new Promise((resolve, reject) => {
Modal.confirm({
content: `确认要将“${row.name}”物料切换为【${getDictLabel(DICT_TYPE.COMMON_STATUS, newStatus)}】吗?`,
async onOk() {
await updateItemStatus(row.id!, newStatus);
message.success($t('ui.actionMessage.operationSuccess'));
resolve(true);
},
onCancel() {
reject(new Error('取消操作'));
},
});
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(handleStatusChange),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getItemPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
itemTypeId: selectedItemTypeId.value,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<MesMdItemApi.Item>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert
title="【基础】物料产品、分类、计量单位"
url="https://doc.iocoder.cn/mes/md/product/"
/>
</template>
<FormModal @success="handleRefresh" />
<ImportModal @success="handleRefresh" />
<div class="flex h-full w-full">
<Card class="mr-4 h-full w-1/6">
<MdItemTypeTree @node-click="handleTypeNodeClick" />
</Card>
<div class="w-5/6">
<Grid table-title="">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['物料']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['mes:md-item:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.import'),
type: 'primary',
icon: ACTION_ICON.UPLOAD,
auth: ['mes:md-item:import'],
onClick: handleImport,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['mes:md-item:export'],
onClick: handleExport,
},
]"
/>
</template>
<template #code="{ row }">
<Button type="link" @click="handleDetail(row)">
{{ row.code }}
</Button>
</template>
<template #actions="{ row }">
<div class="flex items-center justify-center">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'link',
icon: ACTION_ICON.EDIT,
auth: ['mes:md-item:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'link',
danger: true,
icon: ACTION_ICON.DELETE,
auth: ['mes:md-item:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
<PrinterLabel
:biz-id="row.id"
:biz-code="row.code"
biz-type="ITEM"
/>
</div>
</template>
</Grid>
</div>
</div>
</Page>
</template>

View File

@ -0,0 +1,169 @@
<script lang="ts" setup>
import type { MesMdItemApi } from '#/api/mes/md/item';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Button, Empty, message, Tabs } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { createItem, getItem, updateItem } from '#/api/mes/md/item';
import { $t } from '#/locales';
import { BarcodeBizTypeEnum } from '#/views/mes/utils/constants';
import { BarcodeDetail } from '#/views/mes/wm/barcode/components';
import { useFormSchema } from '../data';
import ItemBatchConfigForm from './item-batch-config-form.vue';
import ProductBomForm from './product-bom-form.vue';
import ProductSipForm from './product-sip-form.vue';
import ProductSopForm from './product-sop-form.vue';
type FormMode = 'create' | 'detail' | 'update';
defineOptions({ name: 'MesMdItemForm' });
const emit = defineEmits(['success']);
const formMode = ref<FormMode>('create');
const activeTab = ref('bom');
const formData = ref<MesMdItemApi.Item>();
const barcodeDetailRef = ref<InstanceType<typeof BarcodeDetail>>();
const isDetail = computed(() => formMode.value === 'detail');
const getTitle = computed(() => {
const titles: Record<FormMode, string> = {
create: '新增物料/产品',
update: '修改物料/产品',
detail: '查看物料/产品',
};
return titles[formMode.value];
});
const currentItemOrProduct = computed(() => formData.value?.itemOrProduct || '');
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-1',
labelWidth: 120,
},
wrapperClass: 'grid-cols-3',
layout: 'horizontal',
schema: [],
showDefaultActions: false,
});
/** 表单 schema 需要 formApi 引用,所以通过 setState 设置 schema */
formApi.setState({ schema: useFormSchema(formApi) });
function handleBarcode() {
if (!formData.value?.id) {
return;
}
barcodeDetailRef.value?.openByBusiness(
formData.value.id,
BarcodeBizTypeEnum.ITEM,
formData.value.code,
formData.value.name,
);
}
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
if (isDetail.value) {
await modalApi.close();
return;
}
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
//
const data = (await formApi.getValues()) as MesMdItemApi.Item;
try {
if (formMode.value === 'create') {
const id = await createItem(data);
formData.value = { ...data, id };
formMode.value = 'update';
message.success($t('ui.actionMessage.operationSuccess'));
} else {
await updateItem(data);
formData.value = { ...formData.value, ...data };
message.success($t('ui.actionMessage.operationSuccess'));
}
emit('success');
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
await formApi.resetForm();
activeTab.value = 'bom';
//
const data = modalApi.getData<{ id?: number; type?: FormMode }>();
formMode.value = data?.type || 'create';
formApi.setDisabled(formMode.value === 'detail');
modalApi.setState({ showConfirmButton: formMode.value !== 'detail' });
if (!data?.id) {
return;
}
modalApi.lock();
try {
formData.value = await getItem(data.id);
// values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-4/5">
<Form class="mx-4" />
<Tabs
v-if="formMode !== 'create' && formData?.id"
v-model:active-key="activeTab"
class="mx-4 mt-4"
>
<Tabs.TabPane key="bom" tab="BOM 组成">
<ProductBomForm :form-type="formMode" :item-id="formData.id" />
</Tabs.TabPane>
<Tabs.TabPane v-if="formData.batchFlag" key="batch" tab="批次属性">
<ItemBatchConfigForm
:form-type="formMode"
:item-id="formData.id"
:item-or-product="currentItemOrProduct"
/>
</Tabs.TabPane>
<Tabs.TabPane key="substitute" tab="替代品">
<Empty description="替代品(待实现)" />
</Tabs.TabPane>
<Tabs.TabPane key="sip" tab="SIP">
<ProductSipForm :form-type="formMode" :item-id="formData.id" />
</Tabs.TabPane>
<Tabs.TabPane key="sop" tab="SOP">
<ProductSopForm :form-type="formMode" :item-id="formData.id" />
</Tabs.TabPane>
</Tabs>
<template #prepend-footer>
<div class="flex flex-auto items-center">
<Button
v-if="isDetail && formData?.id"
type="primary"
@click="handleBarcode"
>
查看条码
</Button>
</div>
</template>
<BarcodeDetail ref="barcodeDetailRef" />
</Modal>
</template>

View File

@ -0,0 +1,103 @@
<script lang="ts" setup>
import type { FileType } from 'ant-design-vue/es/upload/interface';
import type { MesMdItemApi } from '#/api/mes/md/item';
import { useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import { Button, message, Upload } from 'ant-design-vue';
import { useVbenForm } from '#/adapter/form';
import { importItem, importItemTemplate } from '#/api/mes/md/item';
import { $t } from '#/locales';
import { useImportFormSchema } from '../data';
defineOptions({ name: 'MesMdItemImportForm' });
const emit = defineEmits(['success']);
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useImportFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
//
const data = await formApi.getValues();
try {
const result = await importItem(data.file, data.updateSupport);
const importData = result as MesMdItemApi.ItemImportRespVO;
let text = `上传成功数量:${importData.createCodes?.length || 0};`;
for (const code of importData.createCodes || []) {
text += `< ${code} >`;
}
text += `更新成功数量:${importData.updateCodes?.length || 0};`;
for (const code of importData.updateCodes || []) {
text += `< ${code} >`;
}
text += `更新失败数量:${Object.keys(importData.failureCodes || {}).length};`;
for (const code in importData.failureCodes || {}) {
text += `< ${code}: ${importData.failureCodes?.[code]} >`;
}
message.info(text);
//
await modalApi.close();
emit('success');
message.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
});
/** 上传前 */
function beforeUpload(file: FileType) {
formApi.setFieldValue('file', file);
return false;
}
/** 下载模版 */
async function handleDownload() {
const data = await importItemTemplate();
downloadFileFromBlobPart({ fileName: '物料导入模板.xls', source: data });
}
</script>
<template>
<Modal :title="$t('ui.actionTitle.import', ['物料'])" class="w-1/3">
<Form class="mx-4">
<template #file>
<div class="w-full">
<Upload
:before-upload="beforeUpload"
:max-count="1"
accept=".xls,.xlsx"
>
<Button type="primary">选择 Excel 文件</Button>
</Upload>
</div>
</template>
</Form>
<template #prepend-footer>
<div class="flex flex-auto items-center">
<Button @click="handleDownload"></Button>
</div>
</template>
</Modal>
</template>

View File

@ -0,0 +1,125 @@
<script lang="ts" setup>
import type { MesMdItemBatchConfigApi } from '#/api/mes/md/item/batchConfig';
import { computed, ref, watch } from 'vue';
import { Button, Checkbox, message, Spin } from 'ant-design-vue';
import {
getBatchConfigByItemId,
saveBatchConfig,
} from '#/api/mes/md/item/batchConfig';
import { MesItemOrProductEnum } from '#/views/mes/utils/constants';
defineOptions({ name: 'MesMdItemBatchConfigForm' });
const props = withDefaults(
defineProps<{
formType?: string;
itemId: number;
itemOrProduct?: string;
}>(),
{
formType: 'update',
itemOrProduct: '',
},
);
const isReadOnly = computed(() => props.formType === 'detail');
const loading = ref(false);
const formData = ref<MesMdItemBatchConfigApi.BatchConfig>(buildDefaultData());
function buildDefaultData(): MesMdItemBatchConfigApi.BatchConfig {
return {
itemId: props.itemId,
produceDateFlag: false,
expireDateFlag: false,
receiptDateFlag: false,
vendorFlag: false,
clientFlag: false,
salesOrderCodeFlag: false,
purchaseOrderCodeFlag: false,
workorderFlag: false,
taskFlag: false,
workstationFlag: false,
toolFlag: false,
moldFlag: false,
lotNumberFlag: false,
qualityStatusFlag: false,
};
}
async function loadData() {
loading.value = true;
try {
const data = await getBatchConfigByItemId(props.itemId);
formData.value = { ...buildDefaultData(), ...data };
} finally {
loading.value = false;
}
}
function hasAnySelected() {
return Object.entries(formData.value).some(
([key, value]) => key.endsWith('Flag') && value === true,
);
}
async function handleSave() {
if (!hasAnySelected()) {
message.warning('至少选择一个批次属性');
return;
}
loading.value = true;
try {
await saveBatchConfig({ ...formData.value, itemId: props.itemId });
message.success('保存成功');
} finally {
loading.value = false;
}
}
watch(
() => props.itemId,
(value) => {
if (value) {
loadData();
}
},
{ immediate: true },
);
</script>
<template>
<Spin :spinning="loading">
<div v-if="!isReadOnly" class="mb-3 flex justify-end">
<Button type="primary" @click="handleSave"></Button>
</div>
<div class="grid grid-cols-5 gap-x-5 gap-y-3">
<Checkbox v-model:checked="formData.produceDateFlag" :disabled="isReadOnly">生产日期</Checkbox>
<Checkbox v-model:checked="formData.qualityStatusFlag" :disabled="isReadOnly">质量状态</Checkbox>
<template v-if="itemOrProduct === MesItemOrProductEnum.ITEM.value">
<Checkbox v-model:checked="formData.vendorFlag" :disabled="isReadOnly">供应商</Checkbox>
<Checkbox v-model:checked="formData.purchaseOrderCodeFlag" :disabled="isReadOnly">
采购订单编号
</Checkbox>
<Checkbox v-model:checked="formData.lotNumberFlag" :disabled="isReadOnly">生产批号</Checkbox>
<Checkbox v-model:checked="formData.expireDateFlag" :disabled="isReadOnly">有效期</Checkbox>
<Checkbox v-model:checked="formData.receiptDateFlag" :disabled="isReadOnly">入库日期</Checkbox>
</template>
<template v-if="itemOrProduct === MesItemOrProductEnum.PRODUCT.value">
<Checkbox v-model:checked="formData.clientFlag" :disabled="isReadOnly">客户</Checkbox>
<Checkbox v-model:checked="formData.salesOrderCodeFlag" :disabled="isReadOnly">
销售订单编号
</Checkbox>
<Checkbox v-model:checked="formData.workorderFlag" :disabled="isReadOnly">生产工单</Checkbox>
<Checkbox v-model:checked="formData.taskFlag" :disabled="isReadOnly">生产任务</Checkbox>
<Checkbox v-model:checked="formData.workstationFlag" :disabled="isReadOnly">工作站</Checkbox>
<Checkbox v-model:checked="formData.toolFlag" :disabled="isReadOnly">工具</Checkbox>
<Checkbox v-model:checked="formData.moldFlag" :disabled="isReadOnly">模具</Checkbox>
</template>
</div>
</Spin>
</template>

View File

@ -0,0 +1,238 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesMdItemApi } from '#/api/mes/md/item';
import type { MesMdProductBomApi } from '#/api/mes/md/item/productBom';
import { computed, ref, watch } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { useVbenForm, z } from '#/adapter/form';
import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
createProductBom,
deleteProductBom,
getProductBomListByItemId,
updateProductBom,
} from '#/api/mes/md/item/productBom';
import { $t } from '#/locales';
import { MdItemSelectDialog } from '../components';
import { useProductBomGridColumns } from '../data';
defineOptions({ name: 'MesMdProductBomForm' });
const props = withDefaults(
defineProps<{
formType?: string;
itemId: number;
}>(),
{
formType: 'update',
},
);
const isReadOnly = computed(() => props.formType === 'detail');
const formOpen = ref(false);
const formLoading = ref(false);
const formData = ref<MesMdProductBomApi.ProductBom>();
const list = ref<MesMdProductBomApi.ProductBom[]>([]);
const itemSelectRef = ref<InstanceType<typeof MdItemSelectDialog>>();
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: [
{ fieldName: 'id', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{ fieldName: 'itemId', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{ fieldName: 'bomItemId', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{
fieldName: 'bomItemCode',
label: 'BOM 物料编码',
component: 'Input',
componentProps: { disabled: true },
},
{
fieldName: 'bomItemName',
label: 'BOM 物料名称',
component: 'Input',
componentProps: { disabled: true },
},
{
fieldName: 'bomItemSpecification',
label: '规格型号',
component: 'Input',
componentProps: { disabled: true },
},
{
fieldName: 'unitMeasureName',
label: '单位',
component: 'Input',
componentProps: { disabled: true },
},
{
fieldName: 'quantity',
label: '用量比例',
component: 'InputNumber',
componentProps: { class: '!w-full', min: 0, precision: 4, step: 0.1 },
rules: z.number().default(1),
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: { placeholder: '请输入备注', rows: 3 },
},
],
showDefaultActions: false,
});
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
autoResize: true,
border: true,
columns: useProductBomGridColumns(isReadOnly.value),
data: list.value,
minHeight: 240,
pagerConfig: {
enabled: false,
},
rowConfig: {
isHover: true,
keyField: 'id',
},
showOverflow: true,
toolbarConfig: {
enabled: false,
},
} as VxeTableGridOptions<MesMdProductBomApi.ProductBom>,
});
async function getList() {
gridApi.setLoading(true);
try {
list.value = await getProductBomListByItemId(props.itemId);
gridApi.setGridOptions({ data: list.value });
} finally {
gridApi.setLoading(false);
}
}
function handleAdd() {
itemSelectRef.value?.open(undefined, { multiple: true });
}
async function handleItemSelected(rows: MesMdItemApi.Item[]) {
if (rows.length === 0) {
return;
}
for (const item of rows) {
await createProductBom({
bomItemId: item.id,
itemId: props.itemId,
quantity: 1,
});
}
message.success($t('ui.actionMessage.operationSuccess'));
await getList();
}
async function openForm(row: MesMdProductBomApi.ProductBom) {
formOpen.value = true;
formData.value = row;
await formApi.resetForm();
await formApi.setValues({
...row,
itemId: props.itemId,
});
}
async function submitForm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
formLoading.value = true;
try {
const data = (await formApi.getValues()) as MesMdProductBomApi.ProductBom;
await (formData.value?.id ? updateProductBom(data) : createProductBom(data));
formOpen.value = false;
message.success($t('ui.actionMessage.operationSuccess'));
await getList();
} finally {
formLoading.value = false;
}
}
async function handleDelete(id: number) {
await deleteProductBom(id);
message.success($t('ui.actionMessage.deleteSuccess', ['BOM']));
await getList();
}
watch(
() => props.itemId,
(value) => {
if (value) {
getList();
}
},
{ immediate: true },
);
</script>
<template>
<div>
<div v-if="!isReadOnly" class="mb-3 flex items-center justify-start">
<TableAction
:actions="[
{
label: '添加 BOM 物料',
type: 'primary',
onClick: handleAdd,
},
]"
/>
</div>
<Grid class="w-full">
<template #actions="{ row }">
<TableAction
:actions="[
{
label: '编辑',
type: 'link',
onClick: openForm.bind(null, row),
},
{
label: '删除',
type: 'link',
danger: true,
popConfirm: {
title: '确认删除该 BOM 吗?',
confirm: handleDelete.bind(null, row.id!),
},
},
]"
/>
</template>
</Grid>
<Modal
v-model:open="formOpen"
title="编辑 BOM"
width="600px"
:confirm-loading="formLoading"
@ok="submitForm"
>
<Form class="mx-4" />
</Modal>
<MdItemSelectDialog ref="itemSelectRef" @selected="handleItemSelected" />
</div>
</template>

View File

@ -0,0 +1,231 @@
<script lang="ts" setup>
import type { MesMdProductSipApi } from '#/api/mes/md/item/productSip';
import type { MesMdProductSopApi } from '#/api/mes/md/item/productSop';
import { computed, markRaw, ref, watch } from 'vue';
import { Button, Card, Empty, Image, message, Modal, Popconfirm, Spin } from 'ant-design-vue';
import { useVbenForm, z } from '#/adapter/form';
import {
createProductSip,
deleteProductSip,
getProductSipListByItemId,
updateProductSip,
} from '#/api/mes/md/item/productSip';
import {
createProductSop,
deleteProductSop,
getProductSopListByItemId,
updateProductSop,
} from '#/api/mes/md/item/productSop';
import { ImageUpload } from '#/components/upload';
import { ProProcessSelect } from '#/views/mes/pro/process/components';
type MediaKind = 'SIP' | 'SOP';
type MediaItem =
| MesMdProductSipApi.ProductSip
| MesMdProductSopApi.ProductSop;
const props = withDefaults(
defineProps<{
formType?: string;
itemId: number;
kind: MediaKind;
}>(),
{
formType: 'update',
},
);
const isReadOnly = computed(() => props.formType === 'detail');
const title = computed(() => props.kind);
const loading = ref(false);
const formOpen = ref(false);
const formLoading = ref(false);
const formData = ref<MediaItem>();
const list = ref<MediaItem[]>([]);
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 100,
},
layout: 'horizontal',
schema: [
{ fieldName: 'id', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{ fieldName: 'itemId', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{
fieldName: 'title',
label: '标题',
component: 'Input',
componentProps: { placeholder: '请输入标题' },
rules: 'required',
},
{
fieldName: 'sort',
label: '展示顺序',
component: 'InputNumber',
componentProps: { class: '!w-full', min: 0, precision: 0 },
rules: z.number().default(0),
},
{
fieldName: 'description',
label: '内容说明',
component: 'Textarea',
componentProps: { placeholder: '请输入详细描述', rows: 3 },
},
{
fieldName: 'processId',
label: '所属工序',
component: markRaw(ProProcessSelect),
},
{
fieldName: 'url',
label: '图片',
component: markRaw(ImageUpload),
componentProps: { maxNumber: 1, showDescription: false },
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: { placeholder: '请输入备注', rows: 3 },
},
],
showDefaultActions: false,
});
function getListApi() {
return props.kind === 'SIP'
? getProductSipListByItemId
: getProductSopListByItemId;
}
function createApi() {
return props.kind === 'SIP' ? createProductSip : createProductSop;
}
function updateApi() {
return props.kind === 'SIP' ? updateProductSip : updateProductSop;
}
function deleteApi() {
return props.kind === 'SIP' ? deleteProductSip : deleteProductSop;
}
async function getList() {
loading.value = true;
try {
list.value = await getListApi()(props.itemId);
} finally {
loading.value = false;
}
}
async function openForm(row?: MediaItem) {
formOpen.value = true;
formData.value = row;
await formApi.resetForm();
await formApi.setValues({
itemId: props.itemId,
sort: 0,
...row,
});
}
async function submitForm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
formLoading.value = true;
try {
const data = (await formApi.getValues()) as MediaItem;
await (formData.value?.id ? updateApi()(data as any) : createApi()(data as any));
formOpen.value = false;
message.success('保存成功');
await getList();
} finally {
formLoading.value = false;
}
}
async function handleDelete(id: number) {
await deleteApi()(id);
message.success('删除成功');
await getList();
}
watch(
() => props.itemId,
(value) => {
if (value) {
getList();
}
},
{ immediate: true },
);
</script>
<template>
<div>
<Button
v-if="!isReadOnly"
class="mb-3"
type="primary"
@click="openForm()"
>
添加 {{ title }}
</Button>
<Spin :spinning="loading">
<div v-if="list.length > 0" class="grid grid-cols-4 gap-3">
<Card
v-for="item in list"
:key="item.id"
hoverable
:body-style="{ padding: '0px' }"
>
<Image
v-if="item.url"
:src="item.url"
class="block h-40 w-full object-cover"
:preview="{ src: item.url }"
/>
<div
v-else
class="flex h-40 w-full items-center justify-center bg-gray-100 text-gray-400"
>
暂无图片
</div>
<div class="p-3">
<div class="mb-1 truncate text-sm font-bold">{{ item.title }}</div>
<div v-if="item.description" class="truncate text-xs text-gray-500">
{{ item.description }}
</div>
<div v-if="!isReadOnly" class="mt-2 flex justify-end">
<Button type="link" size="small" @click="openForm(item)"></Button>
<Popconfirm title="确认删除该数据吗?" @confirm="handleDelete(item.id!)">
<Button danger type="link" size="small">删除</Button>
</Popconfirm>
</div>
</div>
</Card>
</div>
<Empty v-else :description="`暂无 ${title} 数据`" />
</Spin>
<Modal
v-model:open="formOpen"
:title="`${formData?.id ? '编辑' : '新增'} ${title}`"
width="500px"
:confirm-loading="formLoading"
@ok="submitForm"
>
<Form class="mx-4" />
</Modal>
</div>
</template>

View File

@ -0,0 +1,14 @@
<script lang="ts" setup>
import ProductMediaList from './product-media-list.vue';
defineOptions({ name: 'MesMdProductSipForm' });
defineProps<{
formType?: string;
itemId: number;
}>();
</script>
<template>
<ProductMediaList :form-type="formType" :item-id="itemId" kind="SIP" />
</template>

View File

@ -0,0 +1,14 @@
<script lang="ts" setup>
import ProductMediaList from './product-media-list.vue';
defineOptions({ name: 'MesMdProductSopForm' });
defineProps<{
formType?: string;
itemId: number;
}>();
</script>
<template>
<ProductMediaList :form-type="formType" :item-id="itemId" kind="SOP" />
</template>

View File

@ -0,0 +1 @@
export { default as MdUnitMeasureSelect } from './md-unit-measure-select.vue';

View File

@ -0,0 +1,116 @@
<script lang="ts" setup>
import type { MesMdUnitMeasureApi } from '#/api/mes/md/unitmeasure';
import { computed, onMounted, ref, watch } from 'vue';
import { Select, Tag, Tooltip } from 'ant-design-vue';
import { getUnitMeasureSimpleList } from '#/api/mes/md/unitmeasure';
defineOptions({ name: 'MdUnitMeasureSelect', inheritAttrs: false });
const props = withDefaults(
defineProps<{
allowClear?: boolean;
disabled?: boolean;
modelValue?: number;
placeholder?: string;
}>(),
{
allowClear: true,
disabled: false,
modelValue: undefined,
placeholder: '请选择计量单位',
},
);
const emit = defineEmits<{
change: [item: MesMdUnitMeasureApi.UnitMeasure | undefined];
'update:modelValue': [value: number | undefined];
}>();
const allList = ref<MesMdUnitMeasureApi.UnitMeasure[]>([]);
const filteredList = ref<MesMdUnitMeasureApi.UnitMeasure[]>([]);
const selectedItem = ref<MesMdUnitMeasureApi.UnitMeasure>();
const selectValue = computed({
get: () => props.modelValue,
set: (value: number | undefined) => {
emit('update:modelValue', value);
},
});
function handleFilter(input: string, option: any) {
const keyword = input.toLowerCase();
const item = option?.item as MesMdUnitMeasureApi.UnitMeasure | undefined;
return Boolean(
item?.name?.toLowerCase().includes(keyword) ||
item?.code?.toLowerCase().includes(keyword),
);
}
/** 根据当前值同步 tooltip 展示的计量单位详情 */
function syncSelectedItem(value: number | undefined) {
selectedItem.value =
value === undefined ? undefined : allList.value.find((item) => item.id === value);
}
/** 除 v-model 外,额外抛出完整计量单位对象给业务表单使用 */
function handleChange(value: any) {
const nextValue = value === undefined ? undefined : Number(value);
syncSelectedItem(nextValue);
emit('change', selectedItem.value);
}
watch(
() => props.modelValue,
(value) => {
syncSelectedItem(value);
},
);
onMounted(async () => {
allList.value = await getUnitMeasureSimpleList();
filteredList.value = allList.value;
syncSelectedItem(props.modelValue);
});
</script>
<template>
<Tooltip :mouse-enter-delay="0.5" :open="selectedItem ? undefined : false">
<template #title>
<div v-if="selectedItem" class="leading-6">
<div>编码{{ selectedItem.code || '-' }}</div>
<div>名称{{ selectedItem.name || '-' }}</div>
<div>是否主单位{{ selectedItem.primaryFlag ? '是' : '否' }}</div>
<div v-if="!selectedItem.primaryFlag && selectedItem.changeRate != null">
换算比例{{ selectedItem.changeRate }}
</div>
<div v-if="selectedItem.remark">{{ selectedItem.remark }}</div>
</div>
</template>
<Select
v-bind="$attrs"
v-model:value="selectValue"
:allow-clear="allowClear"
:disabled="disabled"
:filter-option="handleFilter"
:placeholder="placeholder"
class="w-full"
show-search
@change="handleChange"
>
<Select.Option
v-for="item in filteredList"
:key="item.id"
:item="item"
:value="item.id"
>
<div class="flex items-center gap-2">
<span>{{ item.name }}</span>
<Tag v-if="item.code" color="default">: {{ item.code }}</Tag>
</div>
</Select.Option>
</Select>
</Tooltip>
</template>

View File

@ -0,0 +1 @@
export { default as ProProcessSelect } from './pro-process-select.vue';

View File

@ -0,0 +1,111 @@
<script lang="ts" setup>
import type { MesProProcessApi } from '#/api/mes/pro/process';
import { computed, onMounted, ref, watch } from 'vue';
import { Select, Tag, Tooltip } from 'ant-design-vue';
import { getProcessSimpleList } from '#/api/mes/pro/process';
defineOptions({ name: 'ProProcessSelect', inheritAttrs: false });
const props = withDefaults(
defineProps<{
allowClear?: boolean;
disabled?: boolean;
modelValue?: number;
placeholder?: string;
}>(),
{
allowClear: true,
disabled: false,
modelValue: undefined,
placeholder: '请选择工序',
},
);
const emit = defineEmits<{
change: [item: MesProProcessApi.Process | undefined];
'update:modelValue': [value: number | undefined];
}>();
const allList = ref<MesProProcessApi.Process[]>([]);
const selectedItem = ref<MesProProcessApi.Process>();
const selectValue = computed({
get: () => props.modelValue,
set: (value: number | undefined) => {
emit('update:modelValue', value);
},
});
function handleFilter(input: string, option: any) {
const keyword = input.toLowerCase();
const item = option?.item as MesProProcessApi.Process | undefined;
return Boolean(
item?.name?.toLowerCase().includes(keyword) ||
item?.code?.toLowerCase().includes(keyword),
);
}
/** 根据当前值同步 tooltip 展示的工序详情 */
function syncSelectedItem(value: number | undefined) {
selectedItem.value =
value === undefined ? undefined : allList.value.find((item) => item.id === value);
}
/** 除 v-model 外,额外抛出完整工序对象给业务表单使用 */
function handleChange(value: any) {
const nextValue = value === undefined ? undefined : Number(value);
syncSelectedItem(nextValue);
emit('change', selectedItem.value);
}
watch(
() => props.modelValue,
(value) => {
syncSelectedItem(value);
},
);
onMounted(async () => {
allList.value = await getProcessSimpleList();
syncSelectedItem(props.modelValue);
});
</script>
<template>
<Tooltip :mouse-enter-delay="0.5" :open="selectedItem ? undefined : false">
<template #title>
<div v-if="selectedItem" class="leading-6">
<div>编码{{ selectedItem.code || '-' }}</div>
<div>名称{{ selectedItem.name || '-' }}</div>
<div>工艺要求{{ selectedItem.attention || '-' }}</div>
<div>备注{{ selectedItem.remark || '-' }}</div>
</div>
</template>
<Select
v-bind="$attrs"
v-model:value="selectValue"
:allow-clear="allowClear"
:disabled="disabled"
:filter-option="handleFilter"
:placeholder="placeholder"
class="w-full"
show-search
@change="handleChange"
>
<Select.Option
v-for="item in allList"
:key="item.id"
:item="item"
:value="item.id"
>
<div class="flex items-center gap-2">
<span>{{ item.name }}</span>
<Tag v-if="item.code" color="default">{{ item.code }}</Tag>
</div>
</Select.Option>
</Select>
</Tooltip>
</template>

View File

@ -0,0 +1,174 @@
<script lang="ts" setup>
import type Barcode from './barcode.vue';
import type { MesWmBarcodeApi } from '#/api/mes/wm/barcode';
import { ref } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import {
Button,
Descriptions,
Empty,
message,
Modal,
Tooltip,
} from 'ant-design-vue';
import {
createBarcode,
getBarcodeByBusiness,
} from '#/api/mes/wm/barcode';
import { DictTag } from '#/components/dict-tag';
import MesWmBarcode from './barcode.vue';
defineOptions({ name: 'MesWmBarcodeDetail' });
const open = ref(false);
const barcodeRef = ref<InstanceType<typeof Barcode>>();
const barcodeData = ref<Partial<MesWmBarcodeApi.Barcode>>({});
function openModal(row: Partial<MesWmBarcodeApi.Barcode>) {
open.value = true;
barcodeData.value = { ...row };
}
async function openByBusiness(
bizId: number,
bizType: number,
bizCode?: string,
bizName?: string,
) {
open.value = true;
try {
const data = await getBarcodeByBusiness(bizType, bizId);
barcodeData.value = data || { bizCode, bizId, bizName, bizType, content: '' };
if (!data) {
message.warning('未找到对应条码数据');
}
} catch {
barcodeData.value = { bizCode, bizId, bizName, bizType, content: '' };
message.error('加载条码数据失败');
}
}
defineExpose({ open: openModal, openByBusiness });
function escapeHtml(value: string) {
return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
}
function handlePrint() {
const base64 = barcodeRef.value?.getImageBase64();
if (!base64) {
message.warning('条码生成失败,无法打印');
return;
}
const printWindow = window.open('', '_blank');
if (!printWindow) {
message.error('无法打开打印窗口,请检查浏览器设置');
return;
}
printWindow.document.write(`<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>打印条码</title>
<style>*{margin:0;padding:0}body{font-family:Arial,sans-serif;padding:20px}.print-container{text-align:center}.barcode-img{max-width:100%;margin:20px 0}.info{margin-top:20px;text-align:left;font-size:12px}.info p{margin:5px 0}@media print{body{padding:0}.print-container{padding:20px}}</style>
</head><body><div class="print-container">
<img src="${base64}" class="barcode-img" alt="条码" />
<div class="info">
<p><strong>业务编码:</strong> ${escapeHtml(barcodeData.value.bizCode || '')}</p>
<p><strong>业务名称:</strong> ${escapeHtml(barcodeData.value.bizName || '')}</p>
<p><strong>条码内容:</strong> ${escapeHtml(barcodeData.value.content || '')}</p>
</div></div></body></html>`);
printWindow.document.close();
printWindow.addEventListener('load', () => {
setTimeout(() => printWindow.print(), 500);
});
}
function handleDownload() {
const base64 = barcodeRef.value?.getImageBase64();
if (!base64) {
message.warning('条码生成失败,无法下载');
return;
}
const link = document.createElement('a');
link.href = base64;
link.download = `barcode_${barcodeData.value.bizCode || 'unknown'}_${Date.now()}.png`;
link.click();
message.success('下载成功');
}
async function handleGenerate() {
const { bizCode, bizId, bizName, bizType } = barcodeData.value;
if (!bizType || !bizId) {
message.warning('缺少业务类型或业务编号,无法生成条码');
return;
}
await createBarcode({ bizCode: bizCode || '', bizId, bizName: bizName || '', bizType });
message.success('条码生成成功');
const data = await getBarcodeByBusiness(bizType, bizId);
if (data) {
barcodeData.value = { ...data };
}
}
</script>
<template>
<Modal v-model:open="open" title="查看条码" width="500px">
<div>
<div class="mb-5 flex min-h-50 items-center justify-center rounded bg-gray-100 p-5">
<div v-if="barcodeData.content" class="flex items-center justify-center">
<MesWmBarcode
ref="barcodeRef"
:content="barcodeData.content"
:format="barcodeData.format"
:height="150"
:width="400"
/>
</div>
<Empty v-else description="暂无条码数据" />
</div>
<Descriptions :column="1" bordered>
<Descriptions.Item label="条码格式">
<DictTag
v-if="barcodeData.format"
:type="DICT_TYPE.MES_WM_BARCODE_FORMAT"
:value="barcodeData.format"
/>
</Descriptions.Item>
<Descriptions.Item label="业务类型">
<DictTag
v-if="barcodeData.bizType"
:type="DICT_TYPE.MES_WM_BARCODE_BIZ_TYPE"
:value="barcodeData.bizType"
/>
</Descriptions.Item>
<Descriptions.Item label="条码内容">
<Tooltip :title="barcodeData.content">
<span class="inline-block max-w-75 overflow-hidden text-ellipsis whitespace-nowrap">
{{ barcodeData.content }}
</span>
</Tooltip>
</Descriptions.Item>
<Descriptions.Item label="业务编码">{{ barcodeData.bizCode || '-' }}</Descriptions.Item>
<Descriptions.Item label="业务名称">{{ barcodeData.bizName || '-' }}</Descriptions.Item>
<Descriptions.Item label="状态">
<DictTag
v-if="barcodeData.status !== undefined"
:type="DICT_TYPE.COMMON_STATUS"
:value="barcodeData.status"
/>
</Descriptions.Item>
<Descriptions.Item label="创建时间">{{ barcodeData.createTime || '-' }}</Descriptions.Item>
</Descriptions>
</div>
<template #footer>
<Button v-if="!barcodeData.content" @click="handleGenerate"></Button>
<Button type="primary" @click="handlePrint"></Button>
<Button @click="handleDownload"></Button>
<Button @click="open = false">关闭</Button>
</template>
</Modal>
</template>

View File

@ -0,0 +1,54 @@
<script lang="ts" setup>
import type { BarcodeFormat } from '@vben/common-ui';
import { computed, ref } from 'vue';
import {
BarcodeFormatEnum,
Barcode as CommonBarcode,
} from '@vben/common-ui';
defineOptions({ name: 'MesWmBarcode' });
const props = withDefaults(
defineProps<{
content?: string;
displayValue?: boolean;
format?: number;
height?: number;
width?: number;
}>(),
{
content: '',
displayValue: true,
format: BarcodeFormatEnum.QR_CODE,
height: 100,
width: 200,
},
);
const emit = defineEmits<{ done: [value: string] }>();
const barcodeRef = ref<InstanceType<typeof CommonBarcode>>();
const commonFormat = computed<BarcodeFormat>(
() => (props.format || BarcodeFormatEnum.QR_CODE) as BarcodeFormat,
);
function getImageBase64() {
return barcodeRef.value?.getImageBase64() || '';
}
defineExpose({ getImageBase64 });
</script>
<template>
<CommonBarcode
ref="barcodeRef"
:content="content"
:display-value="displayValue"
:format="commonFormat"
:height="height"
:width="width"
@done="emit('done', $event)"
/>
</template>

View File

@ -0,0 +1,3 @@
export { default as BarcodeDetail } from './barcode-detail.vue';
export { default as Barcode } from './barcode.vue';
export { default as PrinterLabel } from './printer-label.vue';

View File

@ -0,0 +1,30 @@
<script lang="ts" setup>
import { Button, message } from 'ant-design-vue';
defineOptions({ name: 'MesWmPrinterLabel' });
withDefaults(
defineProps<{
bizCode?: string;
bizId?: number;
bizType?: string;
labelText?: string;
}>(),
{
bizCode: undefined,
bizId: undefined,
bizType: undefined,
labelText: '标签打印',
},
);
function handlePrint() {
message.warning('标签打印功能暂未实现,敬请期待');
}
</script>
<template>
<Button type="link" @click="handlePrint">
{{ labelText }}
</Button>
</template>

View File

@ -0,0 +1,38 @@
import type { PageParam, PageResult } from '@vben/request';
import { requestClient } from '#/api/request';
export namespace MesProProcessApi {
/** MES 生产工序 */
export interface Process {
id: number;
code?: string;
name?: string;
attention?: string;
status?: number;
remark?: string;
createTime?: Date;
}
}
/** 查询生产工序分页 */
export function getProcessPage(params: PageParam) {
return requestClient.get<PageResult<MesProProcessApi.Process>>(
'/mes/pro/process/page',
{ params },
);
}
/** 查询生产工序精简列表 */
export function getProcessSimpleList() {
return requestClient.get<MesProProcessApi.Process[]>(
'/mes/pro/process/simple-list',
);
}
/** 查询生产工序详情 */
export function getProcess(id: number) {
return requestClient.get<MesProProcessApi.Process>(
`/mes/pro/process/get?id=${id}`,
);
}

View File

@ -0,0 +1,65 @@
import type { PageParam, PageResult } from '@vben/request';
import { requestClient } from '#/api/request';
export namespace MesWmBarcodeApi {
/** MES 条码清单 */
export interface Barcode {
id?: number;
configId?: number;
format?: number;
bizType?: number;
content?: string;
bizId?: number;
bizCode?: string;
bizName?: string;
status?: number;
remark?: string;
createTime?: Date;
}
}
/** 查询条码分页 */
export function getBarcodePage(params: PageParam) {
return requestClient.get<PageResult<MesWmBarcodeApi.Barcode>>(
'/mes/wm/barcode/page',
{ params },
);
}
/** 查询条码详情 */
export function getBarcode(id: number) {
return requestClient.get<MesWmBarcodeApi.Barcode>(
`/mes/wm/barcode/get?id=${id}`,
);
}
/** 根据业务对象获取条码 */
export function getBarcodeByBusiness(bizType: number, bizId: number) {
return requestClient.get<MesWmBarcodeApi.Barcode>(
'/mes/wm/barcode/get-by-business',
{ params: { bizType, bizId } },
);
}
/** 新增条码 */
export function createBarcode(data: MesWmBarcodeApi.Barcode) {
return requestClient.post('/mes/wm/barcode/create', data);
}
/** 修改条码 */
export function updateBarcode(data: MesWmBarcodeApi.Barcode) {
return requestClient.put('/mes/wm/barcode/update', data);
}
/** 删除条码 */
export function deleteBarcode(id: number) {
return requestClient.delete(`/mes/wm/barcode/delete?id=${id}`);
}
/** 生成条码内容 */
export function generateBarcodeContent(bizType: number, bizCode: string) {
return requestClient.get<string>('/mes/wm/barcode/generate-content', {
params: { bizType, bizCode },
});
}

View File

@ -0,0 +1,2 @@
export { default as MdItemSelectDialog } from './md-item-select-dialog.vue';
export { default as MdItemSelect } from './md-item-select.vue';

View File

@ -0,0 +1,191 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesMdItemApi } from '#/api/mes/md/item';
import type { MesMdItemTypeApi } from '#/api/mes/md/item/type';
import { nextTick, ref } from 'vue';
import { CommonStatusEnum } from '@vben/constants';
import { ElButton, ElCard, ElDialog, ElMessage } from 'element-plus';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getItemPage } from '#/api/mes/md/item';
import { MdItemTypeTree } from '#/views/mes/md/item/type/components';
import { useItemSelectGridColumns, useItemSelectGridFormSchema } from '../data';
defineOptions({ name: 'MdItemSelectDialog' });
const emit = defineEmits<{
selected: [rows: MesMdItemApi.Item[]];
}>();
const open = ref(false);
const multiple = ref(true);
const syncingSingleSelection = ref(false);
const selectedRows = ref<MesMdItemApi.Item[]>([]);
const selectedItemTypeId = ref<number>();
const preSelectedIds = ref<number[]>([]);
const typeTreeRef = ref<InstanceType<typeof MdItemTypeTree>>();
/** 单选模式下同步 VXE 勾选状态,避免跨页残留多选 */
async function syncSingleSelection(row?: MesMdItemApi.Item) {
syncingSingleSelection.value = true;
await nextTick();
await gridApi.grid.clearCheckboxRow();
if (row) {
await gridApi.grid.setCheckboxRow(row, true);
}
await nextTick();
syncingSingleSelection.value = false;
}
/** 处理勾选变化,单选模式只保留最后一条 */
async function handleCheckboxChange({
checked,
records,
row,
}: {
checked: boolean;
records: MesMdItemApi.Item[];
row?: MesMdItemApi.Item;
}) {
if (syncingSingleSelection.value) {
return;
}
if (!multiple.value) {
const selected = checked && row ? [row] : [];
selectedRows.value = selected;
await syncSingleSelection(selected[0]);
return;
}
selectedRows.value = records;
}
function handleCheckboxAll({ records }: { records: MesMdItemApi.Item[] }) {
if (syncingSingleSelection.value) {
return;
}
selectedRows.value = records;
}
function handleItemTypeNodeClick(row: MesMdItemTypeApi.ItemType | undefined) {
selectedItemTypeId.value = row?.id;
gridApi.query();
}
function applyPreSelection() {
if (preSelectedIds.value.length === 0) {
return;
}
const rows = gridApi.grid.getData() as MesMdItemApi.Item[];
for (const row of rows) {
if (row.id && preSelectedIds.value.includes(row.id)) {
gridApi.grid.setCheckboxRow(row, true);
if (!multiple.value) {
selectedRows.value = [row];
}
}
}
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useItemSelectGridFormSchema(),
},
gridOptions: {
columns: useItemSelectGridColumns(),
height: 560,
keepSource: true,
checkboxConfig: {
highlight: true,
range: true,
reserve: true,
},
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getItemPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
itemTypeId: selectedItemTypeId.value,
status: CommonStatusEnum.ENABLE,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<MesMdItemApi.Item>,
gridEvents: {
checkboxAll: handleCheckboxAll,
checkboxChange: handleCheckboxChange,
},
});
async function resetQueryState() {
selectedItemTypeId.value = undefined;
selectedRows.value = [];
typeTreeRef.value?.reset();
await gridApi.grid.clearCheckboxRow();
await gridApi.formApi.resetForm();
}
async function openModal(selectedIds?: number[], options?: { multiple?: boolean }) {
open.value = true;
multiple.value = options?.multiple ?? true;
preSelectedIds.value = selectedIds || [];
await nextTick();
await resetQueryState();
await gridApi.query();
await nextTick();
applyPreSelection();
}
async function closeModal() {
open.value = false;
await resetQueryState();
}
function handleConfirm() {
if (selectedRows.value.length === 0) {
ElMessage.warning(multiple.value ? '请至少选择一条数据' : '请选择一条数据');
return;
}
emit('selected', multiple.value ? selectedRows.value : [selectedRows.value[0]!]);
open.value = false;
}
defineExpose({ open: openModal });
</script>
<template>
<ElDialog
v-model="open"
title="物料产品选择"
width="80%"
destroy-on-close
@close="closeModal"
>
<div class="flex h-full w-full">
<ElCard class="mr-4 h-full w-1/5">
<MdItemTypeTree ref="typeTreeRef" @node-click="handleItemTypeNodeClick" />
</ElCard>
<div class="w-4/5">
<Grid table-title="" />
</div>
</div>
<template #footer>
<ElButton @click="closeModal"></ElButton>
<ElButton type="primary" @click="handleConfirm"></ElButton>
</template>
</ElDialog>
</template>

View File

@ -0,0 +1,130 @@
<script lang="ts" setup>
import type { MesMdItemApi } from '#/api/mes/md/item';
import { computed, ref, useAttrs, watch } from 'vue';
import { CircleX, Search } from '@vben/icons';
import { ElInput, ElTooltip } from 'element-plus';
import { getItem } from '#/api/mes/md/item';
import MdItemSelectDialog from './md-item-select-dialog.vue';
defineOptions({ name: 'MdItemSelect', inheritAttrs: false });
const props = withDefaults(
defineProps<{
clearable?: boolean;
disabled?: boolean;
modelValue?: number;
placeholder?: string;
}>(),
{
clearable: true,
disabled: false,
modelValue: undefined,
placeholder: '请选择产品物料',
},
);
const emit = defineEmits<{
change: [item: MesMdItemApi.Item | undefined];
'update:modelValue': [value: number | undefined];
}>();
const attrs = useAttrs();
const dialogRef = ref<InstanceType<typeof MdItemSelectDialog>>();
const hovering = ref(false);
const selectedItem = ref<MesMdItemApi.Item>();
const displayLabel = computed(() => selectedItem.value?.name ?? '');
const showClear = computed(
() => props.clearable && !props.disabled && hovering.value && props.modelValue != null,
);
async function resolveItemById(id: number | undefined) {
if (id == null) {
selectedItem.value = undefined;
return;
}
if (selectedItem.value?.id === id) {
return;
}
try {
selectedItem.value = await getItem(id);
} catch (error) {
console.error('[MdItemSelect] resolveItemById failed:', error);
}
}
watch(
() => props.modelValue,
(value) => {
resolveItemById(value);
},
{ immediate: true },
);
function clearSelected() {
selectedItem.value = undefined;
emit('update:modelValue', undefined);
emit('change', undefined);
}
function handleClick(event: MouseEvent) {
if (props.disabled) {
return;
}
const target = event.target as HTMLElement;
if (showClear.value && target.closest('.el-input__suffix')) {
event.stopPropagation();
clearSelected();
return;
}
const selectedIds = props.modelValue == null ? [] : [props.modelValue];
dialogRef.value?.open(selectedIds, { multiple: false });
}
function handleSelected(rows: MesMdItemApi.Item[]) {
const item = rows[0];
if (!item) {
return;
}
selectedItem.value = item;
emit('update:modelValue', item.id);
emit('change', item);
}
</script>
<template>
<div
v-bind="attrs"
class="w-full"
:class="disabled ? 'cursor-not-allowed' : 'cursor-pointer'"
@click="handleClick"
@mouseenter="hovering = true"
@mouseleave="hovering = false"
>
<ElTooltip :disabled="!selectedItem" placement="top" :show-after="500">
<template #content>
<div v-if="selectedItem" class="leading-6">
<div>编码{{ selectedItem.code || '-' }}</div>
<div>名称{{ selectedItem.name || '-' }}</div>
<div>规格{{ selectedItem.specification || '-' }}</div>
<div>单位{{ selectedItem.unitMeasureName || '-' }}</div>
</div>
</template>
<ElInput
:disabled="disabled"
:model-value="displayLabel"
:placeholder="placeholder"
readonly
>
<template #suffix>
<CircleX v-if="showClear" class="size-4" />
<Search v-else class="size-4" />
</template>
</ElInput>
</ElTooltip>
</div>
<MdItemSelectDialog ref="dialogRef" @selected="handleSelected" />
</template>

View File

@ -0,0 +1,478 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesMdItemApi } from '#/api/mes/md/item';
import type { MesMdProductBomApi } from '#/api/mes/md/item/productBom';
import { h, markRaw } from 'vue';
import { CommonStatusEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { ElButton } from 'element-plus';
import { z } from '#/adapter/form';
import { generateAutoCode } from '#/api/mes/md/autocode/record';
import { MdItemTypeSelect } from '#/views/mes/md/item/type/components';
import { MdUnitMeasureSelect } from '#/views/mes/md/unitmeasure/components';
import { MesAutoCodeRuleCode } from '#/views/mes/utils/constants';
/** 新增/修改物料产品的表单 */
export function useFormSchema(formApi?: any): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'code',
label: '物料编码',
component: 'Input',
componentProps: {
maxLength: 64,
placeholder: '请输入物料编码',
},
rules: z.string().min(1, '物料编码不能为空').max(64),
suffix: () =>
h(
ElButton,
{
type: 'default',
onClick: async () => {
try {
const code = await generateAutoCode(
MesAutoCodeRuleCode.MD_ITEM_CODE,
);
await formApi?.setFieldValue('code', code);
} catch (error) {
console.error(error);
}
},
},
{ default: () => '生成' },
),
},
{
fieldName: 'name',
label: '物料名称',
component: 'Input',
componentProps: {
maxLength: 255,
placeholder: '请输入物料名称',
},
rules: z.string().min(1, '物料名称不能为空').max(255),
},
{
fieldName: 'specification',
label: '规格型号',
component: 'Input',
componentProps: {
maxLength: 255,
placeholder: '请输入规格型号',
},
},
{
fieldName: 'unitMeasureId',
label: '单位',
component: markRaw(MdUnitMeasureSelect),
componentProps: {
placeholder: '请选择计量单位',
},
rules: 'selectRequired',
},
{
fieldName: 'itemTypeId',
label: '物料分类',
component: markRaw(MdItemTypeSelect),
componentProps: {
onChange: async (itemType: any) => {
await formApi?.setFieldValue('itemOrProduct', itemType?.itemOrProduct);
},
},
rules: 'selectRequired',
},
{
fieldName: 'status',
label: '状态',
component: 'RadioGroup',
componentProps: {
disabled: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
rules: z.number().default(CommonStatusEnum.DISABLE),
},
{
fieldName: 'highValue',
label: '高值物料',
component: 'Switch',
componentProps: {
activeText: '是',
inactiveText: '否',
inlinePrompt: true,
},
rules: z.boolean().default(false),
},
{
fieldName: 'batchFlag',
label: '批次管理',
component: 'Switch',
componentProps: {
activeText: '是',
inactiveText: '否',
inlinePrompt: true,
},
rules: z.boolean().default(true),
},
{
fieldName: 'safeStockFlag',
label: '安全库存',
component: 'Switch',
componentProps: {
activeText: '是',
inactiveText: '否',
inlinePrompt: true,
},
rules: z.boolean().default(false),
},
{
fieldName: 'minStock',
label: '最低库存量',
component: 'InputNumber',
componentProps: {
class: '!w-full',
controlsPosition: 'right',
min: 0,
precision: 2,
},
dependencies: {
triggerFields: ['safeStockFlag'],
show: (values) => Boolean(values.safeStockFlag),
},
rules: z.number().default(0),
},
{
fieldName: 'maxStock',
label: '最高库存量',
component: 'InputNumber',
componentProps: {
class: '!w-full',
controlsPosition: 'right',
min: 0,
precision: 2,
},
dependencies: {
triggerFields: ['safeStockFlag'],
show: (values) => Boolean(values.safeStockFlag),
},
rules: z.number().default(0),
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: {
placeholder: '请输入备注',
rows: 3,
},
formItemClass: 'col-span-3',
},
{
fieldName: 'itemOrProduct',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'code',
label: '物料编码',
component: 'Input',
componentProps: {
clearable: true,
placeholder: '请输入物料编码',
},
},
{
fieldName: 'name',
label: '物料名称',
component: 'Input',
componentProps: {
clearable: true,
placeholder: '请输入物料名称',
},
},
{
fieldName: 'status',
label: '状态',
component: 'Select',
componentProps: {
clearable: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择状态',
},
},
];
}
/** 物料导入表单 */
export function useImportFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'file',
label: '物料数据',
component: 'Upload',
rules: 'required',
help: '仅允许导入 xls、xlsx 格式文件',
},
{
fieldName: 'updateSupport',
label: '是否覆盖',
component: 'Switch',
componentProps: {
activeText: '是',
inactiveText: '否',
inlinePrompt: true,
},
rules: z.boolean().default(false),
help: '是否更新已经存在的物料数据',
},
];
}
/** 列表的字段 */
export function useGridColumns(
onStatusChange?: (
newStatus: number,
row: MesMdItemApi.Item,
) => PromiseLike<boolean | undefined>,
): VxeTableGridOptions<MesMdItemApi.Item>['columns'] {
return [
{
field: 'code',
title: '物料编码',
minWidth: 160,
slots: { default: 'code' },
},
{
field: 'name',
title: '物料名称',
minWidth: 160,
},
{
field: 'specification',
title: '规格型号',
minWidth: 160,
},
{
field: 'unitMeasureName',
title: '单位',
width: 100,
align: 'center',
},
{
field: 'itemTypeName',
title: '物料分类',
minWidth: 140,
align: 'center',
},
{
field: 'itemOrProduct',
title: '物料/产品',
width: 120,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.MES_MD_ITEM_OR_PRODUCT },
},
},
{
field: 'safeStockFlag',
title: '安全库存',
width: 120,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.INFRA_BOOLEAN_STRING },
},
},
{
field: 'status',
title: '状态',
width: 120,
align: 'center',
cellRender: {
attrs: { beforeChange: onStatusChange },
name: 'CellSwitch',
props: {
inactiveValue: CommonStatusEnum.DISABLE,
activeValue: CommonStatusEnum.ENABLE,
},
},
},
{
field: 'createTime',
title: '创建时间',
width: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 220,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 物料选择弹窗搜索表单 */
export function useItemSelectGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'code',
label: '物料编码',
component: 'Input',
componentProps: {
clearable: true,
placeholder: '请输入物料编码',
},
},
{
fieldName: 'name',
label: '物料名称',
component: 'Input',
componentProps: {
clearable: true,
placeholder: '请输入物料名称',
},
},
];
}
/** 物料选择弹窗列表字段 */
export function useItemSelectGridColumns(): VxeTableGridOptions<MesMdItemApi.Item>['columns'] {
return [
{ type: 'checkbox', width: 50 },
{
field: 'code',
title: '物料编码',
width: 180,
},
{
field: 'name',
title: '物料名称',
minWidth: 160,
align: 'left',
},
{
field: 'specification',
title: '规格型号',
minWidth: 140,
align: 'left',
},
{
field: 'unitMeasureName',
title: '单位',
width: 90,
align: 'center',
},
{
field: 'itemOrProduct',
title: '物料/产品',
width: 110,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.MES_MD_ITEM_OR_PRODUCT },
},
},
{
field: 'itemTypeName',
title: '所属分类',
width: 140,
align: 'center',
},
{
field: 'createTime',
title: '创建时间',
width: 180,
formatter: 'formatDateTime',
},
];
}
/** 产品 BOM 子表字段 */
export function useProductBomGridColumns(
isReadOnly = false,
): VxeTableGridOptions<MesMdProductBomApi.ProductBom>['columns'] {
const columns: VxeTableGridOptions<MesMdProductBomApi.ProductBom>['columns'] = [
{
field: 'bomItemCode',
title: '物料编码',
minWidth: 160,
align: 'center',
},
{
field: 'bomItemName',
title: '物料名称',
minWidth: 160,
align: 'center',
},
{
field: 'bomItemSpecification',
title: '规格型号',
minWidth: 140,
align: 'center',
},
{
field: 'unitMeasureName',
title: '单位',
width: 80,
align: 'center',
},
{
field: 'itemOrProduct',
title: '物料/产品',
width: 110,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.MES_MD_ITEM_OR_PRODUCT },
},
},
{
field: 'quantity',
title: '用量比例',
width: 100,
align: 'center',
},
{
field: 'remark',
title: '备注',
minWidth: 140,
align: 'center',
},
];
if (!isReadOnly) {
columns.push({
field: 'actions',
title: '操作',
width: 120,
align: 'center',
fixed: 'right',
slots: { default: 'actions' },
});
}
return columns;
}

View File

@ -0,0 +1,241 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesMdItemApi } from '#/api/mes/md/item';
import type { MesMdItemTypeApi } from '#/api/mes/md/item/type';
import { ref } from 'vue';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictLabel } from '@vben/hooks';
import { downloadFileFromBlobPart } from '@vben/utils';
import {
ElButton,
ElCard,
ElLoading,
ElMessage,
ElMessageBox,
} from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteItem,
exportItem,
getItemPage,
updateItemStatus,
} from '#/api/mes/md/item';
import { $t } from '#/locales';
import { MdItemTypeTree } from '#/views/mes/md/item/type/components';
import { PrinterLabel } from '#/views/mes/wm/barcode/components';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
import ImportForm from './modules/import-form.vue';
defineOptions({ name: 'MesMdItem' });
const selectedItemTypeId = ref<number>();
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [ImportModal, importModalApi] = useVbenModal({
connectedComponent: ImportForm,
destroyOnClose: true,
});
/** 刷新表格 */
function handleRefresh() {
gridApi.query();
}
/** 创建物料 */
function handleCreate() {
formModalApi.setData({ type: 'create' }).open();
}
/** 查看物料 */
function handleDetail(row: MesMdItemApi.Item) {
formModalApi.setData({ id: row.id, type: 'detail' }).open();
}
/** 编辑物料 */
function handleEdit(row: MesMdItemApi.Item) {
formModalApi.setData({ id: row.id, type: 'update' }).open();
}
/** 删除物料 */
async function handleDelete(row: MesMdItemApi.Item) {
const loadingInstance = ElLoading.service({
text: $t('ui.actionMessage.deleting', [row.name]),
});
try {
await deleteItem(row.id!);
ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
handleRefresh();
} finally {
loadingInstance.close();
}
}
/** 导出物料 */
async function handleExport() {
const data = await exportItem(await gridApi.formApi.getValues());
downloadFileFromBlobPart({ fileName: '物料产品.xls', source: data });
}
/** 导入物料 */
function handleImport() {
importModalApi.open();
}
/** 分类树点击 */
function handleTypeNodeClick(row: MesMdItemTypeApi.ItemType | undefined) {
selectedItemTypeId.value = row?.id;
handleRefresh();
}
/** 更新物料状态 */
async function handleStatusChange(
newStatus: number,
row: MesMdItemApi.Item,
): Promise<boolean | undefined> {
return new Promise((resolve, reject) => {
ElMessageBox.confirm(
`确认要将“${row.name}”物料切换为【${getDictLabel(DICT_TYPE.COMMON_STATUS, newStatus)}】吗?`,
'提示',
{ type: 'warning' },
)
.then(async () => {
await updateItemStatus(row.id!, newStatus);
ElMessage.success($t('ui.actionMessage.operationSuccess'));
resolve(true);
})
.catch(() => {
reject(new Error('取消操作'));
});
});
}
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
},
gridOptions: {
columns: useGridColumns(handleStatusChange),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await getItemPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
itemTypeId: selectedItemTypeId.value,
});
},
},
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<MesMdItemApi.Item>,
});
</script>
<template>
<Page auto-content-height>
<template #doc>
<DocAlert
title="【基础】物料产品、分类、计量单位"
url="https://doc.iocoder.cn/mes/md/product/"
/>
</template>
<FormModal @success="handleRefresh" />
<ImportModal @success="handleRefresh" />
<div class="flex h-full w-full">
<ElCard class="mr-4 h-full w-1/6">
<MdItemTypeTree @node-click="handleTypeNodeClick" />
</ElCard>
<div class="w-5/6">
<Grid table-title="">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: $t('ui.actionTitle.create', ['物料']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['mes:md-item:create'],
onClick: handleCreate,
},
{
label: $t('ui.actionTitle.import'),
type: 'primary',
icon: ACTION_ICON.UPLOAD,
auth: ['mes:md-item:import'],
onClick: handleImport,
},
{
label: $t('ui.actionTitle.export'),
type: 'primary',
icon: ACTION_ICON.DOWNLOAD,
auth: ['mes:md-item:export'],
onClick: handleExport,
},
]"
/>
</template>
<template #code="{ row }">
<ElButton link type="primary" @click="handleDetail(row)">
{{ row.code }}
</ElButton>
</template>
<template #actions="{ row }">
<div class="flex items-center justify-center">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['mes:md-item:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['mes:md-item:delete'],
popConfirm: {
title: $t('ui.actionMessage.deleteConfirm', [row.name]),
confirm: handleDelete.bind(null, row),
},
},
]"
/>
<PrinterLabel
:biz-id="row.id"
:biz-code="row.code"
biz-type="ITEM"
/>
</div>
</template>
</Grid>
</div>
</div>
</Page>
</template>

View File

@ -0,0 +1,169 @@
<script lang="ts" setup>
import type { MesMdItemApi } from '#/api/mes/md/item';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElButton, ElEmpty, ElMessage, ElTabPane, ElTabs } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { createItem, getItem, updateItem } from '#/api/mes/md/item';
import { $t } from '#/locales';
import { BarcodeBizTypeEnum } from '#/views/mes/utils/constants';
import { BarcodeDetail } from '#/views/mes/wm/barcode/components';
import { useFormSchema } from '../data';
import ItemBatchConfigForm from './item-batch-config-form.vue';
import ProductBomForm from './product-bom-form.vue';
import ProductSipForm from './product-sip-form.vue';
import ProductSopForm from './product-sop-form.vue';
type FormMode = 'create' | 'detail' | 'update';
defineOptions({ name: 'MesMdItemForm' });
const emit = defineEmits(['success']);
const formMode = ref<FormMode>('create');
const activeTab = ref('bom');
const formData = ref<MesMdItemApi.Item>();
const barcodeDetailRef = ref<InstanceType<typeof BarcodeDetail>>();
const isDetail = computed(() => formMode.value === 'detail');
const getTitle = computed(() => {
const titles: Record<FormMode, string> = {
create: '新增物料/产品',
update: '修改物料/产品',
detail: '查看物料/产品',
};
return titles[formMode.value];
});
const currentItemOrProduct = computed(() => formData.value?.itemOrProduct || '');
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-1',
labelWidth: 120,
},
wrapperClass: 'grid-cols-3',
layout: 'horizontal',
schema: [],
showDefaultActions: false,
});
/** 表单 schema 需要 formApi 引用,所以通过 setState 设置 schema */
formApi.setState({ schema: useFormSchema(formApi) });
function handleBarcode() {
if (!formData.value?.id) {
return;
}
barcodeDetailRef.value?.openByBusiness(
formData.value.id,
BarcodeBizTypeEnum.ITEM,
formData.value.code,
formData.value.name,
);
}
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
if (isDetail.value) {
await modalApi.close();
return;
}
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
//
const data = (await formApi.getValues()) as MesMdItemApi.Item;
try {
if (formMode.value === 'create') {
const id = await createItem(data);
formData.value = { ...data, id };
formMode.value = 'update';
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} else {
await updateItem(data);
formData.value = { ...formData.value, ...data };
ElMessage.success($t('ui.actionMessage.operationSuccess'));
}
emit('success');
} finally {
modalApi.unlock();
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
return;
}
await formApi.resetForm();
activeTab.value = 'bom';
//
const data = modalApi.getData<{ id?: number; type?: FormMode }>();
formMode.value = data?.type || 'create';
formApi.setDisabled(formMode.value === 'detail');
modalApi.setState({ showConfirmButton: formMode.value !== 'detail' });
if (!data?.id) {
return;
}
modalApi.lock();
try {
formData.value = await getItem(data.id);
// values
await formApi.setValues(formData.value);
} finally {
modalApi.unlock();
}
},
});
</script>
<template>
<Modal :title="getTitle" class="w-4/5">
<Form class="mx-4" />
<ElTabs
v-if="formMode !== 'create' && formData?.id"
v-model="activeTab"
class="mx-4 mt-4"
>
<ElTabPane name="bom" label="BOM 组成">
<ProductBomForm :form-type="formMode" :item-id="formData.id" />
</ElTabPane>
<ElTabPane v-if="formData.batchFlag" name="batch" label="批次属性">
<ItemBatchConfigForm
:form-type="formMode"
:item-id="formData.id"
:item-or-product="currentItemOrProduct"
/>
</ElTabPane>
<ElTabPane name="substitute" label="替代品">
<ElEmpty description="替代品(待实现)" />
</ElTabPane>
<ElTabPane name="sip" label="SIP">
<ProductSipForm :form-type="formMode" :item-id="formData.id" />
</ElTabPane>
<ElTabPane name="sop" label="SOP">
<ProductSopForm :form-type="formMode" :item-id="formData.id" />
</ElTabPane>
</ElTabs>
<template #prepend-footer>
<div class="flex flex-auto items-center">
<ElButton
v-if="isDetail && formData?.id"
type="primary"
@click="handleBarcode"
>
查看条码
</ElButton>
</div>
</template>
<BarcodeDetail ref="barcodeDetailRef" />
</Modal>
</template>

View File

@ -0,0 +1,103 @@
<script lang="ts" setup>
import type { MesMdItemApi } from '#/api/mes/md/item';
import { useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';
import { ElButton, ElMessage, ElUpload } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { importItem, importItemTemplate } from '#/api/mes/md/item';
import { $t } from '#/locales';
import { useImportFormSchema } from '../data';
defineOptions({ name: 'MesMdItemImportForm' });
const emit = defineEmits(['success']);
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useImportFormSchema(),
showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
modalApi.lock();
//
const data = await formApi.getValues();
try {
const result = await importItem(data.file, data.updateSupport);
const importData = result as MesMdItemApi.ItemImportRespVO;
let text = `上传成功数量:${importData.createCodes?.length || 0};`;
for (const code of importData.createCodes || []) {
text += `< ${code} >`;
}
text += `更新成功数量:${importData.updateCodes?.length || 0};`;
for (const code of importData.updateCodes || []) {
text += `< ${code} >`;
}
text += `更新失败数量:${Object.keys(importData.failureCodes || {}).length};`;
for (const code in importData.failureCodes || {}) {
text += `< ${code}: ${importData.failureCodes?.[code]} >`;
}
ElMessage.info(text);
//
await modalApi.close();
emit('success');
ElMessage.success($t('ui.actionMessage.operationSuccess'));
} finally {
modalApi.unlock();
}
},
});
/** 文件改变时 */
function handleChange(file: any) {
if (file.raw) {
formApi.setFieldValue('file', file.raw);
}
}
/** 下载模版 */
async function handleDownload() {
const data = await importItemTemplate();
downloadFileFromBlobPart({ fileName: '物料导入模板.xls', source: data });
}
</script>
<template>
<Modal :title="$t('ui.actionTitle.import', ['物料'])" class="w-1/3">
<Form class="mx-4">
<template #file>
<div class="w-full">
<ElUpload
:auto-upload="false"
:limit="1"
:on-change="handleChange"
accept=".xls,.xlsx"
>
<ElButton type="primary">选择 Excel 文件</ElButton>
</ElUpload>
</div>
</template>
</Form>
<template #prepend-footer>
<div class="flex flex-auto items-center">
<ElButton @click="handleDownload"></ElButton>
</div>
</template>
</Modal>
</template>

View File

@ -0,0 +1,125 @@
<script lang="ts" setup>
import type { MesMdItemBatchConfigApi } from '#/api/mes/md/item/batchConfig';
import { computed, ref, watch } from 'vue';
import { ElButton, ElCheckbox, ElMessage } from 'element-plus';
import {
getBatchConfigByItemId,
saveBatchConfig,
} from '#/api/mes/md/item/batchConfig';
import { MesItemOrProductEnum } from '#/views/mes/utils/constants';
defineOptions({ name: 'MesMdItemBatchConfigForm' });
const props = withDefaults(
defineProps<{
formType?: string;
itemId: number;
itemOrProduct?: string;
}>(),
{
formType: 'update',
itemOrProduct: '',
},
);
const isReadOnly = computed(() => props.formType === 'detail');
const loading = ref(false);
const formData = ref<MesMdItemBatchConfigApi.BatchConfig>(buildDefaultData());
function buildDefaultData(): MesMdItemBatchConfigApi.BatchConfig {
return {
itemId: props.itemId,
produceDateFlag: false,
expireDateFlag: false,
receiptDateFlag: false,
vendorFlag: false,
clientFlag: false,
salesOrderCodeFlag: false,
purchaseOrderCodeFlag: false,
workorderFlag: false,
taskFlag: false,
workstationFlag: false,
toolFlag: false,
moldFlag: false,
lotNumberFlag: false,
qualityStatusFlag: false,
};
}
async function loadData() {
loading.value = true;
try {
const data = await getBatchConfigByItemId(props.itemId);
formData.value = { ...buildDefaultData(), ...data };
} finally {
loading.value = false;
}
}
function hasAnySelected() {
return Object.entries(formData.value).some(
([key, value]) => key.endsWith('Flag') && value === true,
);
}
async function handleSave() {
if (!hasAnySelected()) {
ElMessage.warning('至少选择一个批次属性');
return;
}
loading.value = true;
try {
await saveBatchConfig({ ...formData.value, itemId: props.itemId });
ElMessage.success('保存成功');
} finally {
loading.value = false;
}
}
watch(
() => props.itemId,
(value) => {
if (value) {
loadData();
}
},
{ immediate: true },
);
</script>
<template>
<div v-loading="loading">
<div v-if="!isReadOnly" class="mb-3 flex justify-end">
<ElButton type="primary" @click="handleSave"></ElButton>
</div>
<div class="grid grid-cols-5 gap-x-5 gap-y-3">
<ElCheckbox v-model="formData.produceDateFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.qualityStatusFlag" :disabled="isReadOnly"></ElCheckbox>
<template v-if="itemOrProduct === MesItemOrProductEnum.ITEM.value">
<ElCheckbox v-model="formData.vendorFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.purchaseOrderCodeFlag" :disabled="isReadOnly">
采购订单编号
</ElCheckbox>
<ElCheckbox v-model="formData.lotNumberFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.expireDateFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.receiptDateFlag" :disabled="isReadOnly"></ElCheckbox>
</template>
<template v-if="itemOrProduct === MesItemOrProductEnum.PRODUCT.value">
<ElCheckbox v-model="formData.clientFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.salesOrderCodeFlag" :disabled="isReadOnly">
销售订单编号
</ElCheckbox>
<ElCheckbox v-model="formData.workorderFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.taskFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.workstationFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.toolFlag" :disabled="isReadOnly"></ElCheckbox>
<ElCheckbox v-model="formData.moldFlag" :disabled="isReadOnly"></ElCheckbox>
</template>
</div>
</div>
</template>

View File

@ -0,0 +1,249 @@
<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MesMdItemApi } from '#/api/mes/md/item';
import type { MesMdProductBomApi } from '#/api/mes/md/item/productBom';
import { computed, ref, watch } from 'vue';
import { ElButton, ElDialog, ElMessage } from 'element-plus';
import { useVbenForm, z } from '#/adapter/form';
import { TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
createProductBom,
deleteProductBom,
getProductBomListByItemId,
updateProductBom,
} from '#/api/mes/md/item/productBom';
import { $t } from '#/locales';
import { MdItemSelectDialog } from '../components';
import { useProductBomGridColumns } from '../data';
defineOptions({ name: 'MesMdProductBomForm' });
const props = withDefaults(
defineProps<{
formType?: string;
itemId: number;
}>(),
{
formType: 'update',
},
);
const isReadOnly = computed(() => props.formType === 'detail');
const formOpen = ref(false);
const formLoading = ref(false);
const formData = ref<MesMdProductBomApi.ProductBom>();
const list = ref<MesMdProductBomApi.ProductBom[]>([]);
const itemSelectRef = ref<InstanceType<typeof MdItemSelectDialog>>();
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: [
{ fieldName: 'id', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{ fieldName: 'itemId', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{ fieldName: 'bomItemId', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{
fieldName: 'bomItemCode',
label: 'BOM 物料编码',
component: 'Input',
componentProps: { disabled: true },
},
{
fieldName: 'bomItemName',
label: 'BOM 物料名称',
component: 'Input',
componentProps: { disabled: true },
},
{
fieldName: 'bomItemSpecification',
label: '规格型号',
component: 'Input',
componentProps: { disabled: true },
},
{
fieldName: 'unitMeasureName',
label: '单位',
component: 'Input',
componentProps: { disabled: true },
},
{
fieldName: 'quantity',
label: '用量比例',
component: 'InputNumber',
componentProps: {
class: '!w-full',
controlsPosition: 'right',
min: 0,
precision: 4,
step: 0.1,
},
rules: z.number().default(1),
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: { placeholder: '请输入备注', rows: 3 },
},
],
showDefaultActions: false,
});
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions: {
autoResize: true,
border: true,
columns: useProductBomGridColumns(isReadOnly.value),
data: list.value,
minHeight: 240,
pagerConfig: {
enabled: false,
},
rowConfig: {
isHover: true,
keyField: 'id',
},
showOverflow: true,
toolbarConfig: {
enabled: false,
},
} as VxeTableGridOptions<MesMdProductBomApi.ProductBom>,
});
async function getList() {
gridApi.setLoading(true);
try {
list.value = await getProductBomListByItemId(props.itemId);
gridApi.setGridOptions({ data: list.value });
} finally {
gridApi.setLoading(false);
}
}
function handleAdd() {
itemSelectRef.value?.open(undefined, { multiple: true });
}
async function handleItemSelected(rows: MesMdItemApi.Item[]) {
if (rows.length === 0) {
return;
}
for (const item of rows) {
await createProductBom({
bomItemId: item.id,
itemId: props.itemId,
quantity: 1,
});
}
ElMessage.success($t('ui.actionMessage.operationSuccess'));
await getList();
}
async function openForm(row: MesMdProductBomApi.ProductBom) {
formOpen.value = true;
formData.value = row;
await formApi.resetForm();
await formApi.setValues({
...row,
itemId: props.itemId,
});
}
async function submitForm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
formLoading.value = true;
try {
const data = (await formApi.getValues()) as MesMdProductBomApi.ProductBom;
await (formData.value?.id ? updateProductBom(data) : createProductBom(data));
formOpen.value = false;
ElMessage.success($t('ui.actionMessage.operationSuccess'));
await getList();
} finally {
formLoading.value = false;
}
}
async function handleDelete(id: number) {
await deleteProductBom(id);
ElMessage.success($t('ui.actionMessage.deleteSuccess', ['BOM']));
await getList();
}
watch(
() => props.itemId,
(value) => {
if (value) {
getList();
}
},
{ immediate: true },
);
</script>
<template>
<div>
<div v-if="!isReadOnly" class="mb-3 flex items-center justify-start">
<TableAction
:actions="[
{
label: '添加 BOM 物料',
type: 'primary',
onClick: handleAdd,
},
]"
/>
</div>
<Grid class="w-full">
<template #actions="{ row }">
<TableAction
:actions="[
{
label: '编辑',
type: 'primary',
link: true,
onClick: openForm.bind(null, row),
},
{
label: '删除',
type: 'danger',
link: true,
popConfirm: {
title: '确认删除该 BOM 吗?',
confirm: handleDelete.bind(null, row.id!),
},
},
]"
/>
</template>
</Grid>
<ElDialog
v-model="formOpen"
title="编辑 BOM"
width="600px"
>
<Form class="mx-4" />
<template #footer>
<ElButton @click="formOpen = false">取消</ElButton>
<ElButton type="primary" :loading="formLoading" @click="submitForm">
确定
</ElButton>
</template>
</ElDialog>
<MdItemSelectDialog ref="itemSelectRef" @selected="handleItemSelected" />
</div>
</template>

View File

@ -0,0 +1,251 @@
<script lang="ts" setup>
import type { MesMdProductSipApi } from '#/api/mes/md/item/productSip';
import type { MesMdProductSopApi } from '#/api/mes/md/item/productSop';
import { computed, markRaw, ref, watch } from 'vue';
import {
ElButton,
ElCard,
ElDialog,
ElEmpty,
ElImage,
ElMessage,
ElPopconfirm,
} from 'element-plus';
import { useVbenForm, z } from '#/adapter/form';
import {
createProductSip,
deleteProductSip,
getProductSipListByItemId,
updateProductSip,
} from '#/api/mes/md/item/productSip';
import {
createProductSop,
deleteProductSop,
getProductSopListByItemId,
updateProductSop,
} from '#/api/mes/md/item/productSop';
import { ImageUpload } from '#/components/upload';
import { ProProcessSelect } from '#/views/mes/pro/process/components';
type MediaKind = 'SIP' | 'SOP';
type MediaItem =
| MesMdProductSipApi.ProductSip
| MesMdProductSopApi.ProductSop;
const props = withDefaults(
defineProps<{
formType?: string;
itemId: number;
kind: MediaKind;
}>(),
{
formType: 'update',
},
);
const isReadOnly = computed(() => props.formType === 'detail');
const title = computed(() => props.kind);
const loading = ref(false);
const formOpen = ref(false);
const formLoading = ref(false);
const formData = ref<MediaItem>();
const list = ref<MediaItem[]>([]);
const [Form, formApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 100,
},
layout: 'horizontal',
schema: [
{ fieldName: 'id', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{ fieldName: 'itemId', component: 'Input', dependencies: { triggerFields: [''], show: () => false } },
{
fieldName: 'title',
label: '标题',
component: 'Input',
componentProps: { placeholder: '请输入标题' },
rules: 'required',
},
{
fieldName: 'sort',
label: '展示顺序',
component: 'InputNumber',
componentProps: {
class: '!w-full',
controlsPosition: 'right',
min: 0,
precision: 0,
},
rules: z.number().default(0),
},
{
fieldName: 'description',
label: '内容说明',
component: 'Textarea',
componentProps: { placeholder: '请输入详细描述', rows: 3 },
},
{
fieldName: 'processId',
label: '所属工序',
component: markRaw(ProProcessSelect),
},
{
fieldName: 'url',
label: '图片',
component: markRaw(ImageUpload),
componentProps: { maxNumber: 1, showDescription: false },
},
{
fieldName: 'remark',
label: '备注',
component: 'Textarea',
componentProps: { placeholder: '请输入备注', rows: 3 },
},
],
showDefaultActions: false,
});
function getListApi() {
return props.kind === 'SIP'
? getProductSipListByItemId
: getProductSopListByItemId;
}
function createApi() {
return props.kind === 'SIP' ? createProductSip : createProductSop;
}
function updateApi() {
return props.kind === 'SIP' ? updateProductSip : updateProductSop;
}
function deleteApi() {
return props.kind === 'SIP' ? deleteProductSip : deleteProductSop;
}
async function getList() {
loading.value = true;
try {
list.value = await getListApi()(props.itemId);
} finally {
loading.value = false;
}
}
async function openForm(row?: MediaItem) {
formOpen.value = true;
formData.value = row;
await formApi.resetForm();
await formApi.setValues({
itemId: props.itemId,
sort: 0,
...row,
});
}
async function submitForm() {
const { valid } = await formApi.validate();
if (!valid) {
return;
}
formLoading.value = true;
try {
const data = (await formApi.getValues()) as MediaItem;
await (formData.value?.id ? updateApi()(data as any) : createApi()(data as any));
formOpen.value = false;
ElMessage.success('保存成功');
await getList();
} finally {
formLoading.value = false;
}
}
async function handleDelete(id: number) {
await deleteApi()(id);
ElMessage.success('删除成功');
await getList();
}
watch(
() => props.itemId,
(value) => {
if (value) {
getList();
}
},
{ immediate: true },
);
</script>
<template>
<div>
<ElButton
v-if="!isReadOnly"
class="mb-3"
type="primary"
@click="openForm()"
>
添加 {{ title }}
</ElButton>
<div v-loading="loading">
<div v-if="list.length > 0" class="grid grid-cols-4 gap-3">
<ElCard
v-for="item in list"
:key="item.id"
:body-style="{ padding: '0px' }"
shadow="hover"
>
<ElImage
v-if="item.url"
:src="item.url"
class="block h-40 w-full object-cover"
:preview-src-list="[item.url]"
fit="cover"
/>
<div
v-else
class="flex h-40 w-full items-center justify-center bg-gray-100 text-gray-400"
>
暂无图片
</div>
<div class="p-3">
<div class="mb-1 truncate text-sm font-bold">{{ item.title }}</div>
<div v-if="item.description" class="truncate text-xs text-gray-500">
{{ item.description }}
</div>
<div v-if="!isReadOnly" class="mt-2 flex justify-end">
<ElButton link type="primary" size="small" @click="openForm(item)"></ElButton>
<ElPopconfirm title="确认删除该数据吗?" @confirm="handleDelete(item.id!)">
<template #reference>
<ElButton link type="danger" size="small">删除</ElButton>
</template>
</ElPopconfirm>
</div>
</div>
</ElCard>
</div>
<ElEmpty v-else :description="`暂无 ${title} 数据`" />
</div>
<ElDialog
v-model="formOpen"
:title="`${formData?.id ? '编辑' : '新增'} ${title}`"
width="500px"
>
<Form class="mx-4" />
<template #footer>
<ElButton @click="formOpen = false">取消</ElButton>
<ElButton type="primary" :loading="formLoading" @click="submitForm">
确定
</ElButton>
</template>
</ElDialog>
</div>
</template>

View File

@ -0,0 +1,14 @@
<script lang="ts" setup>
import ProductMediaList from './product-media-list.vue';
defineOptions({ name: 'MesMdProductSipForm' });
defineProps<{
formType?: string;
itemId: number;
}>();
</script>
<template>
<ProductMediaList :form-type="formType" :item-id="itemId" kind="SIP" />
</template>

View File

@ -0,0 +1,14 @@
<script lang="ts" setup>
import ProductMediaList from './product-media-list.vue';
defineOptions({ name: 'MesMdProductSopForm' });
defineProps<{
formType?: string;
itemId: number;
}>();
</script>
<template>
<ProductMediaList :form-type="formType" :item-id="itemId" kind="SOP" />
</template>

View File

@ -0,0 +1 @@
export { default as MdUnitMeasureSelect } from './md-unit-measure-select.vue';

View File

@ -0,0 +1,119 @@
<script lang="ts" setup>
import type { MesMdUnitMeasureApi } from '#/api/mes/md/unitmeasure';
import { computed, onMounted, ref, watch } from 'vue';
import { ElOption, ElSelect, ElTag, ElTooltip } from 'element-plus';
import { getUnitMeasureSimpleList } from '#/api/mes/md/unitmeasure';
defineOptions({ name: 'MdUnitMeasureSelect', inheritAttrs: false });
const props = withDefaults(
defineProps<{
clearable?: boolean;
disabled?: boolean;
modelValue?: number;
placeholder?: string;
}>(),
{
clearable: true,
disabled: false,
modelValue: undefined,
placeholder: '请选择计量单位',
},
);
const emit = defineEmits<{
change: [item: MesMdUnitMeasureApi.UnitMeasure | undefined];
'update:modelValue': [value: number | undefined];
}>();
const allList = ref<MesMdUnitMeasureApi.UnitMeasure[]>([]);
const filteredList = ref<MesMdUnitMeasureApi.UnitMeasure[]>([]);
const selectedItem = ref<MesMdUnitMeasureApi.UnitMeasure>();
const selectValue = computed({
get: () => props.modelValue,
set: (value: number | undefined) => {
emit('update:modelValue', value);
},
});
function handleFilter(query: string) {
if (!query) {
filteredList.value = allList.value;
return;
}
const keyword = query.toLowerCase();
filteredList.value = allList.value.filter(
(item) =>
item.name?.toLowerCase().includes(keyword) ||
item.code?.toLowerCase().includes(keyword),
);
}
/** 根据当前值同步 tooltip 展示的计量单位详情 */
function syncSelectedItem(value: number | undefined) {
selectedItem.value =
value === undefined ? undefined : allList.value.find((item) => item.id === value);
}
/** 除 v-model 外,额外抛出完整计量单位对象给业务表单使用 */
function handleChange(value: number | undefined) {
syncSelectedItem(value);
emit('change', selectedItem.value);
}
watch(
() => props.modelValue,
(value) => {
syncSelectedItem(value);
},
);
onMounted(async () => {
allList.value = await getUnitMeasureSimpleList();
filteredList.value = allList.value;
syncSelectedItem(props.modelValue);
});
</script>
<template>
<ElTooltip :disabled="!selectedItem" placement="top" :show-after="500">
<template #content>
<div v-if="selectedItem" class="leading-6">
<div>编码{{ selectedItem.code || '-' }}</div>
<div>名称{{ selectedItem.name || '-' }}</div>
<div>是否主单位{{ selectedItem.primaryFlag ? '是' : '否' }}</div>
<div v-if="!selectedItem.primaryFlag && selectedItem.changeRate != null">
换算比例{{ selectedItem.changeRate }}
</div>
<div v-if="selectedItem.remark">{{ selectedItem.remark }}</div>
</div>
</template>
<ElSelect
v-bind="$attrs"
v-model="selectValue"
:clearable="clearable"
:disabled="disabled"
:filter-method="handleFilter"
:placeholder="placeholder"
class="w-full"
filterable
@change="handleChange"
>
<ElOption
v-for="item in filteredList"
:key="item.id"
:label="item.name"
:value="item.id"
>
<div class="flex items-center gap-2">
<span>{{ item.name }}</span>
<ElTag v-if="item.code" size="small" type="info">: {{ item.code }}</ElTag>
</div>
</ElOption>
</ElSelect>
</ElTooltip>
</template>

View File

@ -0,0 +1 @@
export { default as ProProcessSelect } from './pro-process-select.vue';

View File

@ -0,0 +1,116 @@
<script lang="ts" setup>
import type { MesProProcessApi } from '#/api/mes/pro/process';
import { computed, onMounted, ref, watch } from 'vue';
import { ElOption, ElSelect, ElTag, ElTooltip } from 'element-plus';
import { getProcessSimpleList } from '#/api/mes/pro/process';
defineOptions({ name: 'ProProcessSelect', inheritAttrs: false });
const props = withDefaults(
defineProps<{
clearable?: boolean;
disabled?: boolean;
modelValue?: number;
placeholder?: string;
}>(),
{
clearable: true,
disabled: false,
modelValue: undefined,
placeholder: '请选择工序',
},
);
const emit = defineEmits<{
change: [item: MesProProcessApi.Process | undefined];
'update:modelValue': [value: number | undefined];
}>();
const allList = ref<MesProProcessApi.Process[]>([]);
const filteredList = ref<MesProProcessApi.Process[]>([]);
const selectedItem = ref<MesProProcessApi.Process>();
const selectValue = computed({
get: () => props.modelValue,
set: (value: number | undefined) => {
emit('update:modelValue', value);
},
});
function handleFilter(query: string) {
if (!query) {
filteredList.value = allList.value;
return;
}
const keyword = query.toLowerCase();
filteredList.value = allList.value.filter(
(item) =>
item.name?.toLowerCase().includes(keyword) ||
item.code?.toLowerCase().includes(keyword),
);
}
/** 根据当前值同步 tooltip 展示的工序详情 */
function syncSelectedItem(value: number | undefined) {
selectedItem.value =
value === undefined ? undefined : allList.value.find((item) => item.id === value);
}
/** 除 v-model 外,额外抛出完整工序对象给业务表单使用 */
function handleChange(value: number | undefined) {
syncSelectedItem(value);
emit('change', selectedItem.value);
}
watch(
() => props.modelValue,
(value) => {
syncSelectedItem(value);
},
);
onMounted(async () => {
allList.value = await getProcessSimpleList();
filteredList.value = allList.value;
syncSelectedItem(props.modelValue);
});
</script>
<template>
<ElTooltip :disabled="!selectedItem" placement="top" :show-after="500">
<template #content>
<div v-if="selectedItem" class="leading-6">
<div>编码{{ selectedItem.code || '-' }}</div>
<div>名称{{ selectedItem.name || '-' }}</div>
<div>工艺要求{{ selectedItem.attention || '-' }}</div>
<div>备注{{ selectedItem.remark || '-' }}</div>
</div>
</template>
<ElSelect
v-bind="$attrs"
v-model="selectValue"
:clearable="clearable"
:disabled="disabled"
:filter-method="handleFilter"
:placeholder="placeholder"
class="w-full"
filterable
@change="handleChange"
>
<ElOption
v-for="item in filteredList"
:key="item.id"
:label="item.name"
:value="item.id"
>
<div class="flex items-center gap-2">
<span>{{ item.name }}</span>
<ElTag v-if="item.code" size="small" type="info">{{ item.code }}</ElTag>
</div>
</ElOption>
</ElSelect>
</ElTooltip>
</template>

View File

@ -0,0 +1,175 @@
<script lang="ts" setup>
import type Barcode from './barcode.vue';
import type { MesWmBarcodeApi } from '#/api/mes/wm/barcode';
import { ref } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import {
ElButton,
ElDescriptions,
ElDescriptionsItem,
ElDialog,
ElEmpty,
ElMessage,
ElTooltip,
} from 'element-plus';
import {
createBarcode,
getBarcodeByBusiness,
} from '#/api/mes/wm/barcode';
import { DictTag } from '#/components/dict-tag';
import MesWmBarcode from './barcode.vue';
defineOptions({ name: 'MesWmBarcodeDetail' });
const open = ref(false);
const barcodeRef = ref<InstanceType<typeof Barcode>>();
const barcodeData = ref<Partial<MesWmBarcodeApi.Barcode>>({});
function openModal(row: Partial<MesWmBarcodeApi.Barcode>) {
open.value = true;
barcodeData.value = { ...row };
}
async function openByBusiness(
bizId: number,
bizType: number,
bizCode?: string,
bizName?: string,
) {
open.value = true;
try {
const data = await getBarcodeByBusiness(bizType, bizId);
barcodeData.value = data || { bizCode, bizId, bizName, bizType, content: '' };
if (!data) {
ElMessage.warning('未找到对应条码数据');
}
} catch {
barcodeData.value = { bizCode, bizId, bizName, bizType, content: '' };
ElMessage.error('加载条码数据失败');
}
}
defineExpose({ open: openModal, openByBusiness });
function escapeHtml(value: string) {
return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
}
function handlePrint() {
const base64 = barcodeRef.value?.getImageBase64();
if (!base64) {
ElMessage.warning('条码生成失败,无法打印');
return;
}
const printWindow = window.open('', '_blank');
if (!printWindow) {
ElMessage.error('无法打开打印窗口,请检查浏览器设置');
return;
}
printWindow.document.write(`<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>打印条码</title>
<style>*{margin:0;padding:0}body{font-family:Arial,sans-serif;padding:20px}.print-container{text-align:center}.barcode-img{max-width:100%;margin:20px 0}.info{margin-top:20px;text-align:left;font-size:12px}.info p{margin:5px 0}@media print{body{padding:0}.print-container{padding:20px}}</style>
</head><body><div class="print-container">
<img src="${base64}" class="barcode-img" alt="条码" />
<div class="info">
<p><strong>业务编码:</strong> ${escapeHtml(barcodeData.value.bizCode || '')}</p>
<p><strong>业务名称:</strong> ${escapeHtml(barcodeData.value.bizName || '')}</p>
<p><strong>条码内容:</strong> ${escapeHtml(barcodeData.value.content || '')}</p>
</div></div></body></html>`);
printWindow.document.close();
printWindow.addEventListener('load', () => {
setTimeout(() => printWindow.print(), 500);
});
}
function handleDownload() {
const base64 = barcodeRef.value?.getImageBase64();
if (!base64) {
ElMessage.warning('条码生成失败,无法下载');
return;
}
const link = document.createElement('a');
link.href = base64;
link.download = `barcode_${barcodeData.value.bizCode || 'unknown'}_${Date.now()}.png`;
link.click();
ElMessage.success('下载成功');
}
async function handleGenerate() {
const { bizCode, bizId, bizName, bizType } = barcodeData.value;
if (!bizType || !bizId) {
ElMessage.warning('缺少业务类型或业务编号,无法生成条码');
return;
}
await createBarcode({ bizCode: bizCode || '', bizId, bizName: bizName || '', bizType });
ElMessage.success('条码生成成功');
const data = await getBarcodeByBusiness(bizType, bizId);
if (data) {
barcodeData.value = { ...data };
}
}
</script>
<template>
<ElDialog v-model="open" title="查看条码" width="500px">
<div>
<div class="mb-5 flex min-h-50 items-center justify-center rounded bg-gray-100 p-5">
<div v-if="barcodeData.content" class="flex items-center justify-center">
<MesWmBarcode
ref="barcodeRef"
:content="barcodeData.content"
:format="barcodeData.format"
:height="150"
:width="400"
/>
</div>
<ElEmpty v-else description="暂无条码数据" />
</div>
<ElDescriptions :column="1" border>
<ElDescriptionsItem label="条码格式">
<DictTag
v-if="barcodeData.format"
:type="DICT_TYPE.MES_WM_BARCODE_FORMAT"
:value="barcodeData.format"
/>
</ElDescriptionsItem>
<ElDescriptionsItem label="业务类型">
<DictTag
v-if="barcodeData.bizType"
:type="DICT_TYPE.MES_WM_BARCODE_BIZ_TYPE"
:value="barcodeData.bizType"
/>
</ElDescriptionsItem>
<ElDescriptionsItem label="条码内容">
<ElTooltip :content="barcodeData.content" placement="top">
<span class="inline-block max-w-75 overflow-hidden text-ellipsis whitespace-nowrap">
{{ barcodeData.content }}
</span>
</ElTooltip>
</ElDescriptionsItem>
<ElDescriptionsItem label="业务编码">{{ barcodeData.bizCode || '-' }}</ElDescriptionsItem>
<ElDescriptionsItem label="业务名称">{{ barcodeData.bizName || '-' }}</ElDescriptionsItem>
<ElDescriptionsItem label="状态">
<DictTag
v-if="barcodeData.status !== undefined"
:type="DICT_TYPE.COMMON_STATUS"
:value="barcodeData.status"
/>
</ElDescriptionsItem>
<ElDescriptionsItem label="创建时间">{{ barcodeData.createTime || '-' }}</ElDescriptionsItem>
</ElDescriptions>
</div>
<template #footer>
<ElButton v-if="!barcodeData.content" @click="handleGenerate"></ElButton>
<ElButton type="primary" @click="handlePrint"></ElButton>
<ElButton @click="handleDownload"></ElButton>
<ElButton @click="open = false">关闭</ElButton>
</template>
</ElDialog>
</template>

View File

@ -0,0 +1,54 @@
<script lang="ts" setup>
import type { BarcodeFormat } from '@vben/common-ui';
import { computed, ref } from 'vue';
import {
BarcodeFormatEnum,
Barcode as CommonBarcode,
} from '@vben/common-ui';
defineOptions({ name: 'MesWmBarcode' });
const props = withDefaults(
defineProps<{
content?: string;
displayValue?: boolean;
format?: number;
height?: number;
width?: number;
}>(),
{
content: '',
displayValue: true,
format: BarcodeFormatEnum.QR_CODE,
height: 100,
width: 200,
},
);
const emit = defineEmits<{ done: [value: string] }>();
const barcodeRef = ref<InstanceType<typeof CommonBarcode>>();
const commonFormat = computed<BarcodeFormat>(
() => (props.format || BarcodeFormatEnum.QR_CODE) as BarcodeFormat,
);
function getImageBase64() {
return barcodeRef.value?.getImageBase64() || '';
}
defineExpose({ getImageBase64 });
</script>
<template>
<CommonBarcode
ref="barcodeRef"
:content="content"
:display-value="displayValue"
:format="commonFormat"
:height="height"
:width="width"
@done="emit('done', $event)"
/>
</template>

View File

@ -0,0 +1,3 @@
export { default as BarcodeDetail } from './barcode-detail.vue';
export { default as Barcode } from './barcode.vue';
export { default as PrinterLabel } from './printer-label.vue';

View File

@ -0,0 +1,30 @@
<script lang="ts" setup>
import { ElMessage } from 'element-plus';
defineOptions({ name: 'MesWmPrinterLabel' });
withDefaults(
defineProps<{
bizCode?: string;
bizId?: number;
bizType?: string;
labelText?: string;
}>(),
{
bizCode: undefined,
bizId: undefined,
bizType: undefined,
labelText: '标签打印',
},
);
function handlePrint() {
ElMessage.warning('标签打印功能暂未实现,敬请期待');
}
</script>
<template>
<ElButton link type="primary" @click="handlePrint">
{{ labelText }}
</ElButton>
</template>