UNPKG

flexbiz-server

Version:

Flexible Server

13 lines (12 loc) 4.87 kB
const {ImapFlow}=require("imapflow"),fetch=require("node-fetch"),{parseStringPromise}=require("xml2js"),Invoice=require("../models/receivedinvoice.js"),mailaccount=require("../models/mailaccount.js");async function convertXmlToJson($xml$$){return parseStringPromise($xml$$,{explicitArray:!1,mergeAttrs:!0,trim:!0})}function extractXmlLink($emailBody_match$$){return($emailBody_match$$=$emailBody_match$$.match(/https?:\/\/[^\s"'<>]+\.xml/gi))?$emailBody_match$$[0]:null} function extractIntermediateLink($emailBody$jscomp$1_match$$){return($emailBody$jscomp$1_match$$=$emailBody$jscomp$1_match$$.match(/https?:\/\/[^\s"'<>]+\/Invoice\/ViewFromEmail\?[^"'<>]+/gi))?$emailBody$jscomp$1_match$$[0]:null} async function extractXmlLinkDeep($emailBody$$){$emailBody$$=extractIntermediateLink($emailBody$$);if(!$emailBody$$)return null;try{const $html$$=await fetch($emailBody$$).then($res$$=>$res$$.text()),$xmlMatch$$=$html$$.match(/https?:\/\/[^\s"'<>]+\.xml/gi);if($xmlMatch$$&&$xmlMatch$$[0])return $xmlMatch$$[0];const $altMatch$$=$html$$.match(/href="([^"]+)"[^>]*>(T\u1ea3i|Download).*XML/i);if($altMatch$$&&$altMatch$$[1]){let $url$$=$altMatch$$[1];$url$$.startsWith("http")||($url$$=`${$emailBody$$.split("/Invoice")[0]}${$url$$}`); return $url$$}}catch($err$$){Logger.warn("\u26a0\ufe0f Kh\u00f4ng th\u1ec3 truy c\u1eadp link trung gian:",$err$$.message)}return null} function extractInvoiceSummary($info_json$$){$info_json$$=$info_json$$?.HDon?.DLHDon;if(!$info_json$$)return null;var $arr$$=$info_json$$?.NDHDon?.DSHHDVu?.HHDVu;$arr$$=Array.isArray($arr$$)?$arr$$:[$arr$$];return{invoice_number:$info_json$$?.TTChung?.SHDon||"",invoice_symbol:$info_json$$?.TTChung?.KHHDon||"",issue_date:$info_json$$?.TTChung?.NLap||null,seller_tax_code:$info_json$$?.NDHDon?.NBan?.MST||"",buyer_tax_code:$info_json$$?.NDHDon?.NMua?.MST||"",total:Number($info_json$$?.NDHDon?.TToan?.TgTTTBSo)|| 0,items:$arr$$}} async function fetchInvoicesFromEmailConfig($emailConfig$$,$body_fetchFromDate_sinceDate$$){const $client$$=new ImapFlow({host:$emailConfig$$.imap.host,port:$emailConfig$$.imap.port,secure:$emailConfig$$.imap.secure,auth:{user:$emailConfig$$.username,pass:$emailConfig$$.password}});await $client$$.connect();await $client$$.mailboxOpen("INBOX");$body_fetchFromDate_sinceDate$$=$body_fetchFromDate_sinceDate$$?new Date($body_fetchFromDate_sinceDate$$):$emailConfig$$.last_checked||new Date(Date.now()-2592E6); var $senderFilters_xmlLink$$=($emailConfig$$.fetchsenders?.length?$emailConfig$$.fetchsenders.split(","):["invoice","hoadon"]).map($keyword$$=>["FROM",$keyword$$]);let $allMessages$$=new Set;for(var $sender_xml_content$$ of $senderFilters_xmlLink$$)(await $client$$.search([$sender_xml_content$$,["SINCE",$body_fetchFromDate_sinceDate$$]].flat(),{sort:["ARRIVAL"],limit:100})).forEach($uid$$=>$allMessages$$.add($uid$$));Logger.info(`\ud83d\udce8 [${$emailConfig$$.username}] T\u00ecm th\u1ea5y ${$allMessages$$.size} email k\u1ec3 t\u1eeb ${$body_fetchFromDate_sinceDate$$.toLocaleDateString("vi-VN")}`); for await(const $msg$$ of $client$$.fetch($allMessages$$,{envelope:!0,source:!0,attachments:!0})){$sender_xml_content$$=null;if($msg$$.attachments?.length)for(const $att$$ of $msg$$.attachments)if($att$$.filename.endsWith(".xml")){$sender_xml_content$$=$att$$.content.toString("utf8");break}$sender_xml_content$$||($body_fetchFromDate_sinceDate$$=$msg$$.source.toString("utf8"),($senderFilters_xmlLink$$=extractXmlLink($body_fetchFromDate_sinceDate$$))||($senderFilters_xmlLink$$=await extractXmlLinkDeep($body_fetchFromDate_sinceDate$$)), $senderFilters_xmlLink$$&&($sender_xml_content$$=await (await fetch($senderFilters_xmlLink$$)).text()));if($sender_xml_content$$)try{const $json$$=await convertXmlToJson($sender_xml_content$$),$summary$$=extractInvoiceSummary($json$$);$summary$$&&(await Invoice.findOne({invoice_number:$summary$$.invoice_number,invoice_symbol:$summary$$.invoice_symbol,seller_tax_code:$summary$$.seller_tax_code})?Logger.info(`\u23e9 H\u00f3a \u0111\u01a1n ${$summary$$.invoice_number} \u0111\u00e3 t\u1ed3n t\u1ea1i.`): (await Invoice.create({...$summary$$,xml_content:$sender_xml_content$$,source_email:$emailConfig$$._id.toString(),id_app:$emailConfig$$.id_app}),Logger.info(`\u2705 \u0110\u00e3 l\u01b0u h\u00f3a \u0111\u01a1n ${$summary$$.invoice_number} t\u1eeb ${$emailConfig$$.user}`)))}catch($e$$){Logger.error("L\u1ed7i x\u1eed l\u00fd email:",$e$$.message)}}await $client$$.logout()} module.exports=async function($configs_id_app$$){$configs_id_app$$=(await mailaccount.find({id_app:$configs_id_app$$,status:!0})).filter($a$$=>$a$$.imap&&$a$$.imap.host);for(const $cfg$$ of $configs_id_app$$)Logger.info(`\ud83d\udcec \u0110ang \u0111\u1ecdc email t\u1eeb c\u1ea5u h\u00ecnh: ${$cfg$$.fullname} (${$cfg$$.username})`),await fetchInvoicesFromEmailConfig($cfg$$),$cfg$$.last_checked=new Date,await $cfg$$.save()};