来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
987 lines
34 KiB
JavaScript
987 lines
34 KiB
JavaScript
const {
|
|
fetchDeliveryTasks,
|
|
fetchDeliveryLoading,
|
|
confirmDeliveryLoadingItem,
|
|
unconfirmDeliveryLoadingItem,
|
|
scanDeliveryLoading,
|
|
startDelivery,
|
|
startDeliveryBatch,
|
|
stopDelivery,
|
|
uploadDeliverySignPhoto,
|
|
uploadDeliveryLoadingPhoto,
|
|
fetchUnits,
|
|
reportDeliveryLocation,
|
|
} = require('../../utils/request');
|
|
const { ensureMobileRole } = require('../../utils/roleGuard');
|
|
const { beginPanelShow, endPanelShow } = require('../../utils/panelShowGate');
|
|
const { formatMpOrderCode } = require('../../utils/orderCodeDisplay');
|
|
const { prepareOrderImageBase64 } = require('../../utils/orderImage');
|
|
const { chinaTodayYmd, shiftChinaYmd } = require('../../utils/chinaDate');
|
|
const { buildUnitPicker, ensureUnitDictionary, getUnitDictionaryLabels } = require('../../utils/units');
|
|
const { parseCoord, openTencentNavigation, buildDeliveryMap, applyMapClientConfig, findNextNavTask } = require('../../utils/deliveryMap');
|
|
const {
|
|
ensureLocationAuth,
|
|
getHighAccuracyLocation,
|
|
getHighAccuracyLocationWithin,
|
|
getLastAcceptedPoint,
|
|
pointFromLocation,
|
|
startDeliveryLocationWatch,
|
|
stopDeliveryLocationWatch,
|
|
} = require('../../utils/deliveryLocation');
|
|
|
|
async function readDepartPoint() {
|
|
try {
|
|
await ensureLocationAuth();
|
|
const res = await getHighAccuracyLocation();
|
|
const point = pointFromLocation(res);
|
|
if (!point) return {};
|
|
return { lat: point.lat, lng: point.lng };
|
|
} catch (error) {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
function presetBounds(preset) {
|
|
const today = chinaTodayYmd();
|
|
if (preset === 'today') return { from: today, to: today };
|
|
const weekday = new Date(`${today}T12:00:00+08:00`).getUTCDay();
|
|
const diffToMonday = weekday === 0 ? 6 : weekday - 1;
|
|
const weekStart = shiftChinaYmd(today, -diffToMonday);
|
|
return { from: weekStart, to: shiftChinaYmd(weekStart, 6) };
|
|
}
|
|
|
|
function formatRangeChip(from, to) {
|
|
if (!from || !to) return '选择起止日期';
|
|
return `${from.slice(5)} ~ ${to.slice(5)}`;
|
|
}
|
|
|
|
function canScanTask(task) {
|
|
const status = Number(task?.task_status);
|
|
return Boolean(task?.task_code) && status < 20;
|
|
}
|
|
|
|
function findNextPendingScanTask(tasks, currentCode) {
|
|
const list = tasks || [];
|
|
const idx = list.findIndex((task) => task.task_code === currentCode);
|
|
const ordered = (idx >= 0 ? list.slice(idx + 1).concat(list.slice(0, idx)) : list).filter(
|
|
(task) => task.task_code !== currentCode && canScanTask(task)
|
|
);
|
|
return ordered.find((task) => !task.loading_ready) || ordered[0] || null;
|
|
}
|
|
|
|
/** 配送任务展示号;保留旧名避免开发者工具缓存仍调用 formatDeliveryOrderCode */
|
|
function formatDeliveryOrderCode(code) {
|
|
if (typeof formatMpOrderCode === 'function') return formatMpOrderCode(code);
|
|
const raw = String(code || '').trim();
|
|
if (!raw) return '';
|
|
const match = raw.match(/MP_(\d{8})_/i);
|
|
if (!match) return raw;
|
|
const tail = raw.length >= 4 ? raw.slice(-4) : raw;
|
|
return `${match[1]}_${tail}`;
|
|
}
|
|
|
|
/** 按配送单样式:分类标题 + 商品行(后端已按分类/品名排序) */
|
|
function buildLoadingRows(items) {
|
|
const rows = [];
|
|
let lastCat = null;
|
|
(items || []).forEach((item, idx) => {
|
|
const cat = String(item.category_top || item.category_name || '未分类').trim() || '未分类';
|
|
if (cat !== lastCat) {
|
|
rows.push({
|
|
row_type: 'category',
|
|
row_key: `cat-${cat}`,
|
|
category_top: cat,
|
|
});
|
|
lastCat = cat;
|
|
}
|
|
rows.push({
|
|
row_type: 'item',
|
|
row_key: `item-${item.id}`,
|
|
...item,
|
|
seq_no: item.seq_no || idx + 1,
|
|
});
|
|
});
|
|
return rows;
|
|
}
|
|
|
|
Component({
|
|
options: { addGlobalClass: true },
|
|
|
|
properties: {
|
|
embedded: { type: Boolean, value: false },
|
|
hideProgress: { type: Boolean, value: false },
|
|
},
|
|
|
|
data: {
|
|
tasks: [],
|
|
loading: false,
|
|
error: '',
|
|
expandedTaskCode: '',
|
|
loadingMode: 'manual',
|
|
loadingItems: [],
|
|
loadingRows: [],
|
|
loadingSummary: null,
|
|
loadingBusy: false,
|
|
weighDraft: {},
|
|
qtyDraft: {},
|
|
pickingScaleEnabled: false,
|
|
scanTip: '',
|
|
scanTipOk: true,
|
|
scanCameraOn: false,
|
|
starting: false,
|
|
stopping: false,
|
|
batchStarting: false,
|
|
uploadingPhoto: false,
|
|
uploadingLoadingPhotoId: '',
|
|
deliverySignPhotoEnabled: false,
|
|
deliveryLoadingPhotoRequired: false,
|
|
readyToStartCount: 0,
|
|
deliveringCount: 0,
|
|
completedCount: 0,
|
|
deliveryDate: '',
|
|
dateRange: 'today',
|
|
dateFrom: '',
|
|
dateTo: '',
|
|
customRangeLabel: '选择起止日期',
|
|
dateRanges: [
|
|
{ value: 'today', label: '今天' },
|
|
{ value: 'week', label: '本周' },
|
|
],
|
|
taskKpiLabel: '今日任务',
|
|
map: {
|
|
show: false,
|
|
latitude: 31.2304,
|
|
longitude: 121.4737,
|
|
scale: 12,
|
|
markers: [],
|
|
includePoints: [],
|
|
polyline: [],
|
|
markerTaskCodes: {},
|
|
},
|
|
routePlan: null,
|
|
nextNavLabel: '',
|
|
},
|
|
|
|
lifetimes: {
|
|
attached() {
|
|
this.onPanelShow();
|
|
},
|
|
detached() {
|
|
stopDeliveryLocationWatch();
|
|
},
|
|
},
|
|
|
|
pageLifetimes: {
|
|
show() {
|
|
this.onPanelShow();
|
|
},
|
|
},
|
|
|
|
methods: {
|
|
async onPanelShow() {
|
|
if (!beginPanelShow(this)) return;
|
|
try {
|
|
const ok = await ensureMobileRole('delivery');
|
|
if (!ok) return;
|
|
await ensureUnitDictionary(fetchUnits);
|
|
this.loadTasks();
|
|
} finally {
|
|
endPanelShow(this);
|
|
}
|
|
},
|
|
|
|
pickActiveDeliveryTask() {
|
|
return (this.data.tasks || []).find((task) => Number(task.task_status) === 20) || null;
|
|
},
|
|
|
|
onDateRange(e) {
|
|
const value = e.currentTarget.dataset.value || 'today';
|
|
this.setData(
|
|
{
|
|
dateRange: value,
|
|
dateFrom: '',
|
|
dateTo: '',
|
|
customRangeLabel: '选择起止日期',
|
|
},
|
|
() => this.loadTasks()
|
|
);
|
|
},
|
|
|
|
onOpenCustomRange() {
|
|
const seeded =
|
|
this.data.dateRange === 'custom' && this.data.dateFrom && this.data.dateTo
|
|
? { from: this.data.dateFrom, to: this.data.dateTo }
|
|
: presetBounds(this.data.dateRange === 'custom' ? 'week' : this.data.dateRange);
|
|
this.setData(
|
|
{
|
|
dateRange: 'custom',
|
|
dateFrom: seeded.from,
|
|
dateTo: seeded.to,
|
|
customRangeLabel: formatRangeChip(seeded.from, seeded.to),
|
|
},
|
|
() => this.loadTasks()
|
|
);
|
|
},
|
|
|
|
onCustomFromChange(e) {
|
|
const dateFrom = String(e.detail.value || '').slice(0, 10);
|
|
let dateTo = this.data.dateTo || dateFrom;
|
|
if (dateFrom && dateTo && dateFrom > dateTo) dateTo = dateFrom;
|
|
this.setData(
|
|
{
|
|
dateRange: 'custom',
|
|
dateFrom,
|
|
dateTo,
|
|
customRangeLabel: formatRangeChip(dateFrom, dateTo),
|
|
},
|
|
() => this.loadTasks()
|
|
);
|
|
},
|
|
|
|
onCustomToChange(e) {
|
|
const dateTo = String(e.detail.value || '').slice(0, 10);
|
|
let dateFrom = this.data.dateFrom || dateTo;
|
|
if (dateFrom && dateTo && dateFrom > dateTo) dateFrom = dateTo;
|
|
this.setData(
|
|
{
|
|
dateRange: 'custom',
|
|
dateFrom,
|
|
dateTo,
|
|
customRangeLabel: formatRangeChip(dateFrom, dateTo),
|
|
},
|
|
() => this.loadTasks()
|
|
);
|
|
},
|
|
|
|
deliveryQueryParams() {
|
|
if (this.data.dateRange === 'custom' && this.data.dateFrom && this.data.dateTo) {
|
|
return { date_from: this.data.dateFrom, date_to: this.data.dateTo };
|
|
}
|
|
const bounds = presetBounds(this.data.dateRange || 'today');
|
|
if (this.data.dateRange === 'week') {
|
|
return { date_from: bounds.from, date_to: bounds.to };
|
|
}
|
|
return { delivery_date: bounds.from };
|
|
},
|
|
|
|
emitProgress(patch = {}) {
|
|
if (!this.properties.hideProgress) return;
|
|
this.triggerEvent('progresschange', {
|
|
taskCount: patch.taskCount != null ? patch.taskCount : (this.data.tasks || []).length,
|
|
deliveringCount:
|
|
patch.deliveringCount != null ? patch.deliveringCount : this.data.deliveringCount,
|
|
completedCount:
|
|
patch.completedCount != null ? patch.completedCount : this.data.completedCount,
|
|
deliveryDate:
|
|
patch.deliveryDate != null ? patch.deliveryDate : this.data.deliveryDate,
|
|
taskLabel: patch.taskLabel != null ? patch.taskLabel : this.data.taskKpiLabel,
|
|
});
|
|
},
|
|
|
|
emitBadgeRefresh() {
|
|
this.triggerEvent('badgechange');
|
|
},
|
|
|
|
scanCameraOnValue(tasks, expandedTaskCode, loadingMode) {
|
|
if (loadingMode !== 'scan' || !expandedTaskCode) return false;
|
|
const task = (tasks || []).find((row) => row.task_code === expandedTaskCode);
|
|
return canScanTask(task);
|
|
},
|
|
|
|
async loadTasks(options) {
|
|
const silent = Boolean(options && options.silent);
|
|
if (!silent) this.setData({ loading: true, error: '' });
|
|
try {
|
|
const result = await fetchDeliveryTasks(this.deliveryQueryParams());
|
|
applyMapClientConfig(result.map_client);
|
|
const tasks = (result.data || []).map((task) => ({
|
|
...task,
|
|
company_name: task.company_name || task.customer_name || '',
|
|
delivery_address: task.address || task.delivery_address || '',
|
|
delivery_photo_signed: Boolean(task.delivery_photo_signed),
|
|
loading_ready: Boolean(task.loading_completed_at || task.loading_ready),
|
|
order_code_short: formatDeliveryOrderCode(task.order_code),
|
|
can_navigate: Boolean(parseCoord(task.lat, task.lng)),
|
|
route_sequence: task.route_sequence != null ? Number(task.route_sequence) : null,
|
|
}));
|
|
const routePlan = result.route_plan || null;
|
|
const nextNav = findNextNavTask(tasks);
|
|
let expandedTaskCode = this.data.expandedTaskCode;
|
|
if (expandedTaskCode && !tasks.some((task) => task.task_code === expandedTaskCode)) {
|
|
expandedTaskCode = '';
|
|
}
|
|
const readyToStartCount = tasks.filter(
|
|
(task) => Number(task.task_status) < 20 && task.loading_ready
|
|
).length;
|
|
const deliveringCount = tasks.filter((task) => Number(task.task_status) === 20).length;
|
|
const completedCount = tasks.filter((task) => Number(task.task_status) === 30).length;
|
|
const taskKpiLabel = this.data.dateRange === 'today' ? '今日任务' : '任务';
|
|
this.setData({
|
|
tasks,
|
|
routePlan,
|
|
nextNavLabel: nextNav
|
|
? `下一站 ${nextNav.route_sequence ? `${nextNav.route_sequence}. ` : ''}${nextNav.company_name || nextNav.order_code}`
|
|
: '',
|
|
map: buildDeliveryMap(tasks, routePlan),
|
|
deliverySignPhotoEnabled: result.delivery_sign_photo_enabled === true,
|
|
deliveryLoadingPhotoRequired: result.delivery_loading_photo_required === true,
|
|
deliveryDate: result.delivery_date || '',
|
|
expandedTaskCode,
|
|
readyToStartCount,
|
|
deliveringCount,
|
|
completedCount,
|
|
taskKpiLabel,
|
|
scanCameraOn: this.scanCameraOnValue(tasks, expandedTaskCode, this.data.loadingMode),
|
|
});
|
|
this.emitProgress({
|
|
taskCount: tasks.length,
|
|
deliveringCount,
|
|
completedCount,
|
|
deliveryDate: result.delivery_date || '',
|
|
taskLabel: taskKpiLabel,
|
|
});
|
|
this.emitBadgeRefresh();
|
|
if (expandedTaskCode) {
|
|
await this.loadLoadingState(expandedTaskCode, false);
|
|
}
|
|
this.syncLocationWatch(tasks);
|
|
} catch (err) {
|
|
this.setData({
|
|
error: err.message || '加载失败',
|
|
tasks: [],
|
|
routePlan: null,
|
|
nextNavLabel: '',
|
|
map: buildDeliveryMap([]),
|
|
expandedTaskCode: '',
|
|
loadingItems: [],
|
|
loadingRows: [],
|
|
loadingSummary: null,
|
|
readyToStartCount: 0,
|
|
deliveringCount: 0,
|
|
completedCount: 0,
|
|
scanCameraOn: false,
|
|
});
|
|
stopDeliveryLocationWatch();
|
|
this.emitProgress({
|
|
taskCount: 0,
|
|
deliveringCount: 0,
|
|
completedCount: 0,
|
|
deliveryDate: '',
|
|
});
|
|
} finally {
|
|
if (!silent) this.setData({ loading: false });
|
|
}
|
|
},
|
|
|
|
syncLocationWatch(tasks) {
|
|
const delivering = (tasks || []).some((task) => Number(task.task_status) === 20);
|
|
if (!delivering) {
|
|
stopDeliveryLocationWatch();
|
|
return;
|
|
}
|
|
const publishPoint = (point) => {
|
|
if (!point || !Number.isFinite(Number(point.lat)) || !Number.isFinite(Number(point.lng))) return;
|
|
const active = this.pickActiveDeliveryTask();
|
|
reportDeliveryLocation({
|
|
lat: point.lat,
|
|
lng: point.lng,
|
|
accuracy: point.accuracy,
|
|
speed: point.speed,
|
|
heading: point.heading,
|
|
task_code: active && active.task_code,
|
|
is_delivering: true,
|
|
}).catch(() => {});
|
|
};
|
|
ensureLocationAuth()
|
|
.then(() => {
|
|
startDeliveryLocationWatch((point) => {
|
|
publishPoint(point);
|
|
});
|
|
// 切导航回来时 watch 可能仍标为在跑、定时器被系统挂起。
|
|
// 不 await:失败/超时忽略,不拖住任务列表刷新。
|
|
getHighAccuracyLocationWithin(3000)
|
|
.then((point) => {
|
|
if (point) publishPoint(point);
|
|
})
|
|
.catch(() => {});
|
|
})
|
|
.catch(() => {});
|
|
},
|
|
|
|
onNavigateNext() {
|
|
this.navigateToTask(findNextNavTask(this.data.tasks));
|
|
},
|
|
|
|
navigateToTask(task) {
|
|
if (!task || !task.can_navigate) {
|
|
wx.showToast({ title: '该站点暂无坐标', icon: 'none' });
|
|
return;
|
|
}
|
|
ensureLocationAuth()
|
|
.catch(() => {})
|
|
.finally(() => {
|
|
openTencentNavigation({
|
|
name: task.company_name || task.order_code,
|
|
address: task.delivery_address,
|
|
lat: task.lat,
|
|
lng: task.lng,
|
|
});
|
|
});
|
|
},
|
|
|
|
onNavigateTask(e) {
|
|
const taskCode = e.currentTarget.dataset.code;
|
|
const task = (this.data.tasks || []).find((row) => row.task_code === taskCode);
|
|
this.navigateToTask(task);
|
|
},
|
|
|
|
onMapMarkerTap(e) {
|
|
const markerId = e.detail && e.detail.markerId;
|
|
const taskCode = this.data.map && this.data.map.markerTaskCodes
|
|
? this.data.map.markerTaskCodes[markerId]
|
|
: '';
|
|
const task = (this.data.tasks || []).find((row) => row.task_code === taskCode);
|
|
this.navigateToTask(task);
|
|
},
|
|
|
|
async toggleTaskPanel(e) {
|
|
const taskCode = e.currentTarget.dataset.code;
|
|
if (!taskCode) return;
|
|
if (this.data.expandedTaskCode === taskCode) {
|
|
this.setData({
|
|
expandedTaskCode: '',
|
|
loadingItems: [],
|
|
loadingRows: [],
|
|
loadingSummary: null,
|
|
weighDraft: {},
|
|
scanTip: '',
|
|
scanTipOk: true,
|
|
scanCameraOn: false,
|
|
});
|
|
return;
|
|
}
|
|
this.setData({
|
|
expandedTaskCode: taskCode,
|
|
scanTip: '',
|
|
scanTipOk: true,
|
|
scanCameraOn: this.scanCameraOnValue(this.data.tasks, taskCode, this.data.loadingMode),
|
|
});
|
|
await this.loadLoadingState(taskCode, true);
|
|
},
|
|
|
|
switchLoadingMode(e) {
|
|
const mode = e.currentTarget.dataset.mode;
|
|
if (!mode || mode === this.data.loadingMode) return;
|
|
this.setData({
|
|
loadingMode: mode,
|
|
scanTip: '',
|
|
scanTipOk: true,
|
|
scanCameraOn: this.scanCameraOnValue(this.data.tasks, this.data.expandedTaskCode, mode),
|
|
});
|
|
},
|
|
|
|
async loadLoadingState(taskCode, showError) {
|
|
try {
|
|
const result = await fetchDeliveryLoading(taskCode);
|
|
const data = result.data || {};
|
|
const allLoaded = Boolean(data.all_loaded);
|
|
const items = (data.items || []).map((item) => {
|
|
const picker = buildUnitPicker(item.unit || '斤', getUnitDictionaryLabels());
|
|
return {
|
|
...item,
|
|
unit: picker.unit,
|
|
unitOptions: picker.unitOptions,
|
|
unitIndex: picker.unitIndex,
|
|
};
|
|
});
|
|
const weighDraft = { ...(this.data.weighDraft || {}) };
|
|
const qtyDraft = { ...(this.data.qtyDraft || {}) };
|
|
items.forEach((item) => {
|
|
if (weighDraft[item.id] === undefined) {
|
|
weighDraft[item.id] =
|
|
Number(item.picked_weight) > 0 ? String(item.picked_weight) : '';
|
|
}
|
|
if (qtyDraft[item.id] === undefined || item.qty_editable) {
|
|
qtyDraft[item.id] =
|
|
Number(item.loaded_qty) > 0
|
|
? String(item.loaded_qty)
|
|
: item.required_qty != null
|
|
? String(item.required_qty)
|
|
: '';
|
|
}
|
|
});
|
|
const nextTasks = this.data.tasks.map((task) =>
|
|
task.task_code === taskCode
|
|
? {
|
|
...task,
|
|
// 以本次核货接口为准,勿 OR 内存里旧的 loading_completed_at(撤销后会误判可发车)
|
|
loading_ready: allLoaded,
|
|
loading_completed_at: allLoaded ? task.loading_completed_at || '1' : null,
|
|
}
|
|
: task
|
|
);
|
|
const readyToStartCount = nextTasks.filter(
|
|
(task) => Number(task.task_status) < 20 && task.loading_ready
|
|
).length;
|
|
this.setData({
|
|
loadingItems: items,
|
|
loadingRows: buildLoadingRows(items),
|
|
weighDraft,
|
|
qtyDraft,
|
|
pickingScaleEnabled: data.picking_scale_enabled === true,
|
|
loadingSummary: {
|
|
loaded_count: data.loaded_count || 0,
|
|
total_count: data.total_count || 0,
|
|
all_loaded: allLoaded,
|
|
can_start_delivery: Boolean(data.can_start_delivery),
|
|
can_sign_delivery: data.can_sign_delivery !== false,
|
|
loading_photo_required: data.loading_photo_required === true,
|
|
task_status: Number(data.task_status || 0),
|
|
order_status: Number(data.order_status || 0),
|
|
},
|
|
deliveryLoadingPhotoRequired: data.loading_photo_required === true,
|
|
tasks: nextTasks,
|
|
readyToStartCount,
|
|
scanCameraOn: this.scanCameraOnValue(nextTasks, taskCode, this.data.loadingMode),
|
|
});
|
|
} catch (err) {
|
|
this.setData({ loadingItems: [], loadingRows: [], loadingSummary: null });
|
|
if (showError) {
|
|
wx.showToast({ title: err.message || '加载核货明细失败', icon: 'none' });
|
|
}
|
|
}
|
|
},
|
|
|
|
onWeighDraftInput(e) {
|
|
const itemId = e.currentTarget.dataset.id;
|
|
if (!itemId) return;
|
|
this.setData({ [`weighDraft.${itemId}`]: e.detail.value });
|
|
},
|
|
|
|
onSkipQtyInput(e) {
|
|
const itemId = e.currentTarget.dataset.id;
|
|
if (!itemId) return;
|
|
this.setData({ [`qtyDraft.${itemId}`]: e.detail.value });
|
|
},
|
|
|
|
onSkipQtyBlur(e) {
|
|
const itemId = e.currentTarget.dataset.id;
|
|
const taskCode = this.data.expandedTaskCode;
|
|
if (!itemId || !taskCode) return;
|
|
this.persistSkipInboundRow(taskCode, itemId, true);
|
|
},
|
|
|
|
onSkipUnitChange(e) {
|
|
const itemId = e.currentTarget.dataset.id;
|
|
if (!itemId) return;
|
|
const items = (this.data.loadingItems || []).map((item) => {
|
|
if (String(item.id) !== String(itemId)) return item;
|
|
const options = item.unitOptions || getUnitDictionaryLabels();
|
|
const index = Number(e.detail.value) || 0;
|
|
const picker = buildUnitPicker(options[index] || item.unit || '斤', options);
|
|
return { ...item, ...picker };
|
|
});
|
|
this.setData({
|
|
loadingItems: items,
|
|
loadingRows: buildLoadingRows(items),
|
|
});
|
|
const taskCode = this.data.expandedTaskCode;
|
|
if (taskCode) this.persistSkipInboundRow(taskCode, itemId, true);
|
|
},
|
|
|
|
persistSkipInboundRow(taskCode, itemId, silent) {
|
|
const row = (this.data.loadingItems || []).find((item) => String(item.id) === String(itemId));
|
|
if (!row || !row.qty_editable) return Promise.resolve();
|
|
if (Number(this.data.loadingSummary?.task_status) >= 20) return Promise.resolve();
|
|
// 仓内未点完成的行:失焦只留草稿,不自动核货完成
|
|
if (!row.loaded_done && !row.skip_inbound) return Promise.resolve();
|
|
return this.submitConfirmLoading(taskCode, itemId, row.item_name || '商品', null, silent);
|
|
},
|
|
|
|
async persistAllSkipInboundDrafts(taskCode) {
|
|
const items = this.data.loadingItems || [];
|
|
for (const row of items) {
|
|
if (!row.qty_editable) continue;
|
|
if (!row.loaded_done) continue;
|
|
await this.persistSkipInboundRow(taskCode, row.id, true);
|
|
}
|
|
},
|
|
|
|
confirmLoadingItem(e) {
|
|
const itemId = e.currentTarget.dataset.id;
|
|
const itemName = e.currentTarget.dataset.name || '商品';
|
|
const taskCode = this.data.expandedTaskCode;
|
|
if (!itemId || !taskCode) return;
|
|
if (Number(this.data.loadingSummary?.task_status) >= 20) {
|
|
wx.showToast({ title: '配送已开始', icon: 'none' });
|
|
return;
|
|
}
|
|
// 不依赖 data-weigheditable(真机 dataset 布尔易丢);有草稿且未锁定则随确认提交
|
|
const row = (this.data.loadingItems || []).find((item) => String(item.id) === String(itemId));
|
|
let pickedWeight = null;
|
|
if (row && row.weigh_editable && !row.weigh_locked) {
|
|
const weight = Number(this.data.weighDraft?.[itemId]);
|
|
if (weight > 0) pickedWeight = weight;
|
|
}
|
|
this.submitConfirmLoading(taskCode, itemId, itemName, pickedWeight);
|
|
},
|
|
|
|
async submitConfirmLoading(taskCode, itemId, itemName, pickedWeight, silent) {
|
|
if (!silent) this.setData({ loadingBusy: true });
|
|
try {
|
|
const payload = {
|
|
task_code: taskCode,
|
|
item_id: itemId,
|
|
};
|
|
if (pickedWeight != null && pickedWeight > 0) {
|
|
payload.picked_weight = pickedWeight;
|
|
}
|
|
const row = (this.data.loadingItems || []).find((item) => String(item.id) === String(itemId));
|
|
if (row && row.qty_editable) {
|
|
const qty = Number(this.data.qtyDraft?.[itemId]);
|
|
if (qty > 0) payload.loaded_qty = qty;
|
|
if (row.unit) payload.unit = row.unit;
|
|
}
|
|
await confirmDeliveryLoadingItem(payload);
|
|
if (!silent) {
|
|
wx.showToast({ title: '已完成', icon: 'success' });
|
|
await this.loadLoadingState(taskCode, false);
|
|
await this.loadTasks();
|
|
}
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '确认失败', icon: 'none' });
|
|
} finally {
|
|
if (!silent) this.setData({ loadingBusy: false });
|
|
}
|
|
},
|
|
|
|
unconfirmLoadingItem(e) {
|
|
const itemId = e.currentTarget.dataset.id;
|
|
const itemName = e.currentTarget.dataset.name || '商品';
|
|
const taskCode = this.data.expandedTaskCode;
|
|
if (!itemId || !taskCode) return;
|
|
if (Number(this.data.loadingSummary?.task_status) >= 20) {
|
|
wx.showToast({ title: '配送已开始,无法撤销', icon: 'none' });
|
|
return;
|
|
}
|
|
wx.showModal({
|
|
title: '撤销核货',
|
|
content: `确认撤销「${itemName}」?撤销后可重新点「完成」。`,
|
|
confirmText: '撤销',
|
|
confirmColor: '#b91c1c',
|
|
success: (res) => {
|
|
if (!res.confirm) return;
|
|
this.submitUnconfirmLoading(taskCode, itemId);
|
|
},
|
|
});
|
|
},
|
|
|
|
async submitUnconfirmLoading(taskCode, itemId) {
|
|
this.setData({ loadingBusy: true });
|
|
try {
|
|
await unconfirmDeliveryLoadingItem({ task_code: taskCode, item_id: itemId });
|
|
wx.showToast({ title: '已撤销', icon: 'success' });
|
|
await this.loadLoadingState(taskCode, false);
|
|
await this.loadTasks();
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '撤销失败', icon: 'none' });
|
|
} finally {
|
|
this.setData({ loadingBusy: false });
|
|
}
|
|
},
|
|
|
|
onLoadingScanCameraError() {
|
|
wx.showToast({ title: '相机不可用,请在设置中允许摄像头权限', icon: 'none' });
|
|
},
|
|
|
|
onContinuousLoadingScan(e) {
|
|
const detail = (e && e.detail) || {};
|
|
const barcode = String(detail.result || detail.code || '').trim();
|
|
if (!barcode) return;
|
|
const taskCode = this.data.expandedTaskCode;
|
|
if (!taskCode || this.data.loadingMode !== 'scan') return;
|
|
const now = Date.now();
|
|
if (barcode === this._lastScanCode && now - (this._lastScanAt || 0) < 3000) return;
|
|
if (this._scanBusy) return;
|
|
this._lastScanCode = barcode;
|
|
this._lastScanAt = now;
|
|
this.submitLoadingScan(taskCode, barcode);
|
|
},
|
|
|
|
async submitLoadingScan(taskCode, barcode) {
|
|
this._scanBusy = true;
|
|
this.setData({ loadingBusy: true });
|
|
try {
|
|
const result = await scanDeliveryLoading({ task_code: taskCode, barcode });
|
|
const data = result.data || {};
|
|
wx.vibrateShort({ type: 'medium' });
|
|
wx.showToast({ title: '已识别', icon: 'success' });
|
|
await this.loadLoadingState(taskCode, false);
|
|
if (data.all_loaded) {
|
|
await this.boardAfterScanComplete(taskCode, data);
|
|
}
|
|
} catch (err) {
|
|
wx.showToast({ title: err.message || '扫码失败', icon: 'none', duration: 2500 });
|
|
} finally {
|
|
this._scanBusy = false;
|
|
this.setData({ loadingBusy: false });
|
|
}
|
|
},
|
|
|
|
cannotStartDeliveryMessage(summary) {
|
|
if (Number(summary?.order_status) < 50) return '请等待仓内分拣完成后再发车';
|
|
if (summary?.loading_photo_required) return '本单已扫完,请先给直送商品拍照后再发车';
|
|
return '本单已扫完,但还不能发车';
|
|
},
|
|
|
|
async boardAfterScanComplete(taskCode, scanData) {
|
|
const summary = this.data.loadingSummary || {};
|
|
const canStart = Boolean(scanData.can_start_delivery || summary.can_start_delivery);
|
|
if (!canStart) {
|
|
wx.showModal({
|
|
title: '本单已扫完',
|
|
content: this.cannotStartDeliveryMessage(summary),
|
|
showCancel: false,
|
|
confirmText: '知道了',
|
|
});
|
|
return;
|
|
}
|
|
const task = (this.data.tasks || []).find((row) => row.task_code === taskCode);
|
|
if (!task) return;
|
|
try {
|
|
await this.persistAllSkipInboundDrafts(taskCode);
|
|
const depart = await readDepartPoint();
|
|
await startDelivery({ task_code: taskCode, order_code: task.order_code, ...depart });
|
|
} catch (err) {
|
|
wx.showModal({
|
|
title: '发车失败',
|
|
content: err.message || '本单已扫完,但发车未成功,请点「确认发车」重试',
|
|
showCancel: false,
|
|
confirmText: '知道了',
|
|
});
|
|
return;
|
|
}
|
|
const next = findNextPendingScanTask(this.data.tasks, taskCode);
|
|
if (next) {
|
|
this.setData({
|
|
expandedTaskCode: next.task_code,
|
|
scanCameraOn: true,
|
|
});
|
|
}
|
|
wx.showModal({
|
|
title: '已发车',
|
|
content: next
|
|
? '本单已核完并已发车,可继续扫下一单。'
|
|
: '本单已核完并已发车。当前没有下一单可扫。',
|
|
showCancel: false,
|
|
confirmText: '好的',
|
|
});
|
|
await this.loadTasks({ silent: true });
|
|
},
|
|
|
|
async ensureTaskLoaded(task) {
|
|
const taskCode = task.task_code;
|
|
if (task.loading_ready) return true;
|
|
if (this.data.expandedTaskCode === taskCode && this.data.loadingSummary?.all_loaded) {
|
|
return true;
|
|
}
|
|
try {
|
|
const result = await fetchDeliveryLoading(taskCode);
|
|
return Boolean(result.data?.all_loaded);
|
|
} catch {
|
|
return false;
|
|
}
|
|
},
|
|
|
|
async startTask(e) {
|
|
const task = e.currentTarget.dataset.task;
|
|
if (!task?.task_code) return;
|
|
|
|
const taskCode = task.task_code;
|
|
if (this.data.expandedTaskCode !== taskCode) {
|
|
this.setData({ expandedTaskCode: taskCode });
|
|
await this.loadLoadingState(taskCode, false);
|
|
}
|
|
const loaded = await this.ensureTaskLoaded(task);
|
|
if (!loaded) {
|
|
wx.showToast({ title: '请先完成全部品类核货', icon: 'none' });
|
|
return;
|
|
}
|
|
const summary = this.data.loadingSummary;
|
|
if (summary && !summary.can_start_delivery) {
|
|
wx.showToast({
|
|
title:
|
|
Number(summary.order_status) < 50
|
|
? '请等待仓内分拣完成'
|
|
: summary.loading_photo_required
|
|
? '请先给直送商品拍照'
|
|
: '请先完成全部品类核货',
|
|
icon: 'none',
|
|
});
|
|
return;
|
|
}
|
|
|
|
this.setData({ starting: true, error: '' });
|
|
try {
|
|
await this.persistAllSkipInboundDrafts(taskCode);
|
|
const depart = await readDepartPoint();
|
|
await startDelivery({ task_code: taskCode, order_code: task.order_code, ...depart });
|
|
wx.showToast({ title: '已发车', icon: 'success' });
|
|
await this.loadTasks();
|
|
} catch (err) {
|
|
this.setData({ error: err.message || '发车失败' });
|
|
wx.showToast({ title: err.message || '发车失败', icon: 'none' });
|
|
} finally {
|
|
this.setData({ starting: false });
|
|
}
|
|
},
|
|
|
|
async startAllReadyTasks() {
|
|
if (!this.data.readyToStartCount) {
|
|
wx.showToast({ title: '没有已核货待发车的订单', icon: 'none' });
|
|
return;
|
|
}
|
|
this.setData({ batchStarting: true, error: '' });
|
|
try {
|
|
const depart = await readDepartPoint();
|
|
const result = await startDeliveryBatch(undefined, depart);
|
|
const count = Number(result.data?.count || result.data?.started?.length || 0);
|
|
if (!count) {
|
|
wx.showToast({ title: '没有成功发车的订单', icon: 'none' });
|
|
} else {
|
|
wx.showToast({ title: `已同时发车 ${count} 单`, icon: 'success' });
|
|
}
|
|
await this.loadTasks();
|
|
} catch (err) {
|
|
this.setData({ error: err.message || '批量发车失败' });
|
|
wx.showToast({ title: err.message || '批量发车失败', icon: 'none' });
|
|
} finally {
|
|
this.setData({ batchStarting: false });
|
|
}
|
|
},
|
|
|
|
chooseLoadingPhoto(e) {
|
|
const itemId = e.currentTarget.dataset.id;
|
|
const itemName = e.currentTarget.dataset.name || '商品';
|
|
const taskCode = this.data.expandedTaskCode;
|
|
if (!itemId || !taskCode) return;
|
|
wx.chooseImage({
|
|
count: 1,
|
|
sizeType: ['compressed'],
|
|
sourceType: ['camera', 'album'],
|
|
success: async (res) => {
|
|
const filePath = (res.tempFilePaths || [])[0];
|
|
if (!filePath) return;
|
|
this.setData({ uploadingLoadingPhotoId: itemId, error: '' });
|
|
wx.showLoading({ title: '上传中…', mask: true });
|
|
try {
|
|
const content = await prepareOrderImageBase64(filePath);
|
|
const ext = (filePath.split('.').pop() || 'jpg').toLowerCase();
|
|
await uploadDeliveryLoadingPhoto({
|
|
task_code: taskCode,
|
|
picking_item_id: itemId,
|
|
content,
|
|
ext,
|
|
});
|
|
const row = (this.data.loadingItems || []).find((item) => String(item.id) === String(itemId));
|
|
const alreadyDone = Boolean(row && row.loaded_done);
|
|
const started = Number(this.data.loadingSummary?.task_status) >= 20;
|
|
const extraDish = Boolean(row && row.is_extra_dish);
|
|
if ((!started || extraDish) && !alreadyDone) {
|
|
let pickedWeight = null;
|
|
if (row && row.weigh_editable && !row.weigh_locked) {
|
|
const weight = Number(this.data.weighDraft?.[itemId]);
|
|
if (weight > 0) pickedWeight = weight;
|
|
}
|
|
wx.hideLoading();
|
|
await this.submitConfirmLoading(taskCode, itemId, itemName, pickedWeight);
|
|
return;
|
|
}
|
|
wx.showToast({ title: itemName ? `已补拍:${itemName}` : '已上传', icon: 'success' });
|
|
await this.loadLoadingState(taskCode, false);
|
|
} catch (err) {
|
|
this.setData({ error: err.message || '补拍失败' });
|
|
wx.showToast({ title: err.message || '补拍失败', icon: 'none' });
|
|
} finally {
|
|
wx.hideLoading();
|
|
this.setData({ uploadingLoadingPhotoId: '' });
|
|
}
|
|
},
|
|
fail: () => wx.showToast({ title: '未选择照片', icon: 'none' }),
|
|
});
|
|
},
|
|
|
|
chooseDeliveryPhoto(e) {
|
|
const taskCode = e.currentTarget.dataset.code;
|
|
if (!taskCode) return;
|
|
if (this.data.loadingSummary && this.data.loadingSummary.can_sign_delivery === false) {
|
|
wx.showToast({ title: '请先给加菜拍核货照', icon: 'none' });
|
|
return;
|
|
}
|
|
|
|
wx.chooseImage({
|
|
count: 1,
|
|
sizeType: ['compressed'],
|
|
sourceType: ['camera', 'album'],
|
|
success: async (res) => {
|
|
const filePath = (res.tempFilePaths || [])[0];
|
|
if (!filePath) return;
|
|
this.setData({ uploadingPhoto: true, error: '' });
|
|
wx.showLoading({ title: '上传中…', mask: true });
|
|
try {
|
|
await this.uploadPhoto(taskCode, filePath);
|
|
wx.showToast({ title: '拍照送达已上传', icon: 'success' });
|
|
this.loadTasks();
|
|
} catch (err) {
|
|
this.setData({ error: err.message || '上传失败' });
|
|
wx.showToast({ title: err.message || '上传失败', icon: 'none' });
|
|
} finally {
|
|
wx.hideLoading();
|
|
this.setData({ uploadingPhoto: false });
|
|
}
|
|
},
|
|
fail: () => wx.showToast({ title: '未选择照片', icon: 'none' }),
|
|
});
|
|
},
|
|
|
|
uploadPhoto(taskCode, filePath) {
|
|
return prepareOrderImageBase64(filePath).then((content) =>
|
|
uploadDeliverySignPhoto({ task_code: taskCode, content, ext: 'jpg' })
|
|
);
|
|
},
|
|
|
|
async finishTask(e) {
|
|
const taskCode = e.currentTarget.dataset.code;
|
|
if (!taskCode) return;
|
|
|
|
const task = this.data.tasks.find((item) => item.task_code === taskCode);
|
|
if (this.data.loadingSummary && this.data.loadingSummary.can_sign_delivery === false) {
|
|
wx.showToast({ title: '请先给加菜拍核货照', icon: 'none' });
|
|
return;
|
|
}
|
|
if (this.data.deliverySignPhotoEnabled && task && !task.delivery_photo_signed) {
|
|
wx.showToast({ title: '请先拍照送达', icon: 'none' });
|
|
return;
|
|
}
|
|
|
|
this.setData({ stopping: true, error: '' });
|
|
try {
|
|
// 结束配送时补一个定位样本:先用实时定位(带 3 秒超时,绝不挂住结束动作),
|
|
// 失败/超时则退回最后一次已知点。
|
|
// 服务端据此补一次进圈判定(否则途中上报断档会让卸货时长永远为空)。
|
|
// 见 docs/design/20260918-delivery-geofence-report-gap.md
|
|
let stopPosition = await getHighAccuracyLocationWithin(3000);
|
|
if (!stopPosition) stopPosition = getLastAcceptedPoint();
|
|
await stopDelivery(taskCode, stopPosition);
|
|
wx.showToast({ title: '该客户配送已结束', icon: 'success' });
|
|
await this.loadTasks();
|
|
} catch (err) {
|
|
this.setData({ error: err.message || '结束配送失败' });
|
|
wx.showToast({ title: err.message || '结束配送失败', icon: 'none' });
|
|
} finally {
|
|
this.setData({ stopping: false });
|
|
}
|
|
},
|
|
},
|
|
});
|