staffDailyReport.js 16.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
/**
 * 驻店日报-新页面 orchestrator
 * @see packageDynamicForm/docs/PAGES.md#驻店日报-新staffdailyreport
 * @see packageDynamicForm/docs/ARCHITECTURE.md
 *
 * 职责:周历选日、表单只读态、提交(无保存草稿)
 * 加载:loadStaffDailyForm → brand|scene|detail 并行 → pageContext → schema → engine.init
 * 写入:onFieldChange → engine.setFieldValue;subform → setGroupFieldValue
 * 周历:refreshWeeklyList 独立于 Loader(templateType=1)
 * 联调:STAFF_DAILY_API_SWITCH(../config/apiSwitch.js)
 * 维护:改动 Page 方法 / 加载链 / 保存逻辑时,同步 PAGES.md、DEVLOG.md 并补方法 JSDoc(见 MAINTENANCE.md § 三页 Page 后续开发)
 */
var timeUtil = require('~/utils/timeFormat/time-utils.js')
const { parseGroupErrorKey } = require('../../form-engine/group-values.js')
const staffDailyApi = require('../../api/staffDailyReport.js')
const { loadStaffDailyForm } = require('../../services/staffDailyFormLoader.js')
const { isApiSuccess } = require('../../utils/api-response.js')
const {
	isDailyReportFormDisabled,
	resolveReportSubmittedPatch
} = require('../../utils/daily-report-edit-state.js')
const { resolveWeekStateForReportDate } = require('../../utils/daily-report-calendar.js')
const { buildDailyReportRequestContext } = require('../../utils/daily-report-request-context.js')
const dailyReportPage = require('../behaviors/dailyReportPage.js')
const dailyReportPageMethods = require('../behaviors/dailyReportPageMethods.js')
const {
	isDateWithinDailyReportEditableWindow
} = require('../../utils/daily-report-editable-window.js')

Page({
	behaviors: [dailyReportPage],
	data: {
		navBarHeight: 0,
		pageTitle: '驻店日报',
		selectWeek: 0,
		timeBean: {},
		reportDate: '',
		weeklyList: [],
		isTodayReport: true,
		isDateWithinEditableWindow: false,
		reportStatus: '0',
		isReportSubmitted: false,
		isEditReport: false,
		merchantName: '',
		fixedFields: [],
		sectionGroups: [],
		groupFields: [],
		values: {},
		errors: {},
		formDisabled: false,
		requestContext: {},
		groupActiveIndex: {},
		groupRowsCache: {},
		groupRowVisibleMap: {},
		groupRowTotalMap: {},
		loading: true,
		loadError: ''
	},

	engine: null,
	reportTemplateId: null,
	dailyReportRecordId: null,
	userContext: null,
	_pageContextSnapshot: null,
	loadSeq: 0,
	refreshSeq: 0,
	engineKey: '',
	_submitting: false,

	/** 页面加载:初始化周历、拉 weekly 标记、加载表单 */
	onLoad(options = {}) {
		if (options.reportTemplateId) {
			this.reportTemplateId = Number(options.reportTemplateId) || options.reportTemplateId
		}
		const ctx = this.getRequestContext()
		if (ctx.shopMerchantName) {
			this.setData({ merchantName: ctx.shopMerchantName })
		}
		if (options.reportDate) {
			const { selectWeek, timeBean } = resolveWeekStateForReportDate(options.reportDate)
			this.applyCalendarState(selectWeek, timeBean)
		} else {
			this.applyCalendarState(this.data.selectWeek)
		}
		this.refreshWeeklyList()
		this.loadFormData()
	},

	/** 自定义导航栏高度回调 */
	navbarReady(e) {
		const height = e?.detail?.height
		if (height == null) return
		this.setData({
			navBarHeight: height
		})
	},

	/** 按 reportDate 重算可编辑窗口(相对今天 ±29 天) */
	refreshEditableWindowState(reportDate = this.data.reportDate) {
		const isDateWithinEditableWindow = reportDate
			? isDateWithinDailyReportEditableWindow(reportDate)
			: false
		Object.assign(this.data, { isDateWithinEditableWindow })
		return { isDateWithinEditableWindow, formDisabled: this.getFormDisabled() }
	},

	/** 根据 selectWeek 计算 reportDate、可编辑窗口、formDisabled */
	buildCalendarState(selectWeek, timeBeanInput) {
		const timeBean = timeBeanInput || timeUtil.getWeekDayList(selectWeek)
		const selectDay = timeBean.selectDay ?? 0
		const date = timeBean.weekDayList?.[selectDay]?.date || ''
		if (date) {
			const time = new Date(date)
			timeBean.yearMonth = `${time.getFullYear()}-${time.getMonth() + 1}`
		}
		const isTodayReport = date ? timeUtil.isTodayReport(date) : true
		const base = {
			timeBean,
			selectWeek,
			reportDate: date,
			isTodayReport
		}
		Object.assign(this.data, base)
		return {
			...base,
			...this.refreshEditableWindowState(date)
		}
	},

	/** 切换周历周偏移并同步 data */
	applyCalendarState(selectWeek, timeBeanInput) {
		this.resetEditReport()
		const state = this.buildCalendarState(selectWeek, timeBeanInput)
		Object.assign(this.data, state)
		state.formDisabled = this.getFormDisabled()
		this.setData(state)
		return state
	},

	/** 周历点击选日:更新 timeBean.selectDay */
	applyDaySelect(selectDay) {
		this.resetEditReport()
		const timeBean = { ...this.data.timeBean, selectDay }
		const state = this.buildCalendarState(this.data.selectWeek, timeBean)
		Object.assign(this.data, state)
		state.formDisabled = this.getFormDisabled()
		this.setData(state)
		return state
	},

	/** 可编辑窗外只读;已提交且未点编辑时只读 */
	getFormDisabled() {
		return isDailyReportFormDisabled({
			isDateWithinEditableWindow: this.data.isDateWithinEditableWindow,
			isReportSubmitted: this.data.isReportSubmitted,
			isEditReport: this.data.isEditReport
		})
	},

	/** 从 detail + weeklyList 同步提交态,并重算可编辑窗口 */
	syncReportSubmittedState(detail = {}) {
		const patch = resolveReportSubmittedPatch({
			detail,
			reportDate: this.data.reportDate,
			weeklyList: this.data.weeklyList || []
		})
		Object.assign(this.data, patch)
		Object.assign(patch, this.refreshEditableWindowState())
		this.setData(patch)
		return patch.isReportSubmitted
	},

	/** 进入编辑态(可编辑窗外不可解锁) */
	editReport() {
		if (!this.data.isDateWithinEditableWindow) {
			return wx.$util.showToast('已超过提交时效')
		}
		dailyReportPageMethods.editReport.call(this)
	},

	/** 复制当前 subform 各 group 的活跃行索引 */
	getGroupActiveIndexMap() {
		return { ...(this.data.groupActiveIndex || {}) }
	},

	/** 将 rowIndex 限制在 [0, rowTotal-1] 并写回 map */
	clampGroupActiveIndex(groupKey, rowIndex, rowTotal = 0) {
		const map = this.getGroupActiveIndexMap()
		let index = Number(rowIndex) || 0
		if (rowTotal <= 0) {
			index = 0
		} else if (index >= rowTotal) {
			index = rowTotal - 1
		} else if (index < 0) {
			index = 0
		}
		map[groupKey] = index
		return map
	},

	/** 校验失败时定位到首个出错 subform 行 */
	buildGroupActiveIndexFromErrors(errorMap = {}) {
		const map = this.getGroupActiveIndexMap()
		Object.keys(errorMap).forEach(errorKey => {
			const parsed = parseGroupErrorKey(errorKey)
			if (parsed) {
				map[parsed.groupKey] = parsed.rowIndex
			}
		})
		return map
	},

	/** 按 key 查找 subform 字段定义 */
	findGroupByKey(groupKey) {
		return (this.data.groupFields || []).find(item => item.key === groupKey)
	},

	/** subform 新增一行 */
	onGroupAdd(e) {
		if (this.data.formDisabled) return
		const { groupKey } = e.detail || {}
		if (!this.engine || !groupKey) return
		const group = this.findGroupByKey(groupKey)
		if (!group) return
		const viewState = this.engine.addGroupRow(group)
		if (viewState.added === false) {
			wx.showToast({ title: '最多添加20条', icon: 'none' })
			return
		}
		const rows = viewState.values[groupKey] || []
		const errors = { ...this.data.errors }
		delete errors[groupKey]
		this.applyEngineView(viewState, {
			errors,
			structureChanged: false,
			changedGroupKey: groupKey,
			groupActiveIndex: this.clampGroupActiveIndex(groupKey, viewState.rowIndex, rows.length)
		})
	},

	/** subform 删除指定行 */
	onGroupRemove(e) {
		if (this.data.formDisabled) return
		const { groupKey, rowIndex } = e.detail || {}
		if (!this.engine || groupKey == null || rowIndex == null) return
		const viewState = this.engine.removeGroupRow(groupKey, rowIndex)
		const rows = viewState.values[groupKey] || []
		const errors = { ...this.data.errors }
		delete errors[groupKey]
		Object.keys(errors).forEach(key => {
			const parsed = parseGroupErrorKey(key)
			if (parsed?.groupKey === groupKey) {
				delete errors[key]
			}
		})
		this.applyEngineView(viewState, {
			errors,
			structureChanged: false,
			changedGroupKey: groupKey,
			groupActiveIndex: this.clampGroupActiveIndex(groupKey, rowIndex, rows.length)
		})
	},

	/** subform 行翻页(direction ±1) */
	onGroupNav(e) {
		const { groupKey, direction } = e.detail || {}
		if (!groupKey || !this.engine) return
		const rows = this.engine.getGroupRows(groupKey) || []
		const current = this.data.groupActiveIndex[groupKey] || 0
		const nextIndex = Math.min(
			Math.max(0, current + (Number(direction) || 0)),
			Math.max(0, rows.length - 1)
		)
		const viewState = this.engine.getViewState()
		this.applyEngineView(viewState, {
			structureChanged: false,
			changedGroupKey: groupKey,
			keepErrors: true,
			groupActiveIndex: this.clampGroupActiveIndex(groupKey, nextIndex, rows.length)
		})
	},

	/** subform 单元格变更 → engine.setGroupFieldValue */
	onGroupChange(e) {
		if (this.data.formDisabled) return
		const { groupKey, rowIndex, childKey, value } = e.detail || {}
		if (!this.engine || !groupKey || childKey == null || rowIndex == null) return
		const viewState = this.engine.mutateSubform(groupKey, rowIndex, childKey, value)
		const errors = { ...this.data.errors }
		delete errors[`${groupKey}__${rowIndex}__${childKey}`]
		this.applyEngineView(viewState, {
			errors,
			structureChanged: false,
			changedGroupKey: groupKey
		})
	},

	/** 周历圆点:标记本周已填日期(templateType=1) */
	updateWeeklyDots(weeklyList = []) {
		const timeBean = { ...this.data.timeBean }
		timeBean.weekDayList = (timeBean.weekDayList || []).map(item => ({
			...item,
			hasDailyValue: weeklyList.includes(item.date)
		}))
		Object.assign(this.data, { timeBean, weeklyList })
		this.setData({
			timeBean,
			weeklyList
		})
		this.syncReportSubmittedState({ reportStatus: this.data.reportStatus })
	},

	/** 拉取 weekly.list 更新周历标记 */
	async refreshWeeklyList() {
		const { timeBean } = this.data
		const ctx = this.userContext || this.getRequestContext()
		if (!ctx.merchantId || !timeBean?.reportStartDate) return
		try {
			const res = await staffDailyApi.fetchWeeklyList({
				merchantId: ctx.merchantId,
				staffUuid: ctx.staffUuid,
				sceneType: ctx.sceneType,
				reportStartDate: timeBean.reportStartDate,
				reportEndDate: timeBean.reportEndDate
			})
			if (res.code === 0) {
				this.updateWeeklyDots(res.data || [])
			}
		} catch (error) {
			console.error(error)
		}
	},

	/** 从登录态解析 merchantId / staffUuid */
	getRequestContext() {
		const userInfo = wx.$util?.getUserInfo?.() || {}
		return staffDailyApi.normalizeUserInfo(userInfo)
	},

	/** 解析 engine / load 快照,供 requestContext 透出场景码(AppData 可见) */
	resolvePageContextForRequest() {
		return (
			this.engine?.getPageContext?.() ||
			this._pageContextSnapshot ||
			{}
		)
	},

	/** 透传给 select/multipleSelect 的 optionsKey 请求上下文 */
	buildFormRequestContext() {
		const ctx = this.userContext || this.getRequestContext()
		return buildDailyReportRequestContext({
			userContext: ctx,
			reportDate: this.data.reportDate,
			reportType: 'staff',
			engineCtx: this.resolvePageContextForRequest(),
			sceneTypeDefault: 0
		})
	},

	/** 主加载:Loader → engine.init → applyEngineView */
	async loadFormData() {
		const { reportDate, timeBean } = this.data
		if (!reportDate) return
		const seq = ++this.loadSeq
		const userContext = this.getRequestContext()
		this.userContext = userContext
		this.setData({ loading: true, loadError: '' })
		try {
			const loadRes = await loadStaffDailyForm({
				userContext,
				reportDate,
				timeBean,
				reportTemplateId: this.reportTemplateId
			})
			if (this.isStaleLoad(seq)) return
			if (!isApiSuccess(loadRes.code) || !loadRes.data) {
				this.setData({ loadError: loadRes.message || '加载失败' })
				console.error('[staffDailyReport] loadFormData failed', loadRes)
				return
			}

			const { pageContext, schema, detail, initialValues } = loadRes.data
			this._pageContextSnapshot = pageContext || null
			this.reportTemplateId = detail.reportTemplateId || this.reportTemplateId
			this.dailyReportRecordId = detail.dailyReportRecordId || null
			this.syncReportSubmittedState(detail)

			const engine = this.ensureEngine(this.getEngineKey(reportDate))
			const finalViewState = engine.init(schema, {
				...pageContext,
				initialValues: initialValues || {}
			})
			if (this.isStaleLoad(seq)) return

			this.setData({
				merchantName:
					pageContext.shopMerchantName || pageContext.merchantName || '',
				loadError: ''
			})
			this.applyEngineView(finalViewState, { structureChanged: true })
			this.scheduleMetadataCacheRevalidate(
				staffDailyApi,
				{
					userContext,
					baseSceneCode: pageContext.baseSceneCode,
					reportTemplateId: this.reportTemplateId
				},
				seq
			)
		} catch (error) {
			if (this.isStaleLoad(seq)) return
			console.error(error)
			this.setData({ loadError: '加载失败' })
		} finally {
			if (this.isStaleLoad(seq)) return
			this.setData({ loading: false })
		}
	},

	/** 顶层字段变更 → engine.setFieldValue(F1-1 触发结构重算) */
	onFieldChange(e) {
		if (this.data.formDisabled) return
		const { key, value } = e.detail || {}
		if (!this.engine || !key) return
		const viewState = this.engine.setFieldValue(key, value)
		const errors = { ...this.data.errors }
		delete errors[key]
		const structureChanged = key === 'F1-1'
		this.applyEngineView(viewState, { errors, structureChanged })
	},

	/** 提交:校验通过后 dynamic.save(无草稿) */
	async submit() {
		if (this._submitting) {
			return wx.$util.showToast('正在提交中,请稍候')
		}
		if (!this.engine) return
		if (!this.data.isDateWithinEditableWindow) {
			return wx.$util.showToast('已超过提交时效')
		}
		if (this.data.isReportSubmitted && !this.data.isEditReport) {
			return wx.$util.showToast('日报已提交,不可再编辑')
		}
		const validation = this.engine.validate()
		if (!validation.ok) {
			this.applyEngineView(this.engine.getViewState(), {
				errors: validation.errorMap,
				structureChanged: true,
				groupActiveIndex: this.buildGroupActiveIndexFromErrors(validation.errorMap)
			})
			return wx.$util.showToast('必填不能为空')
		}
		this.applyEngineView(this.engine.getViewState(), { errors: {}, structureChanged: false })
		if (!this.reportTemplateId) {
			return wx.$util.showToast('缺少报表模板,请联系运营配置')
		}
		this._submitting = true
		wx.$util.showLoading()
		try {
			const res = await staffDailyApi.submitForm({
				engine: this.engine,
				reportTemplateId: this.reportTemplateId,
				dailyReportRecordId: this.dailyReportRecordId,
				reportDate: this.data.reportDate
			})
			if (!isApiSuccess(res.code)) {
				return this.showSubmitFailureToast(res, null)
			}
			if (res.data?.dailyReportRecordId) {
				this.dailyReportRecordId = res.data.dailyReportRecordId
			}
			wx.$util.showToast('提交成功')
			await this.refreshAfterSubmit()
		} catch (error) {
			console.error(error)
			this.showSubmitFailureToast(null, error)
		} finally {
			this._submitting = false
			wx.$util.hideLoading()
		}
	},

	/** 提交成功后轻量重拉详情并刷新周历 */
	async refreshAfterSubmit() {
		const seq = ++this.refreshSeq
		const { reportDate, timeBean } = this.data
		const userContext = this.userContext || this.getRequestContext()
		const loadRes = await loadStaffDailyForm({
			userContext,
			reportDate,
			timeBean,
			reportTemplateId: this.reportTemplateId
		})
		if (this.isStaleRefresh(seq)) return
		if (!isApiSuccess(loadRes.code) || !loadRes.data) return

		const { schema, detail, initialValues, pageContext } = loadRes.data
		this._pageContextSnapshot = pageContext || null
		this.dailyReportRecordId = detail.dailyReportRecordId || this.dailyReportRecordId
		this.syncReportSubmittedState(detail)
		this.resetEditReport()
		if (!this.engine) return
		const viewState = this.reinitEngineFromLoadData({
			pageContext,
			schema,
			initialValues
		})
		if (this.isStaleRefresh(seq)) return
		await this.refreshWeeklyList()
		this.applyEngineView(viewState, { structureChanged: true })
	},

	/** 上一周:刷新 weekly + loadFormData */
	lastWeek() {
		const selectWeek = this.data.selectWeek - 1
		let timeBean = timeUtil.getWeekDayList(selectWeek)
		if (selectWeek !== 0) {
			timeBean.selectDay = 0
		}
		this.applyCalendarState(selectWeek, timeBean)
		this.refreshWeeklyList()
		this.loadFormData()
	},

	/** 下一周:刷新 weekly + loadFormData */
	nextWeek() {
		const selectWeek = this.data.selectWeek + 1
		const timeBean = timeUtil.getWeekDayList(selectWeek)
		timeBean.selectDay = 0
		this.applyCalendarState(selectWeek, timeBean)
		this.refreshWeeklyList()
		this.loadFormData()
	},

	/** 周历点击选日:仅 loadFormData,不重复 refreshWeeklyList */
	dayClick(e) {
		this.applyDaySelect(e.detail)
		this.loadFormData()
	},

	/** 返回上一页 */
	jump() {
		wx.$router.back()
	}
})