feat: 完善商品修改流程与移库语音播报

This commit is contained in:
zm2000 2026-04-17 17:18:35 +08:00
parent a18eb08408
commit 5b7559953d
8 changed files with 1260 additions and 69 deletions

View File

@ -26,13 +26,21 @@
scroll-y="true"
:style="{ height: listHeight + 'rpx' }"
>
<view
v-if="showCreateAction"
class="list-item list-item--create"
@click="handleCreate"
>
<text class="item-text item-text--create">新增“{{ normalizedSearchText }}”</text>
<u-icon name="plus" color="#2979ff" size="22"></u-icon>
</view>
<view class="list-item"
v-for="item in filteredList"
:key="item.value"
:class="{ active: selectedValue === item.value }"
@click="handleSelect(item)"
>
<text class="item-text">{{ item.label }}</text>
<text class="item-text" :style="{ fontSize: itemFontSize + 'rpx' }">{{ item.label }}</text>
<u-icon
v-if="selectedValue === item.value"
name="checkbox-mark"
@ -68,6 +76,33 @@
listHeight: {
type: Number,
default: 600
},
itemFontSize: {
type: Number,
default: 28
},
allowCreate: {
type: Boolean,
default: false
}
},
computed: {
normalizedSearchText() {
return String(this.searchText || '').trim();
},
showCreateAction() {
if (!this.allowCreate || !this.normalizedSearchText) {
return false;
}
return !this.list.some(item => {
if (!item || typeof item !== 'object') {
return false;
}
const label = String(item.label || '').trim().toLowerCase();
return label === this.normalizedSearchText.toLowerCase();
});
}
},
data() {
@ -96,11 +131,41 @@
}
},
methods: {
normalizeInputText(raw) {
if (typeof raw === 'string') {
return raw;
}
if (typeof raw === 'number') {
return String(raw);
}
if (raw && typeof raw === 'object') {
if (typeof raw.detail === 'string') {
return raw.detail;
}
if (raw.detail && typeof raw.detail.value === 'string') {
return raw.detail.value;
}
if (raw.target && typeof raw.target.value === 'string') {
return raw.target.value;
}
if (typeof raw.value === 'string') {
return raw.value;
}
}
return '';
},
handleClose() {
this.$emit('close');
},
handleSearch() {
handleSearch(raw) {
if (typeof raw !== 'undefined') {
const nextText = this.normalizeInputText(raw);
if (nextText !== this.searchText) {
this.searchText = nextText;
}
}
if (!this.searchText.trim()) {
this.filteredList = [...this.list];
return;
@ -126,6 +191,15 @@
this.$emit('change', null);
// 关闭弹窗
this.$emit('close');
},
handleCreate() {
const value = this.normalizedSearchText;
if (!value) {
return;
}
this.$emit('create', value);
this.$emit('close');
}
}
}
@ -223,5 +297,14 @@
border-bottom: none;
}
}
.list-item--create {
background: #f4f8ff;
}
.item-text--create {
color: #2979ff !important;
font-weight: 600;
}
}
</style>

View File

@ -178,6 +178,30 @@ export default {
auth: true,
method: "POST",
isSystemApi: true
},
getProhibitedType: {
path: "stock.warehouse.getProhibitedType",
auth: true,
method: "POST",
isSystemApi: true
},
getStockUnits: {
path: "stock.warehouse.getStockUnits",
auth: true,
method: "POST",
isSystemApi: true
},
checkItemCodeUnique: {
path: "stock.warehouse.checkItemCodeUnique",
auth: true,
method: "POST",
isSystemApi: true
},
saveWarehouseStock: {
path: "stock.warehouse.saveWarehouseStock",
auth: true,
method: "POST",
isSystemApi: true
}
}
},

View File

@ -4,6 +4,7 @@ import {
import {
router
} from '@/core/router'
import voice from './voice'
export default {
normalizeRoutePath(path = '') {
return String(path || '')
@ -140,6 +141,24 @@ export default {
});
},
/**
* 语音播报
* @param {String} text - 播报内容
* @param {Object} options - 播报选项
* @return {Promise<Boolean>}
*/
speakText(text = '', options = {}) {
return voice.speak(text, options);
},
/**
* 停止语音播报
* @return {Boolean}
*/
stopSpeak() {
return voice.stop();
},
/**
* 微信头像
* @param {String} url -图片地址

222
core/utils/voice.js Normal file
View File

@ -0,0 +1,222 @@
class VoiceBroadcastManager {
constructor() {
this.tts = null;
this.initPromise = null;
this.initListener = null;
this.lastText = '';
this.lastSpeakAt = 0;
}
isSupported() {
return typeof plus !== 'undefined' && (!!plus.speech || !!plus.android);
}
hasNativeSpeech() {
return typeof plus !== 'undefined' && !!plus.speech && typeof plus.speech.speak === 'function';
}
async speakByNative(text, options = {}) {
if (!this.hasNativeSpeech()) {
return false;
}
return new Promise(resolve => {
try {
const speechOptions = {
volume: Number(options.volume || 1),
speechRate: Number(options.rate || 1),
pitch: Number(options.pitch || 1)
};
try {
plus.speech.stop();
} catch (error) {
console.warn('[VoiceBroadcast] 停止旧播报失败:', error);
}
plus.speech.speak(
String(text || ''),
() => {
resolve(true);
},
error => {
console.warn('[VoiceBroadcast] 原生语音播报失败:', error);
resolve(false);
},
speechOptions
);
} catch (error) {
console.error('[VoiceBroadcast] 调用原生语音能力异常:', error);
resolve(false);
}
});
}
async ensureReady() {
if (!this.isSupported()) {
return false;
}
if (this.hasNativeSpeech()) {
return true;
}
if (this.tts) {
return true;
}
if (this.initPromise) {
return this.initPromise;
}
this.initPromise = new Promise(resolve => {
try {
const mainActivity = plus.android.runtimeMainActivity();
if (!mainActivity) {
this.initPromise = null;
resolve(false);
return;
}
const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech');
const Locale = plus.android.importClass('java.util.Locale');
const successCode = typeof TextToSpeech.SUCCESS === 'number' ? TextToSpeech.SUCCESS : 0;
this.initListener = plus.android.implements('android.speech.tts.TextToSpeech$OnInitListener', {
onInit: status => {
try {
if (status !== successCode && status !== 0) {
console.warn('[VoiceBroadcast] TTS 初始化失败, status:', status);
resolve(false);
return;
}
if (this.tts && typeof this.tts.setLanguage === 'function') {
const locale = Locale.CHINA || Locale.CHINESE || Locale.SIMPLIFIED_CHINESE || Locale.getDefault();
this.tts.setLanguage(locale);
this.tts.setPitch(1.0);
this.tts.setSpeechRate(1.0);
}
resolve(true);
} catch (error) {
console.error('[VoiceBroadcast] TTS 初始化异常:', error);
resolve(false);
} finally {
this.initPromise = null;
}
}
});
this.tts = new TextToSpeech(mainActivity, this.initListener);
} catch (error) {
console.error('[VoiceBroadcast] 创建 TTS 实例失败:', error);
this.tts = null;
this.initListener = null;
this.initPromise = null;
resolve(false);
}
});
return this.initPromise;
}
async speak(text = '', options = {}) {
const content = String(text || '').trim();
if (!content) {
return false;
}
const now = Date.now();
const minInterval = Number(options.minInterval || 600);
if (!options.force && this.lastText === content && now - this.lastSpeakAt < minInterval) {
return false;
}
if (this.hasNativeSpeech()) {
const nativeResult = await this.speakByNative(content, options);
if (nativeResult) {
this.lastText = content;
this.lastSpeakAt = Date.now();
return true;
}
}
const ready = await this.ensureReady();
if (!ready || !this.tts) {
return false;
}
try {
const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech');
const queueMode = options.flush === false
? (typeof TextToSpeech.QUEUE_ADD === 'number' ? TextToSpeech.QUEUE_ADD : 1)
: (typeof TextToSpeech.QUEUE_FLUSH === 'number' ? TextToSpeech.QUEUE_FLUSH : 0);
const rate = Number(options.rate || 1);
const pitch = Number(options.pitch || 1);
if (typeof this.tts.setSpeechRate === 'function') {
this.tts.setSpeechRate(rate);
}
if (typeof this.tts.setPitch === 'function') {
this.tts.setPitch(pitch);
}
const normalizedContent = content.replace(/\s+/g, ' ');
const utteranceId = `voice_${now}`;
try {
this.tts.speak(normalizedContent, queueMode, null, utteranceId);
} catch (error) {
this.tts.speak(normalizedContent, queueMode, null);
}
this.lastText = content;
this.lastSpeakAt = Date.now();
return true;
} catch (error) {
console.error('[VoiceBroadcast] 语音播报失败:', error);
return false;
}
}
stop() {
if (this.hasNativeSpeech()) {
try {
plus.speech.stop();
return true;
} catch (error) {
console.error('[VoiceBroadcast] 停止原生播报失败:', error);
}
}
if (!this.tts || typeof this.tts.stop !== 'function') {
return false;
}
try {
this.tts.stop();
return true;
} catch (error) {
console.error('[VoiceBroadcast] 停止播报失败:', error);
return false;
}
}
destroy() {
try {
this.stop();
if (this.tts && typeof this.tts.shutdown === 'function') {
this.tts.shutdown();
}
} catch (error) {
console.error('[VoiceBroadcast] 销毁播报器失败:', error);
} finally {
this.tts = null;
this.initPromise = null;
this.initListener = null;
}
}
}
export default new VoiceBroadcastManager();

View File

@ -134,6 +134,13 @@
{
"titleNView": false
}
},
{
"path" : "pages/work/product/edit",
"style" :
{
"titleNView": false
}
}
],

View File

@ -1,7 +1,20 @@
<template>
<view class="goods-detail-page">
<view class="normar_container">
<page-nav :title="title"></page-nav>
<page-nav :title="title">
<template #right>
<u-button
class="nav-edit-btn"
size="mini"
type="info"
text="修改"
:customStyle="{ backgroundColor: '#3c9cff', borderColor: '#3c9cff', color: '#ffffff' }"
@click="openEditPage"
>
<text class="nav-edit-btn__text">修改</text>
</u-button>
</template>
</page-nav>
<view v-if="item" class="detail-fixed-header">
<view class="detail-card detail-card--header">
<view class="detail-header">
@ -77,7 +90,7 @@
<text class="value">{{ getStoreOwnerText(item) }}</text>
</view>
<view class="info-row">
<text class="label">毛重:</text>
<text class="label">毛重(g):</text>
<text class="value">{{ item.gross_weight || '--' }}</text>
</view>
<view class="info-row">
@ -113,16 +126,12 @@
<text class="value">{{ item.stock_unit || '--' }}</text>
</view>
<view class="info-row">
<text class="label">标价:</text>
<text class="value">
<text v-if="item.tag_price !== null && item.tag_price !== undefined && item.tag_price !== ''">¥</text>{{ item.tag_price || '--' }}
</text>
<text class="label">标价(¥):</text>
<text class="value">{{ item.tag_price || '--' }}</text>
</view>
<view class="info-row">
<text class="label">零售价:</text>
<text class="value">
<text v-if="item.retail_price !== null && item.retail_price !== undefined && item.retail_price !== ''">¥</text>{{ item.retail_price || '--' }}
</text>
<text class="label">零售价(¥):</text>
<text class="value">{{ item.retail_price || '--' }}</text>
</view>
<view class="info-row">
<text class="label">ABC分类:</text>
@ -132,6 +141,10 @@
<text class="label">体积:</text>
<text class="value">{{ item.box_volume || '--' }}</text>
</view>
<view class="info-row">
<text class="label">净重(g):</text>
<text class="value">{{ item.net_weight || '--' }}</text>
</view>
<view class="info-row">
<text class="label">创建时间:</text>
<text class="value">{{ item.create_at_display || '--' }}</text>
@ -158,11 +171,29 @@ export default {
return {
title: '商品详情',
item: null,
cacheKey: ''
cacheKey: '',
onProductUpdated: null
};
},
onLoad(options) {
this.cacheKey = (options && options.cacheKey) || '';
this.onProductUpdated = payload => {
const nextItem = payload && payload.item;
if (!nextItem || typeof nextItem !== 'object') {
return;
}
this.item = {
...(this.item || {}),
...nextItem
};
if (this.cacheKey) {
uni.setStorageSync(this.cacheKey, this.item);
}
};
uni.$on('product:detail:updated', this.onProductUpdated);
if (!this.cacheKey) {
return;
}
@ -173,11 +204,31 @@ export default {
}
},
onUnload() {
if (this.onProductUpdated) {
uni.$off('product:detail:updated', this.onProductUpdated);
this.onProductUpdated = null;
}
if (this.cacheKey) {
uni.removeStorageSync(this.cacheKey);
}
},
methods: {
openEditPage() {
if (!this.item || typeof this.item !== 'object') {
uni.showToast({
title: '暂无可修改商品',
icon: 'none'
});
return;
}
const editCacheKey = `product_edit_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
uni.setStorageSync(editCacheKey, this.item);
uni.navigateTo({
url: `/pages/work/product/edit?cacheKey=${editCacheKey}`
});
},
getValueOrDash(value) {
return value === null || value === undefined || value === '' ? '--' : value;
},
@ -296,6 +347,42 @@ export default {
overflow: hidden;
}
::v-deep .nav-title .right {
width: auto;
min-width: 120rpx;
display: flex;
justify-content: flex-end;
align-items: center;
}
::v-deep .nav-edit-btn {
min-width: 132rpx !important;
padding: 0 26rpx !important;
height: 64rpx !important;
line-height: 64rpx !important;
margin-right: 18rpx !important;
border-radius: 12rpx !important;
box-shadow: 0 4rpx 12rpx rgba(60, 156, 255, 0.22);
}
::v-deep .nav-edit-btn .u-button {
background-color: #3c9cff !important;
border-color: #3c9cff !important;
color: #ffffff !important;
border-radius: 12rpx !important;
}
.nav-edit-btn__text {
font-size: 26rpx;
font-weight: 600;
color: #ffffff;
}
::v-deep .nav-edit-btn .u-button__text {
font-size: 26rpx !important;
font-weight: 600 !important;
}
.detail-fixed-header {
flex-shrink: 0;
position: fixed;

698
pages/work/product/edit.vue Normal file
View File

@ -0,0 +1,698 @@
<template>
<view class="product-edit-page">
<view class="normar_container">
<page-nav title="修改商品"></page-nav>
<scroll-view class="edit-content" scroll-y>
<view class="form-card">
<u-form :model="formData" ref="formRef" label-width="170rpx">
<u-form-item label="商品名称" required>
<u-input v-model="formData.item_name" placeholder="请输入商品名称" clearable></u-input>
</u-form-item>
<u-form-item label="商品编码">
<u-input v-model="formData.goods_code" placeholder="请输入商品编码" clearable></u-input>
</u-form-item>
<u-form-item label="品牌">
<u-input v-model="formData.brand_name" placeholder="请输入品牌" clearable></u-input>
</u-form-item>
<u-form-item label="SKU规格">
<u-input v-model="formData.sku_property" placeholder="请输入SKU规格" clearable></u-input>
</u-form-item>
<u-form-item class="prohibited-type-item" label="违禁品类型" label-width="220rpx">
<view class="picker-display" @click="showProhibitedPicker = true">
<view :class="['picker-display__text', !formData.prohibited_type_name ? 'picker-display__placeholder' : '']">
{{ formData.prohibited_type_name || '请选择违禁品类型' }}
</view>
<u-icon name="arrow-right" size="38rpx" color="#c0c4cc"></u-icon>
</view>
</u-form-item>
<u-form-item label="库存单位" required>
<view class="picker-display" @click="showStockUnitPicker = true">
<text :class="['picker-display__text', !formData.stock_unit ? 'picker-display__placeholder' : '']">
{{ formData.stock_unit || '请选择库存单位' }}
</text>
<u-icon name="arrow-right" size="38rpx" color="#c0c4cc"></u-icon>
</view>
</u-form-item>
<u-form-item label="标价(¥)">
<u-input v-model="formData.tag_price" type="digit" placeholder="请输入标价" clearable></u-input>
</u-form-item>
<u-form-item label="零售价(¥)">
<u-input v-model="formData.retail_price" type="digit" placeholder="请输入零售价" clearable></u-input>
</u-form-item>
<u-form-item label="毛重(g)" required>
<u-input v-model="formData.gross_weight" type="digit" placeholder="请输入毛重" clearable></u-input>
</u-form-item>
<u-form-item label="净重(g)">
<u-input v-model="formData.net_weight" type="digit" placeholder="请输入净重" clearable></u-input>
</u-form-item>
</u-form>
</view>
<view class="safe-padding-bottom"></view>
</scroll-view>
<view class="action-bar">
<u-button class="action-btn action-btn--cancel" @click="handleCancel">取消</u-button>
<u-button class="action-btn" type="primary" :loading="saving" @click="handleSave">保存</u-button>
</view>
</view>
<inputAndSelect
title="选择违禁品类型"
:list="prohibitedTypeList"
:show="showProhibitedPicker"
:value="formData.prohibited_type_id"
:itemFontSize="32"
:allowCreate="true"
@change="handleProhibitedTypeChange"
@create="handleProhibitedTypeCreate"
@close="showProhibitedPicker = false"
></inputAndSelect>
<inputAndSelect
title="选择库存单位"
:list="stockUnitList"
:show="showStockUnitPicker"
:value="formData.stock_unit_value"
:itemFontSize="32"
:allowCreate="true"
@change="handleStockUnitChange"
@create="handleStockUnitCreate"
@close="showStockUnitPicker = false"
></inputAndSelect>
</view>
</template>
<script>
export default {
data() {
return {
cacheKey: '',
saving: false,
rawItem: null,
showProhibitedPicker: false,
showStockUnitPicker: false,
prohibitedTypeList: [],
stockUnitList: [],
formData: {
item_name: '',
goods_code: '',
brand_name: '',
sku_property: '',
prohibited_type_id: null,
prohibited_type_name: '',
gross_weight: '',
net_weight: '',
stock_unit_value: '',
stock_unit: '',
tag_price: '',
retail_price: ''
}
};
},
onLoad(options) {
this.cacheKey = (options && options.cacheKey) || '';
this.loadProhibitedTypes();
this.loadStockUnits();
if (!this.cacheKey) {
return;
}
const cached = uni.getStorageSync(this.cacheKey);
if (!cached || typeof cached !== 'object') {
return;
}
this.rawItem = {
...cached
};
this.formData.item_name = String(cached.item_name || cached.product_name || cached.name || '');
this.formData.goods_code = String(cached.goods_code || cached.item_code || '');
this.formData.brand_name = String(cached.brand_name || '');
this.formData.sku_property = String(cached.sku_property || '');
this.formData.prohibited_type_id = this.getProhibitedTypeId(cached);
this.formData.prohibited_type_name = String((cached.prohibited && cached.prohibited.type_name) || '');
this.formData.gross_weight = this.normalizeInputValue(cached.gross_weight);
this.formData.net_weight = this.normalizeInputValue(cached.net_weight);
this.formData.stock_unit = String(cached.stock_unit || '');
this.formData.stock_unit_value = String(cached.stock_unit || '');
this.formData.tag_price = this.normalizeInputValue(cached.tag_price);
this.formData.retail_price = this.normalizeInputValue(cached.retail_price);
},
onUnload() {
if (this.cacheKey) {
uni.removeStorageSync(this.cacheKey);
}
},
methods: {
normalizePositiveId(value) {
const numericValue = Number(value);
if (!Number.isFinite(numericValue)) {
return null;
}
const normalized = Math.trunc(numericValue);
return normalized > 0 ? normalized : null;
},
resolveStoreId(item) {
if (!item || typeof item !== 'object') {
return null;
}
const candidates = [
item.store_id,
item.owner_id,
item.store && item.store.id,
item.store_stock && item.store_stock.store_id
];
for (let i = 0; i < candidates.length; i++) {
const normalized = this.normalizePositiveId(candidates[i]);
if (normalized) {
return normalized;
}
}
return null;
},
resolveWarehouseStockId(item) {
if (!item || typeof item !== 'object') {
return null;
}
const candidates = [
item.id,
item.stock_id,
item.warehouse_stock_id,
item.storage_id
];
for (let i = 0; i < candidates.length; i++) {
const normalized = this.normalizePositiveId(candidates[i]);
if (normalized) {
return normalized;
}
}
return null;
},
buildRefreshQuery(recordId, itemCode, storeId) {
const where = {};
if (recordId) {
where.id = {
operator: 'eq',
value: Number(recordId),
type: 'number'
};
} else {
where.item_code = {
operator: 'eq',
value: String(itemCode || '').trim(),
type: 'string'
};
where.store_id = {
operator: 'eq',
value: Number(storeId),
type: 'number'
};
}
return {
with_stock: true,
pagination: {
page: 1,
pageSize: 1
},
where
};
},
extractFirstListItem(response) {
if (!response || typeof response !== 'object') {
return null;
}
const data = response.data;
if (Array.isArray(data) && data.length > 0) {
return data[0];
}
if (data && typeof data === 'object' && !Array.isArray(data)) {
return data;
}
return null;
},
getProhibitedTypeId(item) {
if (!item || typeof item !== 'object') {
return null;
}
const candidates = [
item.prohibited_type_id,
item.prohibited_id,
item.prohibited && item.prohibited.id,
item.prohibited && item.prohibited.type_id
];
for (let i = 0; i < candidates.length; i++) {
const value = candidates[i];
if (value === null || value === undefined || value === '') {
continue;
}
return value;
}
return null;
},
normalizeProhibitedTypeList(source) {
const list = Array.isArray(source) ? source : [];
return list
.map(item => {
if (!item || typeof item !== 'object') {
return null;
}
const value = item.id || item.type_id || item.value || item.code || item.name || item.type_name;
const label = item.type_name || item.name || item.label || item.title || '';
if (value === null || value === undefined || value === '' || !String(label).trim()) {
return null;
}
return {
value,
label: String(label).trim(),
raw: item
};
})
.filter(Boolean);
},
normalizeStockUnitList(source) {
const list = Array.isArray(source) ? source : [];
return list
.map(item => {
if (item === null || item === undefined) {
return null;
}
if (typeof item === 'string' || typeof item === 'number') {
const text = String(item).trim();
if (!text) {
return null;
}
return {
value: text,
label: text,
raw: item
};
}
if (typeof item !== 'object') {
return null;
}
const value = item.value || item.unit || item.code || item.name || item.label || item.id;
const label = item.label || item.name || item.unit || item.value || item.code;
if (value === null || value === undefined || value === '' || !String(label || '').trim()) {
return null;
}
return {
value: String(value).trim(),
label: String(label).trim(),
raw: item
};
})
.filter(Boolean);
},
async loadProhibitedTypes() {
try {
const res = await this.$http('stock.warehouse.getProhibitedType', {});
if (!res || Number(res.code) !== 200) {
throw new Error((res && res.message) || '违禁品类型获取失败');
}
const dataList = Array.isArray(res.data) ? res.data : [];
this.prohibitedTypeList = this.normalizeProhibitedTypeList(dataList);
} catch (error) {
console.warn('[ProductEdit] 获取违禁品类型失败:', error);
this.prohibitedTypeList = [];
}
},
async loadStockUnits() {
try {
const res = await this.$http('stock.warehouse.getStockUnits', {});
if (!res || Number(res.code) !== 200) {
throw new Error((res && res.message) || '库存单位获取失败');
}
const dataList = Array.isArray(res.data) ? res.data : [];
this.stockUnitList = this.normalizeStockUnitList(dataList);
} catch (error) {
console.warn('[ProductEdit] 获取库存单位失败:', error);
this.stockUnitList = [];
}
},
handleProhibitedTypeChange(option) {
if (!option || typeof option !== 'object') {
this.formData.prohibited_type_id = null;
this.formData.prohibited_type_name = '';
return;
}
this.formData.prohibited_type_id = option.value;
this.formData.prohibited_type_name = String(option.label || '').trim();
},
handleProhibitedTypeCreate(value) {
const text = String(value || '').trim();
if (!text) {
return;
}
if (!this.prohibitedTypeList.some(item => String(item && item.label || '').trim() === text)) {
this.prohibitedTypeList = [
{
value: `custom_prohibited_${Date.now()}`,
label: text,
raw: { type_name: text, is_custom: true }
},
...this.prohibitedTypeList
];
}
this.formData.prohibited_type_id = null;
this.formData.prohibited_type_name = text;
},
handleStockUnitChange(option) {
if (!option || typeof option !== 'object') {
this.formData.stock_unit_value = '';
this.formData.stock_unit = '';
return;
}
this.formData.stock_unit_value = String(option.value || '').trim();
this.formData.stock_unit = String(option.label || option.value || '').trim();
},
handleStockUnitCreate(value) {
const text = String(value || '').trim();
if (!text) {
return;
}
if (!this.stockUnitList.some(item => String(item && item.label || '').trim() === text)) {
this.stockUnitList = [
{
value: text,
label: text,
raw: { unit: text, is_custom: true }
},
...this.stockUnitList
];
}
this.formData.stock_unit_value = text;
this.formData.stock_unit = text;
},
normalizeInputValue(value) {
if (value === null || value === undefined) {
return '';
}
return String(value);
},
handleCancel() {
uni.navigateBack({
delta: 1
});
},
async handleSave() {
if (this.saving) {
return;
}
const itemName = String(this.formData.item_name || '').trim();
if (!itemName) {
uni.showToast({
title: '请输入商品名称',
icon: 'none'
});
return;
}
const itemCode = String(this.formData.goods_code || '').trim();
if (!itemCode) {
uni.showToast({
title: '请输入商品编码',
icon: 'none'
});
return;
}
const grossWeight = String(this.formData.gross_weight || '').trim();
if (!grossWeight) {
uni.showToast({
title: '请输入毛重',
icon: 'none'
});
return;
}
const stockUnit = String(this.formData.stock_unit || '').trim();
if (!stockUnit) {
uni.showToast({
title: '请选择库存单位',
icon: 'none'
});
return;
}
this.saving = true;
try {
const storeId = this.resolveStoreId(this.rawItem || {});
if (!storeId) {
uni.showToast({
title: '未获取到货主ID',
icon: 'none'
});
return;
}
const recordId = this.resolveWarehouseStockId(this.rawItem || {});
const checkPayload = {
item_code: itemCode,
store_id: Number(storeId)
};
if (recordId) {
checkPayload.id = Number(recordId);
}
const checkRes = await this.$http('stock.warehouse.checkItemCodeUnique', checkPayload);
if (!checkRes || Number(checkRes.code) !== 200) {
throw new Error((checkRes && checkRes.message) || '商品编码已存在,请更换');
}
const savePayload = {
store_id: Number(storeId),
item_name: itemName,
item_code: itemCode,
brand_name: String(this.formData.brand_name || '').trim(),
sku_property: String(this.formData.sku_property || '').trim(),
prohibited_type_id: this.formData.prohibited_type_id ? Number(this.formData.prohibited_type_id) : null,
prohibited_type_name: String(this.formData.prohibited_type_name || '').trim(),
gross_weight: grossWeight,
net_weight: String(this.formData.net_weight || '').trim(),
stock_unit: stockUnit,
tag_price: String(this.formData.tag_price || '').trim(),
retail_price: String(this.formData.retail_price || '').trim()
};
if (recordId) {
savePayload.id = Number(recordId);
}
const saveRes = await this.$http('stock.warehouse.saveWarehouseStock', savePayload);
if (!saveRes || Number(saveRes.code) !== 200) {
throw new Error((saveRes && saveRes.message) || '保存失败');
}
let latestItem = null;
try {
const refreshRes = await this.$http(
'stock.warehouse.list',
this.buildRefreshQuery(recordId, itemCode, storeId)
);
if (refreshRes && Number(refreshRes.code) === 200) {
latestItem = this.extractFirstListItem(refreshRes);
}
} catch (refreshError) {
console.warn('[ProductEdit] 刷新商品数据失败:', refreshError);
}
const nextItem = {
...(this.rawItem || {}),
...(latestItem || {}),
id: recordId || (this.rawItem && this.rawItem.id),
store_id: Number(storeId),
item_name: itemName,
product_name: itemName,
name: itemName,
goods_code: itemCode,
item_code: itemCode,
brand_name: String(this.formData.brand_name || '').trim(),
sku_property: String(this.formData.sku_property || '').trim(),
prohibited_type_id: this.formData.prohibited_type_id,
prohibited: {
...((this.rawItem && this.rawItem.prohibited) || {}),
id: this.formData.prohibited_type_id,
type_name: String(this.formData.prohibited_type_name || '').trim()
},
gross_weight: grossWeight,
net_weight: String(this.formData.net_weight || '').trim(),
stock_unit: stockUnit,
tag_price: String(this.formData.tag_price || '').trim(),
retail_price: String(this.formData.retail_price || '').trim()
};
uni.$emit('product:detail:updated', {
item: nextItem,
timestamp: Date.now()
});
uni.setStorageSync('product_query_need_refresh', Date.now());
uni.$emit('product:query:updated', {
item: nextItem,
timestamp: Date.now()
});
uni.showToast({
title: '保存成功',
icon: 'success'
});
setTimeout(() => {
uni.navigateBack({
delta: 1
});
}, 350);
} catch (error) {
uni.showToast({
title: (error && error.message) || '保存失败',
icon: 'none'
});
} finally {
this.saving = false;
}
}
}
};
</script>
<style lang="scss" scoped>
.product-edit-page {
background: #f7f8fa;
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.normar_container {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
}
.edit-content {
flex: 1;
min-height: 0;
}
.form-card {
margin: 20rpx;
padding: 20rpx;
border-radius: 12rpx;
background: #fff;
}
.picker-display {
min-height: 72rpx;
padding: 0 6rpx;
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
min-width: 0;
}
::v-deep .prohibited-type-item .u-form-item__body__right {
flex: 1;
min-width: 0;
overflow: hidden;
}
::v-deep .prohibited-type-item .u-form-item__body {
align-items: center;
}
::v-deep .prohibited-type-item .u-form-item__body__right__content {
width: 100%;
min-width: 0;
overflow: hidden;
}
.picker-display__text {
font-size: 36rpx;
color: #303133;
line-height: 50rpx;
display: block;
max-width: 100%;
height: 50rpx;
padding-right: 16rpx;
flex: 1;
width: 0;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
word-break: normal;
}
::v-deep .prohibited-type-item .u-icon {
flex-shrink: 0;
}
.picker-display__placeholder {
color: #c0c4cc;
}
.safe-padding-bottom {
height: 170rpx;
}
.action-bar {
position: fixed;
left: 0;
right: 0;
bottom: 0;
display: flex;
align-items: center;
gap: 20rpx;
padding: 20rpx;
padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
background: #fff;
box-shadow: 0 -6rpx 20rpx rgba(15, 23, 42, 0.08);
z-index: 99;
}
.action-btn {
flex: 1;
}
.action-btn--cancel {
border: 1rpx solid #d9d9d9;
color: #606266;
background: #fff;
}
</style>

View File

@ -187,6 +187,74 @@
const normalized = Math.trunc(numericValue);
return normalized > 0 ? normalized : null;
},
normalizeSpeechText(message) {
const rawText = String(message || '').trim();
if (!rawText) {
return '';
}
const digitMap = {
'0': '零',
'1': '一',
'2': '二',
'3': '三',
'4': '四',
'5': '五',
'6': '六',
'7': '七',
'8': '八',
'9': '九'
};
const normalizeCodeSegment = (segment) => {
return segment
.split('-')
.map(part => String(part || '')
.split('')
.map(char => (digitMap[char] || char))
.join(''))
.join('的');
};
return rawText.replace(/([A-Za-z0-9]+(?:-[A-Za-z0-9]+)+)/g, normalizeCodeSegment);
},
speakMessage(message, options = {}) {
const text = this.normalizeSpeechText(message);
if (!text) {
return;
}
const tools = this.$tools;
if (!tools || typeof tools.speakText !== 'function') {
return;
}
try {
const task = tools.speakText(text, options);
if (task && typeof task.catch === 'function') {
task.catch(error => {
console.warn('[Relocation] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[Relocation] 语音播报异常:', error);
}
},
showToastMessage(title, icon = 'none', options = {}) {
const message = String(title || '').trim();
if (!message) {
return;
}
uni.showToast({
title: message,
icon
});
if (options.speak !== false) {
this.speakMessage(options.speakText || message, options.voiceOptions || {});
}
},
safeDispatchBroadcast(action, payload) {
try {
const task = this.$store.dispatch(`broadcast/${action}`, payload);
@ -251,10 +319,7 @@
success: (res) => {
const rawCode = this.normalizeUniScanResult(res);
if (!rawCode) {
uni.showToast({
title: '未识别到有效内容',
icon: 'none'
});
this.showToastMessage('未识别到有效内容');
return;
}
@ -266,10 +331,7 @@
return;
}
uni.showToast({
title: '扫码失败,请重试',
icon: 'none'
});
this.showToastMessage('扫码失败,请重试');
}
});
},
@ -325,16 +387,10 @@
return;
}
uni.showToast({
title: '未找到匹配库位',
icon: 'none'
});
this.showToastMessage('未找到匹配库位');
} catch (error) {
console.error('搜索库位失败:', error);
uni.showToast({
title: '库位查询失败',
icon: 'none'
});
this.showToastMessage('库位查询失败');
} finally {
this.loading = false;
}
@ -344,6 +400,12 @@
this.formData[isSource ? 'sourceSpaceId' : 'targetSpaceId'] = item?.id || item?.space_id || null;
this.formData[isSource ? 'sourceSpaceName' : 'targetSpaceName'] = this.getSpaceName(item);
this.formData[isSource ? 'sourceSpaceKeyword' : 'targetSpaceKeyword'] = this.getSpaceCode(item);
if (isSource) {
return;
}
const targetInputText = String(this.formData.targetSpaceKeyword || this.formData.targetSpaceName || '').trim();
this.speakMessage(`已识别移入库位,${targetInputText || this.getSpaceName(item)}`);
},
async searchStock(keyword) {
const rawKeyword = String(keyword || '').trim();
@ -376,16 +438,10 @@
}
this.selectedStock = null;
uni.showToast({
title: '未找到匹配库存',
icon: 'none'
});
this.showToastMessage('未找到匹配库存');
} catch (error) {
console.error('搜索库存失败:', error);
uni.showToast({
title: '库存查询失败',
icon: 'none'
});
this.showToastMessage('库存查询失败');
} finally {
this.loading = false;
}
@ -587,20 +643,29 @@
},
handleMoveQuantityBlur() {
this.formData.moveQuantity = this.normalizeMoveQuantity(this.formData.moveQuantity);
this.validateMoveQuantity(true);
if (!this.validateMoveQuantity(true)) {
return;
}
const quantity = String(this.formData.moveQuantity || '').trim();
if (!quantity) {
return;
}
this.speakMessage(`移库数量,${quantity}`);
},
validateMoveQuantity(showToast = false) {
const quantity = String(this.formData.moveQuantity || '').trim();
if (!quantity) {
if (showToast) {
uni.showToast({ title: '请输入移库数量', icon: 'none' });
this.showToastMessage('请输入移库数量');
}
return false;
}
if (!/^[1-9]\d*$/.test(quantity)) {
if (showToast) {
uni.showToast({ title: '移库数量需为正整数', icon: 'none' });
this.showToastMessage('移库数量需为正整数');
}
return false;
}
@ -608,7 +673,7 @@
const maxQuantity = this.getAvailableStockNumber();
if (maxQuantity > 0 && Number(quantity) > maxQuantity) {
if (showToast) {
uni.showToast({ title: '移库数量不能大于可用库存', icon: 'none' });
this.showToastMessage('移库数量不能大于可用库存');
}
return false;
}
@ -617,47 +682,42 @@
},
handleFillAllQuantity() {
if (!this.selectedStock) {
uni.showToast({
title: '请先选择移库商品',
icon: 'none'
});
this.showToastMessage('请先选择移库商品');
return;
}
const quantity = this.getStockQuantity(this.selectedStock);
if (quantity === '--' || quantity === '' || quantity === null || quantity === undefined) {
uni.showToast({
title: '未获取到可用库存',
icon: 'none'
});
this.showToastMessage('未获取到可用库存');
return;
}
this.formData.moveQuantity = String(quantity);
this.speakMessage(`已填充全部数量,${quantity}`);
},
async handleSubmit() {
if (!this.formData.sourceSpaceKeyword || !this.formData.sourceSpaceName) {
uni.showToast({ title: '请先识别移出库位', icon: 'none' });
this.showToastMessage('请先识别移出库位');
return;
}
if (!this.formData.targetSpaceKeyword || !this.formData.targetSpaceName) {
uni.showToast({ title: '请先识别移入库位', icon: 'none' });
this.showToastMessage('请先识别移入库位');
return;
}
if (!this.selectedStock) {
uni.showToast({ title: '请选择移库商品', icon: 'none' });
this.showToastMessage('请选择移库商品');
return;
}
if (!this.validateMoveQuantity(true)) {
return;
}
if (this.formData.sourceSpaceId && this.formData.targetSpaceId && this.formData.sourceSpaceId === this.formData.targetSpaceId) {
uni.showToast({ title: '移出库位和移入库位不能相同', icon: 'none' });
this.showToastMessage('移出库位和移入库位不能相同');
return;
}
if (!this.formData.targetSpaceId) {
uni.showToast({ title: '请先识别移入库位', icon: 'none' });
this.showToastMessage('请先识别移入库位');
return;
}
@ -670,11 +730,11 @@
const sourceSpaceId = this.normalizePositiveId(this.formData.sourceSpaceId);
const productStockId = this.getProductStockId(this.selectedStock);
if (!sourceSpaceId) {
uni.showToast({ title: '请先识别移出库位', icon: 'none' });
this.showToastMessage('请先识别移出库位');
return;
}
if (!productStockId) {
uni.showToast({ title: '未获取到商品ID', icon: 'none' });
this.showToastMessage('未获取到商品ID');
return;
}
@ -688,7 +748,7 @@
} else {
const storageId = this.getStockStorageId(this.selectedStock);
if (!storageId) {
uni.showToast({ title: '未获取到库存记录ID', icon: 'none' });
this.showToastMessage('未获取到库存记录ID');
return;
}
@ -711,10 +771,7 @@
timestamp: Date.now(),
storageId: storageId ? Number(storageId) : null
});
uni.showToast({
title: res.message || '移库成功',
icon: 'success'
});
this.showToastMessage(res.message || '移库成功', 'success');
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
if (Array.isArray(pages) && pages.length > 1) {
setTimeout(() => {
@ -729,16 +786,10 @@
return;
}
uni.showToast({
title: (res && res.message) || '移库失败',
icon: 'none'
});
this.showToastMessage((res && res.message) || '移库失败');
} catch (error) {
console.error('移库提交失败:', error);
uni.showToast({
title: (error && error.message) || '移库失败',
icon: 'none'
});
this.showToastMessage((error && error.message) || '移库失败');
} finally {
this.submitting = false;
}