public CheckResult Check(IUnitOfWork db, DTOMarketOrder order, IList <ListingOrderDTO> items) { var today = _time.GetAppNowTime(); var futureShipDate = items.Where(l => l.RestockDate.HasValue).Max(l => l.RestockDate); if (futureShipDate.HasValue && futureShipDate.Value > today.Date) { db.OrderNotifies.Add( ComposeNotify(order.Id, (int)OrderNotifyType.FutureShipping, 1, DateHelper.ToDateString(futureShipDate.Value.Date), _time.GetAppNowTime())); return(new CheckResult() { IsSuccess = false }); } return(new CheckResult() { IsSuccess = true }); }
public void RepublishInactive() { _log.Info("Republish"); using (var db = _dbFactory.GetRWDb()) { var lastDate = _time.GetAppNowTime().AddMonths(-1); var items = db.Items.GetAll() .Where(i => i.Market == (int)MarketType.Walmart && i.ItemPublishedStatus == (int)PublishedStatuses.PublishedInactive && (!i.LastForceRepublishedDate.HasValue || i.LastForceRepublishedDate.Value < lastDate)) .ToList(); _log.Info("Count to republish: " + items.Count); foreach (var item in items) { item.ItemPublishedStatusBeforeRepublishing = item.ItemPublishedStatus; item.LastForceRepublishedDate = _time.GetAppNowTime(); item.ItemPublishedStatus = (int)PublishedStatuses.HasChanges; _log.Info("Updated item status, ASIN=" + item.ASIN + ", market=" + MarketType.Walmart); } db.Commit(); } }
public static NotificationInfoViewModel GetInfo(IUnitOfWork db, ISettingsService settings, ITime time) { var notificationUndeliveredCount = db.Notifications.GetAllAsDto().Count(n => n.Type == (int)NotificationType.LabelGotStuck && !n.IsRead); var notificationUnshippedCount = db.Notifications.GetAllAsDto().Count(n => n.Type == (int)NotificationType.LabelNeverShipped && !n.IsRead); var messageCount = settings.GetUnansweredMessageCount() ?? 0; var model = new NotificationInfoViewModel() { UnreadNotificationUndeliveredCount = notificationUndeliveredCount, UnreadNotificationUnshippedCount = notificationUnshippedCount, UnansweredMessageCount = messageCount, }; var lastPickup = db.ScheduledPickups.GetLast(ShipmentProviderType.Dhl); if (lastPickup != null && (lastPickup.RequestPickupDate > time.GetAppNowTime().Date || (lastPickup.RequestPickupDate == time.GetAppNowTime().Date && lastPickup.RequestCloseTime >= time.GetAppNowTime().TimeOfDay))) { model.DhlPickupDate = lastPickup.RequestPickupDate; model.DhlReadyByTime = lastPickup.RequestReadyByTime; model.DhlCloseTime = lastPickup.RequestCloseTime; model.DhlPickupIsSuccess = !String.IsNullOrEmpty(lastPickup.ConfirmationNumber); } else { model.DhlPickupIsSuccess = true; } return(model); }
public bool StoreOrUpdateBarcode(IUnitOfWork db, long styleItemId, string barcode) { var existBarcode = db.StyleItemBarcodes.GetAllAsDto().FirstOrDefault(b => b.Barcode == barcode); if (existBarcode == null) { db.StyleItemBarcodes.Add(new StyleItemBarcode() { StyleItemId = styleItemId, Barcode = barcode, CreateDate = _time.GetAppNowTime(), }); _log.Info("Barcode=" + barcode + " was added, to styleItemId=" + styleItemId); return(true); } else { if (existBarcode.StyleItemId != styleItemId) { _log.Info("Barcode=" + barcode + " was moved, from styleItemId: " + existBarcode.StyleItemId + " => " + styleItemId); existBarcode.StyleItemId = styleItemId; } return(false); } }
public void ProcessAllMarketASINs(AmazonApi advApi) { var asinToProcess = new List <string>(); var fromDate = _time.GetAppNowTime().AddHours(-12); using (var db = _dbFactory.GetRWDb()) { var freshBBQuery = from bb in db.BuyBoxQuantities.GetAll() where bb.CreateDate > fromDate && bb.Market == (int)advApi.Market && bb.MarketplaceId == advApi.MarketplaceId select bb; var asinToProcessQuery = from i in db.Items.GetAllViewAsDto(advApi.Market, advApi.MarketplaceId) join bb in freshBBQuery on new { i.ASIN, i.Market, i.MarketplaceId } equals new { bb.ASIN, bb.Market, bb.MarketplaceId } into withBB from bb in withBB.DefaultIfEmpty() where bb == null select i.ASIN; asinToProcess = asinToProcessQuery.ToList(); } _log.Info("Total asin to process=" + asinToProcess.Count + ", market=" + advApi.Market + ", marketplaceId=" + advApi.MarketplaceId); CartInfo currentCartInfo = null; var index = 0; var step = 50; while (index < asinToProcess.Count) { var stepAsinList = asinToProcess.Skip(index).Take(step).ToList(); _log.Info("ASIN to process: " + String.Join(", ", stepAsinList)); var results = RequestQuantities(advApi, stepAsinList.ToList(), ref currentCartInfo); using (var db = _dbFactory.GetRWDb()) { foreach (var item in results) { _log.Info("Processed ASIN=" + item.ASIN + ", qty=" + item.Quantity + ", seller=" + item.SellerNickname); db.BuyBoxQuantities.Add(new BuyBoxQuantity() { ASIN = item.ASIN, Market = (int)advApi.Market, MarketplaceId = advApi.MarketplaceId, Quantity = item.Quantity, SellerNickname = item.SellerNickname, CreateDate = _time.GetAppNowTime() }); } _log.Info("Before commit"); db.Commit(); _log.Info("After commit"); } index += step; } }
public void CheckSaleEndForAll(IUnitOfWork db) { var saleList = db.StyleItemSales.GetAll().Where(s => !s.IsDeleted).ToList(); foreach (var sale in saleList) { UpdateSoldPieces(db, sale, _time.GetAppNowTime()); } var styleItemIds = saleList.Select(s => s.StyleItemId).ToList(); var styleItems = db.StyleItems .GetAllAsDto() .Where(si => styleItemIds.Contains(si.StyleItemId)) .ToList(); foreach (var sale in saleList) { var isSaleEnd = false; //End time (Amazon should automaticaly stop Sale) if (_time.GetAppNowTime() > sale.SaleEndDate) { _log.Info("Sale end by EndDate, saleId=" + sale.Id); isSaleEnd = true; } if (sale.MaxPiecesOnSale.HasValue) { if (sale.MaxPiecesMode == (int)MaxPiecesOnSaleMode.BySize) { if (sale.MaxPiecesOnSale <= sale.PiecesSoldOnSale) { _log.Info("Sale end by MaxPiecesOnSale, saleId=" + sale.Id); isSaleEnd = true; } } if (sale.MaxPiecesMode == (int)MaxPiecesOnSaleMode.ByStyle) { var saleStyleItem = styleItems.FirstOrDefault(si => si.StyleItemId == sale.StyleItemId); if (saleStyleItem == null) { _log.Info("Sale end by not style item info for them"); isSaleEnd = true; } else { var styleStyleItemIds = styleItems.Where(si => si.StyleId == saleStyleItem.StyleId).Select(si => si.StyleItemId).ToList(); var styleSales = saleList.Where(s => styleStyleItemIds.Contains(s.StyleItemId)).ToList(); var styleSoldPieces = styleSales.Sum(si => si.PiecesSoldOnSale); if (sale.MaxPiecesOnSale <= styleSoldPieces) { _log.Info("Sale end by MaxPiecesOnSale, saleId=" + sale.Id); isSaleEnd = true; } } } } UpdateSale(db, sale, isSaleEnd, _time.GetAppNowTime()); } }
public void ReProcessTrackNotifications(IDbFactory dbFactory) { var from = _time.GetAppNowTime().AddDays(-42); //NOTE: Possible/not sure: After 42 days USPS not update/keep info var orderFrom = _time.GetAppNowTime().AddDays(-90); using (var db = dbFactory.GetRWDb()) { var shippings = db.Orders.GetUnDeliveredShippingInfoes(_time.GetUtcTime(), false, null) .Where(o => (!o.TrackingStateDate.HasValue || o.TrackingStateDate.Value > from) && o.OrderDate > orderFrom) .OrderBy(o => o.OrderDate) .ToList(); shippings.AddRange(db.Orders.GetUnDeliveredMailInfoes(_time.GetUtcTime(), false, null) .Where(o => (!o.TrackingStateDate.HasValue || o.TrackingStateDate.Value > from) && o.OrderDate > orderFrom) .OrderBy(o => o.OrderDate) .ToList()); var actionService = new SystemActionService(_log, _time); var companyAddress = new CompanyAddressService(_company); var addressService = new AddressService(null, companyAddress.GetReturnAddress(MarketIdentifier.Empty()), companyAddress.GetPickupAddress(MarketIdentifier.Empty())); var notificationService = new NotificationService(_log, _time, dbFactory); var ruleList = new List <ITrackingRule>() { //new NeverShippedTrackingRule(_log, notificationService, _time), //new GetStuckTrackingRule(_log, notificationService, _time), //new NoticeLeftTrackingRule(actionService, _log) }; var trackingService = new TrackingManager(_log, actionService, addressService, _emailService, _time, ruleList); foreach (var shipping in shippings) { trackingService.CheckRules(db, shipping, shipping.TrackingStateEvent, shipping.TrackingStateDate, new List <TrackingRecord>() { new TrackingRecord() { Date = shipping.TrackingStateDate, Message = shipping.TrackingStateEvent, } }, ruleList); } } }
public IList <T> GetWithUpdates <T>(string key, Func <DateTime?, IList <T> > getUpdates, TimeSpan lifeTime) where T : IDbCacheableEntry { var existCache = _cacheList.ContainsKey(key) ? _cacheList[key] : null; DateTime?fromDate = null; IList <IDbCacheableEntry> items = new List <IDbCacheableEntry>(); if (existCache != null && existCache.Date.Add(lifeTime) < _time.GetAppNowTime()) { existCache = null; } if (existCache != null) { fromDate = existCache.Date; items = existCache.Items; } var newItems = getUpdates(fromDate); if (existCache == null) { existCache = new CacheEntry() { Date = _time.GetAppNowTime(), Items = newItems.Cast <IDbCacheableEntry>().ToList() }; _cacheList[key] = existCache; } else { foreach (var newItem in newItems) { var existItem = items.FirstOrDefault(i => i.Key == newItem.Key); if (existItem != null) { if (newItem.Deleted) { items.Remove(existItem); } else { var index = items.IndexOf(existItem); items[index] = newItem; } } else { items.Add(newItem); } } _cacheList[key].Date = _time.GetAppNowTime(); } return(_cacheList[key].Items.Cast <T>().ToList()); }
public void AddPoints() { using (var db = _dbFactory.GetRWDb()) { var marketList = new MarketplaceKeeper(_dbFactory, false).GetAll(); var today = _time.GetAppNowTime().Date; foreach (var market in marketList) { var listingErrorCount = (from i in db.Items.GetAll() join l in db.Listings.GetAll() on i.Id equals l.ItemId where l.RealQuantity > 0 && !l.IsRemoved && (i.ItemPublishedStatus == (int)PublishedStatuses.PublishingErrors || i.ItemPublishedStatus == (int)PublishedStatuses.PublishedInProgress) && i.Market == market.Market && (i.MarketplaceId == market.MarketplaceId || String.IsNullOrEmpty(market.MarketplaceId)) select i.Id ).Count(); var marketTag = market.Market + "_" + market.MarketplaceId; var chart = db.Charts.GetAll().FirstOrDefault(ch => ch.ChartName == ChartHelper.ListingErrorChartName && ch.ChartTag == marketTag); if (chart == null) { chart = new Chart() { ChartName = ChartHelper.ListingErrorChartName, ChartSubGroup = MarketHelper.GetMarketName(market.Market, market.MarketplaceId), ChartTag = marketTag, CreateDate = _time.GetAppNowTime() }; db.Charts.Add(chart); db.Commit(); } var existPoint = db.ChartPoints.GetAll().FirstOrDefault(p => p.ChartId == chart.Id && p.Date == today); if (existPoint == null) { existPoint = new ChartPoint() { ChartId = chart.Id, Date = today, }; db.ChartPoints.Add(existPoint); } existPoint.Value = listingErrorCount; } db.Commit(); } }
public void ReCheckPaymentStatuses(IPaymentStatusApi api) { using (var db = _dbFactory.GetRWDb()) { var orderIdsToUpdate = db.Orders.GetAll() .Where(o => o.Market == (int)MarketType.Shopify && o.OrderStatus == OrderStatusEnumEx.Unshipped && o.DropShipperId != DSHelper.OverseasId) .Select(o => o.MarketOrderId) .Distinct() .ToList(); _log.Info("Items to recheck: " + orderIdsToUpdate.Count); var sleeper = new StepSleeper(TimeSpan.FromSeconds(1), 3); foreach (var orderId in orderIdsToUpdate) { var riskStatus = RetryHelper.ActionWithRetries(() => { return(api.GetOrderRisk(orderId)); }, _log); if (riskStatus?.PaymentValidationStatuses == (int)PaymentValidationStatuses.Red) { var validationInfo = new OrderValidationDTO() { CreateDate = _time.GetAppNowTime(), VerificationStatus = riskStatus.Recommendation, Score = StringHelper.TryGetLong(riskStatus.Score) }; var dbOrderList = db.Orders.GetAll().Where(o => o.MarketOrderId == orderId).ToList(); foreach (var dbOrder in dbOrderList) { if (dbOrder.OrderStatus == OrderStatusEnumEx.Shipped) { continue; } if (dbOrder.SignifydStatus == riskStatus.PaymentValidationStatuses) { continue; } dbOrder.SignifydDesc = JsonConvert.SerializeObject(validationInfo, Formatting.Indented); dbOrder.SignifydStatus = riskStatus.PaymentValidationStatuses; _log.Info("OnHold By PaymentChecker, orderId=" + dbOrder.AmazonIdentifier); dbOrder.OnHold = true; dbOrder.OnHoldUpdateDate = _time.GetAppNowTime(); } } } db.Commit(); } }
public CheckResult Check(IUnitOfWork db, DTOMarketOrder order, IList <ListingOrderDTO> items) { var result = DuplicateValidatorCheck(db, order, items); _log.Info("CheckDuplicate, result=" + result.IsSuccess + ", message=" + result.Message); if (!result.IsSuccess) { db.OrderNotifies.Add( ComposeNotify(order.Id, (int)OrderNotifyType.Duplicate, 1, result.Message, _time.GetAppNowTime())); db.Commit(); var emailInfo = new DuplicateEmailInfo(_emailService.AddressService, order.CustomerOrderId, (MarketType)order.Market, new DuplicateOrdersDTO { Items = items, OrderNumbers = result.AdditionalData }, order.BuyerName, order.BuyerEmail); _emailService.SendEmail(emailInfo, CallSource.Service); _log.Info("Send duplicated order email, orderId=" + order.Id); db.OrderEmailNotifies.Add(new OrderEmailNotify() { OrderNumber = order.OrderId, Reason = "System emailed, found duplicate", Type = (int)OrderEmailNotifyType.OutputDuplicateAlertEmail, CreateDate = _time.GetUtcTime(), }); db.OrderComments.Add(new OrderComment() { OrderId = order.Id, Message = "[System] Duplicate order alert email sent", Type = (int)CommentType.OutputEmail, CreateDate = _time.GetAppNowTime(), UpdateDate = _time.GetAppNowTime() }); db.Commit(); } return(result); }
public void RemoveExist(string relatedEntityId, NotificationType type) { using (var db = _dbFactory.GetRWDb()) { var entity = db.Notifications.GetAll().FirstOrDefault(n => n.Type == (int)type && n.RelatedEntityId == relatedEntityId && !n.IsRead); if (entity != null) { _log.Info("RemoveExist. Notification was marked as read, id=" + entity.Id); db.Notifications.MarkAsRead(entity.Id, _time.GetAppNowTime(), null); db.Commit(); } } }
public CallResult UpdateQuantity(ItemDTO item) { using (var db = _dbFactory.GetRWDb()) { var itemView = db.Items.GetAllViewAsDto().FirstOrDefault(i => i.SKU == item.SKU); if (itemView == null) { return(new CallResult() { Status = CallStatus.Fail, Message = "Unable to find item: " + item.SKU }); } if (!itemView.StyleItemId.HasValue) { return(new CallResult() { Status = CallStatus.Fail, Message = "Item hasn't linked StyleItemId: " + item.SKU }); } var dbStyleItem = db.StyleItems.GetAll().FirstOrDefault(si => si.Id == itemView.StyleItemId); if (dbStyleItem == null) { return(new CallResult() { Status = CallStatus.Fail, Message = "Unable to find styleItem: " + dbStyleItem.Id }); } if (dbStyleItem.Quantity != item.RealQuantity) { _log.Info("Quantity changed, SKU=" + item.SKU + ", " + dbStyleItem.Quantity + "=>" + item.RealQuantity); } dbStyleItem.Quantity = item.RealQuantity; dbStyleItem.QuantitySetDate = _time.GetAppNowTime(); dbStyleItem.QuantitySetBy = null; db.Commit(); SystemActionHelper.RequestQuantityDistribution(db, _actionService, dbStyleItem.StyleId, null); } return(new CallResult() { Status = CallStatus.Success }); }
public void ProcessResult(CheckResult result, Order dbOrder, DTOOrder order, IList <ListingOrderDTO> orderItems) { if (result.IsSuccess) { _log.Info("Send sign confirmation request order email, orderId=" + order.Id); var alreadySend = _db.OrderEmailNotifies.IsExist(order.OrderId, OrderEmailNotifyType.OutputSignConfirmationEmail); if (alreadySend) { return; } var emailInfo = new SignConfirmationRequestEmailInfo(_emailService.AddressService, null, order.OrderId, (MarketType)order.Market, orderItems, //NOTE: make sense only express or not ShippingUtils.IsServiceNextDay(order.InitialServiceType) ? ShippingTypeCode.PriorityExpress : ShippingTypeCode.Standard, order.BuyerName, order.BuyerEmail); _emailService.SendEmail(emailInfo, CallSource.Service); _db.OrderEmailNotifies.Add(new OrderEmailNotify() { OrderNumber = order.OrderId, Reason = "System emailed, request signconfirmation", Type = (int)OrderEmailNotifyType.OutputSignConfirmationEmail, CreateDate = _time.GetUtcTime(), }); _db.OrderComments.Add(new OrderComment() { OrderId = order.Id, Message = "[System] Sign Confirmation email sent", Type = (int)CommentType.Address, CreateDate = _time.GetAppNowTime(), UpdateDate = _time.GetAppNowTime() }); _db.Commit(); } }
public IList <DhlInvoiceDTO> GetRecordsFromFile(string filePath) { StreamReader streamReader = new StreamReader(filePath); CsvReader reader = new CsvReader(streamReader, new CsvConfiguration { HasHeaderRecord = true, Delimiter = ",", TrimFields = true, }); var filename = Path.GetFileName(filePath); var results = new List <DhlInvoiceDTO>(); while (reader.Read()) { var invoice = new DhlInvoiceDTO(); invoice.InvoiceNumber = reader.GetField <string>("INVOICE #"); invoice.InvoiceDate = reader.GetField <DateTime>("INVOICE DATE"); invoice.BillNumber = reader.GetField <string>("AIRBILL #"); invoice.Dimensions = reader.GetField <string>("DIMENSIONS"); invoice.SourceFile = filename; invoice.OrderNumber = reader.GetField <string>("SHIPPER REFERENCE"); invoice.ChargedBase = reader.GetField <decimal>("BASE CHARGE AMOUNT"); invoice.ChargedSummary = reader.GetField <decimal>("BASE CHARGE AMOUNT") + (reader.GetField <decimal?>("CHARGE 1 AMT") ?? 0) + (reader.GetField <decimal?>("CHARGE 2 AMT") ?? 0) + (reader.GetField <decimal?>("CHARGE 3 AMT") ?? 0) + (reader.GetField <decimal?>("CHARGE 4 AMT") ?? 0) + (reader.GetField <decimal?>("CHARGE 5 AMT") ?? 0) + (reader.GetField <decimal?>("CHARGE 6 AMT") ?? 0) + (reader.GetField <decimal?>("CHARGE 7 AMT") ?? 0) + (reader.GetField <decimal?>("CHARGE 8 AMT") ?? 0); invoice.ChargedCredit = (reader.GetField <decimal?>("CREDIT 1 AMT") ?? 0) + (reader.GetField <decimal?>("CREDIT 2 AMT") ?? 0) + (reader.GetField <decimal?>("CREDIT 3 AMT") ?? 0); invoice.CreateDate = _time.GetAppNowTime(); results.Add(invoice); } _log.Info("File was processed, file: " + filename + ", records: " + results.Count); return(results); }
public void Check() { if (!_time.IsBusinessDay(_time.GetAppNowTime().Date)) { return; } var warningPeriod = _time.AddBusinessDays(_time.GetAppNowTime().Date, -1); var minDate = DateTime.Now.AddMonths(-3); _log.Info("warningPeriod=" + warningPeriod); var messages = new List <string>(); using (var db = _dbFactory.GetRWDb()) { var items = db.Items.GetAll().Where(i => i.CreateDate > warningPeriod && i.ItemPublishedStatus == (int)PublishedStatuses.PublishingErrors && i.CreatedBy.HasValue) .ToList(); var users = db.Users.GetAllAsDto().ToList(); var userIds = items.Select(i => i.CreatedBy).Distinct().ToList(); foreach (var userId in userIds) { var user = users.FirstOrDefault(u => u.Id == userId); if (user == null) { continue; } var userItems = items.Where(i => i.CreatedBy == userId) .OrderBy(i => i.CreateDate) .ToList(); var message = String.Format("The following listings (created by {0}) have publishing errors: <br/>", user.Name) + String.Join("<br/>", userItems.Select(i => DateHelper.ToDateTimeString(i.CreateDate) + " - " + i.ASIN));// + " - " + i.ItemPublishedStatusReason)); _log.Info(user.Email + " - " + message); _emailService.SendSystemEmail("System Notification: " + Name + " - To Review (" + userItems.Count() + ")", message, user.Email, EmailHelper.RafiEmail + ", " + EmailHelper.SupportDgtexEmail); } } }
private static DateTime GetFromPeriod(ITime time, FilterPeriod period) { DateTime fromDate = DateTime.Today; var today = time.GetAppNowTime().Date; switch (period) { case FilterPeriod.Day: //Day fromDate = today; break; case FilterPeriod.Week: //Week fromDate = today.AddDays(-7); break; case FilterPeriod.Month: //Month fromDate = today.AddMonths(-1); break; case FilterPeriod.ThreeMonth: //3 month fromDate = today.AddMonths(-3); break; } return(fromDate); }
public static void Escalate(IUnitOfWork db, ITime time, long emailId, string orderNumber, bool escalated) { if (orderNumber == null) { throw new ArgumentException("Value cann not be null", "orderNumber"); } var order = db.Orders.GetFiltered(x => x.CustomerOrderId == orderNumber).FirstOrDefault(); if (order == null) { throw new ArgumentException("Value cann not be null", "orderNumber"); } var oldNotifies = db.OrderNotifies.GetFiltered(x => x.OrderId == order.Id && x.Type == (int)OrderNotifyType.Escalated).ToList(); foreach (var o in oldNotifies) { db.OrderNotifies.Remove(o); } if (escalated) { db.OrderNotifies.Add(new Core.Entities.Orders.OrderNotify() { OrderId = order.Id, Type = (int)OrderNotifyType.Escalated, CreateDate = time.GetAppNowTime(), Status = 1 }); } db.Commit(); }
public OpenBoxViewModel ToBox(IUnitOfWork db, ITime time) { var dbStyle = db.Styles.GetAll().FirstOrDefault(st => st.StyleID == StyleString && !st.Deleted); var baseBoxId = dbStyle.StyleID + "-" + time.GetAppNowTime().ToString("MMddyyyy"); var index = 0; var boxId = baseBoxId; while (db.OpenBoxes.GetAll().Count(b => b.BoxBarcode == boxId) > 0) { index++; boxId = baseBoxId + "-" + index; } return(new OpenBoxViewModel() { Id = Id, BoxBarcode = boxId, StyleString = StyleString, StyleId = dbStyle?.Id ?? 0, CreateDateUtc = ReceiveDate, BoxQuantity = BoxQuantity, Type = (int)BoxTypes.Preorder, StyleItems = new StyleItemCollection() { Items = Sizes } }); }
public void Process(IUnitOfWork db, EmailReadingResult result) { var orderIdList = new List <string>(); if (result.MatchedIdList != null) { orderIdList.AddRange(result.MatchedIdList); } orderIdList = orderIdList.Distinct().ToList(); foreach (var orderId in orderIdList) { var existDb = db.FeedbackBlackLists.GetAll().FirstOrDefault(o => o.OrderId == orderId); if (existDb == null) { _log.Debug("Add to black list orderId=" + orderId); db.FeedbackBlackLists.Add(new FeedbackBlackList() { OrderId = orderId, Reason = "[Auto] Has related email messages", CreateDate = _time.GetAppNowTime() }); } } db.Commit(); }
public void AddRecord(string actionName, long styleItemId, string data, long?by) { if (actionName == null) { return; } try { using (var db = _dbFactory.GetRDb()) { var newRecord = new StyleItemActionHistory() { ActionName = actionName, StyleItemId = styleItemId, Data = data, CreateDate = _time.GetAppNowTime(), CreatedBy = by, }; db.StyleItemActionHistories.Add(newRecord); db.Commit(); } } catch (Exception ex) { _log.Error("StyleItemActionHistoryService.AddRecord, styleItemId=" + styleItemId, ex); } }
public void Accept(long userId, HttpRequestBase request) { String ip = null; try { ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ip)) { ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } } catch (Exception ex) { } var details = "DateTime (EST): " + _time.GetAppNowTime() + "\r\n UserHostAddress: " + request.UserHostAddress + "\r\n IPAddress: " + ip + "\r\n Browser: " + request.Browser?.Browser + ", " + request.Browser?.Version + "\r\n UrlReferrer: " + request.UrlReferrer + "\r\n Url: " + request.Url; using (var db = _dbFactory.GetRWDb()) { var user = db.Users.Get(userId); user.IsAcceptedTerms = true; user.AcceptTermsDetails = details; db.Commit(); AccessManager.User.IsAcceptedTerms = true; } }
public void FindListingsSuitableForPromotion() { var today = _time.GetAppNowTime().Date; using (var db = _dbFactory.GetRWDb()) { var parentItems = db.ParentItems.GetAllAsDto(MarketType.eBay, MarketplaceKeeper.eBayAll4Kids).ToList(); var items = db.Items.GetAllViewActual().Where(i => i.Market == (int)MarketType.eBay).ToList(); foreach (var parentItem in parentItems) { var childItems = items.Where(i => i.ParentASIN == parentItem.ASIN).ToList(); if (childItems.Count > 0 && childItems.All(i => i.SalePrice.HasValue && i.SaleStartDate <= today)) { var discountValue = childItems[0].CurrentPrice - childItems[0].SalePrice.Value; if (childItems.All(i => i.CurrentPrice - i.SalePrice.Value == discountValue)) { _log.Info("Enable discount, ParentASIN=" + parentItem.ASIN); //TODO: set update price flag var listingIds = childItems.Select(l => l.ListingEntityId).ToList(); var dbListings = db.Listings.GetAll().Where(l => listingIds.Contains(l.Id)).ToList(); foreach (var dbListing in dbListings) { dbListing.PriceUpdateRequested = true; } } } db.Commit(); } } }
protected void UpdateFeedStatus(IUnitOfWork db, FeedDTO currentFeed, IList <WalmartFeedItemDTO> feedItems, TimeSpan waitTimeOfProcessing) { var thresholdDate = waitTimeOfProcessing == TimeSpan.Zero ? _time.GetAppNowTime().AddHours(-8) : _time.GetAppNowTime().Subtract(waitTimeOfProcessing); _log.Info("thresholdDate=" + thresholdDate); if (feedItems.All(i => WalmartUtils.ConvertFromFeedItemPublishedStatusToStandard(i.Status) != PublishedStatuses.PublishedInProgress) || currentFeed.SubmitDate < thresholdDate) { var feed = db.Feeds.GetAll().FirstOrDefault(f => f.Id == currentFeed.Id); if (feed != null) { feed.Status = (int)FeedStatus.Processed; db.Commit(); currentFeed.Status = (int)FeedStatus.Processed; _log.Info(String.Format("Mark feed, id={0}, marketId={1}, as processed", feed.Id, feed.AmazonIdentifier)); } } }
public static EmailAttachmentViewModel GetStyleImageAsAttachment(IUnitOfWork db, ILogService log, ITime time, string styleString) { var style = db.Styles.GetActiveByStyleIdAsDto(styleString); if (style != null && !String.IsNullOrEmpty(style.Image)) { try { var path = style.Image; var fileExt = Path.GetExtension(Models.UrlHelper.RemoveUrlParams(path)); var sourceFileName = style.StyleID + "_" + time.GetAppNowTime().ToString("yyyyMMddHHmmsss") + fileExt; var dir = Models.UrlHelper.GetUploadEmailAttachmentPath(); var fileName = FileHelper.GetNotExistFileName(dir, sourceFileName); var destinationPath = Path.Combine(dir, fileName); ImageHelper.DownloadRemoteImageFile(style.Image, destinationPath, null); return(new EmailAttachmentViewModel() { ViewUrl = style.Image, ServerFileName = fileName, }); } catch (Exception ex) { log.Error("GetStyleImageAsAttachment, styleString=" + styleString, ex); } } return(null); }
public static void AddQuantityOperation(ILogService log, IUnitOfWork db, IQuantityManager quantityManager, string orderId, IList <DTOOrderItem> items, ITime time, long?by) { var operationDto = new QuantityOperationDTO(); operationDto.Type = (int)QuantityOperationType.FromMailPage; operationDto.OrderId = orderId; operationDto.Comment = String.Empty; operationDto.QuantityChanges = new List <QuantityChangeDTO>(); if (items != null) { foreach (var item in items) { operationDto.QuantityChanges.Add(new QuantityChangeDTO() { StyleId = item.StyleEntityId ?? 0, StyleItemId = item.StyleItemId ?? 0, Quantity = item.Quantity, }); } } quantityManager.AddQuantityOperation(db, operationDto, time.GetAppNowTime(), by); }
public void ProcessRefundsAddComments() { var orderNumbers = new string[] { "002-4984322-1582658", "115-7133068-0543442", "107-3678266-6682660", "104-9680685-2993855", "114-2903306-3741829", "110-9470669-5336239", "701-4988323-0546632", "108-4618630-0086635", "109-8552981-9073035", "114-6351653-1882624", "111-9932301-2780224", "109-4832961-2930620", "108-4433058-4988231", "701-2615147-4537063", "106-3092827-4661027", "102-6937670-6201809", "702-0464553-4177858" }; using (var db = _dbFactory.GetRWDb()) { var actions = db.SystemActions.GetAll() .Where(a => a.Type == (int)SystemActionType.UpdateOnMarketReturnOrder) .ToList(); foreach (var action in actions) { if (!orderNumbers.Contains(action.Tag)) { continue; } var data = JsonConvert.DeserializeObject <ReturnOrderInput>(action.InputData); var order = db.Orders.GetByOrderNumber(data.OrderNumber); var unsuitableData = false; var unsuitableMessage = ""; var message = String.Format( "System accidently deducted shipping twice from a refund. If client complains, confirm additional refund wasn’t processed yet, and refund ONCE additional {0}{1}", PriceHelper.FormatCurrency(order.TotalPriceCurrency), data.Items.Sum(i => i.DeductShippingPrice)); db.OrderComments.Add(new OrderComment() { OrderId = order.Id, Message = message, Type = (int)CommentType.ReturnExchange, CreateDate = _time.GetAppNowTime(), }); db.Commit(); } } }
public void GetBalance() { var labelService = new LabelService(GetShipmentProviders(_company), _log, _time, _dbFactory, _emailService, _pdfMaker, AddressService.Default); using (var db = new UnitOfWork(_log)) { labelService.UpdateBalance(db, _time.GetAppNowTime()); } }
public void ConvertStyleToStyleImages() { using (var db = _dbFactory.GetRWDb()) { var allStyles = db.Styles.GetAll().ToList(); var allStyleImages = db.StyleImages.GetAll().ToList(); foreach (var style in allStyles) { var styleImages = allStyleImages.Where(im => im.StyleId == style.Id).ToList(); if (!styleImages.Any()) { if (!String.IsNullOrEmpty(style.Image)) { db.StyleImages.Add(new StyleImage() { StyleId = style.Id, Image = style.Image, Type = (int)StyleImageType.None, IsDefault = true, CreateDate = _time.GetAppNowTime() }); } if (!String.IsNullOrEmpty(style.AdditionalImages)) { var images = style.AdditionalImages.Split(",;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); foreach (var image in images) { db.StyleImages.Add(new StyleImage() { StyleId = style.Id, Image = image, Type = (int)StyleImageType.None, IsDefault = false, CreateDate = _time.GetAppNowTime() }); } } db.Commit(); } } } }
public bool IsAccept(OrderToTrackDTO orderToTrackInfo, string status, DateTime?statusDate, IList <TrackingRecord> records) { var today = _time.GetAppNowTime().Date; //var now = _time.GetAppNowTime(); //почта после 60 дней за них не отвечает //старше 55 дней if (statusDate.HasValue && statusDate.Value.AddDays(55) < today) { return(false); } //5. Don’t show “Label Never Shipped” for 36 hours after it was generated. //NOTE: round to 2 days //TASK: давай сделаем 10 if (statusDate.HasValue && _time.GetBizDaysCount(statusDate.Value.Date, today) > 10) { return(false); } if (orderToTrackInfo.LabelCanceled) { return(false); } if (orderToTrackInfo.ActualDeliveryDate.HasValue) { return(false); } if (status.ToLower().Contains("delivered")) { return(false); } if ((status.Contains(USPSPreShipmentInfoStatus) || status == USPSShipmentPickedUp || status == USPSNoRecordStatus || status == USPSShipmentProcessing) && statusDate.HasValue) { var dayCount = _time.GetBizDaysCount(statusDate.Value.Date, today); if (dayCount > 1) { return(true); } } return(false); }