/// <summary> /// Performs business logic actions specified for this task handler. /// </summary> protected override void PerformActions() { ClearTemporaryDocumentMedia(); DateTime dateToConsider = Utils.Today.Date; TimeSpan ts; if (TimeSpan.TryParse(Utils.GetSystemValue("AgentExecutionTime"), out ts)) { if (Utils.Now < (Utils.Today + ts)) { dateToConsider = dateToConsider.AddDays(-1); } } ProjectUsageHandler.CreatePaymentSummaries(dateToConsider); //Monthly retry process with in the Graceperiod ProjectFinanceHandler.ProcessInvoicesAndPayments(0, dateToConsider, false, 0); // Run CompanyStatusHandler and ProjectStatusHandler in same datacontext using (StageBitzDB dataContext = new StageBitzDB()) { ProjectStatusHandler.UpdateProjectExpirations(dateToConsider, dataContext); CompanyStatusHandler.UpdateCompanyExpirations(dateToConsider, dataContext); dataContext.SaveChanges(); } CompanyStatusHandler.SuspendNoPaymentOptionCompanies(dateToConsider); SendUserEmailNotifications(dateToConsider); SendBookingNotifications(); SendBookingOverdueAndDelayedEmails(dateToConsider.AddDays(1)); DeleteOldExportedZipFiles(); }
/// <summary> /// Sends the booking delayed emails. /// </summary> /// <param name="dateToConsider">The date to consider.</param> public static void SendBookingDelayedEmails(DateTime dateToConsider) { using (StageBitzDB dataContext = new StageBitzDB()) { InventoryBL inventoryBL = new InventoryBL(dataContext); int delayedEmailCodeId = Utils.GetCodeIdByCodeValue("EmailTemplateTypeCode", "BOOKINGDELAYED"); string userWebUrl = Utils.GetSystemValue("SBUserWebURL"); var delayedBookings = (from ibs in dataContext.ItemBookings.Where(ibs => dataContext.IsItemBookingDelayedByDate(ibs.ItemBookingId, dateToConsider)) from eh in dataContext.EmailHistories.Where(eh => ibs.ItemBookingId == eh.RelatedId && eh.RelatedTable == "ItemBooking" && eh.EmailTemplateTypeCodeId == delayedEmailCodeId).DefaultIfEmpty().Take(1) join b in dataContext.Bookings on ibs.BookingId equals b.BookingId from ib in dataContext.ItemBriefs.Where(ib => ib.ItemBriefId == ibs.RelatedId && b.RelatedTable == "Project").DefaultIfEmpty().Take(1) from npb in dataContext.NonProjectBookings.Where(npb => npb.NonProjectBookingId == b.RelatedId && b.RelatedTable == "NonProject").DefaultIfEmpty().Take(1) join i in dataContext.Items on ibs.ItemId equals i.ItemId join u in dataContext.Users on ibs.CreatedBy equals u.UserId where eh == null && ibs.IsActive && i.CompanyId.HasValue select new { ItemBrief = ib, NonProjectBooking = npb, CompanyId = i.CompanyId.Value, CreatedBy = u, ItemBooking = ibs, Item = i }).ToList(); foreach (var delayedBooking in delayedBookings) { User locationManager = inventoryBL.GetContactBookingManager(delayedBooking.Item.CompanyId.Value, delayedBooking.Item.LocationId); if (locationManager != null) { Data.EmailHistory emailHistory = new EmailHistory { EmailTemplateTypeCodeId = delayedEmailCodeId, RelatedId = delayedBooking.ItemBooking.ItemBookingId, RelatedTable = "ItemBooking", CreatedDate = Utils.Now }; dataContext.EmailHistories.AddObject(emailHistory); dataContext.SaveChanges(); string inventoryManagerName = string.Concat(locationManager.FirstName, " ", locationManager.LastName); if (delayedBooking.ItemBrief != null) { string url = string.Format("{0}/ItemBrief/ItemBriefDetails.aspx?ItemBriefId={1}&TabId=3", userWebUrl, delayedBooking.ItemBrief.ItemBriefId); EmailSender.SendBookingDelayedEmail(delayedBooking.CreatedBy.Email1, delayedBooking.CreatedBy.FirstName, delayedBooking.ItemBrief.Name, url, inventoryManagerName, locationManager.Email1); } else { EmailSender.SendBookingDelayedEmailForNonProject(delayedBooking.CreatedBy.Email1, delayedBooking.CreatedBy.FirstName, delayedBooking.NonProjectBooking.Name, inventoryManagerName, locationManager.Email1); } } } } }
/// <summary> /// Updates the task schedule to to reflect the latest run date and time. /// </summary> private void UpdateLastRunDate() { using (StageBitzDB dataContext = new StageBitzDB()) { SystemTask task = dataContext.SystemTasks.Where(t => t.TaskTypeCodeId == TaskTypeCodeId).FirstOrDefault(); task.LastRunDate = Utils.Now; dataContext.SaveChanges(); } }
/// <summary> /// Creates the payment summaries. /// This will create payment summaries/Invoice Requests for the repeat payments to be charged at the end of the cycle /// </summary> /// <param name="dateToConsider">The date to consider.</param> public static void CreatePaymentSummaries(DateTime dateToConsider) { using (StageBitzDB dataContext = new StageBitzDB()) { FinanceBL financeBL = new FinanceBL(dataContext); CompanyBL companyBL = new CompanyBL(dataContext); //This will get all the CompanyPaymentPackages that needs to be Charged for considering cycle List <CompanyPaymentPackage> companyPaymentPackages = (from cpp in dataContext.CompanyPaymentPackages join cps in dataContext.CompanyPaymentSummaries on cpp.CompanyId equals cps.CompanyId where cps.IsImmidiateFutureRecordCreated == false && cpp.StartDate <= dateToConsider && (cpp.EndDate > dateToConsider || cpp.EndDate == null) && cps.NextPaymentCycleStartingDate <= dateToConsider select cpp).Distinct().ToList(); foreach (CompanyPaymentPackage companyPaymentPackage in companyPaymentPackages) { Data.Company company = companyPaymentPackage.Company; PaymentSummaryDetails paymentSummaryDetails = new PaymentSummaryDetails() { CompanyPaymentPackage = companyPaymentPackage, CompanyId = companyPaymentPackage.CompanyId, ShouldProcess = !(companyBL.IsCompanySuspended(companyPaymentPackage.CompanyId) || companyBL.HasCompanySuspendedbySBAdmin(companyPaymentPackage.CompanyId)), UserId = 0, PackageStartDate = companyPaymentPackage.StartDate, PaymentMethodCodeId = companyPaymentPackage.PaymentMethodCodeId, HasPackageChanged = false, ProjectPaymentPackageTypeId = companyPaymentPackage.ProjectPaymentPackageTypeId, InventoryPaymentPackageTypeId = companyPaymentPackage.InventoryPaymentPackageTypeId, IsEducationPackage = companyPaymentPackage.IsEducationalPackage, PaymentDurationTypeCodeId = companyPaymentPackage.PaymentDurationCodeId, DiscountCodeUsageToApply = financeBL.GetLatestDiscountCodeUsage(companyPaymentPackage.CompanyId) }; //Get IsImmidiateFutureRecordCreated "False" Future Anual Summary records and make them as "True".(To commit as Processed) var unprocessedFutureSummaries = (from cps in dataContext.CompanyPaymentSummaries where cps.IsImmidiateFutureRecordCreated == false && cps.CompanyId == companyPaymentPackage.CompanyId && cps.ToDate <= dateToConsider select cps).ToList(); foreach (CompanyPaymentSummary cps in unprocessedFutureSummaries) { cps.IsImmidiateFutureRecordCreated = true; cps.LastUpdatedDate = Utils.Today; cps.LastUpdatedBy = 0; } CreateCompanyPaymentSummaries(paymentSummaryDetails, dateToConsider, dataContext); } dataContext.SaveChanges(); } }
/// <summary> /// Sends the notifications. /// </summary> public static void SendNotifications() { using (StageBitzDB dataContext = new StageBitzDB()) { var bookingNotifications = from dbn in dataContext.DailyBookingNotifications join cbn in dataContext.CompanyBookingNumbers on dbn.CompanyBookingNumberId equals cbn.CompanyBookingNumberId select new { BookingNotification = dbn, RelatedTable = cbn.Booking.RelatedTable, BookingId = dbn.BookingId, CompanyId = cbn.CompanyId, BookingNumber = cbn.BookingNumber, CompanyName = cbn.Company.CompanyName, UserId = dbn.UserId, IsInventoryManager = dbn.IsInventoryManager, UserName = dbn.User.FirstName, ProjectId = dbn.Booking.RelatedId, UserEmail = dbn.User.Email1 }; foreach (var bookingNotification in bookingNotifications) { string userWebUrl = Utils.GetSystemValue("SBUserWebURL"); string url = string.Empty; if (bookingNotification.IsInventoryManager) { url = string.Format("{0}/Inventory/BookingDetails.aspx?BookingId={1}&CompanyId={2}", userWebUrl, bookingNotification.BookingId, bookingNotification.CompanyId); } else { //Now it has to decide which to open (IM or Non Project Booking User) if (bookingNotification.RelatedTable == "Project") { url = string.Format("{0}/Project/ProjectBookingDetails.aspx?projectid={1}", userWebUrl, bookingNotification.ProjectId); } else { url = string.Format("{0}/Inventory/MyBookingDetails.aspx?BookingId={1}&CompanyId={2}", userWebUrl, bookingNotification.BookingId, bookingNotification.CompanyId); } } EmailSender.SendBookingNotificationEmail(bookingNotification.UserEmail, bookingNotification.UserName, bookingNotification.BookingNumber.ToString(CultureInfo.InvariantCulture), url); dataContext.DailyBookingNotifications.DeleteObject(bookingNotification.BookingNotification); } dataContext.SaveChanges(); } }
/// <summary> /// Update agent execution flag. /// </summary> /// <param name="isExecuted">The is executed.</param> private static void UpDateAgentExecutionFlag(string isExecuted) { try { using (StageBitzDB dataContext = new StageBitzDB()) { SystemValue sysValue = dataContext.SystemValues.Where(sv => sv.Name == "IsAgentRunning").FirstOrDefault(); sysValue.Value = isExecuted; dataContext.SaveChanges(); } } catch (Exception ex) { AgentErrorLog.HandleException(ex); } }
/// <summary> /// Updates the pricing plan and payment summary when closing free trial. /// </summary> /// <param name="companyId">The company identifier.</param> /// <param name="userId">The user identifier.</param> /// <param name="dataContext">The data context.</param> public static void UpdatePricingPlanAndPaymentSummaryClosingFreeTrial(int companyId, int userId, StageBitzDB dataContext) { //if this is the last free trial project which is going to be closed we should end the free trial also take the start date of the selected package to Today //usually a company will have one free trial project, but when clearing finance a company can have more free trial projects, //so closing one free trial project doesn't end the free trial of that company. ProjectBL projectBL = new ProjectBL(dataContext); FinanceBL financeBL = new FinanceBL(dataContext); if (projectBL.GetFreeTrialProjectsNotInClosedStatus(companyId, Utils.Today).Count() == 1) { CompanyPaymentPackage currentPricingPlan = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(companyId); if (currentPricingPlan != null) { currentPricingPlan.StartDate = Utils.Today; } DiscountCodeUsage discountCodeUsage = financeBL.GetDiscountCodeUsageByDate(Utils.Today, companyId); UpdatePaymentSummaryForFreeTrialCompany(companyId, discountCodeUsage, null, userId, dataContext); dataContext.SaveChanges(); } }
/// <summary> /// Suspends the no payment option companies. /// </summary> /// <param name="dateToConsider">The date to consider.</param> public static void SuspendNoPaymentOptionCompanies(DateTime dateToConsider) { using (StageBitzDB dataContext = new StageBitzDB()) { FinanceBL financeBL = new FinanceBL(dataContext); CompanyBL companyBL = new CompanyBL(dataContext); //Change the status to SuspendForNoPaymentOption if there are No option being selected. //Get all the No Payment option companies and check if they have to pay a certain amount before a certain period. //Send them an email, If they have a due amount to pay 2 weeks ahead (PBI 11444). int companyActiveStatusCodeId = Utils.GetCodeIdByCodeValue("CompanyStatus", "ACTIVE"); List <CompanyPaymentPackage> companyPaymentPackages = (from cpp in dataContext.CompanyPaymentPackages where cpp.Company.CompanyStatusCodeId == companyActiveStatusCodeId && cpp.PaymentMethodCodeId == null && cpp.StartDate <= dateToConsider && (cpp.EndDate > dateToConsider || cpp.EndDate == null) select cpp).Distinct().ToList(); foreach (CompanyPaymentPackage cpp in companyPaymentPackages) { int companyId = cpp.CompanyId; decimal totalDue = financeBL.CalculateALLPackageAmountsByPeriod(cpp.ProjectPaymentPackageTypeId, cpp.InventoryPaymentPackageTypeId, cpp.PaymentDurationCodeId); if (totalDue > 0) { DiscountCodeUsage currentdiscountCodeUsage = financeBL.GetDiscountCodeUsageByDate(dateToConsider, companyId); //Get the current DiscountCodeUsage. If the discount is 100%, check whether use has been notified. If not check for 14 days ahead and record if not. if (currentdiscountCodeUsage != null && currentdiscountCodeUsage.DiscountCode.Discount == 100) { CompanyDiscountNotificatonHistory companyDiscountNotificatonHistory = companyBL.GetCompanyDiscountExpireNotifiedRecord(companyId, dataContext); bool hasNotifiedUser = (companyDiscountNotificatonHistory != null); if (!hasNotifiedUser) { //Get the DiscountCode Usage and check whether it has a 100% code DiscountCodeUsage discountCodeUsage = financeBL.GetDiscountCodeUsageByDate(dateToConsider.AddDays(14), companyId); //If there is no 100% discount if (discountCodeUsage == null || discountCodeUsage != null && discountCodeUsage.DiscountCode.Discount != 100) { //1. Notify via email //2. Log in the table CompanyDiscountNotificatonHistory companyDiscountNotificatonHistories = new CompanyDiscountNotificatonHistory() { CompanyId = companyId, Date = Utils.Today, IsActive = true, CreatedDate = Utils.Today, CreatedByUserId = 0, LastUpdatedDate = Utils.Today, LastUpdatedByUserId = 0 }; dataContext.CompanyDiscountNotificatonHistories.AddObject(companyDiscountNotificatonHistories); } } } else if (currentdiscountCodeUsage == null || currentdiscountCodeUsage != null && currentdiscountCodeUsage.DiscountCode.Discount != 100) { //Means We have to suspend the company SuspendProjectsForCompany(companyId, dataContext); } } } dataContext.SaveChanges(); } }
public ItemResult SyncItem(MobileItem mobileItem) { string status = string.Empty; string message = string.Empty; ItemResult itemResult = new ItemResult(); bool isValidVersion = true; try { using (StageBitzDB dataContext = new StageBitzDB()) { isValidVersion = Helper.IsValidAppVersion(mobileItem.Version, out status); if (isValidVersion) { if (mobileItem != null) { //Check if this Item has already been created in MobileItem table //If not create InventoryMobileItem inventoryMobileItem = dataContext.InventoryMobileItems.Where(imi => imi.MobileItemId == mobileItem.DeviceItemId).FirstOrDefault(); if (inventoryMobileItem == null) { int userId = int.Parse(Utils.DecryptStringAES(mobileItem.Token)); //Check if the user can Create the Item CompanyBL companyBL = new CompanyBL(dataContext); FinanceBL financeBL = new FinanceBL(dataContext); InventoryBL inventoryBL = new InventoryBL(dataContext); if (companyBL.HasEditPermissionForInventoryStaff(mobileItem.CompanyId, userId, null)) { //New Creation of Item if (mobileItem.ItemId == 0) { //To create items in the hidden mode, if the limits have reached. bool isFreeTrailCompany = companyBL.IsFreeTrialCompany(mobileItem.CompanyId); CompanyPaymentPackage companyPaymentPackage = financeBL.GetCurrentPaymentPackageFortheCompanyIncludingFreeTrial(mobileItem.CompanyId); InventoryPaymentPackageDetails inventoryPaymentPackageDetails = null; if (companyPaymentPackage != null) { inventoryPaymentPackageDetails = Utils.GetSystemInventoryPackageDetailByPaymentPackageTypeId(companyPaymentPackage.InventoryPaymentPackageTypeId); } CompanyCurrentUsage companyCurrentUsage = financeBL.GetCompanyCurrentUsage(mobileItem.CompanyId, null); if (!financeBL.HasExceededInventoryLimit(isFreeTrailCompany, inventoryPaymentPackageDetails, companyCurrentUsage)) { inventoryMobileItem = new InventoryMobileItem(); inventoryMobileItem.MobileItemId = mobileItem.DeviceItemId; inventoryMobileItem.CreatedBy = userId; inventoryMobileItem.CreatedDate = Utils.Now; dataContext.InventoryMobileItems.AddObject(inventoryMobileItem); Item item = new Item(); item.Name = mobileItem.Name; item.IsManuallyAdded = true; item.ItemTypeId = mobileItem.ItemTypeId; item.Quantity = mobileItem.Quantity; item.Description = mobileItem.Description; item.CompanyId = mobileItem.CompanyId; item.IsActive = true; item.CreatedByUserId = item.LastUpdatedByUserId = userId; item.CreatedDate = item.LastUpdatedDate = Utils.Now; item.VisibilityLevelCodeId = Utils.GetCodeIdByCodeValue("InventoryVisibilityLevel", "ABOVE_SHAREDINVENTORY"); dataContext.Items.AddObject(item); dataContext.SaveChanges(); itemResult.Id = item.ItemId; status = "OK"; } else { status = "LIMITREACHED"; message = "Inventory plan limit reached."; } } else { //Edit existing one Item exItem = inventoryBL.GetItem(mobileItem.ItemId); if (exItem != null && exItem.IsActive) { Code userVisibilityCode = inventoryBL.GetUserInventoryVisibilityLevel(mobileItem.CompanyId, userId, null, false); if (!inventoryBL.GetItemStatusInformationForUser(exItem, mobileItem.CompanyId, userId).IsReadOnly&& exItem.Code.SortOrder >= userVisibilityCode.SortOrder) { if (mobileItem.LastUpdateDate == exItem.LastUpdatedDate) { exItem.Name = mobileItem.Name; exItem.ItemTypeId = mobileItem.ItemTypeId; exItem.Description = mobileItem.Description; exItem.Quantity = mobileItem.Quantity; exItem.LastUpdatedByUserId = userId; exItem.LastUpdatedDate = Utils.Now; dataContext.SaveChanges(); status = "OK"; itemResult.Id = mobileItem.ItemId; } else { status = "ITEMEDITED"; message = "Item already edited."; } } else { status = "NORIGHTS"; message = "Check settings with Company Administrator."; } } else { status = "ITEMDELETED"; message = "Item no longer exists."; } } } else { status = "NOACCESS"; message = "Check settings with Company Administrator."; } } else { itemResult.Id = inventoryMobileItem.ItemId; status = "ITEMEXIST"; message = "Item already synced."; } } } else { status = "INVALIDAPP"; message = "Please update App."; } } } catch (Exception ex) { AgentErrorLog.HandleException(ex); status = "ERROR"; message = "Oops! Unkown error. Sorry..."; } itemResult.MobileId = mobileItem.DeviceItemId; itemResult.Status = status; itemResult.Message = message; return(itemResult); }
public ItemResult SyncImage(MobileDocumentMedia mobileDocumentMedia) { ItemResult itemResult = new ItemResult(); string message = string.Empty; string status = string.Empty; bool isValidVersion = true; int documentMediaId = 0; try { using (StageBitzDB dataContext = new StageBitzDB()) { if (mobileDocumentMedia != null) { isValidVersion = Helper.IsValidAppVersion(mobileDocumentMedia.Version, out status); if (isValidVersion) { if (mobileDocumentMedia != null) { //Check if the Item is already being synced if (dataContext.InventoryMobileDocumentMedias.Where(imdm => imdm.MobileDocumentMediaId == mobileDocumentMedia.MobileImageId && imdm.RelatedTable == mobileDocumentMedia.RelatedTable && imdm.RelatedId == mobileDocumentMedia.RelatedId).FirstOrDefault() == null) { //Check if the Item is exist Data.Item item = dataContext.Items.Where(i => i.ItemId == mobileDocumentMedia.RelatedId).FirstOrDefault(); if (item != null && item.IsActive) { int userId = int.Parse(Utils.DecryptStringAES(mobileDocumentMedia.Token)); InventoryBL inventoryBL = new InventoryBL(dataContext); if (!inventoryBL.GetItemStatusInformationForUser(item, mobileDocumentMedia.CompanyId, userId).IsReadOnly) { //Images can be either deleted or added. if (mobileDocumentMedia.DocumentMediaId == 0) { DocumentMedia documentMedia = new DocumentMedia(); documentMedia.DocumentMediaContent = Helper.LoadImage(mobileDocumentMedia.Image, false, mobileDocumentMedia.FileExtension); documentMedia.Thumbnail = Helper.LoadImage(mobileDocumentMedia.Image, true, mobileDocumentMedia.FileExtension); documentMedia.RelatedId = mobileDocumentMedia.RelatedId; documentMedia.RelatedTableName = mobileDocumentMedia.RelatedTable; documentMedia.SortOrder = inventoryBL.HasDefaultImageSet(mobileDocumentMedia.RelatedId, mobileDocumentMedia.RelatedTable) ? 0 : 1; documentMedia.IsImageFile = true; documentMedia.FileExtension = mobileDocumentMedia.FileExtension; documentMedia.Name = mobileDocumentMedia.Name; documentMedia.CreatedBy = documentMedia.LastUpdatedBy = userId; documentMedia.CreatedDate = documentMedia.LastUpdatedDate = Utils.Today; dataContext.DocumentMedias.AddObject(documentMedia); InventoryMobileDocumentMedia inventoryMobileDocumentMedia = new InventoryMobileDocumentMedia(); inventoryMobileDocumentMedia.MobileDocumentMediaId = mobileDocumentMedia.MobileImageId; inventoryMobileDocumentMedia.DocumentMediaId = documentMedia.DocumentMediaId; inventoryMobileDocumentMedia.RelatedTable = mobileDocumentMedia.RelatedTable; inventoryMobileDocumentMedia.RelatedId = mobileDocumentMedia.RelatedId; inventoryMobileDocumentMedia.CreatedBy = userId; inventoryMobileDocumentMedia.CreatedDate = inventoryMobileDocumentMedia.LastUpdateDate = Utils.Today; dataContext.InventoryMobileDocumentMedias.AddObject(inventoryMobileDocumentMedia); dataContext.SaveChanges(); status = "OK"; documentMediaId = documentMedia.DocumentMediaId; } else { UtilityBL utilityBL = new UtilityBL(dataContext); DocumentMedia documentMedia = utilityBL.GetDocumentMedia(mobileDocumentMedia.DocumentMediaId); if (documentMedia != null) { dataContext.DeleteDocumentMedia(mobileDocumentMedia.DocumentMediaId); status = "OK"; } else { status = "OK"; message = "Image no longer exists."; } } } else { status = "NORIGHTS"; message = "Check settings with Company Administrator."; } } else { status = "ITEMDELETED"; message = "Item no longer exists."; } } else { status = "EXIST"; message = "Image already synced."; } } } else { status = "INVALIDAPP"; message = "Please update App."; } } else { status = "ERROR"; message = "Oops! Unkown error. Sorry..."; } } } catch (Exception ex) { AgentErrorLog.HandleException(ex); status = "ERROR"; message = "Oops! Unkown error. Sorry..."; } itemResult.Id = documentMediaId; itemResult.MobileId = mobileDocumentMedia != null ? mobileDocumentMedia.MobileImageId : "0"; itemResult.Status = status; itemResult.Message = message; return(itemResult); }
public static void SaveItemFieldPreferences(List <ItemTypeFieldsValues> objectList) { using (StageBitzDB dataContext = new StageBitzDB()) { List <ItemTypeField> allItemTypeFields = dataContext.ItemTypeFields.ToList(); List <FieldData> allFields = (from f in dataContext.Fields where f.IsActive == true && f.FieldGroup.IsActive == true orderby f.FieldGroup.SortOrder select new FieldData { Field = f, FieldId = f.FieldId, FieldHtml = f.FieldType.FieldTypeHtml, FieldHtmlControl = f.FieldType.HtmlControl, FieldInnerHtml = f.FieldType.InnerHtmlTemplate, Group = f.FieldGroup, GroupId = f.GroupId, FieldOptions = f.FieldOptions.OrderBy(fo => fo.SortOrder).Select(fo => new FieldOptionValue { OptionId = fo.FieldOptionId, OptionValue = fo.OptionText }), FieldAttributes = f.FieldAttributes.Select(fa => new FieldAttributeValue { TagName = fa.Attribute.TagName, AttributeValue = fa.FieldAttributeValue }), //(from fa in dataContext.FieldAttributes where fa.FieldId==f.FieldId select new FieldAttributeValue { AttributeId = fa.AttributeId, AttributeValue = fa.FieldAttributeValue }).ToList(), }).ToList(); List <Data.FieldGroup> fieldGroups = allFields.Select(fg => fg.Group).OrderBy(fg => fg.SortOrder).Distinct().ToList(); var itemTypeHtmls = (from it in dataContext.ItemTypes from ith in dataContext.ItemTypeHtmls.Where(ith => ith.ItemTypeId == it.ItemTypeId).DefaultIfEmpty() select new { it.ItemTypeId, ith }).ToList(); List <int> itemTypeIds = itemTypeHtmls.Select(ith => ith.ItemTypeId).ToList(); //these are hard coded countries for the Sizing field. List <String> countries = new List <string>(); countries.Add("Australia"); countries.Add("United States"); countries.Add("United Kingdom"); List <Country> countryList = dataContext.Countries.Where(c => countries.Contains(c.CountryName)).ToList(); List <FieldData> groupFields; StringBuilder groupHtml, leftColumnHtml, rightColumnHtml, fieldHtml, fieldOptions, masterHtml; int[] itemTypeFields; const string FIELD_VISIBLE = "Visible"; const string NAME = "Name"; const string COLUMN1 = "@Column1"; const string COLUMN2 = "@Column2"; const string FIELD = "Field"; const string CLASSINVISIBLE = "remove_dynamic_field"; const string FIELDOPTIONS = "@Options"; const string FIELDOPTIONValue = "@Option"; const string FIELDOPTIONID = "@optionvalue"; const string TAGWATERMARK = "@watermark"; const string TAGCLASS = "@class"; const string TAGHEIGHT = "@height"; const string TAGWIDTH = "@width"; const string TAGMAXLENGTH = "@maxlength"; const string TAGFieldId = "@fieldId"; const string TAGCountryId = "@countryId"; bool groupHasFields = false; int i = 0; foreach (int itemTypeId in itemTypeIds) { masterHtml = new StringBuilder(Utils.GetSystemValue("ItemFieldsMasterHtml")); leftColumnHtml = new StringBuilder(); rightColumnHtml = new StringBuilder(); itemTypeFields = objectList.Where(itfv => itfv.ItemTypeId == itemTypeId).Select(itfv => itfv.Fields).FirstOrDefault(); if (itemTypeFields != null) { foreach (Data.FieldGroup fieldGroup in fieldGroups) { groupFields = allFields.Where(f => f.GroupId == fieldGroup.FieldGroupId).ToList(); groupHtml = new StringBuilder(fieldGroup.FieldGroupHtml); groupHtml.Replace(fieldGroup.TagName + ":" + NAME, fieldGroup.DisplayName); foreach (FieldData fieldData in groupFields) { if (itemTypeFields != null && Array.IndexOf(itemTypeFields, fieldData.FieldId) > -1) { groupHasFields = true; groupHtml.Replace(fieldData.Field.TagName + ":" + FIELD_VISIBLE, string.Empty); groupHtml.Replace(fieldData.Field.TagName + ":" + NAME, fieldData.Field.DisplayName); fieldHtml = new StringBuilder(fieldData.FieldHtml); fieldHtml.Replace(TAGFieldId, fieldData.FieldId.ToString()); foreach (FieldAttributeValue attribute in fieldData.FieldAttributes) { fieldHtml.Replace(attribute.TagName, attribute.AttributeValue); } fieldHtml.Replace(TAGWATERMARK, string.Empty); fieldHtml.Replace(TAGCLASS, string.Empty); fieldHtml.Replace(TAGHEIGHT, string.Empty); fieldHtml.Replace(TAGWIDTH, string.Empty); fieldHtml.Replace(TAGMAXLENGTH, string.Empty); if (fieldData.FieldOptions.Count() > 0) { fieldOptions = new StringBuilder(); foreach (FieldOptionValue option in fieldData.FieldOptions) { StringBuilder fieldOption = new StringBuilder(fieldData.FieldInnerHtml); fieldOption.Replace(FIELDOPTIONID, option.OptionId.ToString()); fieldOption.Replace(FIELDOPTIONValue, option.OptionValue); if (fieldData.FieldHtmlControl.Equals("CountryDropDown")) { fieldOption.Replace(TAGCountryId, GetSizingCountryValue(countryList, option.OptionValue)); } fieldOptions.Append(fieldOption); } fieldHtml.Replace(FIELDOPTIONS, fieldOptions.ToString()); } //we need to insert record if and only if the record doesn't exist. if (allItemTypeFields.Where(itf => itf.FieldId == fieldData.FieldId && itf.ItemTypeId == itemTypeId).FirstOrDefault() == null) { Data.ItemTypeField itemTypeField = new ItemTypeField(); itemTypeField.FieldId = fieldData.FieldId; itemTypeField.ItemTypeId = itemTypeId; dataContext.ItemTypeFields.AddObject(itemTypeField); } groupHtml.Replace(fieldData.Field.TagName + ":" + FIELD, fieldHtml.ToString()); } else { //we need to delete the record if only it already exists in the table. Data.ItemTypeField itemTypeField = allItemTypeFields.Where(itf => itf.FieldId == fieldData.FieldId && itf.ItemTypeId == itemTypeId).FirstOrDefault(); if (itemTypeField != null) { dataContext.ItemTypeFields.DeleteObject(itemTypeField); } //hide the field from the group groupHtml.Replace(fieldData.Field.TagName + ":" + FIELD_VISIBLE, CLASSINVISIBLE); } } //if the group has at least one field that group attached to the group. if (groupHasFields) { if (i++ % 2 == 0) { leftColumnHtml.Append(groupHtml); } else { rightColumnHtml.Append(groupHtml); } } groupHasFields = false; } } masterHtml.Replace(COLUMN1, leftColumnHtml.ToString()); masterHtml.Replace(COLUMN2, rightColumnHtml.ToString()); Data.ItemTypeHtml itemTypeHtml = itemTypeHtmls.Where(ith => ith.ItemTypeId == itemTypeId).Select(ith => ith.ith).FirstOrDefault(); if (itemTypeHtml != null) { itemTypeHtml.Html = masterHtml.ToString(); } else { itemTypeHtml = new ItemTypeHtml(); itemTypeHtml.ItemTypeId = itemTypeId; itemTypeHtml.Html = masterHtml.ToString(); dataContext.ItemTypeHtmls.AddObject(itemTypeHtml); } itemTypeFields = null; i = 0; } dataContext.SaveChanges(); } }
/// <summary> /// Sends the booking overdue emails. /// </summary> /// <param name="dateToConsider">The date to consider.</param> public static void SendBookingOverdueEmails(DateTime dateToConsider) { using (StageBitzDB dataContext = new StageBitzDB()) { InventoryBL inventoryBL = new InventoryBL(dataContext); int overdueEmailCodeId = Utils.GetCodeIdByCodeValue("EmailTemplateTypeCode", "BOOKINGOVERDUE"); var overdueBookings = (from ibs in dataContext.ItemBookings.Where(ibs => dataContext.IsItemBookingOverdueByDate(ibs.ItemBookingId, dateToConsider)) from eh in dataContext.EmailHistories.Where(eh => ibs.ItemBookingId == eh.RelatedId && eh.RelatedTable == "ItemBooking" && eh.EmailTemplateTypeCodeId == overdueEmailCodeId).DefaultIfEmpty().Take(1) //join ib in dataContext.ItemBriefs on ibs.RelatedId equals ib.ItemBriefId join b in dataContext.Bookings on ibs.BookingId equals b.BookingId from ib in dataContext.ItemBriefs.Where(ib => ib.ItemBriefId == ibs.RelatedId && b.RelatedTable == "Project").DefaultIfEmpty().Take(1) join i in dataContext.Items on ibs.ItemId equals i.ItemId // join b in dataContext.Bookings on ib.ProjectId equals b.RelatedId join cbn in dataContext.CompanyBookingNumbers on b.BookingId equals cbn.BookingId //join p in dataContext.Projects on ib.ProjectId equals p.ProjectId from p in dataContext.Projects.Where(p => p.ProjectId == b.RelatedId && b.RelatedTable == "Project").DefaultIfEmpty().Take(1) from np in dataContext.NonProjectBookings.Where(npb => npb.NonProjectBookingId == b.RelatedId && b.RelatedTable == "NonProject").DefaultIfEmpty().Take(1) where eh == null && ibs.IsActive && i.CompanyId.HasValue && i.CompanyId.Value == cbn.CompanyId group new { Booking = b, CompayBookingNumber = cbn, Project = p, NonProject = np, ItemBooking = ibs } by cbn.CompanyId into grp select new { BookingInfo = grp.GroupBy(g => g.Booking.BookingId). Select(g => new { Booking = g.FirstOrDefault().Booking, CompayBookingNumber = g.FirstOrDefault().CompayBookingNumber, BookingName = g.FirstOrDefault().Project != null ? g.FirstOrDefault().Project.ProjectName : g.FirstOrDefault().NonProject.Name, ItemBookingIds = g.Select(gx => gx.ItemBooking.ItemBookingId), CompanyId = grp.Key }), CompanyId = grp.Key }).ToList(); string userWebUrl = Utils.GetSystemValue("SBUserWebURL"); Dictionary <User, List <dynamic> > userBookings = new Dictionary <User, List <dynamic> >(); foreach (var companyBookings in overdueBookings) { foreach (var bookingInfo in companyBookings.BookingInfo) { foreach (var itemBookingId in bookingInfo.ItemBookingIds) { ItemBooking itemBooking = inventoryBL.GetItemBooking(itemBookingId); if (itemBooking != null) { User locationManager = inventoryBL.GetContactBookingManager(itemBooking.Item.CompanyId.Value, itemBooking.Item.LocationId); if (locationManager != null) { if (userBookings.Keys.Where(ul => ul.UserId == locationManager.UserId).FirstOrDefault() == null) { userBookings[locationManager] = new List <dynamic>(); } User key = userBookings.Keys.Where(ul => ul.UserId == locationManager.UserId).FirstOrDefault(); if (userBookings[key].Where(bi => bi.Booking.BookingId == bookingInfo.Booking.BookingId).FirstOrDefault() == null) { userBookings[key].Add(bookingInfo); } Data.EmailHistory emailHistory = new EmailHistory { EmailTemplateTypeCodeId = overdueEmailCodeId, RelatedId = itemBookingId, RelatedTable = "ItemBooking", CreatedDate = Utils.Now }; dataContext.EmailHistories.AddObject(emailHistory); } } } dataContext.SaveChanges(); } } foreach (User user in userBookings.Keys) { StringBuilder bookingLinks = new StringBuilder(); List <dynamic> bookingInfos = userBookings[user]; foreach (dynamic bookingInfo in bookingInfos) { if (bookingInfo != null) { string url = string.Format("{0}/Inventory/BookingDetails.aspx?BookingId={1}&CompanyId={2}", userWebUrl, bookingInfo.Booking.BookingId, bookingInfo.CompanyId); string link = string.Format("Booking name: <a href='{0}' target='_blank'>{1}</a> - Booking ID: {2} <br />", url, bookingInfo.BookingName, bookingInfo.CompayBookingNumber.BookingNumber); bookingLinks.Append(link); } } EmailSender.SendBookingOverdueEmail(user.Email1, user.FirstName, bookingLinks.ToString()); } } }
/// <summary> /// This is to be called by monthly agent and manual payment. /// </summary> public static bool ProcessInvoicesAndPayments(int companyId, DateTime dateToConsider, bool shouldCreateInvoices, int userId) { using (StageBitzDB dataContext = new StageBitzDB()) { FinanceSupport.InitializePaymentSettings(); bool isPaymentSuccess = false; bool isManualPayment = (companyId == 0) ? false : true; List <Invoice> invoiceList = new List <Invoice>(); if (shouldCreateInvoices) { List <CompanyPaymentSummary> unProcessedPaymentSummaries = GetUnProcessedCompanyPaymentSummaries(0, dataContext, dateToConsider); //Only consider companies which has payment packages List <Data.Company> companies = (from c in dataContext.Companies join cpp in dataContext.CompanyPaymentPackages on c.CompanyId equals cpp.CompanyId select c).Distinct().ToList(); if (unProcessedPaymentSummaries.Count > 0) { CompanyBL companyBL = new CompanyBL(dataContext); foreach (Data.Company company in companies) { try { List <CompanyPaymentSummary> unProcessedCompanyPaymentSummaries = unProcessedCompanyPaymentSummaries = unProcessedPaymentSummaries.Where(upcs => upcs.CompanyId == company.CompanyId).OrderBy(ups => ups.CompanyPaymentSummaryId).ToList(); //*******Consider payment summaries for the company********* if (unProcessedCompanyPaymentSummaries != null && unProcessedCompanyPaymentSummaries.Count() > 0) { if (!companyBL.IsFreeTrialCompany(company.CompanyId, dateToConsider)) { decimal totalAmount = unProcessedCompanyPaymentSummaries.Sum(ups => ups.Amount); DateTime fromDate = unProcessedCompanyPaymentSummaries.First().FromDate; DateTime toDate = unProcessedCompanyPaymentSummaries.Last().ToDate; Invoice invoice = null; if (totalAmount > 0) //generate the invoice only if there is a due amount to pay { invoice = FinanceSupport.CreateInvoice(company.CompanyId, "Company", "PACKAGEFEE", string.Format("Payment for Company {0}", company.CompanyName), decimal.Round(totalAmount, 2), fromDate, toDate, dataContext); } foreach (CompanyPaymentSummary companyPackagePaymentSummary in unProcessedCompanyPaymentSummaries) { companyPackagePaymentSummary.IsMonthlyAgentProcessed = true; if (invoice != null) { companyPackagePaymentSummary.Invoice = invoice; } companyPackagePaymentSummary.LastUpdatedDate = Utils.Today; companyPackagePaymentSummary.LastUpdatedBy = 0; } } } } catch (Exception ex) { AgentErrorLog.WriteToErrorLog("Failed to create Invoice for projectId" + company.CompanyId); AgentErrorLog.HandleException(ex); isPaymentSuccess = false; } } //Complete upto now. dataContext.SaveChanges(); } //Get all the Unprocessed Invoices to send to the payment gateway. invoiceList = FinanceSupport.GetUnProcessedInvoicesByRelatedTable("Company", companyId, "PACKAGEFEE", dataContext); } else { int companyStatusCodeID = 0; if (!isManualPayment) { //Not Manual means, Payment Retry. companyStatusCodeID = Utils.GetCodeByValue("CompanyStatus", "GRACEPERIOD").CodeId; } //Get all the Unprocessed Invoices to send to the payment gateway. //For Grace period payment Retry process projectId is 0. invoiceList = FinanceSupport.GetPaymentFailedInvoices("PACKAGEFEE", companyStatusCodeID, companyId, "Company", dataContext); } //Because we need Payment Log records before process Invoices. foreach (Invoice invoice in invoiceList) { FinanceSupport.CreatePaymentLog(invoice.InvoiceID, dataContext); } dataContext.SaveChanges(); //Get distinct company Ids within the unprocessed invoice list var companyIds = invoiceList.Select(inv => inv.RelatedID).Distinct(); foreach (int distinctCompanyId in companyIds) { isPaymentSuccess = ProcessInvoicesByCompany(invoiceList, distinctCompanyId, isManualPayment, dataContext); if (isPaymentSuccess) { CompanyBL companyBL = new CompanyBL(dataContext); companyBL.ActivateUnProcessedSummaries(distinctCompanyId, userId); } } dataContext.SaveChanges(); //For the Monthly Agent Runner the return value is not important but for the manual payment. return(isPaymentSuccess); } }