Compare commits

...

3 Commits

8 changed files with 687 additions and 82 deletions

View File

@ -43,6 +43,7 @@ export default {
data() {
return {
internalFileList: [],
knownFileIds: [],
// 记录正在上传的文件,用于避免重复上传
uploadingFiles: new Set()
};
@ -58,6 +59,12 @@ export default {
}
},
watch: {
business_id: {
immediate: true,
handler() {
this.knownFileIds = [];
}
},
value: {
immediate: true,
handler(newVal) {
@ -122,6 +129,23 @@ export default {
return file.id || file.fileId || file.file_id || (file.file && (file.file.id || file.file.fileId || file.file.file_id)) || '';
},
normalizeNumericFileIds(fileIds = []) {
return Array.from(new Set((Array.isArray(fileIds) ? fileIds : [fileIds])
.map(fileId => Number(fileId))
.filter(fileId => Number.isFinite(fileId) && fileId > 0)));
},
collectFileIdsFromList(fileList = []) {
if (!Array.isArray(fileList)) {
return [];
}
return this.normalizeNumericFileIds(fileList.map(item => this.getFileId(item)));
},
mergeKnownFileIds(fileIds = []) {
this.knownFileIds = this.normalizeNumericFileIds([...(this.knownFileIds || []), ...fileIds]);
},
replaceKnownFileIds(fileIds = []) {
this.knownFileIds = this.normalizeNumericFileIds(fileIds);
},
extractImageListFromGetImagesResponse(response) {
if (!response || typeof response !== 'object') {
return [];
@ -189,6 +213,27 @@ export default {
return trimmed.split('?')[0].split('#')[0];
},
getFileUrlSignature(url) {
const normalizedUrl = this.normalizeFileUrl(url);
if (!normalizedUrl) {
return '';
}
const withoutProtocol = normalizedUrl.replace(/^https?:\/\//i, '');
const pathWithHost = withoutProtocol.split('/');
if (pathWithHost.length <= 1) {
return withoutProtocol.toLowerCase();
}
const pathOnly = '/' + pathWithHost.slice(1).join('/');
const pathParts = pathOnly.split('/').filter(Boolean);
if (!pathParts.length) {
return pathOnly.toLowerCase();
}
const tail = pathParts.slice(-2).join('/').toLowerCase();
return tail || pathOnly.toLowerCase();
},
getRemoteFileUrl(file) {
if (!file || typeof file !== 'object') {
return '';
@ -218,12 +263,15 @@ export default {
business_type: this.business_type
});
return this.extractImageListFromGetImagesResponse(response)
const entries = this.extractImageListFromGetImagesResponse(response)
.map(item => ({
fileId: this.getRemoteFileId(item),
url: this.getRemoteFileUrl(item)
}))
.filter(item => item.fileId || item.url);
this.mergeKnownFileIds(entries.map(item => item.fileId));
return entries;
},
async getRemoteFileIds() {
if (!this.business_id) {
@ -241,7 +289,9 @@ export default {
return [];
}
},
async resolveDeletedFileIds(deletedFile) {
async resolveDeletedFileIds(deletedFile, options = {}) {
const deletedIndex = Number(options.deletedIndex);
const hasValidDeletedIndex = Number.isFinite(deletedIndex) && deletedIndex >= 0;
const deletedIds = [];
const directId = this.getFileId(deletedFile);
if (directId) {
@ -255,15 +305,28 @@ export default {
const deletedUrl = this.normalizeFileUrl(
(deletedFile && (deletedFile.url || deletedFile.path || deletedFile.successUrl)) || ''
);
const deletedUrlSignature = this.getFileUrlSignature(deletedUrl);
if (!deletedUrl) {
return [];
if (!hasValidDeletedIndex) {
return [];
}
}
try {
const remoteEntries = await this.getRemoteImageEntries();
const matched = remoteEntries
let matched = remoteEntries
.filter(item => item.fileId && item.url && item.url === deletedUrl)
.map(item => item.fileId);
if (!matched.length && deletedUrlSignature) {
matched = remoteEntries
.filter(item => item.fileId && this.getFileUrlSignature(item.url) === deletedUrlSignature)
.map(item => item.fileId);
}
if (!matched.length && hasValidDeletedIndex && remoteEntries[deletedIndex] && remoteEntries[deletedIndex].fileId) {
matched = [remoteEntries[deletedIndex].fileId];
}
return Array.from(new Set(matched));
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
@ -298,6 +361,11 @@ export default {
id: this.getFileId(item)
};
});
const listFileIds = this.collectFileIdsFromList(this.internalFileList);
if (listFileIds.length > 0) {
this.mergeKnownFileIds(listFileIds);
}
},
/**
@ -414,7 +482,9 @@ export default {
id: configData.fileId,
successUrl: configData.fileUrl // 保存成功后的URL
};
await this.referenceFiles();
await this.referenceFiles({
source: 'upload'
});
return ;
}
// 4. 执行COS上传(这里不会返回响应数据)
@ -436,7 +506,9 @@ export default {
};
// 7. 关联文件
await this.referenceFiles();
await this.referenceFiles({
source: 'upload'
});
// 触发成功事件
this.$emit('upload-success', {
file: this.fileList[fileIndex],
@ -528,28 +600,118 @@ export default {
* 关联文件
*/
async referenceFiles(options = {}) {
const { mergeRemote = true, excludedFileIds = [] } = options;
const { mergeRemote = true, excludedFileIds = [], excludedFileUrls = [], source = '', explicitFileIds = null } = options;
console.log("this.fileList",this.fileList);
try {
// 获取所有成功的文件(包括之前已经关联的)
const localFileIds = this.fileList
.filter(item => item.status === "success" && this.getFileId(item))
.map(item => this.getFileId(item));
const explicitIds = Array.isArray(explicitFileIds)
? explicitFileIds
.map(fileId => Number(fileId))
.filter(fileId => Number.isFinite(fileId) && fileId > 0)
: null;
const remoteFileIds = mergeRemote ? await this.getRemoteFileIds() : [];
if (explicitIds) {
const validFiles = Array.from(new Set(explicitIds)).map(fileId => ({ file_id: fileId }));
if (process.env.NODE_ENV !== 'production') {
console.log('[UploadImgCos] ReferenceFile payload debug', {
source,
business_id: this.business_id,
type: this.business_type,
explicit_file_ids: validFiles.map(item => item.file_id)
});
}
const requestPayload = {
id: this.business_id,
type: this.business_type,
images: validFiles
};
console.log('[UploadImgCos] ReferenceFile request', {
source,
payload: requestPayload
});
const response = await this.$http('common.ReferenceFile', requestPayload);
console.log('[UploadImgCos] ReferenceFile response', {
source,
response
});
this.replaceKnownFileIds(validFiles.map(item => item.file_id));
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
return response;
}
// 获取当前本地成功文件(以本地列表为准)
const localEntries = this.fileList
.filter(item => {
const status = String((item && item.status) || '').toLowerCase();
if (!status) {
return true;
}
return status !== 'uploading' && status !== 'pending' && status !== 'error';
})
.map(item => ({
fileId: this.getFileId(item),
url: this.normalizeFileUrl(item.url || item.path || item.successUrl || '')
}));
const remoteEntries = mergeRemote ? await this.getRemoteImageEntries() : [];
const remoteFileIds = (remoteEntries || []).map(item => item.fileId).filter(Boolean);
const localFileIds = (localEntries || []).map(item => item.fileId).filter(Boolean);
const knownFileIds = this.normalizeNumericFileIds(this.knownFileIds || []);
const excludedSet = new Set(
(Array.isArray(excludedFileIds) ? excludedFileIds : [excludedFileIds]).filter(Boolean)
(Array.isArray(excludedFileIds) ? excludedFileIds : [excludedFileIds])
.filter(Boolean)
.map(fileId => String(fileId))
);
const mergedFileIds = Array.from(new Set([...(remoteFileIds || []), ...(localFileIds || [])]))
.filter(fileId => !excludedSet.has(fileId));
const excludedUrlSet = new Set(
(Array.isArray(excludedFileUrls) ? excludedFileUrls : [excludedFileUrls])
.map(url => this.normalizeFileUrl(url))
.filter(Boolean)
);
// 优先使用本地已有file_id;若本地项缺失file_id,则按URL从远端补全
const localUrlSet = new Set(
localEntries
.map(item => this.normalizeFileUrl(item.url || ''))
.filter(Boolean)
);
const recoveredFileIds = mergeRemote
? (remoteEntries || [])
.filter(item => {
const normalizedUrl = this.normalizeFileUrl(item && item.url ? item.url : '');
return normalizedUrl && localUrlSet.has(normalizedUrl);
})
.map(item => item.fileId)
.filter(Boolean)
: [];
const shouldKeepAllRemoteIds = mergeRemote && source !== 'delete';
const candidateFileIds = shouldKeepAllRemoteIds
? [...knownFileIds, ...(remoteFileIds || []), ...(localFileIds || [])]
: [...knownFileIds, ...(localFileIds || []), ...(recoveredFileIds || [])];
const mergedFileIds = Array.from(new Set(candidateFileIds
.map(fileId => String(fileId))
.filter(Boolean)))
.filter(fileId => !excludedSet.has(fileId))
.map(fileId => Number(fileId))
.filter(fileId => Number.isFinite(fileId) && fileId > 0);
const validFiles = mergedFileIds.map(fileId => ({ file_id: fileId }));
if (process.env.NODE_ENV !== 'production') {
console.log('[UploadImgCos] ReferenceFile payload debug', {
source,
business_id: this.business_id,
type: this.business_type,
merge_remote: mergeRemote,
excluded_file_ids: Array.from(excludedSet),
excluded_file_urls: Array.from(excludedUrlSet),
remote_file_ids: remoteFileIds,
local_file_ids: localFileIds,
file_ids: validFiles.map(item => item.file_id),
@ -564,24 +726,50 @@ export default {
if (validFiles.length === 0) {
// 如果没有成功文件,也要通知后端清空关联
const response = await this.$http('common.ReferenceFile', {
const requestPayload = {
id: this.business_id,
type: this.business_type,
images: []
};
console.log('[UploadImgCos] ReferenceFile request', {
source,
payload: requestPayload
});
const response = await this.$http('common.ReferenceFile', requestPayload);
console.log('[UploadImgCos] ReferenceFile response', {
source,
response
});
this.replaceKnownFileIds([]);
// 更新外部绑定
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
return response;
}
const response = await this.$http('common.ReferenceFile', {
const requestPayload = {
id: this.business_id,
type: this.business_type,
images: validFiles
};
console.log('[UploadImgCos] ReferenceFile request', {
source,
payload: requestPayload
});
const response = await this.$http('common.ReferenceFile', requestPayload);
console.log('[UploadImgCos] ReferenceFile response', {
source,
response
});
this.replaceKnownFileIds(validFiles.map(item => item.file_id));
// 更新外部绑定
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
@ -604,6 +792,9 @@ export default {
}
const deletedFile = this.fileList[index];
const deletedFileUrl = this.normalizeFileUrl(
(deletedFile && (deletedFile.url || deletedFile.path || deletedFile.successUrl)) || ''
);
// 从列表中移除
this.fileList.splice(index, 1);
@ -618,16 +809,59 @@ export default {
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
// 异步更新文件关联:合并远端+本地,仅排除当前删除项,避免误删其他图片
// 异步更新文件关联:删除场景显式提交“剩余file_id”,避免误清空
try {
const deletedFileIds = await this.resolveDeletedFileIds(deletedFile);
const remoteEntries = await this.getRemoteImageEntries();
const deletedFileIds = await this.resolveDeletedFileIds(deletedFile, {
deletedIndex: index
});
const deletedIdSet = new Set((deletedFileIds || []).map(fileId => String(fileId)).filter(Boolean));
const deletedDirectId = String(this.getFileId(deletedFile) || '').trim();
if (deletedDirectId) {
deletedIdSet.add(deletedDirectId);
}
const remoteAllIds = this.normalizeNumericFileIds((remoteEntries || []).map(item => item && item.fileId));
const knownAllIds = this.normalizeNumericFileIds(this.knownFileIds || []);
let finalFileIds = remoteAllIds.length > 0
? remoteAllIds.filter(fileId => !deletedIdSet.has(String(fileId)))
: knownAllIds.filter(fileId => !deletedIdSet.has(String(fileId)));
if (this.fileList.length > 0 && finalFileIds.length === 0) {
console.warn('[UploadImgCos] 删除后未能可靠计算剩余file_id,已阻止空关联提交', {
deleted_file_ids: deletedFileIds,
deleted_file_url: deletedFileUrl,
remote_entries_count: Array.isArray(remoteEntries) ? remoteEntries.length : 0,
remote_all_ids: remoteAllIds,
known_all_ids: knownAllIds,
known_file_ids_count: Array.isArray(this.knownFileIds) ? this.knownFileIds.length : 0
});
// 回滚UI,避免前端显示与后端实际不一致
this.fileList.splice(index, 0, deletedFile);
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
uni.showToast({
title: '删除失败,请重试',
icon: 'none'
});
return;
}
this.replaceKnownFileIds(finalFileIds);
await this.referenceFiles({
mergeRemote: true,
excludedFileIds: deletedFileIds
explicitFileIds: finalFileIds,
source: 'delete'
});
} catch (error) {
console.error("删除后重新关联失败:", error);
// 这里可以选择给用户提示,但不阻塞UI
this.fileList.splice(index, 0, deletedFile);
this.$emit('change', this.fileList);
this.$emit('input', this.fileList);
uni.showToast({
title: '删除失败,请重试',
icon: 'none'
});
}
},
@ -653,6 +887,7 @@ export default {
*/
clearFiles() {
this.fileList = [];
this.replaceKnownFileIds([]);
this.$emit('input', []);
this.$emit('change', []);
}

View File

@ -680,6 +680,19 @@
title: '已移出常用功能',
icon: 'success'
});
const tools = this.$tools;
if (tools && typeof tools.speakText === 'function') {
try {
const task = tools.speakText('已移出常用功能');
if (task && typeof task.catch === 'function') {
task.catch(error => {
console.warn('[HomeIndex] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[HomeIndex] 语音播报异常:', error);
}
}
},
handleWrapperTouchStart(event) {
if (this.dragState.active) {

View File

@ -910,10 +910,24 @@ export default {
}
}
await this.$http('common.ReferenceFile', {
const requestPayload = {
id: Number(businessId),
type: 'stock',
images: targetFileIds.map(fileId => ({ file_id: fileId }))
};
console.log('[ProductEdit] ReferenceFile request', {
source: 'cancel-or-back',
trigger: this.canceling ? 'cancel' : 'back',
payload: requestPayload
});
const response = await this.$http('common.ReferenceFile', requestPayload);
console.log('[ProductEdit] ReferenceFile response', {
source: 'cancel-or-back',
trigger: this.canceling ? 'cancel' : 'back',
response
});
this.formData.images = snapshot;

View File

@ -167,6 +167,28 @@
this.$store.dispatch('broadcast/stop');
},
methods: {
speakMessage(message, options = {}) {
const text = String(message || '').trim();
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('[ReceivingDetail-DetailContainer] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[ReceivingDetail-DetailContainer] 语音播报异常:', error);
}
},
// === 事件处理方法 ===
truncateText(text, length = 20) {
if (!text) return '';
@ -326,6 +348,7 @@
if(this.isSpaceInput){
this.$emit('searchSpace', data.data);
}else{
this.speakMessage('商品条码扫描成功');
this.$emit('tryGetStock', data.data);
}
},

View File

@ -13,7 +13,7 @@
<view
v-if="canBindStore"
class="store-bind-trigger"
@click="showStorePicker = true"
@click="openStorePicker"
>
<text class="store-bind-text">{{ pendingStoreName || '请选择货主绑定' }}</text>
<view class="store-bind-action">
@ -204,6 +204,31 @@
}
},
methods: {
speakMessage(message, options = {}) {
const text = String(message || '').trim();
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('[ReceivingDetail-InfoContainer] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[ReceivingDetail-InfoContainer] 语音播报异常:', error);
}
},
openStorePicker() {
this.showStorePicker = true;
},
async loadStoreList() {
try {
const res = await this.$http('common.store', {});
@ -221,6 +246,8 @@
return;
}
this.speakMessage('请确认货主绑定');
uni.showModal({
title: '货主绑定',
content: `是否将当前收货单绑定到货主【${option.label}】?绑定后不可更改。`,
@ -253,6 +280,7 @@
if (res && res.code === 200) {
this.pendingStoreId = option.value;
this.pendingStoreName = option.label;
this.speakMessage('绑定成功');
uni.showToast({
title: '绑定成功',
icon: 'success'

View File

@ -123,7 +123,7 @@
</u-form-item>
<u-form-item label="创建时间" borderBottom>
<view class="date-range" @click="showSelectDate = true">
<view class="date-range" @click="openDateFilter">
<text>{{where.startDate}} - {{where.endDate}}</text>
</view>
</u-form-item>
@ -205,6 +205,8 @@
loading: false,
storeId:null,
refreshing: false,
pageChangeSilentVoice: true,
nextListVoiceDelay: 0,
pageSize: 20,
currentPage: 1,
totalItems: 0,
@ -281,8 +283,13 @@
watch: {
currentPage(newval) {
console.log('页码变化:', newval);
const silentVoice = this.pageChangeSilentVoice;
const voiceDelay = Number(this.nextListVoiceDelay || 0);
this.pageChangeSilentVoice = true;
this.nextListVoiceDelay = 0;
this.loadReceivingList({
silentVoice: false
silentVoice,
voiceDelay
});
}
},
@ -531,6 +538,7 @@
// 加载收货列表
async loadReceivingList(options = {}) {
const silentVoice = !!(options && options.silentVoice);
const voiceDelay = Number((options && options.voiceDelay) || 0);
if (this.loading) return;
this.loading = true;
@ -597,9 +605,7 @@
this.updateStatusCount(summary);
}
if (!silentVoice) {
this.speakReceivingMessage(this.getReceivingListVoiceText());
}
}
} catch (error) {
console.error('加载收货列表失败:', error);
@ -608,7 +614,13 @@
icon: 'error'
});
if (!silentVoice) {
this.speakReceivingMessage('加载收货列表失败,请重试');
if (voiceDelay > 0) {
setTimeout(() => {
this.speakReceivingMessage('加载收货列表失败,请重试');
}, voiceDelay);
} else {
this.speakReceivingMessage('加载收货列表失败,请重试');
}
}
} finally {
this.loading = false;
@ -651,6 +663,7 @@
// 搜索处理
handleSearch() {
if (this.currentPage !== 1) {
this.pageChangeSilentVoice = false;
this.currentPage = 1;
return;
}
@ -663,6 +676,7 @@
changeStatus(status) {
this.activeStatus = status;
if (this.currentPage !== 1) {
this.pageChangeSilentVoice = false;
this.currentPage = 1;
return;
}
@ -675,6 +689,7 @@
onRefresh() {
this.refreshing = true;
if (this.currentPage !== 1) {
this.pageChangeSilentVoice = false;
this.currentPage = 1;
return;
}
@ -687,6 +702,9 @@
showFilterPopup() {
this.filterVisible = true;
},
openDateFilter() {
this.showSelectDate = true;
},
// 重置筛选
resetFilter() {
@ -704,12 +722,15 @@
// 应用筛选
applyFilter() {
this.filterVisible = false;
this.nextListVoiceDelay = 700;
if (this.currentPage !== 1) {
this.pageChangeSilentVoice = false;
this.currentPage = 1;
return;
}
this.loadReceivingList({
silentVoice: false
silentVoice: false,
voiceDelay: 700
});
},
@ -765,6 +786,7 @@
},
handlePageChange(page) {
this.pageChangeSilentVoice = true;
this.currentPage = page;
}
}

View File

@ -9,7 +9,7 @@
<view class="section-title">基础信息</view>
<!-- 店铺信息 -->
<u-form-item label="货主" @click="showStorePicker = true">
<u-form-item label="货主" @click="openStorePicker">
<view class="store-select-display">
<text :class="['store-select-text', !formData.store_id ? 'store-select-placeholder' : '']">{{ storeName || '请选择货主' }}</text>
<u-icon name="arrow-right" size="24rpx" color="#c0c4cc"></u-icon>
@ -194,6 +194,111 @@
},
methods: {
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('[ReceivingCreate] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[ReceivingCreate] 语音播报异常:', error);
}
},
stopSpeak() {
const tools = this.$tools;
if (!tools || typeof tools.stopSpeak !== 'function') {
return;
}
try {
tools.stopSpeak();
} catch (error) {
console.warn('[ReceivingCreate] 停止语音播报异常:', 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 || {});
}
},
extractErrorMessage(error, fallback = '操作失败') {
if (!error) {
return fallback;
}
if (typeof error === 'string') {
return error;
}
if (typeof error.message === 'string' && error.message.trim()) {
return error.message.trim();
}
if (Array.isArray(error) && error.length) {
const firstError = error[0];
if (typeof firstError === 'string') {
return firstError;
}
if (firstError && typeof firstError.message === 'string') {
return firstError.message;
}
}
return fallback;
},
getPlatformInfo() {
const systemInfo = typeof uni.getSystemInfoSync === 'function' ? uni.getSystemInfoSync() : {};
return {
@ -385,9 +490,8 @@
}
this.formData.license_plate = licensePlate;
uni.showToast({
title: '识别成功',
icon: 'success'
this.showToastMessage('识别成功', 'success', {
speakText: `识别成功,车牌:${licensePlate}`
});
} catch (error) {
const errMsg = String(error?.errMsg || error?.message || error || '').toLowerCase();
@ -395,10 +499,7 @@
return;
}
uni.showToast({
title: (error && error.message) || '车牌识别失败',
icon: 'none'
});
this.showToastMessage((error && error.message) || '车牌识别失败');
} finally {
this.recognizingPlate = false;
uni.hideLoading();
@ -440,14 +541,12 @@
success: (res) => {
const rawCode = this.normalizeUniScanResult(res);
if (!rawCode) {
uni.showToast({
title: '未识别到有效内容',
icon: 'none'
});
this.showToastMessage('未识别到有效内容');
return;
}
this.formData.tracking_number = rawCode;
this.speakMessage('扫描成功');
},
fail: (error) => {
const errMsg = String(error?.errMsg || '').toLowerCase();
@ -455,10 +554,7 @@
return;
}
uni.showToast({
title: '扫码失败,请重试',
icon: 'none'
});
this.showToastMessage('扫码失败,请重试');
}
});
},
@ -499,11 +595,7 @@
this.formData.video_device_id = deviceCode;
// 可选:给用户一个提示
uni.showToast({
title: `已扫描录像设备: ${deviceCode}`,
icon: 'success',
duration: 2000
});
this.showToastMessage(`已扫描录像设备: ${deviceCode}`, 'success');
}
// 如果没有提取到设备编号,也直接忽略,不提示用户
return;
@ -511,6 +603,7 @@
if (this.formData.delivery_method === 'express') {
this.formData.tracking_number = scanText;
this.speakMessage('扫描成功');
}
}
},
@ -526,10 +619,7 @@
const result = await this.$http("storage.receiving.create",submitData);
if(result.code==200){
uni.showToast({
title: '创建成功',
icon: 'success'
});
this.showToastMessage('创建成功', 'success');
}else{
throw new Error("创建失败"+result.message);
@ -541,16 +631,14 @@
}, 1500);
} catch (error) {
uni.showToast({
title: '创建失败'+error,
icon: 'error'
});
this.showToastMessage(this.extractErrorMessage(error, '创建失败'));
} finally {
this.submitting = false;
}
},
handleReset() {
this.speakMessage('请确认重置表单');
uni.showModal({
title: '确认重置',
content: '确定要重置所有表单数据吗?',
@ -559,11 +647,20 @@
this.$refs.formRef.resetFields();
this.storeName = "不设置";
this.formData.store_id = null;
this.showToastMessage('已重置表单');
} else {
this.showToastMessage('已取消', 'none', {
speak: false
});
}
}
});
},
openStorePicker() {
this.showStorePicker = true;
},
handleStoreChange(option) {
if (!option) {
this.storeName = "不设置";
@ -588,9 +685,11 @@
},
onHide() {
this.$store.dispatch('broadcast/pause');
this.stopSpeak();
},
onUnload() {
this.$store.dispatch('broadcast/stop');
this.stopSpeak();
}
};
</script>

View File

@ -151,6 +151,87 @@
},
methods: {
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('[ReceivingDetail] 语音播报失败:', error);
});
}
} catch (error) {
console.warn('[ReceivingDetail] 语音播报异常:', error);
}
},
stopSpeak() {
const tools = this.$tools;
if (!tools || typeof tools.stopSpeak !== 'function') {
return;
}
try {
tools.stopSpeak();
} catch (error) {
console.warn('[ReceivingDetail] 停止语音播报异常:', error);
}
},
showToastMessage(title, icon = 'none', options = {}) {
const message = String(title || '').trim();
if (!message) {
return;
}
uni.showToast({
title: message,
icon,
duration: options.duration || 1500
});
if (options.speak !== false) {
this.speakMessage(options.speakText || message, options.voiceOptions || {});
}
},
getTodayStartTimestamp() {
const today = new Date();
today.setHours(0, 0, 0, 0);
@ -222,6 +303,41 @@
return invalidDetail || null;
},
validateReceivingBaseFields() {
const detailList = this.details || [];
// 1) 先校验商品名称
const invalidNameDetail = detailList.find(detail => !String(detail?.product_name || '').trim());
if (invalidNameDetail) {
return {
detail: invalidNameDetail,
message: `${invalidNameDetail.product_name || '当前商品'}缺少商品名称`
};
}
// 2) 再校验实际数量是否为空
const invalidEmptyQtyDetail = detailList.find(detail => !String(detail?.actual_quantity ?? '').trim());
if (invalidEmptyQtyDetail) {
return {
detail: invalidEmptyQtyDetail,
message: `${invalidEmptyQtyDetail.product_name || '当前商品'}缺少实际数量`
};
}
// 3) 最后校验实际数量是否大于0
const invalidQtyValueDetail = detailList.find(detail => {
const quantityValue = Number(String(detail?.actual_quantity ?? '').trim());
return !Number.isFinite(quantityValue) || quantityValue <= 0;
});
if (invalidQtyValueDetail) {
return {
detail: invalidQtyValueDetail,
message: `${invalidQtyValueDetail.product_name || '当前商品'}实际数量需大于0`
};
}
return null;
},
// 初始化数据
async initData() {
await this.loadReceivingInfo();
@ -274,14 +390,15 @@
try {
// 货主确认逻辑
if (this.receivingInfo.store_id == null && data.system_product_id) {
this.speakMessage('请确认货主');
const confirm = await this.confirmStoreOwner();
if (!confirm) {
uni.showToast({
title: '已取消',
icon: 'none'
this.showToastMessage('已取消', 'none', {
speak: false
});
return;
}
this.speakMessage('已确认');
}
// 调用API更新
@ -362,6 +479,8 @@
return;
}
this.speakMessage('请确认删除');
uni.showModal({
title: '确认删除',
content: `确定要删除商品"${detailToDelete.product_name}"吗?`,
@ -374,9 +493,8 @@
});
if (result.code === 200) {
uni.showToast({
title: '删除成功',
icon: 'success'
this.showToastMessage('删除成功', 'success', {
speakText: '删除成功'
});
// 删除后统一以服务端最新数据重建列表与选中态,避免残留旧引用
@ -411,6 +529,10 @@
icon: 'error'
});
}
} else {
this.showToastMessage('已取消', 'none', {
speak: false
});
}
}
});
@ -423,9 +545,8 @@
});
if (result.code === 200) {
uni.showToast({
title: '添加成功',
icon: 'success'
this.showToastMessage('添加成功', 'success', {
speak: false
});
if (result.data.selectId) {
@ -516,6 +637,20 @@
},
async completeReceiving() {
this.showComplete = false;
const baseValidation = this.validateReceivingBaseFields();
if (baseValidation) {
this.currentTab = 1;
this.selectedDetail = baseValidation.detail;
const message = baseValidation.message || '商品信息不完整';
this.speakMessage(message);
uni.showModal({
title: '商品信息不完整',
content: message,
showCancel: false
});
return;
}
const shelfLifeValidation = this.validateShelfLifeRequiredFields();
if (shelfLifeValidation) {
this.currentTab = 1;
@ -539,6 +674,34 @@
return;
}
try {
const tools = this.$tools;
if (tools && typeof tools.speakText === 'function') {
try {
const speakTask = tools.speakText('请确认完成收货', {
force: true,
minInterval: 0
});
if (speakTask && typeof speakTask.catch === 'function') {
speakTask.catch(error => {
console.warn('[ReceivingDetail] 完成收货前语音播报失败:', error);
});
}
} catch (error) {
console.warn('[ReceivingDetail] 完成收货前语音播报失败:', error);
}
} else {
this.speakMessage('请确认完成收货', {
force: true,
minInterval: 0
});
}
uni.showToast({
title: '请确认完成收货',
icon: 'none',
duration: 800
});
await new Promise(resolve => setTimeout(resolve, 900));
// 1. 显示确认弹窗
const confirmResult = await uni.showModal({
title: '完成收货',
@ -553,6 +716,9 @@
// 修正:直接使用confirmResult.confirm
if (!confirmResult[1].confirm) {
this.showToastMessage('已取消', 'none', {
speak: false
});
return;
}
@ -576,11 +742,7 @@
// 根据你的后端响应结构调整
if (res.code === 200 || res.success) {
// 成功提示
uni.showToast({
title: '收货完成成功',
icon: 'success',
duration: 1500
});
this.showToastMessage('收货完成成功', 'success');
// 延迟跳转
setTimeout(() => {
@ -628,15 +790,14 @@
uni.hideLoading();
console.error('完成收货失败:', error);
this.currentTab = 1;
uni.showToast({
title: error.message || '操作失败,请稍后重试',
icon: 'none',
duration: 3000
this.showToastMessage(error.message || '操作失败,请稍后重试', 'none', {
duration: 3000
});
}
},
async cancel() {
try {
this.speakMessage('请确认作废');
// 1. 显示确认弹窗
const confirmResult = await uni.showModal({
title: '整单作废',
@ -648,6 +809,9 @@
});
console.log(confirmResult);
if (!confirmResult[1].confirm) {
this.showToastMessage('已取消', 'none', {
speak: false
});
return;
}
@ -670,10 +834,8 @@
throw new Error("取消失败"+res.message)
}
// 5. 显示成功提示
uni.showToast({
title: '取消成功',
icon: 'success',
duration: 1500
this.showToastMessage('取消成功', 'success', {
speakText: '取消成功'
});
// 6. 延迟跳转,让用户看到成功提示
@ -810,12 +972,15 @@
const spaceInfo = await this.$http("common.searchSpace",{keyword:data});
if(spaceInfo.code==200){
if (spaceInfo.total == 1 && this.selectedDetail.space_id!=spaceInfo.data[0].id) {
const matchedSpace = spaceInfo.data[0] || {};
const spaceLabel = matchedSpace.space_code || matchedSpace.custom_name || matchedSpace.custom_barcode || String(data || '').trim();
const updateData = {
...this.selectedDetail, // 保留原有的所有属性
space_id: spaceInfo.data[0].id
};
console.log("更新仓位",updateData);
await this.handleSelectDetailChange(updateData);
this.speakMessage(`扫描成功,库位:${spaceLabel}`);
} else if (spaceInfo.total > 1) {
console.log("多个仓位",spaceInfo.data);
this.showSpaceList = true;
@ -841,6 +1006,12 @@
this.$nextTick(() => {
this.updateReceivingListHeaderTop();
});
},
onHide() {
this.stopSpeak();
},
onUnload() {
this.stopSpeak();
}
};
</script>