예제 #1
0
        //-----------------------------------------------------------
        public int StartProcess()
        {
            int result = 1;
            if (core == null)
            {
                throw new Exception("Empty core object");
            }
            try
            {
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Start processing");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Reading dynamic configuration");
              #region Variables from xml configuration
              String url = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "url");
              String apiKey = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "api-key");
              String secretApiKey = PasswordEncoder.PtrDecryptText(ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "secret-api-key"));
              String sharedKey = PasswordEncoder.PtrDecryptText(ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "web-service-shared-key"));
              String serviceURL = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "blue-media-ws-url");
              EntriesDownloadMode entriesDownloadMode = (EntriesDownloadMode)Convert.ToInt32(ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode").Substring(0, 1));
              EntriesDownloadDate entriesDownloadDate =
                ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode:automatic-date").Substring(0, 3).ToUpper() == "YES" ?
                EntriesDownloadDate.AUTOMATIC : EntriesDownloadDate.MANUAL;
              String startDateString = ConfigXmlReader.XmlGetUIConfigParam(core.ProcessConfigurationXml, "get-entries-mode:automatic-date:start-date");
              DateTime startDate = DateTime.MinValue;
              if(entriesDownloadDate == EntriesDownloadDate.MANUAL)
              {
                if(!DateTime.TryParseExact(startDateString, "yyyy-MM-dd", null, DateTimeStyles.None, out startDate))
                {
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Could not parse the date provided in the configuration. Taking all entries.");
                  entriesDownloadMode = EntriesDownloadMode.ALL;
                }
              }
              String connectionString = ConverterUtils.GetDBConvertersConnectionString(core);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Url to connect to: {0}", url);
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Api key: {0}", apiKey);
              if(entriesDownloadMode == EntriesDownloadMode.SELECTED && entriesDownloadDate == EntriesDownloadDate.AUTOMATIC)
              {
                using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(connectionString))
                {
                  startDate = (from dinfo in dc.entry_status_change_update_times
                               orderby dinfo.last_verification_status_change_update_date descending
                               select dinfo.last_verification_status_change_update_date).FirstOrDefault();
                  if(startDate == DateTime.MinValue)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "No record indicating last update time in database. Taking all entries.");
                    entriesDownloadMode = EntriesDownloadMode.ALL;
                  }
                }
              }

              if(entriesDownloadMode == EntriesDownloadMode.ALL)
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Downloading all entries");
              }
              else
              {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Downloading selected entries from {0}.", startDate.ToString("yyyy-MM-dd HH:mm:ss.fff"));
              }
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Secret api key decrypted succesfully");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Web service shared key decrypted succesfully");
              #endregion
              XNamespace serv = "http://leader.raiffeisen.pl/api";
              //url = "http://localhost:65301/LeaderTestWebApp/Test/";
              ActiveForm form = new ActiveForm(serv, apiKey, secretApiKey, url);

              List<Tuple<String, String>> messageParameters = new List<Tuple<String, String>>();
              messageParameters.Add(new Tuple<string, string>("lastVerificationStatusUpdateThreshold", String.Empty));
              ActiveForm.ActiveFormAnswer answer = form.CallActiveFormsMethod("getEntriesAfterEmployeeVerification", messageParameters);
              XElement entryData = answer.ResponseXml;
              //Przygotowanie do generowania
              using(RaiffeisenPazrDataClassesDataContext dc = new RaiffeisenPazrDataClassesDataContext(ConverterUtils.GetDBConvertersConnectionString(core)))
              {
                if(answer.AnswerCode == ActiveForm.AnswerCodes.OK)
                {
                  var verifiedEntryList = (from entry in entryData.Descendants(serv + "entry")
                                           select new
                                           {
                                             entryId = Int32.Parse(entry.Descendants(serv + "entryId").First().Value.Trim()),
                                             verificationStatus = Int32.Parse(entry.Descendants(serv + "verificationStatusId").First().Value.Trim()),
                                           }).ToList();
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Retreived {0} entries with updated status.", verifiedEntryList.Count);
                  if(verifiedEntryList.Count > 0)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Their ids are {0}.", String.Join(",",verifiedEntryList.Select(x=>x.entryId.ToString()).ToArray()));
                  }
                  var entryList = (from entry in dc.leader_entries
                                   where verifiedEntryList.Select(x => x.entryId).Contains(entry.entryId)
                                   select entry).ToList();
                  foreach(var item in entryList)
                  {
                    item.status = verifiedEntryList.Where(x => x.entryId == item.entryId).First().verificationStatus;
                  }
                  var temp1 = verifiedEntryList.Select(x => x.entryId.ToString());
                  var temp2 = entryList.Select(x=>x.entryId.ToString());
                  var temp3 = temp1.Except(temp2);
                  if(verifiedEntryList.Count > entryList.Count)
                  {
                    PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Some of them ({0}) are missing from leader_entries table.",
                        String.Join(",",temp3.ToArray()));
                  }
                  String lastVerificationStatusDateString = String.Empty;
                  try
                  {
                    lastVerificationStatusDateString = entryData.Descendants(serv + "lastVerificationStatusUpdateTime").First().Value;
                  }
                  catch(Exception)
                  {
                  }
                  DateTime lastVerificationStatusDate;
                  if(!String.IsNullOrEmpty(lastVerificationStatusDateString))
                  {
                    Boolean success = DateTime.TryParse(lastVerificationStatusDateString, out lastVerificationStatusDate);
                    if(success)
                    {
                      entry_status_change_update_time time = new entry_status_change_update_time() { last_verification_status_change_update_date = lastVerificationStatusDate, date_received = DateTime.Now };
                      dc.entry_status_change_update_times.InsertOnSubmit(time);
                    }
                  }
                  dc.SubmitChanges();
                }
                else
                {
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Could not get valid response from Leader. Error: {0}. Will continue processing without updating leader entries.", answer.AnswerCode.ToString());
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Full response xml:", answer.ResponseXml.ToString());
                }
                //var recordsToRetransfer = from entry in dc.leader_entries
                //                          join itn in dc.itn_transactions
                //                          on entry.transactionId equals itn.orderID into itn_
                //                          from itn__ in itn_.DefaultIfEmpty()
                //                          where ((entry.status == 3 || entry.status == 4 || entry.status == 5 || (entry.status == 100 && itn__ != null))
                //                          && !itn__.retransferConfirmationDate.HasValue)
                //                          select new
                //                         {
                //                           itn = itn__,
                //                           entry = entry
                //                         };
                var recordsToRetransfer = (from entry in dc.leader_entries
                                          join itn in dc.itn_transactions on entry.transactionId equals itn.orderID
                                          join retr in dc.retransfers on itn.id equals retr.itn_transaction_id into retr_join
                                          from ret in retr_join.DefaultIfEmpty()
                                          group new
                                          {
                                            itn = itn,
                                            entry = entry,
                                            ret = ret
                                          } by new {
                                            itn = itn,
                                            entry = entry
                                          } into groups
                                          from g in groups
                                          where (g.entry.status == 3 || g.entry.status == 4 || g.entry.status == 5 || g.entry.status == 100) && g.itn.retransferConfirmationDate == null
                                            && groups.Count(x=>x.ret != null) < 3
                                          select new
                                          {
                                            itn = groups.Key.itn, entry=groups.Key.entry, triesCount = groups.Count(x=>x.ret != null)
                                          }).Distinct().ToList();
                int recordToRetransferCount = recordsToRetransfer.Count();
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "There are {0} transaction to retransfer", recordToRetransferCount);
                int lastTimeRetransferCount = recordsToRetransfer.Count(x => x.triesCount == 2);
                //if(lastTimeRetransferCount > 0)
                //{
                //  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "There are {0} transaction(s) which will be tried to retransfer for the third time. This is the last try.", lastTimeRetransferCount);
                //  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "These transactions id(s): {0}", String.Join(",",recordsToRetransfer.Where(x=>x.triesCount == 2).Select(x=>x.itn.id.ToString()).ToArray()));
                //}
                DateTime now = DateTime.Now;
                foreach (var record in recordsToRetransfer)
                {
                  ChangeNullStringToEmpty(record.entry);
                  BMWebReference.TransactionIn trin = new global::BMRetransfer.BMWebReference.TransactionIn();
                  trin.parentTransactionMerchantID = record.itn.merchantID.ToString();
                  trin.parentTransactionOrderID = record.itn.orderID;

                  BMWebReference.TransactionOut trout = new global::BMRetransfer.BMWebReference.TransactionOut();
                  trout.amount = new global::BMRetransfer.BMWebReference.Money() { currency = global::BMRetransfer.BMWebReference.Currency.PLN, value = record.itn.value };
                  trout.bmAccountId = "RAIFFEISENVERIFICATION";
                  trout.receiverAccount = record.itn.customerAccount;
                  trout.receiverName = record.entry.firstName + " " + record.entry.lastName; // record.itn.customerAddress;
                  trout.receiverAddress = String.Join(" ",
                    new String[] { record.entry.street,
                      String.IsNullOrEmpty(record.entry.apartmentNumber.Trim()) ? record.entry.houseNumber :
                        record.entry.houseNumber + "/" + record.entry.apartmentNumber, record.entry.postCode, record.entry.city });
                  switch(record.entry.status)
                  {
                    case 3:
                    {
                      trout.title = "Umowa o konta, kartę i kanały elektroniczne w Raiffeisen Polbank nie została zawarta";
                      break;
                    }
                    case 4:
                    {
                      trout.title = "Potwierdzamy zawarcie umów o konta, kartę i kanały elektroniczne w Raiffeisen Polbank";
                      break;
                    }
                    case 5:
                    {
                      trout.title = "Umowa o konta, kartę i kanały elektroniczne w Raiffeisen Polbank nie została zawarta";
                      break;
                    }
                    default:
                      break;
                  }
                  trout.transferBankId = record.itn.id.ToString(); //TU SIĘ ZASTANOWIC
                  StringBuilder hashedValue = new StringBuilder();
                  hashedValue.Append(trin.parentTransactionOrderID).Append(trin.parentTransactionMerchantID).
                    Append(trout.transferBankId).Append(trout.bmAccountId).
                    Append(trout.amount.value.ToString("0.00").Replace(",", ".")).
                    Append(trout.amount.currency.ToString()).
                    Append(trout.title).
                    Append(trout.receiverAccount).
                    Append(trout.receiverName).
                    Append(trout.receiverAddress).
                    Append(sharedKey);
                  String hash = String.Empty;
                  using (MD5 md5Hash = MD5.Create())
                  {
                    hash = GetHash(md5Hash,hashedValue.ToString());
                  }
                  PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Sending the retransfer order for transaction with id {0}.", record.itn.orderID);
                  BMWebReference.TransferData td = new BMWebReference.TransferData() { transactionIn = trin, transactionOut = trout, hash = hash };
                  BMWebReference.TransferService ts = new BMWebReference.TransferService();
                  BMWebReference.TransferConfirmation tc = ts.ReceiveTransfer(td);
                  if(tc != null)
                  {
                    retransfer retr = new retransfer() { itn_transaction_id = record.itn.id, retransfer_try_date = now  };
                    dc.retransfers.InsertOnSubmit(retr);
                    if(tc.trStatus == global::BMRetransfer.BMWebReference.ConfirmationStatus.CONFIRMED)
                    {
                      record.itn.retransferConfirmationDate = DateTime.Now;
                      retr.confirmed = true;
                      PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Retransfer for transaction with id {0} was confirmed.", record.itn.orderID);
                    }
                    else if(tc.trStatus == global::BMRetransfer.BMWebReference.ConfirmationStatus.ALREADY_CONFIRMED)
                    {
                      PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Retransfer for transaction with id {0} was already confirmed. This is not a normal situation and should be verified.", record.itn.orderID);
                      retr.confirmed = true;
                    }
                    else
                    {
                      if(record.triesCount == 2)
                      {
                        PTR3Core.LOG.Log(MsgStatusEnum.MS_Warning, "Retransfer for transaction with id {0} was not confirmed. This was the third and the last try", record.itn.orderID);
                      }
                      else
                      {
                        PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Retransfer for transaction with id {0} was not confirmed. Will try again when the converter is executed again", record.itn.orderID);
                      }

                      retr.confirmed = false;
                    }
                    dc.SubmitChanges();
                  }
                }
              }
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Save dynamic configuration");
              PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Finish processing");

            }
            catch (Exception ex)
            {
                PTR3Core.LOG.Log(MsgStatusEnum.MS_Error, ex, "");
                result = -1;
            }
            return result;
        }
 partial void Deleteretransfer(retransfer instance);
 partial void Insertretransfer(retransfer instance);
 partial void Updateretransfer(retransfer instance);
		private void detach_retransfers(retransfer entity)
		{
			this.SendPropertyChanging();
			entity.itn_transaction = null;
		}