Exemplo n.º 1
0
        public static StudyRootStudyIdentifier ToIdentifier(this DicomExplorerSearchCriteria explorerSearchCriteria, bool addWildcards)
        {
            if (addWildcards)
            {
                return(new StudyRootStudyIdentifier
                {
                    PatientsName = ConvertNameToSearchCriteria(explorerSearchCriteria.PatientsName),
                    ReferringPhysiciansName = ConvertNameToSearchCriteria(explorerSearchCriteria.ReferringPhysiciansName),
                    PatientId = ConvertStringToWildcardSearchCriteria(explorerSearchCriteria.PatientId, false, true),
                    AccessionNumber = ConvertStringToWildcardSearchCriteria(explorerSearchCriteria.AccessionNumber, false, true),
                    StudyDescription = ConvertStringToWildcardSearchCriteria(explorerSearchCriteria.StudyDescription, false, true),
                    StudyDate = DateRangeHelper.GetDicomDateRangeQueryString(explorerSearchCriteria.StudyDateFrom, explorerSearchCriteria.StudyDateTo),
                    //At the application level, ClearCanvas defines the 'ModalitiesInStudy' filter as a multi-valued
                    //Key Attribute.  This goes against the Dicom standard for C-FIND SCU behaviour, so the
                    //underlying IStudyFinder(s) must handle this special case, either by ignoring the filter
                    //or by running multiple queries, one per modality specified (for example).
                    ModalitiesInStudy = explorerSearchCriteria.Modalities.ToArray()
                });
            }

            return(new StudyRootStudyIdentifier
            {
                PatientsName = explorerSearchCriteria.PatientsName,
                ReferringPhysiciansName = explorerSearchCriteria.ReferringPhysiciansName,
                PatientId = explorerSearchCriteria.PatientId,
                AccessionNumber = explorerSearchCriteria.AccessionNumber,
                StudyDescription = explorerSearchCriteria.StudyDescription,
                StudyDate = DateRangeHelper.GetDicomDateRangeQueryString(explorerSearchCriteria.StudyDateFrom, explorerSearchCriteria.StudyDateTo),
                //At the application level, ClearCanvas defines the 'ModalitiesInStudy' filter as a multi-valued
                //Key Attribute.  This goes against the Dicom standard for C-FIND SCU behaviour, so the
                //underlying IStudyFinder(s) must handle this special case, either by ignoring the filter
                //or by running multiple queries, one per modality specified (for example).
                ModalitiesInStudy = explorerSearchCriteria.Modalities.ToArray()
            });
        }
Exemplo n.º 2
0
        internal Campaign GetEntity(Campaign campaign)
        {
            var executionTime = DateRangeHelper.GetDateRange(ExecutionTime);
            var regTime       = DateRangeHelper.GetDateRange(RegisterTime);
            var feedbackTime  = DateRangeHelper.GetDateRange(FeedbackBefore);


            campaign.Quantity       = Quantity;
            campaign.DateStart      = regTime != null ? (DateTime?)regTime.Value.Start : null;
            campaign.DateEnd        = regTime != null ? (DateTime?)regTime.Value.End : null;
            campaign.CustomKolNames = CustomKolNames.ToListString();
            campaign.KPIMin         = KPIMin;

            campaign.InteractiveMin = InteractiveMin;

            //campaign.InteractiveMin = KPIMin + InteractiveMin;

            campaign.ExecutionStart = executionTime != null ? (DateTime?)executionTime.Value.Start : null;
            campaign.ExecutionEnd   = executionTime != null ? (DateTime?)executionTime.Value.End : null;
            campaign.FeedbackStart  = feedbackTime != null ? (DateTime?)feedbackTime.Value.Start : null;
            campaign.FeedbackEnd    = feedbackTime != null ? (DateTime?)feedbackTime.Value.End : null;
            campaign.AmountMax      = AmountMax;
            campaign.AmountMin      = AmountMin;

            return(campaign);
        }
        public void FlattenIntoASingleRangeTest()
        {
            //[(1, 5), (2, 4), (3, 6)] --->  [(1,6)]
            var ranges = new List <DateRange>()
            {
                QuickRange(1, 5),
                QuickRange(2, 4),
                QuickRange(3, 6),
            };

            var flattened = DateRangeHelper.Flatten(ranges).ToList();

            Assert.IsTrue(flattened.Count == 1, "flattened.Count == 1");
            Assert.AreEqual(QuickRange(1, 6), flattened[0]);
        }
Exemplo n.º 4
0
        private static int GeWorkDaysOff(DateRange analyzedPeriod, IEnumerable <DateRange> timeOffs)
        {
            IEnumerable <DateRange> flattened = DateRangeHelper.Flatten(timeOffs);

            return((from interval in flattened
                    where analyzedPeriod.Overlaps(interval)
                    let minDate = interval.StartDate <analyzedPeriod.StartDate
                                                      ?analyzedPeriod.StartDate
                                                      : interval.StartDate
                                                      let maxDate = interval.EndDate> analyzedPeriod.EndDate
                    ? analyzedPeriod.EndDate
                    : interval.EndDate
                                  select new DateRange(minDate, maxDate)
                                  into trimmed
                                  select GetWorkingDays(trimmed)).Sum());
        }
Exemplo n.º 5
0
            private static string ConvertDateCriteria(string dateCriteria, string columnName)
            {
                string fromDate, toDate;
                bool   isRange;

                DateRangeHelper.Parse(dateCriteria, out fromDate, out toDate, out isRange);
                StringBuilder dateRangeCriteria = new StringBuilder();

                if (fromDate != "")
                {
                    //When a dicom date is specified with no '-', it is to be taken as an exact date.
                    if (!isRange)
                    {
                        dateRangeCriteria.AppendFormat("( {0} = '{1}' )", columnName, fromDate);
                    }
                    else
                    {
                        dateRangeCriteria.AppendFormat("( {0} IS NOT NULL AND {0} >= '{1}' )", columnName, fromDate);
                    }
                }

                if (toDate != "")
                {
                    if (fromDate == "")
                    {
                        dateRangeCriteria.AppendFormat("( {0} IS NULL OR ", columnName);
                    }
                    else
                    {
                        dateRangeCriteria.AppendFormat(" AND (");
                    }

                    dateRangeCriteria.AppendFormat("{0} <= '{1}' )", columnName, toDate);
                }

                //will only happen if the query string is bad.
                string returnCriteria = dateRangeCriteria.ToString();

                if (String.IsNullOrEmpty(returnCriteria))
                {
                    return(returnCriteria);
                }

                return(String.Format("({0})", returnCriteria));
            }
        public void FlattenIntoMultipleRanges()
        {
            //[(0, 3), (1, 2), (2, 4), (5, 9), (6, 8)] --> [(0, 4), (5, 9)]
            var ranges = new List <DateRange>()
            {
                QuickRange(1, 2),
                QuickRange(5, 9),
                QuickRange(2, 4),
                QuickRange(6, 8),
                QuickRange(0, 3),
            };

            List <DateRange> flattened = DateRangeHelper.Flatten(ranges).ToList();

            Assert.IsTrue(flattened.Count == 2, "flattened.Count == 2");
            Assert.AreEqual(QuickRange(0, 4), flattened[0]);
            Assert.AreEqual(QuickRange(5, 9), flattened[1]);
        }
Exemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (this.Parent.ID != null)
                {
                    if (!this.Parent.ID.Equals("datepanel"))
                    {
                        SettingCategory = this.Parent.ID;
                    }
                    else
                    {
                        var parent = (Panel)this.Parent;
                        if (parent.ToolTip.Contains("Date"))
                        {
                            SettingCategory = parent.ToolTip;
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                else
                {
                    SettingCategory = "General";
                }
                LoadText();

                var dateRangeData = Framework.Components.UserPreference.DateRangeTitleDataManager.GetList(SessionVariables.RequestProfile);
                UIHelper.LoadDropDown(dateRangeData, drpDateRange, StandardDataModel.StandardDataColumns.Name,
                                      DateRangeTitleDataModel.DataColumns.DateRangeTitleId);

                drpDateRange.SelectedItem.Value = PerferenceUtility.GetUserPreferenceByKey(ApplicationCommon.DateRangeFormat, SettingCategory);

                var Dates = DateRangeHelper.FillUpDate(drpDateRange.SelectedItem.Text, SessionVariables.UserDateFormat);
                txtSearchVerticalFromDate.Text = Dates[0];
                txtSearchVerticalToDate.Text   = Dates[1];
                lblUserDateFormat.Text         = SessionVariables.UserDateFormat;
            }
        }
        public async Task <IEnumerable <DoorActionDto> > GetAllAsync(
            PageHelper pageFilter           = default,
            DateTime?dateFilter             = default,
            DateRangeHelper dateRangeFilter = default,
            IList <int> cardIds             = default,
            IList <string> userIds          = default,
            params string[] includes)
        {
            var doorActions = await _applicationContext.DoorActions
                              .GetDoorActionQuery(false)
                              .Includes(includes)
                              .ApplyPagination(pageFilter)
                              .ApplyFilterByDate(dateFilter)
                              .ApplyFilterByDateRange(dateRangeFilter)
                              .ApplyFilterByCardIds(cardIds)
                              .ApplyFilterByUserIds(userIds)
                              .ToListAsync();

            return(!doorActions.Any()
                ? new List <DoorActionDto>()
                : _mapper.Map <IEnumerable <DoorActionDto> >(doorActions));
        }
        public async Task LoadContributorStats(string contributorId, string dateRange = DateRangesConsts.All)
        {
            IsLoading = true;

            DateTime contributorStatsDateTo         = DateTimeConsts.Today;
            DateTime contributorStatsDateFrom       = DateRangeHelper.GetStartRangeDateTime(dateRange);
            var      contributorStatsDateToString   = (contributorStatsDateTo).ToString(DateTimeConsts.DateTimeFormat);
            var      contributorStatsDateFromString = (contributorStatsDateFrom).ToString(DateTimeConsts.DateTimeFormat);

            ContributorStatsDateRange = string.Format(ContributorStatsDateRangeStringFormat, contributorStatsDateFromString, contributorStatsDateToString);

            ContributorStats = await _contributorService.GetContributorStats(contributorId, contributorStatsDateFrom, contributorStatsDateTo);

            if (dateRange == DateRangesConsts.All)
            {
                var previousContributorStats = await _contributorService.GetContributorStats(contributorId, DateTimeConsts.UnixEpoch, DateTimeConsts.Yesterday);

                ContributorStatsIncrement = new ContributorStatsDto
                {
                    Commits          = contributorStats.Commits - previousContributorStats.Commits,
                    Merges           = contributorStats.Merges - previousContributorStats.Merges,
                    LinesOfCode      = contributorStats.LinesOfCode - previousContributorStats.LinesOfCode,
                    ContribToProject = contributorStats.ContribToProject - previousContributorStats.ContribToProject
                };
            }
            else
            {
                ContributorStatsIncrement = new ContributorStatsDto
                {
                    Commits          = int.MinValue,
                    Merges           = int.MinValue,
                    LinesOfCode      = int.MinValue,
                    ContribToProject = double.MinValue
                };
            }

            IsLoading = false;
        }
Exemplo n.º 10
0
        public override void OnApplyTemplate()
        {
            // base.OnApplyTemplate(); //not needed if deriving from Control

            PrevRangeButton = GetTemplateChild(PrevRangeButtonName) as Button;
            NextRangeButton = GetTemplateChild(NextRangeButtonName) as Button;

            SetTextBlockLocalizedText(FromTextBlockName, FromTextBlockResourceKey);
            SetTextBlockLocalizedText(ToTextBlockName, ToTextBlockResourceKey);

            if (null == _dateRanges)
            {
                _dateRanges = DateRangeHelper.BuildDateRangeList(_firstDayOfWeekProvider, _resourceManager);
                _dateRanges.CurrentChanged += OnCurrentChanged;
            }

            InitDatePropertiesSetByUser();

            var rangeComboBox     = GetTemplateChild(RangeComboBoxName) as ItemsControl;
            var bindingExpression = rangeComboBox?.GetBindingExpression(ItemsControl.ItemsSourceProperty);

            bindingExpression?.UpdateTarget();
        }
Exemplo n.º 11
0
        public Metrics GetMetrics()
        {
            Metrics result = new Metrics();

            using (MailPusherDBContext context = new MailPusherDBContext())
            {
                result.TotalConfirmedSubscriptions = context.Publishers.Where(x => x.Status == PublisherStatus.Confirmed).Count();
                result.TotalSubscriptions          = context.Publishers.Where(x => (x.Status & (PublisherStatus.Confirmed | PublisherStatus.Subscribed)) > 0).Count();

                DateRange lastMonthRange = DateRangeHelper.GetLastMonth();
                result.ConfirmedSubscriptionsLastMonth = context.Publishers.Where(
                    x => x.StatusChanged != null &&
                    DbFunctions.TruncateTime(x.StatusChanged) >= DbFunctions.TruncateTime(lastMonthRange.Start) &&
                    DbFunctions.TruncateTime(x.StatusChanged) <= DbFunctions.TruncateTime(lastMonthRange.End) &&
                    x.Status == PublisherStatus.Confirmed).Count();

                DateRange lastWeekRange = DateRangeHelper.GetLastWeek();
                result.ConfirmedSubscriptionsLastWeek = context.Publishers.Where(x =>
                                                                                 x.StatusChanged != null &&
                                                                                 DbFunctions.TruncateTime(x.StatusChanged) >= DbFunctions.TruncateTime(lastWeekRange.Start) &&
                                                                                 DbFunctions.TruncateTime(x.StatusChanged) <= DbFunctions.TruncateTime(lastWeekRange.End) &&
                                                                                 x.Status == PublisherStatus.Confirmed).Count();

                DateRange currentMonthRange = DateRangeHelper.GetCurrentMonth();
                result.ConfirmedSubscriptionsThisMonth = context.Publishers.Where(
                    x => x.StatusChanged != null &&
                    DbFunctions.TruncateTime(x.StatusChanged) >= DbFunctions.TruncateTime(currentMonthRange.Start) &&
                    x.Status == PublisherStatus.Confirmed).Count();

                DateRange currentWeekRange = DateRangeHelper.GetCurrentWeek();
                result.ConfirmedSubscriptionsThisWeek = context.Publishers.Where(
                    x => x.StatusChanged != null &&
                    DbFunctions.TruncateTime(x.StatusChanged) >= DbFunctions.TruncateTime(currentWeekRange.Start) &&
                    x.Status == PublisherStatus.Confirmed).Count();
            }
            return(result);
        }
        public void GetAllAsync_DoorActionsExist_DoorActionRetrievedByDateRangeFilter()
        {
            // Arrange
            var defaultStartDate = new DateTime(2000, 1, 2);
            var defaultEndDate   = new DateTime(2000, 1, 3);

            var dateRange = new DateRangeHelper(defaultStartDate, defaultEndDate);

            var doorAction1 = new DoorAction
            {
                Id           = 1,
                DoorReaderId = 1,
                CardId       = 1,
                Status       = DoorActionStatusType.Success,
                TimeStamp    = new DateTime(2000, 1, 1),
            };

            var doorAction2 = new DoorAction
            {
                Id           = 2,
                DoorReaderId = 1,
                CardId       = 1,
                Status       = DoorActionStatusType.Error,
                TimeStamp    = defaultStartDate,
            };

            var doorAction3 = new DoorAction
            {
                Id           = 3,
                DoorReaderId = 1,
                CardId       = 1,
                Status       = DoorActionStatusType.Error,
                TimeStamp    = defaultEndDate,
            };

            var doorAction4 = new DoorAction
            {
                Id           = 4,
                DoorReaderId = 1,
                CardId       = 1,
                Status       = DoorActionStatusType.Error,
                TimeStamp    = new DateTime(2000, 1, 4),
            };

            _applicationContext.DoorActions.AddRange(
                doorAction1,
                doorAction2,
                doorAction3,
                doorAction4);

            _applicationContext.SaveChanges();

            // Act
            var receivedDoorActionDtos = _doorActionManager
                                         .GetAllAsync(dateRangeFilter: dateRange)
                                         .GetAwaiter()
                                         .GetResult();

            // Assert
            Assert.Equal(2, receivedDoorActionDtos.Count());
            Assert.Single(receivedDoorActionDtos.Where(doorActionDto => doorActionDto.Id == doorAction2.Id));
            Assert.Single(receivedDoorActionDtos.Where(doorActionDto => doorActionDto.Id == doorAction3.Id));
        }
Exemplo n.º 13
0
 private void ParseCriterion()
 {
     _parsedCriterion = true;
     DateRangeHelper.Parse(Criterion.GetString(0, ""), out _date1, out _date2, out _isRange);
 }
        public ActionResult Index()
        {
            try
            {
                var userId = User.Identity.GetUserId();

                // Retrieve delegations for user where the status is active
                var delegations = departmentDelegationService.GetAll()
                                  .Where(x => x.UserId == userId)
                                  .Where(x => x.Status == CustomStatus.isActive).ToList();

                if (delegations != null)
                {
                    foreach (var item in delegations)
                    {
                        DateRangeHelper      dateRangeHelper = new DateRangeHelper(item.StartDate, item.EndDate);
                        ApplicationDbContext context         = new ApplicationDbContext();
                        var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
                        //Check if the delegation period is now
                        bool check = dateRangeHelper.Includes(DateTime.Now);
                        if (check)
                        {
                            userManager.AddToRole(userId, "DepartmentHead");
                        }
                        else
                        {
                            userManager.RemoveFromRole(userId, "DepartmentHead");
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            if (User.IsInRole("StoreClerk") || User.IsInRole("StoreManager") || User.IsInRole("StoreSupervisor"))
            {
                var purchaseOrderCount = purchaseOrderService.GetAll().Where(po => po.Status == CustomStatus.PendingApproval).Count();
                ViewBag.Poc = purchaseOrderCount;
                var stockAdjustmentCount = stockAdjustmentService.GetAll().Where(sa => sa.Status == CustomStatus.PendingApproval).Count();
                ViewBag.Sac = stockAdjustmentCount;
                var disbursementCount = disbursementService.GetAll().Where(x => x.Status == CustomStatus.ForRetrieval).Count();
                ViewBag.D = disbursementCount;
                var itemCount = itemService.GetItemsLowerThanReorderLevel().Count();
                ViewBag.I = itemCount;

                dynamic viewModel = new ItemViewModel()
                {
                    Items = itemService.GetAll()
                };
                return(View("Index", viewModel));
            }
            if (User.IsInRole("Employee") || User.IsInRole("DepartmentHead") || User.IsInRole("Representative"))
            {
                var requisitionCount = requisitionService.GetAll()
                                       .Where(x => x.DepartmentId == User.Identity.GetDepartmentId())
                                       .Where(r => r.Status == CustomStatus.PendingApproval).Count();
                ViewBag.R = requisitionCount;

                var collectionCount = itemDisbursementService.GetDepartmentCollection(User.Identity.GetDepartmentId()).Count();
                ViewBag.C = collectionCount;

                var activeDelegationCount = departmentDelegationService.GetAll().Where(x => x.DepartmentId == User.Identity.GetDepartmentId()).Where(x => x.Status == CustomStatus.isActive).Count();
                ViewBag.adC = activeDelegationCount;

                var pendingDelegationCount = departmentDelegationService.GetAll().Where(x => x.DepartmentId == User.Identity.GetDepartmentId()).Where(x => x.Status == CustomStatus.isNotActive).Where(x => x.StartDate > DateTime.Now).Count();
                ViewBag.pdC = pendingDelegationCount;

                dynamic requistionViewModel = new RequisitionViewModel()
                {
                    Items        = itemService.GetAll(),
                    Requisitions = requisitionService.GetAll()
                                   .Where(x => x.DepartmentId == User.Identity.GetDepartmentId())
                                   .OrderByDescending(r => r.createdDateTime)
                                   .OrderByDescending(r => r.Status)
                };
                return(View("Index", requistionViewModel));
            }
            return(View());
        }
Exemplo n.º 15
0
        public void GetSpanDatesTest(DateRangeKind kind, DateRangeValue expected)
        {
            var result = DateRangeHelper.GetDateRangeDates(kind, _fromIn, _toIn);

            Assert.AreEqual(expected, result);
        }
Exemplo n.º 16
0
        public void OnStudyQuery(DicomMessage message, SelectCallback <IStudyData> callback)
        {
            // Supported Query Condition includes:
            // PatientsName, PatientsId, PatientsSex, PatientsBirthDate, PatientsBirthTime
            // StudyInstanceUid, StudyId, StudyDescription, AccessionNumber, ModalitiesInStudy
            // ReferringPhysiciansName, StudyDate, StudyTime

            var data = message.DataSet;

            using (var ctx = new PacsContext())
            {
                #region Build Query

                //Linq query is lazy query mechanism
                var results = from study in ctx.Studies select study;
                foreach (var attrib in message.DataSet)
                {
                    if (!attrib.IsNull)
                    {
                        switch (attrib.Tag.TagValue)
                        {
                        case DicomTags.PatientsName:
                        {
                            var patientName = data[DicomTags.PatientsName].GetString(0,
                                                                                     string.Empty);
                            if (patientName.Length == 0)
                            {
                                break;
                            }

                            var replaced = QueryHelper.ReplacsWildcard(patientName);
                            if (replaced == null)
                            {
                                results = from study in results
                                          where study.PatientName.Equals(patientName)
                                          select study;
                            }
                            else
                            {
                                results = from study in results
                                          where study.PatientName.Contains(replaced)
                                          select study;
                            }

                            break;
                        }

                        case DicomTags.PatientId:
                        {
                            var patientId = data[DicomTags.PatientId].GetString(0, string.Empty);
                            if (patientId.Length == 0)
                            {
                                break;
                            }

                            var replaced = QueryHelper.ReplacsWildcard(patientId);
                            if (replaced == null)
                            {
                                results = from row in results
                                          where row.PatientId.Equals(patientId)
                                          select row;
                            }
                            else
                            {
                                results = from row in results
                                          where row.PatientId.Contains(replaced)
                                          select row;
                            }

                            break;
                        }

                        case DicomTags.PatientsSex:
                        {
                            var values = (string[])data[DicomTags.PatientsSex].Values;
                            if (values == null || values.Length == 0)
                            {
                                break;
                            }

                            results = from study in results
                                      where values.Length == 1
                                        ? study.PatientSex.Equals(values[0])
                                        : values.Contains(study.PatientSex)
                                      select study;
                            break;
                        }

                        case DicomTags.PatientsBirthDate:
                        {
                            var values = (string[])data[DicomTags.PatientsBirthDate].Values;
                            if (values == null || values.Length == 0)
                            {
                                break;
                            }

                            var dt = DateParser.Parse(values[0]);
                            if (dt == null)
                            {
                                break;
                            }

                            results = from study in results
                                      where values.Length == 1
                                        ? study.PatientBirthday.Equals(dt.Value)
                                        : values.Contains(DateParser.ToDicomString(study.PatientBirthday))
                                      select study;
                            break;
                        }

                        case DicomTags.StudyDate:
                        {
                            var v = data[DicomTags.StudyDate].GetString(0, string.Empty);
                            if (string.IsNullOrEmpty(v))
                            {
                                break;
                            }

                            DateTime?startDate;
                            DateTime?toDate;
                            bool     isRange;
                            DateRangeHelper.Parse(v, out startDate, out toDate, out isRange);

                            if (isRange)
                            {
                                results = from study in results
                                          where study.StudyDate >= startDate.Value &&
                                          study.StudyDate <= toDate.Value
                                          select study;
                            }
                            else
                            {
                                if (startDate != null)
                                {
                                    results = from study in results
                                              where study.StudyDate >= startDate.Value
                                              select study;
                                }
                                else
                                {
                                    results = from study in results
                                              where study.StudyDate <= toDate.Value
                                              select study;
                                }
                            }

                            break;
                        }
                        }
                    }
                }

                #endregion

                Logger.Warn(results.ToString());

                foreach (var source in results.ToList())
                {
                    callback(source);
                }
            }
        }
Exemplo n.º 17
0
        public Campaign GetEntity(Campaign campaign)
        {
            campaign.Title       = Title;
            campaign.Description = Description;
            campaign.Data        = Data;
            var image = string.Empty;

            if (!string.IsNullOrEmpty(Image))
            {
                image = Image;
            }
            else
            {
                image = AddonImages.ToListString();
            }

            //if (Type == CampaignType.ChangeAvatar)
            //{
            //    image = Image;
            //}
            //else if (Type == CampaignType.ShareContentWithCaption)
            //{
            //    image = AddonImages.ToListString();
            //}

            campaign.Image       = image;
            campaign.Requirement = Requirement;

            campaign.AccountChargeTime = AccountChargeTime ?? 1;
            campaign.Type          = Type;
            campaign.IsSendProduct = SendProduct;
            campaign.Code          = campaign.Code;
            campaign.Hashtag       = HashTag.ToListString();

            if (!string.IsNullOrEmpty(SampleContent.ToListString()))
            {
                campaign.SampleContent = SampleContent.ToListString();
            }


            campaign.SampleContentText = SampleContentText;
            campaign.Method            = Method;

            var reviewTime = DateRangeHelper.GetDateRange(ReviewDate);


            campaign.ReviewStart = reviewTime != null ? (DateTime?)reviewTime.Value.Start : null;
            campaign.ReviewEnd   = reviewTime != null ? (DateTime?)reviewTime.Value.End : null;

            if (ReviewType == CampaignReviewType.GuiSanPham)
            {
                campaign.ReviewAddress = ReviewAddress;
            }
            else
            {
                campaign.ReviewAddress = ReviewAddress;
            }


            if (ReviewPayback.HasValue == true)
            {
                if (ReviewPayback.Value == 1)
                {
                    campaign.ReviewPayback = true;
                }
                else
                {
                    campaign.ReviewPayback = false;
                }
            }
            else
            {
                campaign.ReviewPayback = false;
            }

            campaign.ReviewType = ReviewType;



            return(campaign);
        }
Exemplo n.º 18
0
        public static Campaign GetEntity(int agencyid, CreateCampaignInfoViewModel info, CreateCampaignTargetViewModel target,
                                         CampaignTypeCharge campaignTypeCharge, Core.Models.SettingModel setting, string code, string username)
        {
            var executionTime = DateRangeHelper.GetDateRange(target.ExecutionTime);
            var regTime       = DateRangeHelper.GetDateRange(target.RegisterTime);
            var feedbackTime  = DateRangeHelper.GetDateRange(target.FeedbackBefore);

            var reviewTime = DateRangeHelper.GetDateRange(info.ReviewDate);


            var image = string.Empty;

            if (!string.IsNullOrEmpty(info.Image))
            {
                image = info.Image;
            }
            else
            {
                image = info.AddonImages.ToListString();
            }



            //if (info.Type == CampaignType.ChangeAvatar)
            //{

            //}
            //else if (info.Type == CampaignType.ShareContentWithCaption)
            //{
            //    image = info.AddonImages.ToListString();
            //}

            var reviewaddress = "";
            var reviewpayback = false;

            if (info.Type == CampaignType.ReviewProduct && info.ReviewType.HasValue)
            {
                if (info.ReviewType == CampaignReviewType.GuiSanPham)
                {
                    if (1 == info.ReviewPayback)
                    {
                        reviewaddress = info.ReviewAddress;
                        reviewpayback = true;
                    }
                }
                else
                {
                    reviewaddress = info.ReviewAddress2;
                }
            }

            var campaign = new Campaign()
            {
                DateCreated  = DateTime.Now,
                AgencyId     = agencyid,
                Data         = info.Data,
                DateModified = DateTime.Now,
                Deleted      = false,
                Description  = info.Description,
                Image        = image,
                Published    = true,
                Status       = CampaignStatus.Created, // cap nhat status da duyet luon de facebook check,
                //Status = CampaignStatus.Confirmed,
                Title                     = info.Title,
                UserCreated               = username,
                UserModified              = username,
                ExtraOptionChargePercent  = setting.CampaignExtraOptionChargePercent,
                ServiceChargePercent      = setting.CampaignServiceChargePercent,
                ServiceVATPercent         = setting.CampaignVATChargePercent,
                ServiceChargeAmount       = 0,
                AccountChargeExtraPercent = 0,
                AccountChargeAmount       = 0,
                EnabledAccountChargeExtra = false,
                AccountChargeTime         = info.AccountChargeTime ?? 1, //change avatar campaign
                Requirement               = info.Requirement,
                Type      = info.Type,
                Code      = code,
                Quantity  = target.Quantity,
                DateStart = regTime != null ? (DateTime?)regTime.Value.Start : null,
                DateEnd   = regTime != null ? (DateTime?)regTime.Value.End.AddSeconds(59) : null,
                //AccountFeedbackBefore = target.FeedbackBefore.ToViDateTime(),
                CustomKolNames    = target.CustomKolNames.ToListString(),
                Method            = CampaignMethod.OpenJoined,
                SampleContent     = info.SampleContent.ToListString(),
                Hashtag           = info.HashTag.ToListString(),
                SampleContentText = info.SampleContentText,
                KPIMin            = target.KPIMin,
                //InteractiveMin = target.InteractiveMin,
                InteractiveMin = target.KPIMin + target.InteractiveMin,

                ExecutionStart = executionTime != null ? (DateTime?)executionTime.Value.Start : null,
                ExecutionEnd   = executionTime != null ? (DateTime?)executionTime.Value.End : null,

                FeedbackStart = feedbackTime != null ? (DateTime?)feedbackTime.Value.Start : null,
                FeedbackEnd   = feedbackTime != null ? (DateTime?)feedbackTime.Value.End : null,
                AmountMax     = target.AmountMax,
                AmountMin     = target.AmountMin,
                IsSendProduct = info.SendProduct,
                ReviewStart   = reviewTime != null ? (DateTime?)reviewTime.Value.Start : null,
                ReviewEnd     = reviewTime != null ? (DateTime?)reviewTime.Value.End : null,

                ReviewAddress = reviewaddress,
                ReviewType    = info.ReviewType,
                ReviewPayback = reviewpayback
            };


            try {
                AccountType _accountType = target.AccountType[0];
                campaign.FilterAccountType = (int)_accountType;


                if (_accountType == AccountType.HotMom)
                {
                    if (target.ChildType.HasValue)
                    {
                        campaign.FilterAccountChildrenGender = target.ChildType.Value;
                    }

                    if (target.ChildAgeMin.HasValue)
                    {
                        campaign.FilterAccountAgeChildrenFrom = target.ChildAgeMin.Value;
                    }

                    if (target.ChildAgeMax.HasValue)
                    {
                        campaign.FilterAccountAgeChildrenTo = target.ChildAgeMax.Value;
                    }
                }
            }
            catch { }

            try
            {
                if (target.EnabledCity && target.CityId != null && target.CityId.Count > 0)
                {
                    string _arrCity = string.Empty;
                    foreach (var cityId in target.CityId)
                    {
                        _arrCity += _arrCity == string.Empty ? $" {cityId.ToString()} " : $"| {cityId} ";
                    }
                    campaign.FilterAccountRegion = _arrCity;
                }
            }
            catch { }

            try {
                if (target.EnabledGender && target.Gender.HasValue)
                {
                    campaign.FilterAccountGender = (int)target.Gender.Value;
                }
            }
            catch { }

            try {
                if (target.EnabledAgeRange && target.AgeEnd.HasValue && target.AgeStart.HasValue)
                {
                    campaign.FilterAccountAgeFrom = target.AgeStart.Value;
                    campaign.FilterAccountAgeTo   = target.AgeEnd.Value;
                }
            }
            catch { }

            try
            {
                if (target.EnabledCategory && target.CategoryId != null && target.CategoryId.Count > 0)
                {
                    string _arrCategories = string.Empty;
                    foreach (var categoryid in target.CategoryId)
                    {
                        _arrCategories += _arrCategories == string.Empty ? $" {categoryid.ToString()} " : $"| {categoryid} ";
                    }
                    campaign.FilterAccountCategories = _arrCategories;
                }
            }
            catch { }


            return(campaign);
        }
Exemplo n.º 19
0
        public void TestDateRangeParser()
        {
            string[,] tests =
            {
                { "20070101",           "20070101", "",         "False"     },
                { "20070101-",          "20070101", "",         "True"      },
                { "-20070101",          "",         "20070101", "True"      },
                { "20070101-20070101",  "20070101", "20070101", "True"      },
                { "20070101-20070202",  "20070101", "20070202", "True"      },

                //from date is after to
                { "20070102-20070101",  "",         "",         "exception" },

                //bad format, extra '-'
                { "20070101-20070101-", "",         "",         "exception" },
                { "-20070101-20070101", "",         "",         "exception" },

                //bad format, missing '-'
                { "2007010120070101",   "",         "",         "exception" },

                //bad format, missing character
                { "20070101-2007010",   "",         "",         "exception" },

                //bad format, bad characters
                { "2007010a-20070101",  "",         "",         "exception" }
            };

            for (int i = 0; i < tests.Length / 4; ++i)
            {
                string dateRange        = tests[i, 0];
                string expectedFromDate = tests[i, 1];
                string expectedToDate   = tests[i, 2];
                string expectedResult   = tests[i, 3];

                bool isRange;

                try
                {
                    DateTime?from, to;

                    DateRangeHelper.Parse(dateRange, out from, out to, out isRange);
                    if (expectedResult == "exception")
                    {
                        Assert.Fail("expected an exception");
                    }

                    if (expectedFromDate == "")
                    {
                        Assert.IsNull(from);
                    }
                    else
                    {
                        Assert.AreEqual(((DateTime)from).ToString(DateParser.DicomDateFormat), expectedFromDate);
                    }

                    if (expectedToDate == "")
                    {
                        Assert.IsNull(to);
                    }
                    else
                    {
                        Assert.AreEqual(((DateTime)to).ToString(DateParser.DicomDateFormat), expectedToDate);
                    }

                    Assert.AreEqual(isRange.ToString(), expectedResult);
                }
                catch (Exception e)
                {
                    if (expectedResult != "exception")
                    {
                        Assert.Fail(e.Message);
                    }
                }

                try
                {
                    string fromString, toString;

                    DateRangeHelper.Parse(dateRange, out fromString, out toString, out isRange);
                    if (expectedResult == "exception")
                    {
                        Assert.Fail("expected an exception");
                    }

                    Assert.AreEqual(fromString, expectedFromDate);
                    Assert.AreEqual(toString, expectedToDate);
                    Assert.AreEqual(isRange.ToString(), expectedResult);
                }
                catch (Exception e)
                {
                    if (expectedResult != "exception")
                    {
                        Assert.Fail(e.Message);
                    }
                }

                try
                {
                    int fromInt, toInt;

                    DateRangeHelper.Parse(dateRange, out fromInt, out toInt, out isRange);
                    if (expectedResult == "exception")
                    {
                        Assert.Fail("expected an exception");
                    }

                    if (expectedFromDate == "")
                    {
                        Assert.AreEqual(fromInt, 0);
                    }
                    else
                    {
                        Assert.AreEqual(fromInt, Convert.ToInt32(expectedFromDate, CultureInfo.InvariantCulture));
                    }

                    if (expectedToDate == "")
                    {
                        Assert.AreEqual(toInt, 0);
                    }
                    else
                    {
                        Assert.AreEqual(toInt, Convert.ToInt32(expectedToDate, CultureInfo.InvariantCulture));
                    }
                }
                catch (Exception e)
                {
                    if (expectedResult != "exception")
                    {
                        Assert.Fail(e.Message);
                    }
                }
            }
        }
Exemplo n.º 20
0
        private static IEnumerable <TestCaseData> OnApplyTemplateCases()
        {
            var testName = nameof(OnApplyTemplateCases);

            yield return(new TestCaseData(
                             new PickerDataProps(), new PickerDataProps(Today, Today, DateRangeKind.Today))
                         .SetName($"{testName}: 010"));

            yield return(new TestCaseData(
                             new PickerDataProps(null, null, DateRangeKind.Custom), new PickerDataProps(Yesterday, Today, DateRangeKind.Custom))
                         .SetName($"{testName}: 020"));


            foreach (var kind in new DateRangeKind?[] { null, DateRangeKind.Custom })
            {
                yield return(new TestCaseData(
                                 new PickerDataProps(null, PastDate1, kind), new PickerDataProps(PastDate1, PastDate1, DateRangeKind.Custom))
                             .SetName($"{testName}: 030 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(null, FutureDate, kind), new PickerDataProps(Yesterday, FutureDate, DateRangeKind.Custom))
                             .SetName($"{testName}: 040 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(PastDate1, null, kind), new PickerDataProps(PastDate1, Today, DateRangeKind.Custom))
                             .SetName($"{testName}: 050 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(FutureDate, null, kind), new PickerDataProps(FutureDate, FutureDate, DateRangeKind.Custom))
                             .SetName($"{testName}: 060 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(PastDate1, PastDate2, kind), new PickerDataProps(PastDate1, PastDate2, DateRangeKind.Custom))
                             .SetName($"{testName}: 070 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(PastDate2, PastDate1, kind), new PickerDataProps(PastDate2, PastDate2, DateRangeKind.Custom))
                             .SetName($"{testName}: 080 {kind}"));
            }


            foreach (DateRangeKind kind in Enum.GetValues(typeof(DateRangeKind)))
            {
                var kindsToPassBy = new DateRangeKind[] { DateRangeKind.Custom, DateRangeKind.Week, DateRangeKind.Month, DateRangeKind.Year };

                if (kindsToPassBy.Contains(kind))
                {
                    continue;
                }

                //for the case when DateRangeKind enum has more kinds than are actually contained in the Picker's DateRangeList.
                var dateRange = DateRangeHelper.GetDateRangeOfKind(kind);
                if (null == dateRange)
                {
                    continue;
                }

                yield return(new TestCaseData(
                                 new PickerDataProps(null, null, kind),
                                 new PickerDataProps(dateRange.From, dateRange.To, kind))
                             .SetName($"{testName}: 110 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(PastDate1, null, kind),
                                 new PickerDataProps(dateRange.From, dateRange.To, kind))
                             .SetName($"{testName}: 120 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(null, PastDate1, kind),
                                 new PickerDataProps(dateRange.From, dateRange.To, kind))
                             .SetName($"{testName}: 130 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(PastDate1, PastDate2, kind),
                                 new PickerDataProps(dateRange.From, dateRange.To, kind))
                             .SetName($"{testName}: 140 {kind}"));

                yield return(new TestCaseData(
                                 new PickerDataProps(PastDate2, PastDate1, kind),
                                 new PickerDataProps(dateRange.From, dateRange.To, kind))
                             .SetName($"{testName}: 150 {kind}"));
            }
        }