DigitalInvoiceUploadComponent.vue 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. <!--文件上传组件-->
  2. <template>
  3. <div :key="uploadKey">
  4. <el-divider v-if="showDivider" content-position="left"><i class="el-icon-document"></i> {{dividerName}}
  5. <el-upload ref="upload" style="display: inline-block; :show-header='status'" action=""
  6. :limit="999" :http-request="httpRequest"
  7. multiple
  8. :on-exceed="(files, fileList) =>{
  9. $message.warning(`当前限制选择 999 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
  10. }"
  11. :show-file-list="false"
  12. :before-upload="beforeUpload"
  13. :on-change="changes"
  14. :on-progress="uploadVideoProcess"
  15. :file-list="fileList">
  16. <template v-if="auth==='view'&&uploadFlag===false" #tip>
  17. <el-button :loading="loading" type="primary" size="default" :disabled="true"> 点击上传 </el-button>
  18. </template>
  19. <template v-else #trigger>
  20. <el-button :loading="loading" type="primary" size="default"> 点击上传 </el-button> <span style="margin-left: 20px;font-size:14px;font-weight:normal;color:red;" type="primary"> 上传报销的数电发票xml文件</span>
  21. </template>
  22. </el-upload>
  23. </el-divider>
  24. <div style="height: calc(100% - 80px);margin-top: 10px">
  25. <!-- 进度条 -->
  26. <el-progress style="margin-left: 5em" v-if="progressFlag" :percentage="loadProgress"></el-progress>
  27. <el-table
  28. ref="uploadTable"
  29. v-loading="loading"
  30. :key="tableKey"
  31. :summary-method="getSummaries"
  32. show-summary
  33. :data="dataListNew">
  34. <!-- <el-table-column type="seq" width="40"></el-table-column>-->
  35. <el-table-column label="文件名称" prop="name" align="center" width="290">
  36. <template #default="scope">
  37. <div v-if="ifName(scope.row) === true">
  38. <el-image
  39. style="width: 30px; height: 30px;padding-top: 4px;"
  40. :src="scope.row.lsUrl"
  41. :preview-src-list="[scope.row.lsUrl]"
  42. :preview-teleported="true"
  43. ></el-image>
  44. </div>
  45. <div v-else>
  46. <el-link type="primary" :underline="false" @click="showFile(scope.row)">{{scope.row.name}}</el-link>
  47. </div>
  48. </template>
  49. </el-table-column>
  50. <el-table-column label="创建人" prop="createBy.name" align="center"></el-table-column>
  51. <el-table-column label="创建时间" prop="createTime" align="center" width="110"></el-table-column>
  52. <el-table-column label="文件大小" prop="size" align="center">
  53. <template #default="scope">
  54. {{getSize(scope.row.size)}}
  55. </template>
  56. </el-table-column>
  57. <el-table-column prop="invoiceType" label="发票类型" align="center" show-overflow="title">
  58. <template #default="scope">
  59. {{
  60. $dictUtils.getDictLabel(
  61. "invoice_reimbursement_type",
  62. scope.row.invoiceType,
  63. "-"
  64. )
  65. }}
  66. </template>
  67. </el-table-column>
  68. <el-table-column prop="invoiceProjectName" label="发票项目名" align="center" width="150" :edit-render="{}" show-overflow="title">
  69. <template #edit="scope">
  70. <el-input maxlength="50" readonly="true" v-model="scope.row.invoiceProjectName" ></el-input>
  71. </template>
  72. </el-table-column >
  73. <el-table-column prop="number" label="发票号" align="center" width="150" :edit-render="{}" show-overflow="title">
  74. <template #edit="scope">
  75. <el-input oninput ="value=value.replace(/\D|^/g,'')" readonly="true" maxlength="30" @change="isExict(scope.row)" v-model="scope.row.number" ></el-input>
  76. </template>
  77. </el-table-column >
  78. <el-table-column prop="invoiceDate" label="开票日期" align="center" width="110" :edit-render="{}" show-overflow="title">
  79. <template v-slot:edit="scope">
  80. <el-input v-model="scope.row.invoiceDate" readonly="true" type="date" transfer placeholder="请选择日期"></el-input>
  81. </template>
  82. </el-table-column >
  83. <el-table-column prop="invoiceUnit" label="开票单位" align="center" width="200" :edit-render="{}" show-overflow="title">
  84. <template #edit="scope">
  85. <el-input maxlength="50" readonly="true" v-model="scope.row.invoiceUnit" ></el-input>
  86. </template>
  87. </el-table-column >
  88. <el-table-column prop="buyerName" label="购买方名称" align="center" width="200" :edit-render="{}" show-overflow="title">
  89. <template #edit="scope">
  90. <el-input maxlength="50" readonly="true" v-model="scope.row.buyerName" ></el-input>
  91. </template>
  92. </el-table-column >
  93. <el-table-column prop="amount" label="金额" align="center" width="120" :edit-render="{}" show-overflow="title">
  94. <template #edit="scope">
  95. <el-input maxlength="15" readonly="true" v-model="scope.row.amount" @input="scope.row.amount = twoDecimalPlaces(scope.row.amount)" @change="countAmount(scope.row)"></el-input>
  96. </template>
  97. </el-table-column >
  98. <el-table-column prop="taxAmount" label="税额" align="center" width="120" :edit-render="{}" show-overflow="title">
  99. <template #edit="scope">
  100. <el-input maxlength="15" readonly="true" v-model="scope.row.taxAmount" @input="scope.row.taxAmount = twoDecimalPlaces(scope.row.taxAmount)" @change="countAmount(scope.row)"></el-input>
  101. </template>
  102. </el-table-column >
  103. <el-table-column prop="count" label="价税合计" align="center" width="120" :edit-render="{}" show-overflow="title">
  104. <template #edit="scope">
  105. <el-input disabled="true" v-model="scope.row.count" ></el-input>
  106. </template>
  107. </el-table-column >
  108. <el-table-column label="操作" width="200px" fixed="right" align="center">
  109. <template #default="scope">
  110. <el-button text type="primary" key="01" icon="el-icon-download" size="small" @click="toHref(scope.row)" >下载</el-button>
  111. <el-button text type="primary" key="02" icon="el-icon-delete" size="small" @click="deleteFileById(scope.row, scope.$index,this.dataListNew)" :disabled="auth==='view'&&delFlag === false&&createBy!==scope.row.createBy.name">删除</el-button>
  112. </template>
  113. </el-table-column>
  114. </el-table>
  115. </div>
  116. <!-- <el-image-viewer v-if="showViewer" :on-close="closeViewer" :url-list="[url]" :zIndex=9999></el-image-viewer>-->
  117. </div>
  118. </template>
  119. <script>
  120. // eslint-disable-next-line no-unused-vars
  121. import OSSSerivce, {
  122. httpRequest,
  123. // eslint-disable-next-line no-unused-vars
  124. handleRemove,
  125. fileNameInvoice,
  126. // eslint-disable-next-line no-unused-vars
  127. beforeAvatarUpload,
  128. exnameFix,
  129. // eslint-disable-next-line no-unused-vars
  130. openWindowOnUrl,
  131. // eslint-disable-next-line no-unused-vars
  132. toHref
  133. } from '@/api/sys/OSSService'
  134. // import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
  135. import moment from 'moment'
  136. export default {
  137. data () {
  138. return {
  139. uploadKey: '',
  140. progressFlag: false,
  141. loadProgress: 0,
  142. fileList: [],
  143. dataList: [],
  144. oldDataList: [],
  145. dataListNew: [],
  146. url: '',
  147. showViewer: false,
  148. ossService: null,
  149. auth: '',
  150. directory: 'public',
  151. maxValue: 300,
  152. tableKey: '',
  153. fileLoading: true,
  154. dividerName: '',
  155. uploadFlag: false,
  156. delFlag: false,
  157. createBy: '',
  158. showDivider: true,
  159. loading: false,
  160. dataListLength: '',
  161. uploadDelFlag: false,
  162. uploadingCount: 0, // 记录当前正在上传的文件数量
  163. totalCount: 0, // 记录总的文件数量
  164. duplicateFileNames: [], // 存储重复文件名
  165. noXmlFiles: [], // 存储非当前公司的文件名
  166. // reNumFiles: [], // 存储重复发票号
  167. toCompany:'', //用于区分属于哪个公司的数电发票,
  168. }
  169. },
  170. watch: {
  171. },
  172. created () {
  173. this.ossService = new OSSSerivce()
  174. },
  175. components: {
  176. // ElImageViewer
  177. },
  178. mounted () {
  179. window.onPreview = this.onPreview
  180. },
  181. methods: {
  182. /**
  183. * dividerName: 组件中divider的名称赋值
  184. * showDivider: ‘附件‘Divider是否展示
  185. * 注:值为空时,默认值为true
  186. * showDivider=false时 ‘附件‘Divider隐藏
  187. **/
  188. setDividerName (dividerName, showDivider) {
  189. if (this.commonJS.isNotEmpty(dividerName)) {
  190. this.dividerName = dividerName
  191. }
  192. if (this.commonJS.isNotEmpty(showDivider)) {
  193. if (showDivider === false) {
  194. this.showDivider = false
  195. } else {
  196. this.showDivider = true
  197. }
  198. } else {
  199. this.showDivider = true
  200. }
  201. },
  202. /**
  203. * 文件上传组件初始化
  204. * @param auth
  205. * auth的值为"view"时,不可上传/编辑文件
  206. * auth为其他值时,可上传/编辑文件
  207. * @param fileList 要显示到文件上传列表中的文件。
  208. * 注:文件必须要有url属性并且文件的url属性值必须是在oss中的路径值
  209. * 例:'/attachment-file/xxx/xxx/2022/9/08/xxx.jpg'
  210. * @param directory 要存放到oss的哪个文件夹下。
  211. * 注:值为空时,默认存放到"public"文件夹
  212. * @param maxValue 上传文件允许的最大值,单位:MB
  213. * 注:值为空时,默认值为300MB
  214. * @param dividerName 组件中divider的名称
  215. * 注:值为空时,默认值为‘附件’
  216. * @param uploadFlag ‘上传文件’按钮是否禁用
  217. * 注:值为空时,默认值为false
  218. * auth=view&&uploadFlag=false时 ‘上传文件’按钮禁用
  219. * @param delFlag ‘删除’按钮是否禁用
  220. * 注:值为空时,默认值为false
  221. * auth=view&&delFlag=false时 ‘删除’按钮禁用
  222. * @param showDivider ‘附件‘Divider是否展示
  223. * 注:值为空时,默认值为true
  224. * showDivider=false时 ‘附件‘Divider隐藏
  225. * * @param toCompany ‘动态区分属于那个公司
  226. * 注:值为空时,默认值为 '江苏兴光项目管理有限公司'
  227. *
  228. *
  229. */
  230. async newUpload (auth, fileList, directory, maxValue, dividerName, uploadFlag, delFlag, showDivider,toCompany) {
  231. this.uploadKey = Math.random()
  232. await this.fileLoadingFalse()
  233. if (this.commonJS.isEmpty(fileList)) {
  234. fileList = []
  235. this.fileLoading = true
  236. } else {
  237. this.dataListLength = fileList.length
  238. }
  239. if (this.commonJS.isEmpty(dividerName)) {
  240. this.dividerName = '数电发票信息'
  241. } else {
  242. this.dividerName = dividerName
  243. }
  244. if (this.commonJS.isEmpty(toCompany)) {
  245. this.toCompany = '江苏兴光会计师事务所有限责任公司'
  246. } else {
  247. //对公司名中的括号进行转化,便于与附件中的公司名进行比较
  248. toCompany = toCompany
  249. .replace(/(/g, '(')
  250. .replace(/)/g, ')');
  251. this.toCompany = toCompany
  252. }
  253. if (directory !== undefined && directory !== null && directory !== '' && directory !== {}) {
  254. this.directory = directory
  255. } else {
  256. this.directory = 'public'
  257. }
  258. if (maxValue !== undefined && maxValue !== null && maxValue !== '' && maxValue !== 0) {
  259. this.maxValue = maxValue
  260. } else {
  261. this.maxValue = 300
  262. }
  263. this.auth = auth
  264. if (this.commonJS.isEmpty(uploadFlag)) {
  265. this.uploadFlag = false
  266. } else {
  267. if (uploadFlag !== true && uploadFlag !== false) {
  268. this.uploadFlag = false
  269. } else {
  270. this.uploadFlag = uploadFlag
  271. }
  272. }
  273. if (this.commonJS.isEmpty(delFlag)) {
  274. this.delFlag = false
  275. } else {
  276. if (delFlag !== true && delFlag !== false) {
  277. this.delFlag = false
  278. this.createBy = delFlag
  279. } else {
  280. this.delFlag = delFlag
  281. }
  282. }
  283. this.oldDataList = []
  284. for await (let item of fileList) {
  285. await this.ossService.getFileSizeByUrl(item.url).then((data) => {
  286. item.lsUrl = data.url
  287. item.size = data.size
  288. this.dataList.push(item)
  289. this.oldDataList.push(item)
  290. this.dataListNew.push(item)
  291. if (this.dataListNew.length === fileList.length) {
  292. this.fileLoading = true
  293. }
  294. })
  295. }
  296. // this.dataList = JSON.parse(JSON.stringify(fileList))
  297. // this.dataListNew = JSON.parse(JSON.stringify(fileList))
  298. if (this.commonJS.isEmpty(showDivider)) {
  299. this.showDivider = true
  300. } else {
  301. if (showDivider === false) {
  302. this.showDivider = false
  303. } else {
  304. this.showDivider = true
  305. }
  306. }
  307. },
  308. async httpRequest (file) {
  309. await httpRequest(file, fileNameInvoice(file), this.directory, this.maxValue)
  310. },
  311. async beforeUpload(file) {
  312. if(this.uploadDelFlag){
  313. this.$message.warning('该文件已上传,请勿重复上传');
  314. this.uploadKey = Math.random()
  315. return false; // 取消上传
  316. }else{
  317. // 对文件进行判定
  318. const isXml = file.type === 'text/xml'; // 假设只接受 XML 文件
  319. if (!isXml) {
  320. this.$message.error('只能上传 XML 文件');
  321. return false; // 取消上传
  322. }else{
  323. try {
  324. //对上传的xml文件信息进行处理并通过后端接口进行解析返回到父页面进行调整
  325. const formBody = new FormData()
  326. formBody.append('file', file)
  327. await this.ossService.disposeXmlFile(formBody).then((data) => {
  328. if(JSON.stringify(data) === "{}"){
  329. this.$message.warning('数电发票:'+file.name+'格式错误');
  330. this.loading = false;
  331. // 在验证失败时删除已经添加的行
  332. const index = this.fileList.findIndex(item => item.name === file.name);
  333. if (index !== -1) {
  334. this.deleteFileById(this.fileList[index], index, this.fileList);
  335. }
  336. }
  337. })
  338. } catch (error) {
  339. console.error(error);
  340. }
  341. }
  342. // 其他判定逻辑...
  343. return true; // 允许上传
  344. }
  345. },
  346. uploadVideoProcess (event, file, fileList) {
  347. this.progressFlag = true // 显示进度条
  348. this.loadProgress = parseInt(event.percent) // 动态获取文件上传进度
  349. if (this.loadProgress >= 100) {
  350. this.loadProgress = 100
  351. // var fileName = file.raw.name;
  352. //
  353. // const spliceLength2 = fileName.lastIndexOf(".");
  354. // var fileNameSuffix = fileName.slice(spliceLength2 + 1);
  355. // let lowerFileNameSuffix = fileNameSuffix.toLowerCase();
  356. // if(lowerFileNameSuffix === "xml" ) {
  357. // //对上传的xml文件信息进行处理并通过后端接口进行解析返回到父页面进行调整
  358. // const formBody = new FormData()
  359. // formBody.append('file', file.raw)
  360. // this.ossService.disposeXmlFile(formBody).then((data) => {
  361. // if(Object.keys(data).length > 0){
  362. // this.invoiceReimbursementDisposeData(data,file)
  363. // } else{
  364. // this.$message.warning('上传的数电发票格式错误')
  365. // this.loading = false;
  366. // // 在验证失败时删除已经添加的行
  367. // const index = this.fileList.findIndex(item => item.name === file.name);
  368. // if (index !== -1) {
  369. // this.deleteFileById(this.fileList[index], index, this.fileList);
  370. // }
  371. // }
  372. // })
  373. // }
  374. setTimeout(() => {
  375. this.progressFlag = false
  376. }, 1000) // 一秒后关闭进度条
  377. }
  378. },
  379. invoiceReimbursementDisposeData: function (data,file) {
  380. var invoiceReimbursements = this.dataListNew;
  381. //创建判断值,若行信息存在相同的发票号,则进行数据检查调整,若不存在发票号,则新增行,并将信息写入
  382. var includeFlag = false;
  383. if(!invoiceReimbursements) {
  384. invoiceReimbursements = [];
  385. }
  386. if(this.toCompany === data.BuyerInformationBuyerName){
  387. invoiceReimbursements.forEach(item => {
  388. if (file.name === item.name){
  389. item.invoiceType = data.InherentLabelGeneralOrSpecialVATLabelCode;
  390. item.invoiceProjectName = data.IssuItemInformationItemName;
  391. item.number = data.InvoiceNumber;
  392. item.invoiceDate = this.formatDate(data.IssueTime);
  393. item.invoiceUnit = data.SellerInformationSellerName;
  394. item.amount = data.BasicInformationTotalAmWithoutTax;
  395. item.taxAmount = data.BasicInformationTotalTaxAm;
  396. item.count = data.BasicInformationTotalTaxincludedAmount;
  397. item.buyerName = data.BuyerInformationBuyerName;
  398. }
  399. })
  400. }
  401. },
  402. formatDate(date) {
  403. // 正则表达式匹配 "xxx年x月x日" 格式的日期
  404. const regex = /(\d{4})年(\d{1,2})月(\d{1,2})日/;
  405. const matches = date.match(regex);
  406. const parts = date.split('/');
  407. if (matches) {
  408. const year = matches[1]; // 年
  409. const month = String(matches[2]).padStart(2, '0'); // 月,确保是两位数
  410. const day = String(matches[3]).padStart(2, '0'); // 日,确保是两位数
  411. return `${year}-${month}-${day}`; // 返回 yyyy-mm-dd 格式的日期
  412. } else if(parts.length === 3){
  413. const year = parts[0]; // 年份
  414. const month = String(parts[1]).padStart(2, '0'); // 月,确保是两位数
  415. const day = String(parts[2]).padStart(2, '0'); // 日,确保是两位数
  416. return `${year}-${month}-${day}`; // 返回 yyyy-mm-dd 格式的日期
  417. } else {
  418. const d = new Date(date);
  419. const year = d.getFullYear();
  420. const month = String(d.getMonth() + 1).padStart(2, '0'); // 获取月份并确保是两位数
  421. const day = String(d.getDate()).padStart(2, '0'); // 获取日期并确保是两位数
  422. return `${year}-${month}-${day}`;
  423. }
  424. },
  425. getSize (value) {
  426. if (this.commonJS.isEmpty(value)) {
  427. return '0 B'
  428. } else {
  429. let val = parseInt(value)
  430. if (this.commonJS.isEmpty(val)) {
  431. return '0 B'
  432. }
  433. if (isNaN(val)) {
  434. return '0 B'
  435. }
  436. if (val === 0) {
  437. return '0 B'
  438. }
  439. let k = 1024
  440. let sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB']
  441. let i = Math.floor(Math.log(val) / Math.log(k))
  442. let result = val / Math.pow(k, i);
  443. let kb = parseFloat(result.toPrecision(3));
  444. return kb + '' + sizes[i]
  445. }
  446. },
  447. async changes(file, fileList) {
  448. this.uploadKey = Math.random();
  449. // 用来存放没有重复且有有效URL的文件,准备上传
  450. let filesToUpload = [];
  451. let validFiles = [];
  452. // 用于存储已经上传的文件 `lastModified` + `size` 作为唯一标识
  453. let uploadedFileIdentifiers = new Set();
  454. for (let existingFile of this.dataListNew) {
  455. const existingFileName = existingFile.name; // 假设每个文件有 `name` 属性
  456. uploadedFileIdentifiers.add(existingFileName); // 将已有文件的名称添加到 Set 中
  457. }
  458. // 2. 文件大小检查
  459. if (!beforeAvatarUpload(file, fileList, this.maxValue)) {
  460. this.$message.error('文件大小不能超过 ' + this.maxValue + ' MB!');
  461. return;
  462. }
  463. // 3. 验证文件是否重复(使用 `lastModified` 和 `size` 来判断)
  464. for (let item of fileList) {
  465. const fileName = item.raw ? item.raw.name : item.name;
  466. const fileIdentifier = fileName; // 唯一标识:文件大小 + 修改时间
  467. // 检查该文件标识是否已存在
  468. if (uploadedFileIdentifiers.has(fileIdentifier)) {
  469. // 记录重复文件名
  470. const formBody = new FormData();
  471. formBody.append('file', item.raw);
  472. const data = await this.ossService.disposeXmlFile(formBody);
  473. if (this.commonJS.isNotEmpty(data.InvoiceNumber)){
  474. this.duplicateFileNames.push("文件名: "+fileName +"—— 发票号:"+data.InvoiceNumber);
  475. console.log('222',data.InvoiceNumber)
  476. console.log('this.duplicateFileNames',this.duplicateFileNames)
  477. }
  478. } else {
  479. // 文件没有重复,加入上传列表
  480. filesToUpload.push(item);
  481. uploadedFileIdentifiers.add(fileIdentifier); // 将文件标识加入已上传集合
  482. }
  483. }
  484. // 4. 如果没有文件需要上传,则直接返回
  485. // if (filesToUpload.length === 0) return;
  486. // 5. 删除无效URL的文件
  487. let invalidFiles = []; // 用于存储需要删除的文件
  488. // 使用异步操作来判断文件URL的有效性
  489. for (let item of filesToUpload) {
  490. const fileUrl = item.raw ? item.raw.url : item.url;
  491. // 检查临时 URL 是否有效
  492. if (fileUrl && fileUrl.trim() !== '') {
  493. try {
  494. const temporaryUrl = await this.ossService.getTemporaryUrl(fileUrl);
  495. if (!temporaryUrl || temporaryUrl.trim() === '') {
  496. // 如果临时 URL 无效,则标记该文件为无效并删除
  497. invalidFiles.push(item);
  498. } else {
  499. // 如果临时 URL 有效,继续添加文件到有效文件列表
  500. validFiles.push(item);
  501. item.lsUrl = temporaryUrl;
  502. }
  503. } catch (error) {
  504. // 如果临时 URL 获取失败,也标记该文件为无效
  505. invalidFiles.push(item);
  506. }
  507. }
  508. }
  509. filesToUpload = validFiles; // 只保留有效的文件
  510. // 6. 给文件添加上传时间和上传人
  511. for (let item of filesToUpload) {
  512. item.createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
  513. item.createBy = {
  514. id: this.$store.state.user.id,
  515. name: this.$store.state.user.name,
  516. };
  517. }
  518. const validCompanyFiles = [];//存放符合公司的文件
  519. let errorFiles = [];//存放数据格式错误的文件
  520. let errorDateFiles = [];//存放日期格式错误的文件
  521. let isUsedFiles = [];//存放已经被报销的文件
  522. for (let i = 0; i < filesToUpload.length; i++) {
  523. const item = filesToUpload[i];
  524. if (item.raw !== undefined && item.raw !== null && item.raw !== {}) {
  525. // 设置文件的 URL
  526. item.url = item.raw.url;
  527. // 仅处理 XML 文件
  528. if (item.raw.name && item.raw.name.toLowerCase().endsWith(".xml")) {
  529. // 创建 FormData 对象并发送文件
  530. const formBody = new FormData();
  531. formBody.append('file', item.raw);
  532. // 调用后端接口解析 XML 文件
  533. const data = await this.ossService.disposeXmlFile(formBody);
  534. if (Object.keys(data).length > 0) {
  535. // 如果文件的公司名称与this.toCompany不一致,则删除该文件
  536. // 检查 data 是否包含 BuyerInformationBuyerName 属性
  537. if (data && 'BuyerInformationBuyerName' in data) {
  538. // 验证是否有效,并进行替换操作
  539. if (typeof data.BuyerInformationBuyerName === 'string') {
  540. var buyerInformationBuyerName = data.BuyerInformationBuyerName
  541. .replace(/(/g, '(')
  542. .replace(/)/g, ')');
  543. data.BuyerInformationBuyerName = buyerInformationBuyerName
  544. }
  545. }
  546. if (this.toCompany !== data.BuyerInformationBuyerName) {
  547. this.noXmlFiles.push("文件名: "+item.raw.name +"—— 发票号:"+data.InvoiceNumber)
  548. // this.$message.warning("仅可上传江苏兴光项目管理有限公司的报销数电发票");
  549. continue;
  550. }
  551. if (this.commonJS.isNotEmpty(data.InvoiceNumber)){
  552. var flag = this.invoiceReimbursementDispose(data)
  553. if (flag){
  554. this.duplicateFileNames.push(item.raw.name +"-"+data.InvoiceNumber)
  555. continue;
  556. }
  557. //查询当前发票号是否已经被报销
  558. let isUsed = await this.ossService.isUsedByInvoiceNumber(data.InvoiceNumber);
  559. if (isUsed){
  560. isUsedFiles.push("文件名: "+item.raw.name +"—— 发票号:"+data.InvoiceNumber)
  561. continue;
  562. }
  563. let inDate = this.formatDate(data.IssueTime)
  564. if (inDate.indexOf("NaN") != -1 && this.commonJS.isNotEmpty(inDate)){
  565. errorDateFiles.push("文件名: "+item.raw.name +"—— 发票号:"+data.InvoiceNumber);
  566. continue;
  567. }
  568. validCompanyFiles.push(item); // 符合条件的文件
  569. }
  570. }
  571. }
  572. }
  573. }
  574. filesToUpload = validCompanyFiles;
  575. // 将新符合条件的文件追加到原文件列表上
  576. this.dataListNew = [...this.dataList, ...filesToUpload];
  577. this.fileList = [...filesToUpload];
  578. // 记录上传文件的数量
  579. this.totalCount = fileList.length;
  580. //记录changes方法执行了多少次,此处加判定是为了处理防抖,change方法会对每一个文件执行两次,此处判定后只会增加一次
  581. if (file.status !== 'ready'){
  582. this.uploadingCount++
  583. }
  584. // 9. 检查是否是最后一个文件上传,如果是,执行一次去重和提示
  585. if (this.uploadingCount === this.totalCount) {
  586. this.duplicateFileNames = [...new Set(this.duplicateFileNames)];
  587. this.noXmlFiles = [...new Set(this.noXmlFiles)];
  588. // this.reNumFiles = [...new Set(this.reNumFiles)];
  589. errorFiles = [...new Set(errorFiles)];
  590. invalidFiles = [...new Set(invalidFiles)];
  591. errorDateFiles = [...new Set(errorDateFiles)];
  592. isUsedFiles = [...new Set(isUsedFiles)];
  593. // 提示重复文件
  594. if (this.duplicateFileNames.length > 0) {
  595. this.$message.warning({message:`以下文件已经上传,请勿重复上传:<br>${this.duplicateFileNames.join('<br>')} `,dangerouslyUseHTMLString: true});
  596. }
  597. // 提示xml文件不是当前公司报销的文件
  598. if (this.noXmlFiles.length > 0) {
  599. this.$message.warning({message:`仅可上传${this.toCompany}的报销数电发票:<br>${this.noXmlFiles.join('<br>')}<br>上传失败 `,dangerouslyUseHTMLString: true});
  600. }
  601. // 提示发票号重复文件
  602. // if (this.reNumFiles.length > 0) {
  603. // this.$message.error(`发票号:\n${this.reNumFiles.join('\n')}已上传,请勿重复上传`);
  604. // }
  605. //数电发票格式错误的文件
  606. if (errorFiles.length > 0){
  607. this.$message.warning({message:`上传的数电发票格式错误:<br>${errorFiles.join('<br>')}`,dangerouslyUseHTMLString: true});
  608. }
  609. //临时路径错误的文件
  610. if (invalidFiles.length > 0){
  611. this.$message.warning({message:`数电发票: <br>${invalidFiles.join('<br>')}<br>获取失败,上传失败。`,dangerouslyUseHTMLString: true});
  612. }
  613. //临时路径错误的文件
  614. if (errorDateFiles.length > 0){
  615. this.$message.warning({message:`数电发票: <br>${errorDateFiles.join('<br>')}<br>日期格式错误,上传失败。`,dangerouslyUseHTMLString: true});
  616. }
  617. //已经被报销的文件
  618. if (isUsedFiles.length > 0){
  619. this.$message.warning({message:`数电发票: <br>${isUsedFiles.join('<br>')}<br>已经发起或已完成报销,无法重复报销`,dangerouslyUseHTMLString: true});
  620. }
  621. // 重置计数器
  622. this.uploadingCount = 0;
  623. this.totalCount = 0; // 可以根据需求来重置
  624. this.duplicateFileNames = []; // 清空记录
  625. this.noXmlFiles = []; // 清空记录
  626. this.reNumFiles = []; // 清空记录
  627. this.dataList = this.dataListNew
  628. }
  629. // 清空 fileList,如果 fileList 不为空
  630. if (fileList && fileList.length > 0) {
  631. this.fileList = [];
  632. }
  633. // 在 changes 完成后,手动调用 handleUploadSuccess
  634. await this.handleUploadSuccess(null, null, this.fileList); // 传入空参数或实际参数
  635. },
  636. async handleUploadSuccess(response, file, fileList) {
  637. // 遍历当前的数据列表
  638. if (this.dataListNew.length>0){
  639. for (let item of this.dataListNew) {
  640. // 如果 item.raw 存在且有效
  641. if (item.raw !== undefined && item.raw !== null && item.raw !== {}) {
  642. // 设置文件的 URL
  643. item.url = item.raw.url;
  644. // 仅处理 XML 文件
  645. if (item.raw.name && item.raw.name.toLowerCase().endsWith(".xml")) {
  646. // 创建 FormData 对象并发送文件
  647. const formBody = new FormData();
  648. formBody.append('file', item.raw);
  649. try {
  650. // 调用后端接口解析 XML 文件
  651. const data = await this.ossService.disposeXmlFile(formBody);
  652. console.log(data)
  653. // 检查 data 是否包含 BuyerInformationBuyerName 属性
  654. if (data && 'BuyerInformationBuyerName' in data) {
  655. // 验证是否有效,并进行替换操作
  656. if (typeof data.BuyerInformationBuyerName === 'string') {
  657. var buyerInformationBuyerName = data.BuyerInformationBuyerName
  658. .replace(/(/g, '(')
  659. .replace(/)/g, ')');
  660. data.BuyerInformationBuyerName = buyerInformationBuyerName
  661. }
  662. }
  663. if (Object.keys(data).length > 0) {
  664. // 解析成功,更新数据行
  665. await this.invoiceReimbursementDisposeData(data, item);
  666. }
  667. // else {
  668. // // XML 格式错误,删除文件
  669. // this.$message.warning('上传的数电发票格式错误');
  670. // const index = this.fileList.findIndex(f => f.name === item.name);
  671. // if (index !== -1) {
  672. // this.deleteFileById(this.fileList[index], index, this.fileList);
  673. // }
  674. // }
  675. } catch (error) {
  676. this.$message.error('处理 XML 文件失败');
  677. console.log('XML 处理失败', error);
  678. }
  679. }
  680. }
  681. }
  682. // 更新表格数据
  683. this.$nextTick(() => {
  684. this.$forceUpdate(); // 强制更新表格
  685. });
  686. }
  687. },
  688. invoiceReimbursementDispose(data) {
  689. var invoiceReimbursements = this.dataList;
  690. //创建判断值,若行信息存在相同的发票号,则进行数据检查调整,若不存在发票号,则新增行,并将信息写入
  691. var includeFlag = false;
  692. if(!invoiceReimbursements) {
  693. invoiceReimbursements = [];
  694. }
  695. invoiceReimbursements.forEach(item => {
  696. if(item.number === data.InvoiceNumber) {
  697. includeFlag = true;
  698. }
  699. })
  700. return includeFlag;
  701. },
  702. showFile (row) {
  703. openWindowOnUrl(row)
  704. },
  705. onPreview (url) {
  706. this.url = url
  707. this.showViewer = true
  708. },
  709. // 关闭查看器
  710. closeViewer () {
  711. this.url = ''
  712. this.showViewer = false
  713. },
  714. toHref (row) {
  715. toHref(row)
  716. },
  717. async deleteById (row, index,fileList) {
  718. // this.$refs.upload.handleRemove(this.dataListNew[index])
  719. await this.dataListNew.splice(index, 1)
  720. await this.dataList.splice(index, 1)
  721. // if (this.commonJS.isNotEmpty(row.id)) {
  722. // this.ossService.deleteMsgById(row.id)
  723. // }
  724. var newFileList = [];
  725. for (var i = 0; i < fileList.length; i++) {
  726. if (fileList[i].name !== row.name) {
  727. newFileList.push(fileList[i])
  728. }
  729. }
  730. this.fileList = newFileList;
  731. },
  732. deleteFileById (row, index,fileList) {
  733. // this.$refs.upload.handleRemove(this.dataListNew[index])
  734. this.dataListNew.splice(index, 1)
  735. this.dataList = this.dataListNew
  736. // if (this.commonJS.isNotEmpty(row.id)) {
  737. // this.ossService.deleteMsgById(row.id)
  738. // }
  739. // var newFileList = [];
  740. // for (var i = 0; i < this.dataListNew.length; i++) {
  741. // if (this.dataListNew[i].name !== row.name) {
  742. // newFileList.push(this.dataListNew[i])
  743. // }
  744. // }
  745. // this.fileList = newFileList;
  746. // 更新表格数据
  747. this.$nextTick(() => {
  748. this.$forceUpdate(); // 强制更新表格
  749. });
  750. },
  751. /**
  752. * 关闭dialog时使用 清除el-upload中上传的文件
  753. */
  754. clearUpload () {
  755. this.fileList = []//用于清除上传文件的缓存
  756. this.$refs.upload.clearFiles()
  757. this.dataList = []
  758. this.dataListNew = []
  759. this.createBy = ''
  760. },
  761. /**
  762. * 获取当前文件列表中的文件数据
  763. */
  764. getDataList () {
  765. return this.dataListNew
  766. },
  767. /**
  768. * 判断进度条是否结束,附件是否加载完成
  769. * @returns {boolean}
  770. */
  771. checkProgress () {
  772. if (this.progressFlag === true) {
  773. this.$message.warning('请等待附件上传完成再进行操作')
  774. return true
  775. }
  776. if (this.fileLoading === false) {
  777. this.$message.warning('请等待附件加载完成再进行操作')
  778. if (this.dataListLength === this.dataListNew.length) {
  779. this.fileLoading = true
  780. }
  781. return true
  782. }
  783. return false
  784. },
  785. ifName (row) {
  786. if (this.commonJS.isEmpty(row.name)) {
  787. row.name = '---'
  788. return false
  789. }
  790. let suffix = row.name.substring(row.name.lastIndexOf('.') + 1)
  791. if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'bmp' || suffix === 'jpeg') {
  792. return true
  793. } else {
  794. return false
  795. }
  796. },
  797. fileLoadingFalse () {
  798. this.fileLoading = false
  799. },
  800. // 开启/关闭页面的加载中状态
  801. changeLoading (loading) {
  802. if (this.commonJS.isNotEmpty(loading)) {
  803. this.loading = loading
  804. } else {
  805. this.loading = false
  806. }
  807. },
  808. getSummaries(param) {
  809. const { columns, data } = param;
  810. // 初始化汇总数组
  811. const sums = [];
  812. // 遍历列
  813. columns.forEach((column, index) => {
  814. if (index === 0) {
  815. // 第一列(通常是序号列),我们不需要进行汇总,直接设置为“汇总”
  816. sums[index] = '汇总';
  817. }
  818. if (column.property === 'amount'){
  819. // 如果当前列是 'amount',进行汇总
  820. const values = data.map((item) => Number(item[column.property]));
  821. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  822. return prev + curr; // 汇总价税合计列
  823. }, 0));
  824. }
  825. if (column.property === 'taxAmount'){
  826. // 如果当前列是 'amount',进行汇总
  827. const values = data.map((item) => Number(item[column.property]));
  828. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  829. return prev + curr; // 汇总价税合计列
  830. }, 0));
  831. }
  832. if (column.property === 'count'){
  833. // 如果当前列是 'amount',进行汇总
  834. const values = data.map((item) => Number(item[column.property]));
  835. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  836. return prev + curr; // 汇总价税合计列
  837. }, 0));
  838. }
  839. });
  840. return sums;
  841. },
  842. formatNumber(number) {
  843. return number.toFixed(2); // 保留两位小数,返回字符串
  844. },
  845. }
  846. }
  847. </script>
  848. <style scoped lang="scss">
  849. ::v-deep .el-table{
  850. .el-table__footer-wrapper tbody td.el-table__cell, .el-table__header-wrapper tbody td.el-table__cell{
  851. background-color: #fff; /* 设置背景颜色与表格一致 */
  852. }
  853. /* 设置汇总行的背景颜色与表格一致 */
  854. .el-table__footer {
  855. background-color: #fff; /* 设置背景颜色与表格一致 */
  856. }
  857. /* 让第一列的汇总居中 */
  858. .el-table__footer .el-table__cell:nth-child(1) {
  859. text-align: center; /* 让第一列居中 */
  860. font-weight: bold; /* 可以根据需要加粗 */
  861. }
  862. }
  863. .el-divider__text {
  864. font-size: 16px;
  865. font-weight: bold;
  866. }
  867. </style>
  868. <style>
  869. </style>