Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a396d79a2 | ||
|
|
9c4944702b | ||
|
|
e06f89dcf6 | ||
|
|
f343f12645 | ||
|
|
1032631318 | ||
|
|
f9f79479e8 | ||
|
|
e488b86c35 | ||
|
|
6a78c28121 | ||
|
|
c7905b5da0 |
No files matched your search
@@ -1,6 +1,10 @@
|
||||
-- Issue #24:协议单操作过程日志(before / action / after)
|
||||
-- MySQL 5.7;可重复执行(CREATE IF NOT EXISTS)。上线前须备份并在目标副本验证。
|
||||
-- DDL 隐式提交;该脚本不作为自动应用启动步骤。
|
||||
--
|
||||
-- 注意:若目标库已存在同名「采集协议单操作日志」旧表(含 collection_protocol_id /
|
||||
-- operation_code 等列),本脚本会因 IF NOT EXISTS 直接跳过,不会纠偏。
|
||||
-- 生产纠偏请改用:2026-11-09-protocol-operation-log-rebuild.sql
|
||||
|
||||
CREATE TABLE IF NOT EXISTS biz_protocol_operation_log (
|
||||
id VARCHAR(64) NOT NULL,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
-- =============================================================================
|
||||
-- 协议操作日志:兼容生产旧表同名冲突,重建为 Issue #24 模型
|
||||
-- MySQL 5.7;可重复执行。上线前须备份,并在目标副本验证。
|
||||
--
|
||||
-- 背景:
|
||||
-- 生产曾有「采集协议单操作日志」同名表(collection_protocol_id / operation_*),
|
||||
-- 与当前代码(biz_type / before_json / after_json)不兼容。
|
||||
-- 旧脚本 2026-11-05-protocol-operation-log.sql 使用 CREATE IF NOT EXISTS,
|
||||
-- 遇到旧表会直接跳过,无法纠偏。本脚本用于生产纠偏与新环境兜底。
|
||||
--
|
||||
-- 行为:
|
||||
-- 1) 已是新模型(有 biz_type)→ 跳过结构变更
|
||||
-- 2) 旧模型且 0 行 → DROP 后按新模型 CREATE
|
||||
-- 3) 旧模型且有数据 → RENAME 为 biz_protocol_operation_log_legacy_20261109 再 CREATE
|
||||
-- 4) 表不存在 → 直接 CREATE
|
||||
-- =============================================================================
|
||||
|
||||
SET @db := DATABASE();
|
||||
|
||||
SET @table_exists := (
|
||||
SELECT COUNT(*) FROM information_schema.tables
|
||||
WHERE table_schema = @db AND table_name = 'biz_protocol_operation_log'
|
||||
);
|
||||
|
||||
SET @has_legacy_col := (
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = @db
|
||||
AND table_name = 'biz_protocol_operation_log'
|
||||
AND column_name = 'collection_protocol_id'
|
||||
);
|
||||
|
||||
SET @has_new_col := (
|
||||
SELECT COUNT(*) FROM information_schema.columns
|
||||
WHERE table_schema = @db
|
||||
AND table_name = 'biz_protocol_operation_log'
|
||||
AND column_name = 'biz_type'
|
||||
);
|
||||
|
||||
SET @is_legacy := IF(@table_exists > 0 AND @has_legacy_col > 0 AND @has_new_col = 0, 1, 0);
|
||||
|
||||
SET @legacy_rows := 0;
|
||||
SET @cnt_sql := IF(
|
||||
@is_legacy = 1,
|
||||
'SET @legacy_rows = (SELECT COUNT(*) FROM `biz_protocol_operation_log`)',
|
||||
'SET @legacy_rows = 0'
|
||||
);
|
||||
PREPARE pol_stmt FROM @cnt_sql;
|
||||
EXECUTE pol_stmt;
|
||||
DEALLOCATE PREPARE pol_stmt;
|
||||
|
||||
-- 空旧表:直接删除
|
||||
SET @drop_sql := IF(
|
||||
@is_legacy = 1 AND @legacy_rows = 0,
|
||||
'DROP TABLE `biz_protocol_operation_log`',
|
||||
'SELECT ''skip drop empty legacy biz_protocol_operation_log'' AS migration_status'
|
||||
);
|
||||
PREPARE pol_stmt FROM @drop_sql;
|
||||
EXECUTE pol_stmt;
|
||||
DEALLOCATE PREPARE pol_stmt;
|
||||
|
||||
-- 有数据的旧表:改名保留,避免丢历史(当前生产为 0 行,通常不会走到这里)
|
||||
SET @legacy_backup_exists := (
|
||||
SELECT COUNT(*) FROM information_schema.tables
|
||||
WHERE table_schema = @db AND table_name = 'biz_protocol_operation_log_legacy_20261109'
|
||||
);
|
||||
SET @rename_sql := IF(
|
||||
@is_legacy = 1 AND @legacy_rows > 0 AND @legacy_backup_exists = 0,
|
||||
'RENAME TABLE `biz_protocol_operation_log` TO `biz_protocol_operation_log_legacy_20261109`',
|
||||
IF(
|
||||
@is_legacy = 1 AND @legacy_rows > 0 AND @legacy_backup_exists > 0,
|
||||
'SELECT ''ERROR: legacy backup biz_protocol_operation_log_legacy_20261109 already exists; resolve manually'' AS migration_status',
|
||||
'SELECT ''skip rename legacy biz_protocol_operation_log'' AS migration_status'
|
||||
)
|
||||
);
|
||||
PREPARE pol_stmt FROM @rename_sql;
|
||||
EXECUTE pol_stmt;
|
||||
DEALLOCATE PREPARE pol_stmt;
|
||||
|
||||
-- 新模型建表(纠偏后或全新环境)
|
||||
CREATE TABLE IF NOT EXISTS `biz_protocol_operation_log` (
|
||||
`id` VARCHAR(64) NOT NULL COMMENT '主键ID',
|
||||
`biz_type` VARCHAR(32) NOT NULL COMMENT '业务类型 cell_storage/research_donation',
|
||||
`biz_id` VARCHAR(64) NOT NULL COMMENT '协议单或捐赠单ID',
|
||||
`protocol_no` VARCHAR(64) NULL COMMENT '协议/捐赠编号快照',
|
||||
`action` VARCHAR(32) NOT NULL COMMENT '动作 create/update/delete/void/activate/expire/to_research/to_storage/audit',
|
||||
`client_channel` VARCHAR(16) NOT NULL DEFAULT 'web' COMMENT '来源端 web/mini',
|
||||
`before_json` MEDIUMTEXT NULL COMMENT '操作前协议信息JSON',
|
||||
`after_json` MEDIUMTEXT NULL COMMENT '操作后协议信息JSON',
|
||||
`operator_user_id` VARCHAR(64) NULL COMMENT '操作人用户ID',
|
||||
`operator_user_name` VARCHAR(64) NULL COMMENT '操作人姓名快照',
|
||||
`operate_time` DATETIME NOT NULL COMMENT '业务操作时间',
|
||||
`tenant_no` VARCHAR(64) NOT NULL COMMENT '租户编号',
|
||||
`order_num` INT NULL COMMENT '排序号',
|
||||
`remark` VARCHAR(512) NULL COMMENT '备注',
|
||||
`create_by` VARCHAR(64) NULL COMMENT '创建人id',
|
||||
`create_dept_id` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '创建人部门ID',
|
||||
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`update_by` VARCHAR(64) NULL COMMENT '更新人id',
|
||||
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`del_flag` SMALLINT NOT NULL DEFAULT 0 COMMENT '删除标记',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `ix_pol_biz` (`tenant_no`, `biz_type`, `biz_id`, `del_flag`),
|
||||
KEY `ix_pol_time` (`tenant_no`, `operate_time`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='协议单操作过程日志';
|
||||
|
||||
-- 验收:新模型关键列应存在
|
||||
SELECT
|
||||
COLUMN_NAME,
|
||||
COLUMN_TYPE,
|
||||
IS_NULLABLE,
|
||||
COLUMN_COMMENT
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = DATABASE()
|
||||
AND table_name = 'biz_protocol_operation_log'
|
||||
AND COLUMN_NAME IN (
|
||||
'biz_type', 'biz_id', 'action', 'before_json', 'after_json',
|
||||
'client_channel', 'operate_time', 'collection_protocol_id', 'operation_code'
|
||||
)
|
||||
ORDER BY ORDINAL_POSITION;
|
||||
@@ -49,11 +49,11 @@
|
||||
/* 快应用特有相关 */
|
||||
"quickapp" : {},
|
||||
/* 小程序特有相关 */
|
||||
/* 当前:生产 AppID;切测试时把 appid 改为下方测试值 */
|
||||
/* 当前:测试 AppID;切生产时把 appid 改为下方生产值 */
|
||||
/* 生产 AppID:wx2b139581f4c855e4 */
|
||||
/* 测试 AppID:wxa261ad85f2c99b26 */
|
||||
"mp-weixin" : {
|
||||
"appid" : "wx2b139581f4c855e4",
|
||||
"appid" : "wxa261ad85f2c99b26",
|
||||
"setting" : {
|
||||
"urlCheck" : false,
|
||||
"es6" : true
|
||||
|
||||
@@ -95,6 +95,14 @@
|
||||
"navigationBarTextStyle": "black"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "pages/oa/file-preview/index",
|
||||
"style": {
|
||||
"navigationBarTitleText": "附件预览",
|
||||
"navigationBarBackgroundColor": "#ecfdf5",
|
||||
"navigationBarTextStyle": "black"
|
||||
}
|
||||
},
|
||||
{
|
||||
"path": "pages/market/webview/index",
|
||||
"style": {
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
<template>
|
||||
<view class="file-preview">
|
||||
<view class="file-preview__tip">{{ tip }}</view>
|
||||
</view>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { API_BASE_URL, MINIO_BASE_URL } from '../../../utils/config.js'
|
||||
import { getToken } from '../../../utils/auth.js'
|
||||
import {
|
||||
buildDirectMinioUrl,
|
||||
pdfPreviewLog,
|
||||
toAbsoluteDownloadUrl
|
||||
} from '../../../utils/oa-pdf-preview-query.js'
|
||||
import { parseFilePreviewQuery } from '../../../utils/oa-file-preview.js'
|
||||
|
||||
function absolutize(url) {
|
||||
const abs = toAbsoluteDownloadUrl(url, {
|
||||
apiBaseUrl: API_BASE_URL,
|
||||
minioBaseUrl: MINIO_BASE_URL
|
||||
})
|
||||
if (String(url || '').trim() && abs && abs !== url) {
|
||||
pdfPreviewLog('file-preview absolutize', {
|
||||
from: String(url).slice(0, 120),
|
||||
to: abs.slice(0, 160)
|
||||
})
|
||||
}
|
||||
return abs
|
||||
}
|
||||
|
||||
function directMinio(fileUrl) {
|
||||
return buildDirectMinioUrl(fileUrl, {
|
||||
apiBaseUrl: API_BASE_URL,
|
||||
minioBaseUrl: MINIO_BASE_URL
|
||||
})
|
||||
}
|
||||
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
tip: '正在打开附件…',
|
||||
_opened: false
|
||||
}
|
||||
},
|
||||
onLoad(query) {
|
||||
pdfPreviewLog('file-preview onLoad raw query', query)
|
||||
this.openFromQuery(query || {})
|
||||
},
|
||||
methods: {
|
||||
async openFromQuery(query) {
|
||||
const parsed = parseFilePreviewQuery(query)
|
||||
const { fileUrl, legacyUrl, name, fileType, rawKeys } = parsed
|
||||
pdfPreviewLog('file-preview parsed query', {
|
||||
rawKeys,
|
||||
name,
|
||||
fileType,
|
||||
fileUrlLen: fileUrl.length,
|
||||
fileUrlPreview: fileUrl.slice(0, 160),
|
||||
legacyUrlLen: legacyUrl.length,
|
||||
legacyUrlPreview: legacyUrl.slice(0, 120),
|
||||
hasToken: !!getToken(),
|
||||
minioBase: String(MINIO_BASE_URL || '').slice(0, 80)
|
||||
})
|
||||
|
||||
// 与 PDF 预览一致:优先 MinIO 公网直链;预签名经 /minio 改写后真机常 403。
|
||||
let url = ''
|
||||
let fallbackUrl = ''
|
||||
let source = ''
|
||||
|
||||
if (legacyUrl) {
|
||||
const absLegacy = absolutize(legacyUrl)
|
||||
const direct = directMinio(fileUrl || legacyUrl)
|
||||
if (direct && /^https?:\/\//i.test(direct)) {
|
||||
url = direct
|
||||
fallbackUrl = absLegacy && absLegacy !== direct ? absLegacy : ''
|
||||
source = 'minio-direct(+legacy-fallback)'
|
||||
} else {
|
||||
url = absLegacy
|
||||
source = 'query.url'
|
||||
}
|
||||
} else if (fileUrl) {
|
||||
url = directMinio(fileUrl)
|
||||
source = 'minio-direct'
|
||||
pdfPreviewLog('file-preview minio-direct', {
|
||||
urlPreview: String(url || '').slice(0, 160)
|
||||
})
|
||||
}
|
||||
|
||||
url = absolutize(url) || url
|
||||
fallbackUrl = absolutize(fallbackUrl) || fallbackUrl
|
||||
|
||||
if (!url || !/^https?:\/\//i.test(url)) {
|
||||
const reason = !fileUrl && !legacyUrl
|
||||
? '缺少 fileUrl/url 参数(请确认小程序与 oa-h5 已同步部署)'
|
||||
: '无法解析为 http(s) 下载地址'
|
||||
pdfPreviewLog('file-preview invalid url', { reason, fileUrl, legacyUrl, url })
|
||||
this.tip = '文件地址无效'
|
||||
uni.showToast({ title: '文件地址无效', icon: 'none' })
|
||||
return
|
||||
}
|
||||
|
||||
pdfPreviewLog('file-preview open', {
|
||||
source,
|
||||
name,
|
||||
fileType,
|
||||
urlPreview: url.slice(0, 160),
|
||||
hasFallback: !!fallbackUrl
|
||||
})
|
||||
this.openFile(url, name, fileType, fallbackUrl)
|
||||
},
|
||||
openFile(url, name, fileType, fallbackUrl) {
|
||||
if (this._opened) return
|
||||
this._opened = true
|
||||
this._tryDownload(url, name, fileType, fallbackUrl, false)
|
||||
},
|
||||
_tryDownload(url, name, fileType, fallbackUrl, isRetry) {
|
||||
pdfPreviewLog('file-preview downloadFile start', {
|
||||
name,
|
||||
fileType,
|
||||
isRetry: !!isRetry,
|
||||
urlPreview: String(url || '').slice(0, 160)
|
||||
})
|
||||
uni.downloadFile({
|
||||
url,
|
||||
success: (res) => {
|
||||
const code = res && res.statusCode
|
||||
pdfPreviewLog('file-preview downloadFile success', {
|
||||
statusCode: code,
|
||||
hasTemp: !!(res && res.tempFilePath),
|
||||
isRetry: !!isRetry
|
||||
})
|
||||
if (code === 403 && fallbackUrl && !isRetry) {
|
||||
pdfPreviewLog('file-preview 403 → retry fallback', {
|
||||
fallbackPreview: String(fallbackUrl).slice(0, 160)
|
||||
})
|
||||
this._tryDownload(fallbackUrl, name, fileType, '', true)
|
||||
return
|
||||
}
|
||||
if (!res || code !== 200 || !res.tempFilePath) {
|
||||
this.tip = '下载失败' + (code ? '(' + code + ')' : '')
|
||||
uni.showToast({
|
||||
title: '下载失败' + (code ? ' ' + code : ''),
|
||||
icon: 'none'
|
||||
})
|
||||
this._opened = false
|
||||
return
|
||||
}
|
||||
const openOpts = {
|
||||
filePath: res.tempFilePath,
|
||||
showMenu: true,
|
||||
success: () => {
|
||||
pdfPreviewLog('file-preview openDocument success')
|
||||
this.tip = '已打开预览'
|
||||
setTimeout(() => {
|
||||
uni.navigateBack({ fail: () => {} })
|
||||
}, 300)
|
||||
},
|
||||
fail: (err) => {
|
||||
pdfPreviewLog('file-preview openDocument fail', err)
|
||||
this.tip = '无法打开附件,请通过右上角菜单转发或用其他应用打开'
|
||||
uni.showToast({ title: '无法打开附件', icon: 'none' })
|
||||
this._opened = false
|
||||
}
|
||||
}
|
||||
if (fileType) openOpts.fileType = fileType
|
||||
uni.openDocument(openOpts)
|
||||
},
|
||||
fail: (err) => {
|
||||
pdfPreviewLog('file-preview downloadFile fail', err)
|
||||
if (fallbackUrl && !isRetry) {
|
||||
pdfPreviewLog('file-preview fail → retry fallback')
|
||||
this._tryDownload(fallbackUrl, name, fileType, '', true)
|
||||
return
|
||||
}
|
||||
this.tip = '下载失败'
|
||||
uni.showToast({ title: '下载失败', icon: 'none' })
|
||||
this._opened = false
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.file-preview {
|
||||
min-height: 100vh;
|
||||
padding: 48rpx 32rpx;
|
||||
background: #f5f7fa;
|
||||
}
|
||||
.file-preview__tip {
|
||||
text-align: center;
|
||||
color: #64748b;
|
||||
font-size: 28rpx;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* OA / 市场附件:小程序宿主预览页的 query 与 openDocument 类型
|
||||
*/
|
||||
|
||||
import {
|
||||
pickQueryValue,
|
||||
safeDecodeURIComponent
|
||||
} from './oa-pdf-preview-query.js'
|
||||
|
||||
const OPEN_DOCUMENT_EXTS = {
|
||||
pdf: 'pdf',
|
||||
doc: 'doc',
|
||||
docx: 'docx',
|
||||
xls: 'xls',
|
||||
xlsx: 'xlsx',
|
||||
ppt: 'ppt',
|
||||
pptx: 'pptx'
|
||||
}
|
||||
|
||||
export function fileExtension(fileName) {
|
||||
const match = String(fileName || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.match(/\.([a-z0-9]+)$/)
|
||||
return match ? match[1] : ''
|
||||
}
|
||||
|
||||
export function openDocumentFileType(fileName) {
|
||||
const ext = fileExtension(fileName)
|
||||
return OPEN_DOCUMENT_EXTS[ext] || ''
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {{ fileUrl: string, legacyUrl: string, name: string, fileType: string, rawKeys: string[] }}
|
||||
*/
|
||||
export function parseFilePreviewQuery(query) {
|
||||
const rawKeys = Object.keys(query && typeof query === 'object' ? query : {})
|
||||
const fileUrl = safeDecodeURIComponent(
|
||||
pickQueryValue(query, ['fileUrl', 'fileurl', 'file_url', 'f'])
|
||||
)
|
||||
const legacyUrl = safeDecodeURIComponent(
|
||||
pickQueryValue(query, ['url', 'downloadUrl', 'download_url'])
|
||||
)
|
||||
const name =
|
||||
safeDecodeURIComponent(pickQueryValue(query, ['name', 'fileName', 'file_name', 'n'])) ||
|
||||
'file.bin'
|
||||
const fileType =
|
||||
safeDecodeURIComponent(pickQueryValue(query, ['fileType', 'file_type', 't'])) ||
|
||||
openDocumentFileType(name)
|
||||
return { fileUrl, legacyUrl, name, fileType, rawKeys }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
openDocumentFileType,
|
||||
parseFilePreviewQuery
|
||||
} from './oa-file-preview.js'
|
||||
|
||||
assert.equal(openDocumentFileType('a.xlsx'), 'xlsx')
|
||||
assert.equal(openDocumentFileType('a.zip'), '')
|
||||
|
||||
const parsed = parseFilePreviewQuery({
|
||||
fileUrl: encodeURIComponent('oa-approval/202610/abc.xlsx'),
|
||||
n: 'file.xlsx'
|
||||
})
|
||||
assert.equal(parsed.fileUrl, 'oa-approval/202610/abc.xlsx')
|
||||
assert.equal(parsed.name, 'file.xlsx')
|
||||
assert.equal(parsed.fileType, 'xlsx')
|
||||
|
||||
const fallback = parseFilePreviewQuery({
|
||||
f: 'oa-approval/x.pdf'
|
||||
})
|
||||
assert.equal(fallback.fileUrl, 'oa-approval/x.pdf')
|
||||
assert.equal(fallback.name, 'file.bin')
|
||||
assert.equal(fallback.fileType, '')
|
||||
|
||||
console.log('oa-file-preview: ok')
|
||||
@@ -0,0 +1,110 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import vm from 'node:vm'
|
||||
import * as Vue from 'vue'
|
||||
import { compile } from '@vue/compiler-dom'
|
||||
import { projectValidation } from './project-assignment.js'
|
||||
|
||||
const source = readFileSync(new URL('../views/market/MarketModuleForm.vue', import.meta.url), 'utf8')
|
||||
// Render the real loop/slot/ref structure; native host nodes need no browser or service.
|
||||
const template = source.slice(source.indexOf('<template v-for="section in leadingSections"'), source.indexOf('\n\n <section'))
|
||||
const render = new Function('Vue', compile(template, { prefixIdentifiers: true }).code)(Vue)
|
||||
const submitSource = source.slice(source.indexOf('async function submit()'), source.indexOf('\nasync function confirmLeave()'))
|
||||
const renderer = Vue.createRenderer({
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
insert(node, parent, anchor = null) {
|
||||
parent.children ||= []
|
||||
node.parent = parent
|
||||
const index = parent.children.indexOf(anchor)
|
||||
parent.children.splice(index < 0 ? parent.children.length : index, 0, node)
|
||||
},
|
||||
remove(node) {
|
||||
const siblings = node.parent?.children || []
|
||||
const index = siblings.indexOf(node)
|
||||
if (index >= 0) siblings.splice(index, 1)
|
||||
},
|
||||
setText() {}, setElementText() {}, patchProp() {},
|
||||
parentNode: (node) => node.parent,
|
||||
nextSibling: (node) => {
|
||||
const siblings = node.parent?.children || []
|
||||
return siblings[siblings.indexOf(node) + 1] || null
|
||||
}
|
||||
})
|
||||
|
||||
async function mountForm({ role, mode = 'create', projectId = 'project-1', loading = false, error = '' }) {
|
||||
const projectAssignment = Vue.ref(null)
|
||||
const formData = Vue.ref({ source: 'research_donation', projectId })
|
||||
const messages = [], requests = []
|
||||
let validations = 0
|
||||
const ProjectAssignmentField = {
|
||||
setup(_, { expose }) {
|
||||
expose({ validate() {
|
||||
validations++
|
||||
return projectValidation({ editing: mode === 'edit', required: true, projectId, loading, error })
|
||||
} })
|
||||
return () => Vue.h('div')
|
||||
}
|
||||
}
|
||||
const Section = { setup: (_, { slots }) => () => slots.insert?.() }
|
||||
const context = Vue.ref({ module: 'protocol', marketRole: role })
|
||||
const app = renderer.createApp({
|
||||
components: { MarketFormSection: Section, ProjectAssignmentField },
|
||||
setup: () => ({
|
||||
projectAssignment, context, formData, mode,
|
||||
leadingSections: [{ key: 'customer' }, { key: 'protocol' }],
|
||||
formOptions: {}, fieldsLocked: false, dirty: false,
|
||||
sectionValue: () => ({}), searchProtocolCustomers() {}, setSectionValue() {},
|
||||
uploadField() {}, handleFieldChange() {}, handleCustomerSelect() {}
|
||||
}), render
|
||||
})
|
||||
app.mount({})
|
||||
await Vue.nextTick()
|
||||
const scope = {
|
||||
projectAssignment, context, formData, mode: Vue.ref(mode),
|
||||
submitting: Vue.ref(false), uploadPending: Vue.ref(0), isProtocolV2: Vue.ref(false),
|
||||
isProtocolV1: Vue.ref(false), id: Vue.ref(mode === 'edit' ? 'record-1' : ''),
|
||||
action: Vue.ref(mode), visibleSections: Vue.ref([]), dirty: Vue.ref(true),
|
||||
showToast: (text) => messages.push(text), showSuccessToast: (text) => messages.push(text),
|
||||
validateRequiredFields: () => '', buildMarketActionPayload: (_module, _action, data) => data,
|
||||
sanitizeMarketPayload: (data) => data, buildPayload: () => formData.value,
|
||||
AbortController, submitController: null, allowLeave: false,
|
||||
saveMarketRecord: async (...args) => { requests.push(args); return { id: 'saved' } },
|
||||
mountGuard: { isCurrent: () => true }, mountToken: 1,
|
||||
resolveMarketSavedDetailId: () => 'saved', router: { replace: async () => {} },
|
||||
route: { query: {} }, marketRecordNavigationQuery: () => ({}),
|
||||
marketErrorMessage: (cause) => cause.message
|
||||
}
|
||||
const submit = vm.runInNewContext(`${submitSource}\nsubmit`, scope)
|
||||
return { submit, messages, requests, app, validations: () => validations }
|
||||
}
|
||||
|
||||
for (const role of ['specialist', 'manager']) {
|
||||
for (const mode of ['create', 'edit']) {
|
||||
test(`${role} ${mode}: a valid project reaches the save request`, async () => {
|
||||
const form = await mountForm({ role, mode })
|
||||
try {
|
||||
await form.submit()
|
||||
assert.equal(form.validations(), 1)
|
||||
assert.equal(form.requests.length, 1)
|
||||
assert.equal(form.requests[0][0].marketRole, role)
|
||||
assert.deepEqual(form.messages, ['保存成功'])
|
||||
} finally { form.app.unmount() }
|
||||
})
|
||||
}
|
||||
for (const [state, message] of [
|
||||
[{ projectId: '' }, '请选择所属项目'],
|
||||
[{ loading: true }, '项目选项加载中,请稍后保存'],
|
||||
[{ error: 'network' }, '项目选项加载失败,请重试后保存']
|
||||
]) {
|
||||
test(`${role}: ${message}`, async () => {
|
||||
const form = await mountForm({ role, ...state })
|
||||
try {
|
||||
await form.submit()
|
||||
assert.equal(form.validations(), 1)
|
||||
assert.equal(form.requests.length, 0)
|
||||
assert.deepEqual(form.messages, [message])
|
||||
} finally { form.app.unmount() }
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
/** 附件下载:优先后端预签名 URL,保证跨域场景保留原始文件名 */
|
||||
/** 附件下载:小程序 WebView 走宿主原生页;其它环境用预签名 URL 打开 */
|
||||
|
||||
import { fetchAttachmentDownloadUrl } from '../api/oa.js'
|
||||
import { attachmentFullUrl } from './attachment.js'
|
||||
import {
|
||||
isWeChatMiniWebView,
|
||||
navigateToHostFilePreview
|
||||
} from './host-file-preview-nav.js'
|
||||
|
||||
function openDownloadUrl(href, fileName) {
|
||||
// 微信 web-view 对 a[download] 支持差;优先新开页打开带 Content-Disposition 的地址
|
||||
@@ -17,13 +21,19 @@ function openDownloadUrl(href, fileName) {
|
||||
document.body.removeChild(a)
|
||||
}
|
||||
|
||||
async function openViaHostPreview(fileUrl, fileName, deps = {}) {
|
||||
const navigate = deps.navigateToHostFilePreview || navigateToHostFilePreview
|
||||
const detectMini = deps.isWeChatMiniWebView || isWeChatMiniWebView
|
||||
if (!detectMini(deps.window)) return false
|
||||
const nav = await navigate({ fileUrl, fileName }, { window: deps.window })
|
||||
if (nav && nav.ok) return true
|
||||
throw new Error((nav && nav.message) || '无法打开附件预览页')
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ fileUrl?: string, url?: string, fileName?: string, name?: string }} file
|
||||
*/
|
||||
export async function downloadAttachmentFile(
|
||||
file,
|
||||
options = {}
|
||||
) {
|
||||
export async function downloadAttachmentFile(file, options = {}) {
|
||||
const hasAuthorizedResolver = typeof options.fetchDownloadUrl === 'function'
|
||||
const fetchDownloadUrl = options.fetchDownloadUrl || fetchAttachmentDownloadUrl
|
||||
const fileUrl = String(file?.fileUrl || file?.url || '').trim()
|
||||
@@ -31,6 +41,10 @@ export async function downloadAttachmentFile(
|
||||
const explicitFileName = String(file?.fileName || file?.name || '').trim()
|
||||
const fallbackFileName = explicitFileName || fileUrl.split('/').pop() || 'download'
|
||||
|
||||
// 小程序 WebView(含鸿蒙):跳转宿主 downloadFile + openDocument,避免 window.open 静默失败
|
||||
const openedOnHost = await openViaHostPreview(fileUrl, fallbackFileName, options)
|
||||
if (openedOnHost) return
|
||||
|
||||
try {
|
||||
const res = await fetchDownloadUrl({
|
||||
fileUrl,
|
||||
|
||||
@@ -18,6 +18,7 @@ test('uses an injected authorized resolver before opening the signed download ur
|
||||
await downloadAttachmentFile(
|
||||
{ fileUrl: 'market/specialist/protocol/a.png', fileName: '协议扫描件.png' },
|
||||
{
|
||||
isWeChatMiniWebView: () => false,
|
||||
fetchDownloadUrl: async (payload) => {
|
||||
requested = payload
|
||||
return { downloadUrl: 'https://files.test/signed-download' }
|
||||
@@ -52,6 +53,7 @@ test('never falls back to the raw object url when an authorized resolver rejects
|
||||
downloadAttachmentFile(
|
||||
{ fileUrl: 'https://files.test/private.pdf', fileName: '私密附件.pdf' },
|
||||
{
|
||||
isWeChatMiniWebView: () => false,
|
||||
fetchDownloadUrl: async () => {
|
||||
throw new Error('附件不存在或无权下载')
|
||||
}
|
||||
@@ -65,3 +67,54 @@ test('never falls back to the raw object url when an authorized resolver rejects
|
||||
|
||||
assert.deepEqual(opened, [])
|
||||
})
|
||||
|
||||
test('mini program webview navigates to host file preview instead of window.open', async () => {
|
||||
const originalWindow = globalThis.window
|
||||
const opened = []
|
||||
const navCalls = []
|
||||
globalThis.window = {
|
||||
open(href) {
|
||||
opened.push(href)
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await downloadAttachmentFile(
|
||||
{ fileUrl: 'oa-approval/202610/task.xlsx', fileName: '生产任务.xlsx' },
|
||||
{
|
||||
isWeChatMiniWebView: () => true,
|
||||
navigateToHostFilePreview: async (payload) => {
|
||||
navCalls.push(payload)
|
||||
return { ok: true, via: 'test' }
|
||||
},
|
||||
fetchDownloadUrl: async () => {
|
||||
throw new Error('should not fetch download-url in mini path')
|
||||
}
|
||||
}
|
||||
)
|
||||
} finally {
|
||||
globalThis.window = originalWindow
|
||||
}
|
||||
|
||||
assert.deepEqual(navCalls, [
|
||||
{ fileUrl: 'oa-approval/202610/task.xlsx', fileName: '生产任务.xlsx' }
|
||||
])
|
||||
assert.deepEqual(opened, [])
|
||||
})
|
||||
|
||||
test('mini program navigate failure surfaces as download error', async () => {
|
||||
await assert.rejects(
|
||||
downloadAttachmentFile(
|
||||
{ fileUrl: 'oa-approval/x.xlsx', fileName: 'x.xlsx' },
|
||||
{
|
||||
isWeChatMiniWebView: () => true,
|
||||
navigateToHostFilePreview: async () => ({
|
||||
ok: false,
|
||||
message: '无法跳转附件预览页'
|
||||
})
|
||||
}
|
||||
),
|
||||
/无法跳转附件预览页/
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* 微信 web-view → 小程序附件预览/下载页
|
||||
* 对齐 OA 打印 PDF 的宿主跳转;避免 H5 window.open 在鸿蒙 ArkWeb 静默失败。
|
||||
*/
|
||||
|
||||
import {
|
||||
getOaPrintHostApis,
|
||||
isWeChatMiniWebView,
|
||||
printNavLog
|
||||
} from '../oa/print/oa-pdf-preview-nav.js'
|
||||
|
||||
const OPEN_DOCUMENT_EXTS = new Set([
|
||||
'pdf',
|
||||
'doc',
|
||||
'docx',
|
||||
'xls',
|
||||
'xlsx',
|
||||
'ppt',
|
||||
'pptx'
|
||||
])
|
||||
|
||||
export function fileExtension(fileName) {
|
||||
const match = String(fileName || '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.match(/\.([a-z0-9]+)$/)
|
||||
return match ? match[1] : ''
|
||||
}
|
||||
|
||||
/** openDocument 支持的类型;其它扩展返回空串 */
|
||||
export function openDocumentFileType(fileName) {
|
||||
const ext = fileExtension(fileName)
|
||||
return OPEN_DOCUMENT_EXTS.has(ext) ? ext : ''
|
||||
}
|
||||
|
||||
/** query 只用 ASCII 名,避免 navigateTo 被中文撑爆;扩展名保留供宿主识别类型 */
|
||||
export function asciiHostFileName(fileName) {
|
||||
const ext = fileExtension(fileName) || 'bin'
|
||||
return `file.${ext}`
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {{ path: string, queryLen: number, fileUrlLen: number, name: string, fileType: string }}
|
||||
*/
|
||||
export function buildHostFilePreviewPath({ fileUrl, fileName } = {}) {
|
||||
const key = String(fileUrl || '').trim()
|
||||
const name = asciiHostFileName(fileName)
|
||||
const fileType = openDocumentFileType(name)
|
||||
const q =
|
||||
'fileUrl=' +
|
||||
encodeURIComponent(key) +
|
||||
'&f=' +
|
||||
encodeURIComponent(key) +
|
||||
'&n=' +
|
||||
encodeURIComponent(name)
|
||||
const path = '/pages/oa/file-preview/index?' + q
|
||||
return {
|
||||
path,
|
||||
queryLen: q.length,
|
||||
fileUrlLen: key.length,
|
||||
name,
|
||||
fileType
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<{ ok: boolean, via?: string, path?: string, message?: string, assumed?: boolean }>}
|
||||
*/
|
||||
export function navigateToHostFilePreview({ fileUrl, fileName } = {}, deps = {}) {
|
||||
const { path, queryLen, fileUrlLen, name, fileType } = buildHostFilePreviewPath({
|
||||
fileUrl,
|
||||
fileName
|
||||
})
|
||||
const win =
|
||||
deps.window !== undefined
|
||||
? deps.window
|
||||
: typeof window !== 'undefined'
|
||||
? window
|
||||
: undefined
|
||||
const log = deps.log || printNavLog
|
||||
const { wxApi, uniApi } = getOaPrintHostApis(win)
|
||||
|
||||
log('file-preview navigate start', {
|
||||
fileUrlLen,
|
||||
queryLen,
|
||||
pathLen: path.length,
|
||||
name,
|
||||
fileType,
|
||||
fileUrlPreview: String(fileUrl || '').slice(0, 120),
|
||||
hasWindowWx: !!(win && win.wx),
|
||||
hasWxMiniNavigate: !!(wxApi && wxApi.miniProgram && wxApi.miniProgram.navigateTo),
|
||||
hasUniWebViewNavigate: !!(uniApi && uniApi.webView && uniApi.webView.navigateTo),
|
||||
__wxjs_environment: win && win.__wxjs_environment
|
||||
})
|
||||
|
||||
if (!String(fileUrl || '').trim()) {
|
||||
log('file-preview navigate abort: empty fileUrl')
|
||||
return Promise.resolve({ ok: false, message: '缺少 fileUrl' })
|
||||
}
|
||||
|
||||
if (path.length > 900) {
|
||||
log('file-preview warn path long', { pathLen: path.length })
|
||||
}
|
||||
|
||||
const invokeNavigate = (label, navigateFn) =>
|
||||
new Promise((resolve) => {
|
||||
if (typeof navigateFn !== 'function') {
|
||||
resolve(null)
|
||||
return
|
||||
}
|
||||
let settled = false
|
||||
const done = (result) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
resolve(result)
|
||||
}
|
||||
try {
|
||||
navigateFn({
|
||||
url: path,
|
||||
success: (res) => {
|
||||
log(label + ' success', res)
|
||||
done({ ok: true, via: label, path })
|
||||
},
|
||||
fail: (err) => {
|
||||
log(label + ' fail', err)
|
||||
done({
|
||||
ok: false,
|
||||
via: label,
|
||||
path,
|
||||
message: (err && (err.errMsg || err.message)) || 'navigateTo fail'
|
||||
})
|
||||
}
|
||||
})
|
||||
setTimeout(() => {
|
||||
if (!settled) {
|
||||
log(label + ' no-callback → assume ok', { pathLen: path.length })
|
||||
done({ ok: true, via: label, path, assumed: true })
|
||||
}
|
||||
}, 80)
|
||||
} catch (e) {
|
||||
log(label + ' throw', String(e && e.message ? e.message : e))
|
||||
done({
|
||||
ok: false,
|
||||
via: label,
|
||||
path,
|
||||
message: String(e && e.message ? e.message : e)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return invokeNavigate(
|
||||
'wx.miniProgram.navigateTo',
|
||||
wxApi && wxApi.miniProgram && wxApi.miniProgram.navigateTo
|
||||
? wxApi.miniProgram.navigateTo.bind(wxApi.miniProgram)
|
||||
: null
|
||||
).then((wxRes) => {
|
||||
if (wxRes && wxRes.ok) return wxRes
|
||||
if (wxRes && wxRes.ok === false) {
|
||||
log('file-preview wx failed, try uni', wxRes.message)
|
||||
}
|
||||
return invokeNavigate(
|
||||
'uni.webView.navigateTo',
|
||||
uniApi && uniApi.webView && uniApi.webView.navigateTo
|
||||
? uniApi.webView.navigateTo.bind(uniApi.webView)
|
||||
: null
|
||||
).then((uniRes) => {
|
||||
if (uniRes) return uniRes
|
||||
if (wxRes) return wxRes
|
||||
log('file-preview navigate unavailable')
|
||||
return {
|
||||
ok: false,
|
||||
message: '无法跳转附件预览页:未找到 wx/uni navigateTo'
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export { isWeChatMiniWebView }
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
asciiHostFileName,
|
||||
buildHostFilePreviewPath,
|
||||
openDocumentFileType
|
||||
} from './host-file-preview-nav.js'
|
||||
|
||||
test('ascii host file name keeps extension only', () => {
|
||||
assert.equal(asciiHostFileName('26-10生产任务.xlsx'), 'file.xlsx')
|
||||
assert.equal(asciiHostFileName('report.PDF'), 'file.pdf')
|
||||
assert.equal(asciiHostFileName('plain'), 'file.bin')
|
||||
})
|
||||
|
||||
test('openDocument file types cover office docs', () => {
|
||||
assert.equal(openDocumentFileType('a.xlsx'), 'xlsx')
|
||||
assert.equal(openDocumentFileType('a.XLS'), 'xls')
|
||||
assert.equal(openDocumentFileType('a.docx'), 'docx')
|
||||
assert.equal(openDocumentFileType('a.zip'), '')
|
||||
})
|
||||
|
||||
test('host file preview path is short and points at file-preview page', () => {
|
||||
const built = buildHostFilePreviewPath({
|
||||
fileUrl: 'oa-approval/202610/abc.xlsx',
|
||||
fileName: '26-10生产任务.xlsx'
|
||||
})
|
||||
assert.ok(built.path.startsWith('/pages/oa/file-preview/index?'))
|
||||
assert.ok(built.path.includes('fileUrl='))
|
||||
assert.ok(built.path.includes('&f='))
|
||||
assert.ok(built.path.includes('&n=file.xlsx'))
|
||||
assert.equal(built.fileType, 'xlsx')
|
||||
assert.ok(!built.path.includes('%E7%94%9F'))
|
||||
assert.ok(built.queryLen < 400)
|
||||
assert.ok(built.path.length < 500)
|
||||
})
|
||||
@@ -46,7 +46,7 @@
|
||||
>
|
||||
<template #insert>
|
||||
<ProjectAssignmentField
|
||||
ref="projectAssignment"
|
||||
:ref="(instance) => (projectAssignment = instance)"
|
||||
embedded
|
||||
v-model="formData.projectId"
|
||||
:biz-type="formData.source"
|
||||
|
||||
Reference in new issue
Block a user