DigitalInvoiceUploadComponent.vue 36 KB

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