Selaa lähdekoodia

修正下载初稿、返稿、定稿文件bug
修改抓取程序参数为开始时间和结束时间

luocaiyang 9 kuukautta sitten
vanhempi
commit
2bf3b8d89b

+ 5 - 2
wispro.sp.api/Controllers/PerformanceItemController.cs

@@ -1329,9 +1329,12 @@ namespace wispro.sp.api.Controllers
             spDbContext spDb = new spDbContext();
 
             var calMonth = spDb.CalMonths.FirstOrDefault(c => c.Status == 0);
-            _RefreshBasePoint(calMonth, spDb);
 
-            StatisticsLevelCount(calMonth.Year, calMonth.Month);
+            if (calMonth != null) {
+                _RefreshBasePoint(calMonth, spDb);
+
+                StatisticsLevelCount(calMonth.Year, calMonth.Month);
+            }
 
         }
 

+ 168 - 23
wispro.sp.utility/IPEasyUtility.cs

@@ -7,13 +7,8 @@ using System.Dynamic;
 using System.IO;
 using System.Linq;
 using System.Threading;
-using System.Xml.Linq;
-using Microsoft.Extensions.Primitives;
-using NPOI.HPSF;
-using NPOI.SS.Formula.Functions;
 using OpenQA.Selenium;
 using OpenQA.Selenium.Chrome;
-using OpenQA.Selenium.Interactions;
 using OpenQA.Selenium.Support.Extensions;
 using OpenQA.Selenium.Support.UI;
 
@@ -47,7 +42,7 @@ namespace wispro.sp.utility
                 long currentSize = new FileInfo(fileName).Length;
                 while (previousSize != currentSize && currentSize>0)
                 {
-                    Debug.WriteLine($"{fileName}文件大小:{previousSize},{currentSize}");
+                    //Debug.WriteLine($"{fileName}文件大小:{previousSize},{currentSize}");
                     previousSize = currentSize;
                     try
                     {
@@ -61,8 +56,8 @@ namespace wispro.sp.utility
                         break;
                     }
 
-                    Debug.WriteLine("等待一段时间!");
-                    Debug.WriteLine($"{fileName}文件大小:{previousSize},{currentSize}");
+                    //Debug.WriteLine("等待一段时间!");
+                    //Debug.WriteLine($"{fileName}文件大小:{previousSize},{currentSize}");
                     Thread.Sleep(3000); // 等待一段时间
                 }
 
@@ -70,12 +65,12 @@ namespace wispro.sp.utility
                 {
                     if ((fileName.Contains(".crdownload") || fileName.Contains(".tmp")) && File.Exists(fileName))
                     {
-                        Debug.WriteLine(".crdownload文件,等待!");
+                        //Debug.WriteLine(".crdownload文件,等待!");
                         Thread.Sleep(1000);
                     }
                     else
                     {
-                        Debug.WriteLine($"文件大小相同跳出循环");
+                        //Debug.WriteLine($"文件大小相同跳出循环");
                         break;
                     }
                 }
@@ -84,7 +79,7 @@ namespace wispro.sp.utility
             }
 
             fileName = Directory.GetFiles(downloadDir).FirstOrDefault(); 
-            while(fileName.Contains(".crdownload") || fileName.Contains(".tmp")){
+            while((fileName.Contains(".crdownload") || fileName.Contains(".tmp")) && !string.IsNullOrEmpty(fileName)){
                 fileName = Directory.GetFiles(downloadDir).FirstOrDefault();
                 Thread.Sleep(1000);
             }
@@ -108,7 +103,7 @@ namespace wispro.sp.utility
                     foreach (var f in new DirectoryInfo(strFolder).GetFiles())
                     {
                         string temName = f.Name.Trim();
-                        if (temName == filename || temName.Replace(" ", "") == filename)
+                        if (temName == filename || temName.Replace("\u00A0", "").Replace(" ","") == filename.Replace("\u00A0", "").Replace(" ", ""))
                         {
                             outFilePath = f.FullName;
                             return true;
@@ -310,6 +305,17 @@ namespace wispro.sp.utility
         {
             dynamic retObject = new ExpandoObject();
 
+            string[] splitCase = caseNo.Split(new[] { '-' });
+            if(splitCase.Length > 1)
+            {
+                string temCaseNo = "";
+                for(int i = 0; i < splitCase.Length - 1; i++)
+                {
+                    temCaseNo = string.IsNullOrEmpty(temCaseNo)?splitCase[i]:$"{temCaseNo}-{splitCase[i]}";
+                }
+                caseNo = temCaseNo.Trim();
+                
+            }
             retObject.CaseNo = caseNo.Trim();
             string strDownloadPath = Path.Combine(strFileSavePath, caseNo);
             if (!Directory.Exists(strDownloadPath))
@@ -364,12 +370,19 @@ namespace wispro.sp.utility
                     {
                         var caseLink = wait.Until((d) =>
                         {
-                            return d.FindElement(By.XPath($"//a[contains(text(),'{caseNo}')]"));
+                            try
+                            {
+                                return d.FindElement(By.XPath($"//a[contains(text(),'{caseNo}')]"));
+                            }
+                            catch {
+                                return null;
+                            }
                         });
                         driver.ExecuteJavaScript("arguments[0].click();", caseLink);
                     }
                     catch(Exception ex)
                     {
+                        throw(ex);
                         if(ex.Message.Contains("no such element: Unable to locate element"))
                         {
                             return retObject;
@@ -395,14 +408,44 @@ namespace wispro.sp.utility
                     retObject.Country = waitGetElementById(wait, "p_case_info__country_id").GetAttribute("value");
 
                     #region 下载新申请第一次返稿文档
+                    retObject.firstReturnFile = null;
                     var kzTab = wait.Until(d => d.FindElement(By.XPath($"//span[contains(text(),'往来信息')]")));
                     kzTab.Click();
                     
 
                     var kzTable = waitGetElementById(wait, "table_SendList");
                     System.Threading.Thread.Sleep(500);
-                    retObject.firstReturnFile = Download(driver, wait, kzTable, new { fileNameCol =2,fileTypeCol=-1,uploadDateCol=9}, "新申请第一次返稿", strDownloadPath,new string[] { "申请文件"},new string[] { "检索报告","查新报告"});
-                    retObject.firstReturnFile = CopyFile(retObject.firstReturnFile);
+                    var retRows = GetWeidijiaoFile(driver, wait, kzTable);
+
+                    foreach ( var row in retRows)
+                    {
+                        var btnDownload = waitGetElementByClassName(wait, "tbview", row[row.Count - 1]);
+                        driver.ExecuteJavaScript("arguments[0].click();", btnDownload);
+
+                        driver.SwitchTo().DefaultContent()
+                            .SwitchTo().Frame(3);
+                        System.Threading.Thread.Sleep (1000);
+                        var attachTable = wait.Until(d => d.FindElement(By.Id($"table_mailfile")));
+                        System.Threading.Thread.Sleep(1000);
+                        retObject.firstReturnFile = Download(driver, wait, attachTable, new { fileNameCol = 2, fileTypeCol = -1, uploadDateCol = 6 }, "新申请第一次返稿", strDownloadPath, new string[] { "申请文件","申请文档","说明书"}, new string[] { "检索报告", "查新报告","交底书","对比文件","图档" });
+                        driver.SwitchTo().ParentFrame();
+                        var closer = wait.Until((d) => { return driver.FindElement(By.XPath("//li[@class=\"active\"]/div[@title=\"关闭\"]")); });
+                        
+                        closer.Click();
+                        driver.SwitchTo().Frame(2);
+
+                        if (retObject.firstReturnFile != null)
+                        {
+                            retObject.firstReturnFile = CopyFile(retObject.firstReturnFile);
+                            break;
+                        }
+                    }
+
+                    if (retRows.Count > 0 && retObject.firstReturnFile ==null)
+                    {
+                        throw new Exception("未抓取到第一次返稿文件!");
+                    }
+                    
                     #endregion
 
                     var table = waitGetElementById(wait, "table_ProcList");
@@ -504,7 +547,7 @@ namespace wispro.sp.utility
 
                     if (Directory.Exists(strDownloadPath))
                     {
-                        Directory.Delete(strDownloadPath);
+                        Directory.Delete(strDownloadPath,true);
                     }
 
                 }
@@ -527,7 +570,7 @@ namespace wispro.sp.utility
         /// <param name="type">类型0:递交中、1:前一天完成</param>
         /// <returns></returns>
         /// <exception cref="Exception"></exception>
-        public static DataTable GetFinished3FilesCases(int type,int days=1)
+        public static DataTable GetFinished3FilesCases(int type,DateTime start,DateTime end)
         {
             DataTable  retObject = new DataTable();
             
@@ -605,7 +648,7 @@ namespace wispro.sp.utility
                             startDate.Click();
                             System.Threading.Thread.Sleep(500);
                             
-                            startDate.SendKeys(DateTime.Now.AddDays(0-days).ToString("yyyy-MM-dd"));
+                            startDate.SendKeys(start.ToString("yyyy-MM-dd"));
 
                             Log($"{DateTime.Now}\t输入处理事项完成日期:结束日期");
 
@@ -625,7 +668,7 @@ namespace wispro.sp.utility
                             driver.ExecuteJavaScript("arguments[0].scrollIntoView();", endDate);
                             endDate.Click();
                             System.Threading.Thread.Sleep (500);
-                            endDate.SendKeys(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"));
+                            endDate.SendKeys(end.ToString("yyyy-MM-dd"));
                         }
                     }
 
@@ -713,7 +756,7 @@ namespace wispro.sp.utility
                 finally
                 {
                     driver.Quit();
-                    killChromProcess();
+                    //killChromProcess();
                 }
             }
 
@@ -740,6 +783,44 @@ namespace wispro.sp.utility
             }
         }
 
+        private static List<ReadOnlyCollection<IWebElement>> GetWeidijiaoFile(IWebDriver driver, WebDriverWait wait, IWebElement table_filelist)
+        {
+            var tBody = waitGetElementByTagName(wait, "tbody", table_filelist);
+            var Rows = waitGetElementsByTagName(wait, "tr", tBody);
+
+            List<ReadOnlyCollection<IWebElement>> retRows = new List<ReadOnlyCollection<IWebElement>>();
+            
+            DateTime dateTime = DateTime.Now;
+            foreach (var row in Rows)
+            {
+                var cols = waitGetElementsByTagName(wait, "td", row);
+                System.Threading.Thread.Sleep(500);
+
+                if (cols.Count == 1 && cols[0].Text == "无数据")
+                {
+                    break;
+                }
+
+                
+                if (cols[3].Text == "未递交" || cols[2].Text.Contains("申请"))
+                {
+                    DateTime temDate = DateTime.Parse(cols[9].Text);
+                    if (temDate < dateTime)
+                    {
+                        retRows.Insert(0, cols);
+                        dateTime = temDate;
+                    }
+                    else
+                    {
+                        retRows.Add(cols);
+                    }
+                }
+            }
+
+            return retRows;
+
+        }
+
         private static string Download(IWebDriver driver, WebDriverWait wait, IWebElement table_filelist, dynamic config,string fileType, string downloadPath = null, string[] includesStrings = null, string[] unincludeStrings = null)
         {
             if(downloadPath == null)
@@ -756,18 +837,28 @@ namespace wispro.sp.utility
             {
                 includesStrings = new string[] { };
             }
-            
+
+            try
+            {
+                driver.ExecuteJavaScript("arguments[0].scrollIntoView();", table_filelist);
+            }
+            catch { }
+
             var tBody = waitGetElementByTagName(wait, "tbody", table_filelist);
             var Rows = waitGetElementsByTagName(wait, "tr", tBody);
 
             ReadOnlyCollection<IWebElement> temRow =null;
+            ReadOnlyCollection<IWebElement> temRow1 = null;
             DateTime dateTime = DateTime.Now;
-            foreach(var row in Rows)
+            DateTime dateTime1 = DateTime.Now;
+            foreach (var row in Rows)
             {
+                
+
                 var cols = waitGetElementsByTagName(wait,"td",row);
                 System.Threading.Thread.Sleep(500);
 
-                if(cols.Count ==1 && cols[0].Text == "无数据")
+                if (cols!=null && cols.Count ==1 && cols[0].Text == "无数据")
                 {
                     break;
                 }
@@ -801,11 +892,53 @@ namespace wispro.sp.utility
                                 }
                             }
                         }
+                        else
+                        {
+                            if (temRow1 == null)
+                            {
+                                temRow1 = cols;
+                                dateTime1 = temDate;
+                            }
+                            else
+                            {
+                                if (temDate < dateTime1)
+                                {
+                                    temRow1 = cols;
+                                    dateTime1 = temDate;
+                                }
+                            }
+                        }
                         
                     }
+                    else
+                    {
+                        DateTime temDate = DateTime.Parse(cols[config.uploadDateCol].Text);
+                        if (fileNameValid(cols[config.fileNameCol].Text, includesStrings))
+                        {
+                            if (temRow1 == null)
+                            {
+                                temRow1 = cols;
+                                dateTime1 = temDate;
+                            }
+                            else
+                            {
+                                if (temDate < dateTime1)
+                                {
+                                    temRow1 = cols;
+                                    dateTime1 = temDate;
+                                }
+                            }
+
+                        }
+                    }
                 }
             }
 
+            if(temRow == null && temRow1 != null)
+            {
+                temRow = temRow1;
+            }
+
             if (temRow != null)
             {
                 //清除下载路径的文件
@@ -814,6 +947,12 @@ namespace wispro.sp.utility
 
 
                 var btnDownload = waitGetElementByClassName(wait, "tbdownload", temRow[temRow.Count - 1]);
+                try
+                {
+                    driver.ExecuteJavaScript("arguments[0].scrollIntoView();", btnDownload);
+                }
+                catch { }
+                System.Threading.Thread.Sleep(500);
                 driver.ExecuteJavaScript("arguments[0].click();", btnDownload);
 
 
@@ -830,6 +969,12 @@ namespace wispro.sp.utility
 
         private static string Download(IWebDriver driver, WebDriverWait wait, IWebElement table_filelist, string fileType,string downloadPath=null)
         {
+            try
+            {
+                driver.ExecuteJavaScript("arguments[0].scrollIntoView();", table_filelist);
+            }
+            catch { }
+
             if (string.IsNullOrEmpty(downloadPath))
             {
                 downloadPath = strFileSavePath;

+ 33 - 19
wispro.sp.winClient/frmCaseFileCompare.cs

@@ -24,6 +24,7 @@ using OpenQA.Selenium.Support.UI;
 using System.Dynamic;
 using System.Diagnostics;
 using NPOI.Util;
+using NPOI.SS.Formula.Functions;
 
 namespace wispro.sp.winClient
 {
@@ -126,39 +127,45 @@ namespace wispro.sp.winClient
 
         }
 
-        private async Task compareCaseFile(int days)
+        private async Task compareCaseFile(DateTime start,DateTime end)
         {
-            DataTable table = wispro.sp.utility.IPEasyUtility.GetFinished3FilesCases(1,days);
+            DataTable table = wispro.sp.utility.IPEasyUtility.GetFinished3FilesCases(1,start,end);
 
             if (table != null)
             {
+                int iIndex = 0;
                 foreach (DataRow row in table.Rows)
                 {
+                    iIndex++;
+                    string CaseNo = row["我方文号"].ToString();
                     if (row["申请类型"].ToString().Trim() == "外观设计")
                     {
+                        string str = $"{DateTime.Now}\t{iIndex}/{CaseNo}\t外观设计";
+                        DebugLog(str);
                         continue;
                     }
 
                     string draftFile = string.Empty;
                     string returnFile = string.Empty;
                     string finalFile = string.Empty;
+                    
 
-                    string CaseNo = row["我方文号"].ToString();
-
-                    if (!CaseNo.StartsWith("PACN"))
+                    if (!string.IsNullOrEmpty(CaseNo) && !CaseNo.StartsWith("PACN"))
                     {
+                        DebugLog($"{DateTime.Now}\t{iIndex}/{table.Rows.Count}\t{CaseNo}\t非中国专利申请");
                         continue ;
                     }
 
                     var isExistResp = await new APIService().CaseExist(CaseNo);
 
-                    //isExistResp.Wait();
-
                     if (isExistResp || !CaseNo.StartsWith("PACN"))
                     {
+                        DebugLog($"{DateTime.Now}\t{iIndex}/{table.Rows.Count}\t{CaseNo}\t已存在!");
                         continue;
                     }
 
+                    int iTry = 0;
+                  tryAgain:
                     try
                     {
                         CaseInfo caseInfo = getCaseInfo_files(CaseNo, out draftFile, out returnFile, out finalFile);
@@ -168,17 +175,12 @@ namespace wispro.sp.winClient
                             (string.IsNullOrEmpty(returnFile) ? 0 : 1) +
                             (string.IsNullOrEmpty(finalFile) ? 0 : 1);
 
-                        using (StreamWriter writer = new StreamWriter(@"c:\temp\caseFileInfo.txt", true))
-                        {
-                            writer.WriteLine($"{caseInfo.CaseNo},{(string.IsNullOrEmpty(draftFile) ? 0 : 1)},{(string.IsNullOrEmpty(returnFile) ? 0 : 1)},{(string.IsNullOrEmpty(finalFile) ? 0 : 1)}");
-                        }
-
-                        if (i > 1)
+                        DebugLog($"{DateTime.Now}\t{iIndex}/{table.Rows.Count}\t{CaseNo},{(string.IsNullOrEmpty(draftFile) ? 0 : 1)},{(string.IsNullOrEmpty(returnFile) ? 0 : 1)},{(string.IsNullOrEmpty(finalFile) ? 0 : 1)}");
+                        
+                        if (i > 1 && returnFile != null)
                         {
                             CompareFiles(draftFile, returnFile, finalFile, caseInfo);
-
                             await new APIService().SaveCompareResult(caseInfo);
-
                         }
 
                         try
@@ -202,12 +204,25 @@ namespace wispro.sp.winClient
                     }
                     catch(Exception ex)
                     {
-                        Debug.WriteLine($"{CaseNo}\t{ex.Message}");
+                        if(iTry < 3)
+                        {
+                            iTry++;
+                            goto tryAgain;
+                        }
+                        DebugLog($"{DateTime.Now}\t{ iIndex}/{ table.Rows.Count}\t{CaseNo},{ ex.Message}");
                     }
 
 
                 }
             }
+
+            static void DebugLog(string str)
+            {
+                using (StreamWriter writer = new StreamWriter(@"c:\temp\caseFileInfo.txt", true))
+                {
+                    writer.WriteLine(str);
+                }
+            }
         }
 
         private void CompareFiles(string draftFile, string returnFile, string finalFile, CaseInfo caseInfo)
@@ -324,10 +339,9 @@ namespace wispro.sp.winClient
         {
             if (string.IsNullOrEmpty(this.txtCaseNo.Text))
             {
-                
                 if (MessageBox.Show("获取前一天所有的完成案件,并比较文档?", "提示框", MessageBoxButtons.YesNo) == DialogResult.Yes)
                 {
-                    compareCaseFile(30);
+                    compareCaseFile(DateTime.Parse("2024-12-01"),DateTime.Now);
                     return;
                 }
                 else
@@ -349,7 +363,7 @@ namespace wispro.sp.winClient
                             (string.IsNullOrEmpty(returnFile) ? 0 : 1) +
                             (string.IsNullOrEmpty(finalFile) ? 0 : 1);
 
-                if (i > 1)
+              if (i > 1)
                 {
                     CompareFiles(draftFile, returnFile, finalFile, caseInfo);
                     new APIService().SaveCompareResult(caseInfo);