DigitalInvoiceUploadComponent.vue 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909
  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.dividerName = '江苏兴光项目管理有限公司'
  246. } else {
  247. this.toCompany = toCompany
  248. }
  249. if (directory !== undefined && directory !== null && directory !== '' && directory !== {}) {
  250. this.directory = directory
  251. } else {
  252. this.directory = 'public'
  253. }
  254. if (maxValue !== undefined && maxValue !== null && maxValue !== '' && maxValue !== 0) {
  255. this.maxValue = maxValue
  256. } else {
  257. this.maxValue = 300
  258. }
  259. this.auth = auth
  260. if (this.commonJS.isEmpty(uploadFlag)) {
  261. this.uploadFlag = false
  262. } else {
  263. if (uploadFlag !== true && uploadFlag !== false) {
  264. this.uploadFlag = false
  265. } else {
  266. this.uploadFlag = uploadFlag
  267. }
  268. }
  269. if (this.commonJS.isEmpty(delFlag)) {
  270. this.delFlag = false
  271. } else {
  272. if (delFlag !== true && delFlag !== false) {
  273. this.delFlag = false
  274. this.createBy = delFlag
  275. } else {
  276. this.delFlag = delFlag
  277. }
  278. }
  279. this.oldDataList = []
  280. for await (let item of fileList) {
  281. await this.ossService.getFileSizeByUrl(item.url).then((data) => {
  282. item.lsUrl = data.url
  283. item.size = data.size
  284. this.dataList.push(item)
  285. this.oldDataList.push(item)
  286. this.dataListNew.push(item)
  287. if (this.dataListNew.length === fileList.length) {
  288. this.fileLoading = true
  289. }
  290. })
  291. }
  292. // this.dataList = JSON.parse(JSON.stringify(fileList))
  293. // this.dataListNew = JSON.parse(JSON.stringify(fileList))
  294. if (this.commonJS.isEmpty(showDivider)) {
  295. this.showDivider = true
  296. } else {
  297. if (showDivider === false) {
  298. this.showDivider = false
  299. } else {
  300. this.showDivider = true
  301. }
  302. }
  303. },
  304. async httpRequest (file) {
  305. await httpRequest(file, fileNameInvoice(file), this.directory, this.maxValue)
  306. },
  307. async beforeUpload(file) {
  308. if(this.uploadDelFlag){
  309. this.$message.warning('该文件已上传,请勿重复上传');
  310. this.uploadKey = Math.random()
  311. return false; // 取消上传
  312. }else{
  313. // 对文件进行判定
  314. const isXml = file.type === 'text/xml'; // 假设只接受 XML 文件
  315. if (!isXml) {
  316. this.$message.error('只能上传 XML 文件');
  317. return false; // 取消上传
  318. }else{
  319. try {
  320. //对上传的xml文件信息进行处理并通过后端接口进行解析返回到父页面进行调整
  321. const formBody = new FormData()
  322. formBody.append('file', file)
  323. await this.ossService.disposeXmlFile(formBody).then((data) => {
  324. if(JSON.stringify(data) === "{}"){
  325. this.$message.warning('数电发票:'+file.name+'格式错误');
  326. this.loading = false;
  327. // 在验证失败时删除已经添加的行
  328. const index = this.fileList.findIndex(item => item.name === file.name);
  329. if (index !== -1) {
  330. this.deleteFileById(this.fileList[index], index, this.fileList);
  331. }
  332. }
  333. })
  334. } catch (error) {
  335. console.error(error);
  336. }
  337. }
  338. // 其他判定逻辑...
  339. return true; // 允许上传
  340. }
  341. },
  342. uploadVideoProcess (event, file, fileList) {
  343. this.progressFlag = true // 显示进度条
  344. this.loadProgress = parseInt(event.percent) // 动态获取文件上传进度
  345. if (this.loadProgress >= 100) {
  346. this.loadProgress = 100
  347. // var fileName = file.raw.name;
  348. //
  349. // const spliceLength2 = fileName.lastIndexOf(".");
  350. // var fileNameSuffix = fileName.slice(spliceLength2 + 1);
  351. // let lowerFileNameSuffix = fileNameSuffix.toLowerCase();
  352. // if(lowerFileNameSuffix === "xml" ) {
  353. // //对上传的xml文件信息进行处理并通过后端接口进行解析返回到父页面进行调整
  354. // const formBody = new FormData()
  355. // formBody.append('file', file.raw)
  356. // this.ossService.disposeXmlFile(formBody).then((data) => {
  357. // if(Object.keys(data).length > 0){
  358. // this.invoiceReimbursementDisposeData(data,file)
  359. // } else{
  360. // this.$message.warning('上传的数电发票格式错误')
  361. // this.loading = false;
  362. // // 在验证失败时删除已经添加的行
  363. // const index = this.fileList.findIndex(item => item.name === file.name);
  364. // if (index !== -1) {
  365. // this.deleteFileById(this.fileList[index], index, this.fileList);
  366. // }
  367. // }
  368. // })
  369. // }
  370. setTimeout(() => {
  371. this.progressFlag = false
  372. }, 1000) // 一秒后关闭进度条
  373. }
  374. },
  375. invoiceReimbursementDisposeData: function (data,file) {
  376. var invoiceReimbursements = this.dataListNew;
  377. //创建判断值,若行信息存在相同的发票号,则进行数据检查调整,若不存在发票号,则新增行,并将信息写入
  378. var includeFlag = false;
  379. if(!invoiceReimbursements) {
  380. invoiceReimbursements = [];
  381. }
  382. if(this.toCompany === data.BuyerInformationBuyerName){
  383. invoiceReimbursements.forEach(item => {
  384. if (file.name === item.name){
  385. item.invoiceType = data.InherentLabelGeneralOrSpecialVATLabelCode;
  386. item.invoiceProjectName = data.IssuItemInformationItemName;
  387. item.number = data.InvoiceNumber;
  388. item.invoiceDate = this.formatDate(data.IssueTime);
  389. item.invoiceUnit = data.SellerInformationSellerName;
  390. item.amount = data.BasicInformationTotalAmWithoutTax;
  391. item.taxAmount = data.BasicInformationTotalTaxAm;
  392. item.count = data.BasicInformationTotalTaxincludedAmount;
  393. item.buyerName = data.BuyerInformationBuyerName;
  394. }
  395. })
  396. }
  397. },
  398. formatDate(date) {
  399. // 正则表达式匹配 "xxx年x月x日" 格式的日期
  400. const regex = /(\d{4})年(\d{1,2})月(\d{1,2})日/;
  401. const matches = date.match(regex);
  402. const parts = date.split('/');
  403. if (matches) {
  404. const year = matches[1]; // 年
  405. const month = String(matches[2]).padStart(2, '0'); // 月,确保是两位数
  406. const day = String(matches[3]).padStart(2, '0'); // 日,确保是两位数
  407. return `${year}-${month}-${day}`; // 返回 yyyy-mm-dd 格式的日期
  408. } else if(parts.length === 3){
  409. const year = parts[0]; // 年份
  410. const month = String(parts[1]).padStart(2, '0'); // 月,确保是两位数
  411. const day = String(parts[2]).padStart(2, '0'); // 日,确保是两位数
  412. return `${year}-${month}-${day}`; // 返回 yyyy-mm-dd 格式的日期
  413. } else {
  414. const d = new Date(date);
  415. const year = d.getFullYear();
  416. const month = String(d.getMonth() + 1).padStart(2, '0'); // 获取月份并确保是两位数
  417. const day = String(d.getDate()).padStart(2, '0'); // 获取日期并确保是两位数
  418. return `${year}-${month}-${day}`;
  419. }
  420. },
  421. getSize (value) {
  422. if (this.commonJS.isEmpty(value)) {
  423. return '0 B'
  424. } else {
  425. let val = parseInt(value)
  426. if (this.commonJS.isEmpty(val)) {
  427. return '0 B'
  428. }
  429. if (isNaN(val)) {
  430. return '0 B'
  431. }
  432. if (val === 0) {
  433. return '0 B'
  434. }
  435. let k = 1024
  436. let sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB']
  437. let i = Math.floor(Math.log(val) / Math.log(k))
  438. let result = val / Math.pow(k, i);
  439. let kb = parseFloat(result.toPrecision(3));
  440. return kb + '' + sizes[i]
  441. }
  442. },
  443. async changes(file, fileList) {
  444. this.uploadKey = Math.random();
  445. // 用来存放没有重复且有有效URL的文件,准备上传
  446. let filesToUpload = [];
  447. let validFiles = [];
  448. // 用于存储已经上传的文件 `lastModified` + `size` 作为唯一标识
  449. let uploadedFileIdentifiers = new Set();
  450. for (let existingFile of this.dataListNew) {
  451. const existingFileName = existingFile.name; // 假设每个文件有 `name` 属性
  452. uploadedFileIdentifiers.add(existingFileName); // 将已有文件的名称添加到 Set 中
  453. }
  454. // 2. 文件大小检查
  455. if (!beforeAvatarUpload(file, fileList, this.maxValue)) {
  456. this.$message.error('文件大小不能超过 ' + this.maxValue + ' MB!');
  457. return;
  458. }
  459. // 3. 验证文件是否重复(使用 `lastModified` 和 `size` 来判断)
  460. for (let item of fileList) {
  461. const fileName = item.raw ? item.raw.name : item.name;
  462. const fileIdentifier = fileName; // 唯一标识:文件大小 + 修改时间
  463. // 检查该文件标识是否已存在
  464. if (uploadedFileIdentifiers.has(fileIdentifier)) {
  465. // 记录重复文件名
  466. const formBody = new FormData();
  467. formBody.append('file', item.raw);
  468. const data = await this.ossService.disposeXmlFile(formBody);
  469. if (this.commonJS.isNotEmpty(data.InvoiceNumber)){
  470. this.duplicateFileNames.push("文件名: "+fileName +"—— 发票号:"+data.InvoiceNumber);
  471. console.log('222',data.InvoiceNumber)
  472. console.log('this.duplicateFileNames',this.duplicateFileNames)
  473. }
  474. } else {
  475. // 文件没有重复,加入上传列表
  476. filesToUpload.push(item);
  477. uploadedFileIdentifiers.add(fileIdentifier); // 将文件标识加入已上传集合
  478. }
  479. }
  480. // 4. 如果没有文件需要上传,则直接返回
  481. // if (filesToUpload.length === 0) return;
  482. // 5. 删除无效URL的文件
  483. let invalidFiles = []; // 用于存储需要删除的文件
  484. // 使用异步操作来判断文件URL的有效性
  485. for (let item of filesToUpload) {
  486. const fileUrl = item.raw ? item.raw.url : item.url;
  487. // 检查临时 URL 是否有效
  488. if (fileUrl && fileUrl.trim() !== '') {
  489. try {
  490. const temporaryUrl = await this.ossService.getTemporaryUrl(fileUrl);
  491. if (!temporaryUrl || temporaryUrl.trim() === '') {
  492. // 如果临时 URL 无效,则标记该文件为无效并删除
  493. invalidFiles.push(item);
  494. } else {
  495. // 如果临时 URL 有效,继续添加文件到有效文件列表
  496. validFiles.push(item);
  497. item.lsUrl = temporaryUrl;
  498. }
  499. } catch (error) {
  500. // 如果临时 URL 获取失败,也标记该文件为无效
  501. invalidFiles.push(item);
  502. }
  503. }
  504. }
  505. filesToUpload = validFiles; // 只保留有效的文件
  506. // 6. 给文件添加上传时间和上传人
  507. for (let item of filesToUpload) {
  508. item.createTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
  509. item.createBy = {
  510. id: this.$store.state.user.id,
  511. name: this.$store.state.user.name,
  512. };
  513. }
  514. const validCompanyFiles = [];//存放符合公司的文件
  515. let errorFiles = [];//存放数据格式错误的文件
  516. let errorDateFiles = [];//存放日期格式错误的文件
  517. let isUsedFiles = [];//存放已经被报销的文件
  518. for (let i = 0; i < filesToUpload.length; i++) {
  519. const item = filesToUpload[i];
  520. if (item.raw !== undefined && item.raw !== null && item.raw !== {}) {
  521. // 设置文件的 URL
  522. item.url = item.raw.url;
  523. // 仅处理 XML 文件
  524. if (item.raw.name && item.raw.name.toLowerCase().endsWith(".xml")) {
  525. // 创建 FormData 对象并发送文件
  526. const formBody = new FormData();
  527. formBody.append('file', item.raw);
  528. // 调用后端接口解析 XML 文件
  529. const data = await this.ossService.disposeXmlFile(formBody);
  530. if (Object.keys(data).length > 0) {
  531. // 如果文件的公司名称与this.toCompany不一致,则删除该文件
  532. // 检查 data 是否包含 BuyerInformationBuyerName 属性
  533. if (data && 'BuyerInformationBuyerName' in data) {
  534. // 验证是否有效,并进行替换操作
  535. if (typeof data.BuyerInformationBuyerName === 'string') {
  536. var buyerInformationBuyerName = data.BuyerInformationBuyerName
  537. .replace(/(/g, '(')
  538. .replace(/)/g, ')');
  539. data.BuyerInformationBuyerName = buyerInformationBuyerName
  540. }
  541. }
  542. if (this.toCompany !== data.BuyerInformationBuyerName) {
  543. this.noXmlFiles.push("文件名: "+item.raw.name +"—— 发票号:"+data.InvoiceNumber)
  544. // this.$message.warning("仅可上传江苏兴光项目管理有限公司的报销数电发票");
  545. continue;
  546. }
  547. if (this.commonJS.isNotEmpty(data.InvoiceNumber)){
  548. var flag = this.invoiceReimbursementDispose(data)
  549. if (flag){
  550. this.duplicateFileNames.push(item.raw.name +"-"+data.InvoiceNumber)
  551. continue;
  552. }
  553. //查询当前发票号是否已经被报销
  554. let isUsed = await this.ossService.isUsedByInvoiceNumber(data.InvoiceNumber);
  555. if (isUsed){
  556. isUsedFiles.push("文件名: "+item.raw.name +"—— 发票号:"+data.InvoiceNumber)
  557. continue;
  558. }
  559. let inDate = this.formatDate(data.IssueTime)
  560. if (inDate.indexOf("NaN") != -1 && this.commonJS.isNotEmpty(inDate)){
  561. errorDateFiles.push("文件名: "+item.raw.name +"—— 发票号:"+data.InvoiceNumber);
  562. continue;
  563. }
  564. validCompanyFiles.push(item); // 符合条件的文件
  565. }
  566. }
  567. }
  568. }
  569. }
  570. filesToUpload = validCompanyFiles;
  571. // 将新符合条件的文件追加到原文件列表上
  572. this.dataListNew = [...this.dataList, ...filesToUpload];
  573. this.fileList = [...filesToUpload];
  574. // 记录上传文件的数量
  575. this.totalCount = fileList.length;
  576. //记录changes方法执行了多少次,此处加判定是为了处理防抖,change方法会对每一个文件执行两次,此处判定后只会增加一次
  577. if (file.status !== 'ready'){
  578. this.uploadingCount++
  579. }
  580. // 9. 检查是否是最后一个文件上传,如果是,执行一次去重和提示
  581. if (this.uploadingCount === this.totalCount) {
  582. this.duplicateFileNames = [...new Set(this.duplicateFileNames)];
  583. this.noXmlFiles = [...new Set(this.noXmlFiles)];
  584. // this.reNumFiles = [...new Set(this.reNumFiles)];
  585. errorFiles = [...new Set(errorFiles)];
  586. invalidFiles = [...new Set(invalidFiles)];
  587. errorDateFiles = [...new Set(errorDateFiles)];
  588. isUsedFiles = [...new Set(isUsedFiles)];
  589. // 提示重复文件
  590. if (this.duplicateFileNames.length > 0) {
  591. this.$message.warning({message:`以下文件已经上传,请勿重复上传:<br>${this.duplicateFileNames.join('<br>')} `,dangerouslyUseHTMLString: true});
  592. }
  593. // 提示xml文件不是当前公司报销的文件
  594. if (this.noXmlFiles.length > 0) {
  595. this.$message.warning({message:`仅可上传${this.toCompany}的报销数电发票:<br>${this.noXmlFiles.join('<br>')}<br>上传失败 `,dangerouslyUseHTMLString: true});
  596. }
  597. // 提示发票号重复文件
  598. // if (this.reNumFiles.length > 0) {
  599. // this.$message.error(`发票号:\n${this.reNumFiles.join('\n')}已上传,请勿重复上传`);
  600. // }
  601. //数电发票格式错误的文件
  602. if (errorFiles.length > 0){
  603. this.$message.warning({message:`上传的数电发票格式错误:<br>${errorFiles.join('<br>')}`,dangerouslyUseHTMLString: true});
  604. }
  605. //临时路径错误的文件
  606. if (invalidFiles.length > 0){
  607. this.$message.warning({message:`数电发票: <br>${invalidFiles.join('<br>')}<br>获取失败,上传失败。`,dangerouslyUseHTMLString: true});
  608. }
  609. //临时路径错误的文件
  610. if (errorDateFiles.length > 0){
  611. this.$message.warning({message:`数电发票: <br>${errorDateFiles.join('<br>')}<br>日期格式错误,上传失败。`,dangerouslyUseHTMLString: true});
  612. }
  613. //已经被报销的文件
  614. if (isUsedFiles.length > 0){
  615. this.$message.warning({message:`数电发票: <br>${isUsedFiles.join('<br>')}<br>已经发起或已完成报销,无法重复报销`,dangerouslyUseHTMLString: true});
  616. }
  617. // 重置计数器
  618. this.uploadingCount = 0;
  619. this.totalCount = 0; // 可以根据需求来重置
  620. this.duplicateFileNames = []; // 清空记录
  621. this.noXmlFiles = []; // 清空记录
  622. this.reNumFiles = []; // 清空记录
  623. this.dataList = this.dataListNew
  624. }
  625. // 清空 fileList,如果 fileList 不为空
  626. if (fileList && fileList.length > 0) {
  627. this.fileList = [];
  628. }
  629. // 在 changes 完成后,手动调用 handleUploadSuccess
  630. await this.handleUploadSuccess(null, null, this.fileList); // 传入空参数或实际参数
  631. },
  632. async handleUploadSuccess(response, file, fileList) {
  633. // 遍历当前的数据列表
  634. if (this.dataListNew.length>0){
  635. for (let item of this.dataListNew) {
  636. // 如果 item.raw 存在且有效
  637. if (item.raw !== undefined && item.raw !== null && item.raw !== {}) {
  638. // 设置文件的 URL
  639. item.url = item.raw.url;
  640. // 仅处理 XML 文件
  641. if (item.raw.name && item.raw.name.toLowerCase().endsWith(".xml")) {
  642. // 创建 FormData 对象并发送文件
  643. const formBody = new FormData();
  644. formBody.append('file', item.raw);
  645. try {
  646. // 调用后端接口解析 XML 文件
  647. const data = await this.ossService.disposeXmlFile(formBody);
  648. console.log(data)
  649. // 检查 data 是否包含 BuyerInformationBuyerName 属性
  650. if (data && 'BuyerInformationBuyerName' in data) {
  651. // 验证是否有效,并进行替换操作
  652. if (typeof data.BuyerInformationBuyerName === 'string') {
  653. var buyerInformationBuyerName = data.BuyerInformationBuyerName
  654. .replace(/(/g, '(')
  655. .replace(/)/g, ')');
  656. data.BuyerInformationBuyerName = buyerInformationBuyerName
  657. }
  658. }
  659. if (Object.keys(data).length > 0) {
  660. // 解析成功,更新数据行
  661. await this.invoiceReimbursementDisposeData(data, item);
  662. }
  663. // else {
  664. // // XML 格式错误,删除文件
  665. // this.$message.warning('上传的数电发票格式错误');
  666. // const index = this.fileList.findIndex(f => f.name === item.name);
  667. // if (index !== -1) {
  668. // this.deleteFileById(this.fileList[index], index, this.fileList);
  669. // }
  670. // }
  671. } catch (error) {
  672. this.$message.error('处理 XML 文件失败');
  673. console.log('XML 处理失败', error);
  674. }
  675. }
  676. }
  677. }
  678. // 更新表格数据
  679. this.$nextTick(() => {
  680. this.$forceUpdate(); // 强制更新表格
  681. });
  682. }
  683. },
  684. invoiceReimbursementDispose(data) {
  685. var invoiceReimbursements = this.dataList;
  686. //创建判断值,若行信息存在相同的发票号,则进行数据检查调整,若不存在发票号,则新增行,并将信息写入
  687. var includeFlag = false;
  688. if(!invoiceReimbursements) {
  689. invoiceReimbursements = [];
  690. }
  691. invoiceReimbursements.forEach(item => {
  692. if(item.number === data.InvoiceNumber) {
  693. includeFlag = true;
  694. }
  695. })
  696. return includeFlag;
  697. },
  698. showFile (row) {
  699. openWindowOnUrl(row)
  700. },
  701. onPreview (url) {
  702. this.url = url
  703. this.showViewer = true
  704. },
  705. // 关闭查看器
  706. closeViewer () {
  707. this.url = ''
  708. this.showViewer = false
  709. },
  710. toHref (row) {
  711. toHref(row)
  712. },
  713. async deleteById (row, index,fileList) {
  714. // this.$refs.upload.handleRemove(this.dataListNew[index])
  715. await this.dataListNew.splice(index, 1)
  716. await this.dataList.splice(index, 1)
  717. // if (this.commonJS.isNotEmpty(row.id)) {
  718. // this.ossService.deleteMsgById(row.id)
  719. // }
  720. var newFileList = [];
  721. for (var i = 0; i < fileList.length; i++) {
  722. if (fileList[i].name !== row.name) {
  723. newFileList.push(fileList[i])
  724. }
  725. }
  726. this.fileList = newFileList;
  727. },
  728. deleteFileById (row, index,fileList) {
  729. // this.$refs.upload.handleRemove(this.dataListNew[index])
  730. this.dataListNew.splice(index, 1)
  731. this.dataList = this.dataListNew
  732. // if (this.commonJS.isNotEmpty(row.id)) {
  733. // this.ossService.deleteMsgById(row.id)
  734. // }
  735. // var newFileList = [];
  736. // for (var i = 0; i < this.dataListNew.length; i++) {
  737. // if (this.dataListNew[i].name !== row.name) {
  738. // newFileList.push(this.dataListNew[i])
  739. // }
  740. // }
  741. // this.fileList = newFileList;
  742. // 更新表格数据
  743. this.$nextTick(() => {
  744. this.$forceUpdate(); // 强制更新表格
  745. });
  746. },
  747. /**
  748. * 关闭dialog时使用 清除el-upload中上传的文件
  749. */
  750. clearUpload () {
  751. this.fileList = []//用于清除上传文件的缓存
  752. this.$refs.upload.clearFiles()
  753. this.dataList = []
  754. this.dataListNew = []
  755. this.createBy = ''
  756. },
  757. /**
  758. * 获取当前文件列表中的文件数据
  759. */
  760. getDataList () {
  761. return this.dataListNew
  762. },
  763. /**
  764. * 判断进度条是否结束,附件是否加载完成
  765. * @returns {boolean}
  766. */
  767. checkProgress () {
  768. if (this.progressFlag === true) {
  769. this.$message.warning('请等待附件上传完成再进行操作')
  770. return true
  771. }
  772. if (this.fileLoading === false) {
  773. this.$message.warning('请等待附件加载完成再进行操作')
  774. if (this.dataListLength === this.dataListNew.length) {
  775. this.fileLoading = true
  776. }
  777. return true
  778. }
  779. return false
  780. },
  781. ifName (row) {
  782. if (this.commonJS.isEmpty(row.name)) {
  783. row.name = '---'
  784. return false
  785. }
  786. let suffix = row.name.substring(row.name.lastIndexOf('.') + 1)
  787. if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'bmp' || suffix === 'jpeg') {
  788. return true
  789. } else {
  790. return false
  791. }
  792. },
  793. fileLoadingFalse () {
  794. this.fileLoading = false
  795. },
  796. // 开启/关闭页面的加载中状态
  797. changeLoading (loading) {
  798. if (this.commonJS.isNotEmpty(loading)) {
  799. this.loading = loading
  800. } else {
  801. this.loading = false
  802. }
  803. },
  804. getSummaries(param) {
  805. const { columns, data } = param;
  806. // 初始化汇总数组
  807. const sums = [];
  808. // 遍历列
  809. columns.forEach((column, index) => {
  810. if (index === 0) {
  811. // 第一列(通常是序号列),我们不需要进行汇总,直接设置为“汇总”
  812. sums[index] = '汇总';
  813. }
  814. if (column.property === 'amount'){
  815. // 如果当前列是 'amount',进行汇总
  816. const values = data.map((item) => Number(item[column.property]));
  817. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  818. return prev + curr; // 汇总价税合计列
  819. }, 0));
  820. }
  821. if (column.property === 'taxAmount'){
  822. // 如果当前列是 'amount',进行汇总
  823. const values = data.map((item) => Number(item[column.property]));
  824. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  825. return prev + curr; // 汇总价税合计列
  826. }, 0));
  827. }
  828. if (column.property === 'count'){
  829. // 如果当前列是 'amount',进行汇总
  830. const values = data.map((item) => Number(item[column.property]));
  831. sums[index] = this.formatNumber(values.reduce((prev, curr) => {
  832. return prev + curr; // 汇总价税合计列
  833. }, 0));
  834. }
  835. });
  836. return sums;
  837. },
  838. formatNumber(number) {
  839. return number.toFixed(2); // 保留两位小数,返回字符串
  840. },
  841. }
  842. }
  843. </script>
  844. <style scoped lang="scss">
  845. ::v-deep .el-table{
  846. .el-table__footer-wrapper tbody td.el-table__cell, .el-table__header-wrapper tbody td.el-table__cell{
  847. background-color: #fff; /* 设置背景颜色与表格一致 */
  848. }
  849. /* 设置汇总行的背景颜色与表格一致 */
  850. .el-table__footer {
  851. background-color: #fff; /* 设置背景颜色与表格一致 */
  852. }
  853. /* 让第一列的汇总居中 */
  854. .el-table__footer .el-table__cell:nth-child(1) {
  855. text-align: center; /* 让第一列居中 */
  856. font-weight: bold; /* 可以根据需要加粗 */
  857. }
  858. }
  859. .el-divider__text {
  860. font-size: 16px;
  861. font-weight: bold;
  862. }
  863. </style>
  864. <style>
  865. </style>