public ActionResult Edit(string id)
        {
            ReceiptViewModel model = ReceiptHelper.GetReceipt(id);

            if (model.CustomerSites == null)
            {
                model.CustomerSites = CustomerHelper.GetCustomerSites(model.CustomerId).Select(a => new SelectListItem
                {
                    Text  = a.SiteName.ToString(),
                    Value = a.Id.ToString()
                }).ToList();
            }

            if (model.Banks == null)
            {
                model.Banks = BankHelper.GetBankList(model.SOBId);
            }

            if (model.BankAccounts == null)
            {
                model.BankAccounts = BankHelper.GetBankAccountList(model.BankId);
            }

            SessionHelper.Calendar       = CalendarHelper.GetCalendar(model.PeriodId.ToString());
            SessionHelper.PrecisionLimit = CurrencyHelper.GetCurrency(model.CurrencyId.ToString()).Precision;
            return(View("Create", model));
        }
Exemplo n.º 2
0
        public async Task <CreateOperationalTaskViewModel> CreateOtherTask(IOperationalTaskModel model)
        {
            int weekNumber = CalendarHelper.GetWeekNumber(model.Date.Value);

            model.JobId = await taskIdGenerator.Other();

            var addressList = new List <JobAddress>();

            addressList.Add(new JobAddress {
                HousingDepartmentId = model.DepartmentId, Address = model.Address
            });
            await messageBus.Publish(new CreateJobCommand(model.JobId, Guid.Empty, model.Title, JobTypeEnum.Other, model.CreatorId, RoleType.Coordinator, addressList, null, null));

            var jobAssignId = Guid.NewGuid();
            CreateOperationalTaskAssignCommand tenantkAssignCommand = GetCreateOperationalTaskAssignCommand(model, model.JobId, jobAssignId, weekNumber);
            await messageBus.Publish(tenantkAssignCommand);

            var dayAssignId = Guid.NewGuid();
            CreateDayAssignCommand dayAssign = GetCreateDayAssignCommand(model, dayAssignId, jobAssignId, weekNumber);
            await messageBus.Publish(dayAssign);

            await SetStatusAfterCreation(dayAssignId, model.TeamLeadId);

            CreateOperationalTaskViewModel result = new CreateOperationalTaskViewModel
            {
                Id           = model.JobId,
                DepartmentId = model.DepartmentId,
                DayAssignId  = dayAssignId
            };

            return(result);
        }
        public ActionResult Edit(string id)
        {
            PaymentViewModel model = PaymentHelper.GetPayment(id);

            SessionHelper.PeriodId = model.PeriodId;
            SessionHelper.Calendar = CalendarHelper.GetCalendar(PayablePeriodHelper.GetPayablePeriod(model.PeriodId.ToString()).CalendarId.ToString());

            if (model.BankAccount == null)
            {
                model.BankAccount   = BankHelper.GetBankAccountList(model.BankId);
                model.BankAccountId = model.BankAccount.Any() ?
                                      Convert.ToInt32(model.BankAccount.First().Value) : 0;
            }
            if (model.VendorSite == null)
            {
                model.VendorSite = VendorHelper.GetAllSites(model.VendorId)
                                   .Select(x => new SelectListItem
                {
                    Text  = x.Name,
                    Value = x.Id.ToString()
                }).ToList();
                model.VendorSiteId = model.VendorSite.Any() ?
                                     Convert.ToInt32(model.VendorSite.First().Value) : 0;
            }

            model.PaymentInvoiceLines = PaymentHelper.GetPaymentLines(id).ToList();
            model.SOBId           = SessionHelper.SOBId;
            SessionHelper.Payment = model;

            return(View("Create", model));
        }
Exemplo n.º 4
0
        public ViewModel()
        {
            var date = CalendarHelper.GetFirstDayOfWeek(DateTime.Today, DayOfWeek.Monday);

            var meetingApp = new Appointment()
            {
                Subject = "Meeting with John",
                Start   = date.AddHours(7),
                End     = date.AddHours(8)
            };

            meetingApp.Resources.Add(new Resource("Room 1", "Room"));

            var scrumApp = new Appointment()
            {
                Subject = "Morning Scrum",
                Start   = date.AddHours(9),
                End     = date.AddHours(9).AddMinutes(30)
            };

            scrumApp.Resources.Add(new Resource("Room 1", "Room"));
            scrumApp.RecurrenceRule = new RecurrenceRule(
                new RecurrencePattern()
            {
                Frequency      = RecurrenceFrequency.Daily,
                MaxOccurrences = 5
            }
                );
            Appointments = new ObservableCollection <Appointment>()
            {
                scrumApp, meetingApp
            };
            this.SelectedAppointment = meetingApp;
        }
Exemplo n.º 5
0
        internal static DateTime FirstDayOfFirstWeekOfMonthForVisibleDate(this IScheduler scheduler, DateTime startDate)
        {
            DateTime visibleDate      = startDate;
            var      firstDateOfMonth = new DateTime(visibleDate.Year, visibleDate.Month, 1);

            return(CalendarHelper.GetFirstDayOfWeek(firstDateOfMonth, scheduler.GetFirstDayOfWeekInUse()));
        }
Exemplo n.º 6
0
        public ActionResult Create()
        {
            GLHeaderModel model = SessionHelper.JV;

            if (model == null)
            {
                model = new GLHeaderModel();
                model = new GLHeaderModel
                {
                    CompanyId      = AuthenticationHelper.CompanyId.Value,
                    SOBId          = SessionHelper.SOBId,
                    GlLines        = new List <GLLinesModel>(),
                    DocumentNo     = "New",
                    ConversionRate = 1
                };
                SessionHelper.JV = model;
            }
            model.Currencies = CurrencyHelper.GetCurrencyList(SessionHelper.SOBId);
            model.Periods    = CalendarHelper.GetCalendarsList(SessionHelper.SOBId);

            if (model.Currencies != null && model.Currencies.Count() > 0)
            {
                model.CurrencyId             = Convert.ToInt64(model.Currencies.FirstOrDefault().Value);
                SessionHelper.PrecisionLimit = CurrencyHelper.GetCurrency(model.CurrencyId.ToString()).Precision;
            }
            if (model.Periods != null && model.Periods.Count() > 0)
            {
                model.PeriodId         = Convert.ToInt64(model.Periods.FirstOrDefault().Value);
                SessionHelper.Calendar = CalendarHelper.GetCalendar(model.PeriodId.ToString());
                model.GLDate           = SessionHelper.Calendar.StartDate;
            }

            return(View(model));
        }
Exemplo n.º 7
0
 public ChaplainController()
 {
     ViewBag.Logs      = ContactLogHelper.GetContactLogsByMentorId(ref this._db, _userId).Take(3);
     ViewBag.Messages  = MessagingHelper.GetMessagesToUserId(ref this._db, _userId).Take(3);
     ViewBag.Events    = CalendarHelper.GetEventsByUserId(ref this._db, _userId).Take(3);
     ViewBag.Resources = ResourceHelper.GetResources(ref this._db).Take(3);
 }
Exemplo n.º 8
0
        public override async Task InitializeAsync(object navigationData)
        {
            try
            {
                IsBusy = true;

                var today    = DateTime.Today;
                var nextWeek = today.AddDays(7);

                // Get pickup and drop time based on scheduled calendar events
                var events = await _calendarService.GetDayEventsAsync(today, nextWeek);

                CalendarHelper.CalculateWeekdaysCalendarWorkTime(events, out _arrivalTime, out _departureTime);

                // Get user photo
                var photo = await _userService.GetUserPhotoAsync(App.CurrentUser.Mail);

                if (photo != null)
                {
                    App.CurrentUser.PhotoStream = ImageSource.FromStream(() => new MemoryStream(photo));
                }
            }
            catch (Exception ex)
            {
                _arrivalTime   = DateTime.Today + AppSettings.DefaultArrivalTime;
                _departureTime = DateTime.Today + AppSettings.DefaultDepartureTime;
                Debug.WriteLine($"[UserPreferences] Error getting user info in: {ex}");
            }
            finally
            {
                IsBusy = false;
            }
        }
        public ActionResult GetDatabyPeriod(long periodId)
        {
            PaymentViewModel model = new PaymentViewModel();

            SessionHelper.Calendar = CalendarHelper.GetCalendar(PayablePeriodHelper.GetPayablePeriod(periodId.ToString()).CalendarId.ToString());

            if (model.Vendor == null)
            {
                model.Vendor   = VendorHelper.GetVendorList(SessionHelper.Calendar.StartDate, SessionHelper.Calendar.EndDate);
                model.VendorId = model.Vendor.Any() ? Convert.ToInt32(model.Vendor.First().Value) : 0;

                if (model.VendorId > 0)
                {
                    model.VendorSite   = VendorHelper.GetVendorSiteList(model.VendorId);
                    model.VendorSiteId = model.VendorSite.Any() ? Convert.ToInt64(model.VendorSite.First().Value) : 0;
                }
            }

            if (model.Bank == null)
            {
                model.Bank   = BankHelper.GetBankList(model.SOBId);
                model.BankId = model.Bank.Any() ? Convert.ToInt32(model.Bank.First().Value) : 0;

                if (model.BankId > 0)
                {
                    model.BankAccount   = BankHelper.GetBankAccountList(model.BankId);
                    model.BankAccountId = model.BankAccount.Any() ? Convert.ToInt64(model.BankAccount.First().Value) : 0;
                }
            }

            return(Json(model, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Duration2s the unit.
        /// </summary>
        /// <param name="duration">The duration.</param>
        /// <returns></returns>
        private static TimePhasedDataType.TimePhaseUnit Duration2Unit(long duration)
        {
            TimePhasedDataType.TimePhaseUnit retVal = TimePhasedDataType.TimePhaseUnit.Minute;

            if (duration / CalendarHelper.MilisPerYear() > 0)
            {
                retVal = TimePhasedDataType.TimePhaseUnit.Year;
            }
            else if (duration / CalendarHelper.MilisPerMonth() > 0)
            {
                retVal = TimePhasedDataType.TimePhaseUnit.Year;
            }
            else if (duration / CalendarHelper.MilisPerWeek() > 0)
            {
                retVal = TimePhasedDataType.TimePhaseUnit.Mounth;
            }
            else if (duration / CalendarHelper.MilisPerDay() > 0)
            {
                retVal = TimePhasedDataType.TimePhaseUnit.Week;
            }
            else if (duration / CalendarHelper.MilisPerHour() > 0)
            {
                retVal = TimePhasedDataType.TimePhaseUnit.Day;
            }
            else if (duration / CalendarHelper.MilisPerMinute() > 0)
            {
                retVal = TimePhasedDataType.TimePhaseUnit.Hours;
            }

            return(retVal);
        }
Exemplo n.º 11
0
        public ActionResult InsertHoliday(Holiday holiday)
        {
            ViewBag.Section = ActiveSection.Week;

            CarPoolToolEntities entities = new CarPoolToolEntities();

            if (holiday != null)
            {
                //Segno festivo
                entities.Holidays.Add(holiday);

                //Rimuovo eventuali persone segnate
                var log = from a in entities.CarpoolLogs
                          where a.data == holiday.data
                          select a;
                if (log != null)
                {
                    entities.CarpoolLogs.RemoveRange(log);
                }

                entities.SaveChanges();

                CalendarHelper.UpdateGoogleCalendar(holiday.data, holiday.data.AddDays(1));
            }


            return(RedirectToAction("Week", new { start = holiday.data, skipAheadIfWeekend = false }));
        }
        public IDictionary <Guid, bool> GetDayAbsencesForMembers(IEnumerable <Guid> memberIds, int year, int week, int weekDay)
        {
            var date            = CalendarHelper.GetDateByWeekAndDayNumber(year, week, weekDay);
            var membersAbsences = memberIds.ToDictionary(memberId => memberId, memberId => IsMemberAbsentAtDate(memberId, date));

            return(membersAbsences);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Unit2durations the specified unit.
        /// </summary>
        /// <param name="unit">The unit.</param>
        /// <returns></returns>
        private static long Unit2duration(TimePhasedDataType.TimePhaseUnit unit)
        {
            long retVal = 0;

            switch (unit)
            {
            case TimePhasedDataType.TimePhaseUnit.Hours:
                retVal = CalendarHelper.MilisPerHour();
                break;

            case TimePhasedDataType.TimePhaseUnit.Minute:
                retVal = CalendarHelper.MilisPerMinute();
                break;

            case TimePhasedDataType.TimePhaseUnit.Day:
                retVal = CalendarHelper.MilisPerDay();
                break;

            case TimePhasedDataType.TimePhaseUnit.Week:
                retVal = CalendarHelper.MilisPerWeek();
                break;
            }

            return(retVal);
        }
Exemplo n.º 14
0
        public ActionResult WeekEdit(DateTime day, Dictionary <DayOfWeek, DayLog> weekdata, bool updateGoogleCalendar)
        {
            ViewBag.Section = ActiveSection.Week;

            CarPoolToolEntities entities = new CarPoolToolEntities();

            foreach (var daylog in weekdata.Values)
            {
                EntitiesHelper.PersistDayLog(daylog, entities, UserStatus.Absent, false);
            }

            entities.SaveChanges();

            if (updateGoogleCalendar)
            {
                try
                {
                    CalendarHelper.UpdateGoogleCalendar(weekdata.First().Value.Date, weekdata.Last().Value.Date.AddDays(1));
                }
                catch (Exception)
                {
                }
            }

            return(RedirectToAction("Week", new { start = day, skipAheadIfWeekend = false }));
        }
        async void OnSaveClicked(Object sender, EventArgs args)
        {
            DateTime startDateTime;
            DateTime endDateTime;

            if (IsAllDayMeeting)
            {
                startDateTime = ThisMeetingDate.Date;
                endDateTime   = ThisMeetingDate.Date.AddDays(1);
            }
            else
            {
                startDateTime = (DatePicker.Date.Date + StartTimePicker.Time).ToUniversalTime();
                endDateTime   = (DatePicker.Date.Date + EndTimePicker.Time).ToUniversalTime();
            }

            var eventUpdated = await CalendarHelper.UpdateEventAsync(ThisMeeting.Id, AttendeesBox.Text, Description.Text, Location.Text, Subject.Text, startDateTime, endDateTime, IsAllDayMeeting);

            if (eventUpdated)
            {
                await Navigation.PopAsync();
            }
            else
            {
                await DisplayAlert(SampleStrings.ErrorText, SampleStrings.CreateMeetingFailed, SampleStrings.OKButtonText);
            }
        }
Exemplo n.º 16
0
        private decimal GetAbsenceTimeInHours(DateTime startDate, DateTime endDate)
        {
            IDictionary <int, int> weekDaysWorkingMinutes = appSettingHelper.GetDictionaryAppSetting <int, int>(Constants.AppSetting.DaysWorkingMinutes);
            decimal totalMinutes = CalendarHelper.GetDatesRange(startDate, endDate).Sum(day => weekDaysWorkingMinutes[day.GetWeekDayNumber()]);

            return(totalMinutes / Constants.Common.MinutesInOneHour);
        }
Exemplo n.º 17
0
 public EventsController(
     IRepository repository,
     IProcessedContentRepository processedContentRepository,
     EventEmailBuilder emailBuilder,
     IRssFeedFactory rssFeedFactory,
     ILogger <EventsController> logger,
     IApplicationConfiguration config,
     BusinessId businessId,
     IFilteredUrl filteredUrl,
     CalendarHelper helper,
     ITimeProvider timeProvider,
     IDateCalculator dateCalculator,
     IStockportApiEventsService stockportApiEventsService)
 {
     _repository = repository;
     _processedContentRepository = processedContentRepository;
     _emailBuilder              = emailBuilder;
     _rssFeedFactory            = rssFeedFactory;
     _logger                    = logger;
     _config                    = config;
     _businessId                = businessId;
     _filteredUrl               = filteredUrl;
     _helper                    = helper;
     _dateCalculator            = dateCalculator;
     _stockportApiEventsService = stockportApiEventsService;
 }
        public Response GetToNextWorkingDay(string token, [FromBody] GetToNextWorkingDayParam param)
        {
            Response response = new Response();

            if (string.IsNullOrEmpty(token) || !token.Equals(_token))
            {
                response.code    = "404";
                response.message = "Invild token";
            }
            else
            {
                List <SingleField> lstResult = CalendarHelper.GetToNextWorkingDay(param);
                if (lstResult.Count == 0)
                {
                    response.code    = "500";
                    response.message = "No Data";
                }
                else
                {
                    response.code    = "200";
                    response.content = lstResult;
                }
            }
            return(response);
        }
Exemplo n.º 19
0
        public virtual decimal GetEmployeeHoursFromCalendar(int?employeeID)
        {
            decimal    hours    = 40;
            var        select   = new PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPEmployee.bAccountID> > > >(graph);
            EPEmployee employee = select.Select(employeeID);

            if (employee != null && employee.CalendarID != null)
            {
                CSCalendar calendar = PXSelect <CSCalendar, Where <CSCalendar.calendarID, Equal <Required <CSCalendar.calendarID> > > > .Select(graph, employee.CalendarID);

                if (calendar != null)
                {
                    hours  = 0;
                    hours += CalendarHelper.GetHoursWorkedOnDay(calendar, DayOfWeek.Monday);
                    hours += CalendarHelper.GetHoursWorkedOnDay(calendar, DayOfWeek.Tuesday);
                    hours += CalendarHelper.GetHoursWorkedOnDay(calendar, DayOfWeek.Wednesday);
                    hours += CalendarHelper.GetHoursWorkedOnDay(calendar, DayOfWeek.Thursday);
                    hours += CalendarHelper.GetHoursWorkedOnDay(calendar, DayOfWeek.Friday);
                    hours += CalendarHelper.GetHoursWorkedOnDay(calendar, DayOfWeek.Saturday);
                    hours += CalendarHelper.GetHoursWorkedOnDay(calendar, DayOfWeek.Sunday);
                }
            }

            return(hours);
        }
        public async Task <IActionResult> GetHorarioPorFecha(int negocio, int anio, int mes, int dia)
        {
            try
            {
                DateTime fecha         = new DateTime(anio, mes, dia);
                var      diaSemana     = CalendarHelper.CalcularDiaDeLaSemana(fecha);
                Horario  horarioResult = await _repository.GetHorario(negocio, diaSemana);

                if (horarioResult == null)
                {
                    return(NotFound());
                }

                var horaAperturaFormateada = String.Format("{0:t}", horarioResult.HorarioApertura);
                var horaCierreFormateada   = String.Format("{0:t}", horarioResult.HorarioCierre);

                var horarioResponse = new { horarioApertura = horaAperturaFormateada, horarioCierre = horaCierreFormateada };
                return(Ok(horarioResponse));
            }

            catch (Exception exception)
            {
                _logger.LogInformation($"Fallo en la busqueda del negocio: { negocio } -- Problema: {exception.Message}");
                return(BadRequest($"Problema al intentar realizar el horario del negocio: {negocio}"));
            }
        }
Exemplo n.º 21
0
        public async Task <Guid> ChangeDayAssignDate(INewDayAssignModel model)
        {
            var year = model.Year != default(int) ? model.Year : DateTime.UtcNow.Year;

            if (model.WeekDay.HasValue)
            {
                model.Date = CalendarHelper.GetDateByWeekAndDayNumber(year, model.WeekNumber, model.WeekDay.Value);
            }

            var dayAssign = model.DayAssignId.HasValue ? dayAssignProvider.Get(model.DayAssignId.Value) : null;

            if (dayAssign == null)
            {
                return(await CreateDayAssign(model));
            }
            else
            {
                model.Id = model.DayAssignId.Value;
                await messageBus.Publish(model.Map <ChangeDayAssignDateCommand>());

                if (dayAssign.StatusId == JobStatus.Expired)
                {
                    await jobStatusService.Pending(dayAssign.Id, dayAssign.StatusId);
                }

                return(model.DayAssignId.Value);
            }
        }
Exemplo n.º 22
0
        protected virtual void EPActivityApprove_EarningTypeID_FieldDefaulting(PXCache cache, PXFieldDefaultingEventArgs e)
        {
            EPActivityApprove row = (EPActivityApprove)e.Row;

            if (row == null || EPsetingst.Current == null)
            {
                return;
            }

            EPEmployee rowEmploye = PXSelect <EPEmployee> .Search <EPEmployee.userID>(this, Filter.Current.OwnerID);

            if (rowEmploye == null || row.StartDate == null)
            {
                return;
            }

            if (CalendarHelper.IsWorkDay(this, rowEmploye.CalendarID, (DateTime)row.StartDate))
            {
                e.NewValue = EPsetingst.Current.RegularHoursType;
            }
            else
            {
                e.NewValue = EPsetingst.Current.HolidaysType;
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// 排课
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool StudentArrangeCourse(CreateStudentCourseArrangeInput input)
        {
            Logger.Info("AddStudentCourseArrange: " + input);
            var    arrange    = input.MapTo <StudentCourseArrange>();
            string studentIds = GenerateStudentIds(input);

            arrange.StudentId = studentIds;
            bool result = true;

            if (!string.IsNullOrEmpty(input.Id))
            {
                result = !string.IsNullOrEmpty(_studentCourseArrangeRepository.Update(arrange).Id);
            }
            else
            {
                arrange.Id            = IdentityCreator.NewGuid;
                arrange.ArrangeTime   = DateTime.Now;
                arrange.CreatorUserId = AbpSession.UserId.Value;
                result = validDate(input);
                if (result)
                {
                    if (input.CrossWeek != null && input.CrossWeek.Value)
                    {
                        StringBuilder builder = new StringBuilder();
                        using (var unitOfWork = _unitOfWorkManager.Begin()) //启用工作单元
                        {
                            try
                            {
                                var lastDate   = CalendarHelper.LastDayOfMonth(input.BeginTime);
                                var crossTimes = Math.Floor(Convert.ToDecimal((lastDate.Day - input.BeginTime.Day) / 7));
                                for (int i = 0; i <= crossTimes; i++)
                                {
                                    var newArrange = input.MapTo <StudentCourseArrange>();
                                    newArrange.Id            = IdentityCreator.NewGuid;
                                    newArrange.ArrangeTime   = DateTime.Now;
                                    newArrange.CreatorUserId = AbpSession.UserId.Value;
                                    newArrange.StudentId     = studentIds;
                                    newArrange.BeginTime     = newArrange.BeginTime.Value.AddDays(7 * i);
                                    newArrange.EndTime       = newArrange.EndTime.Value.AddDays(7 * i);
                                    _studentCourseArrangeRepository.Insert(newArrange);
                                }
                                unitOfWork.Complete(); //提交事务
                            }
                            catch (Exception ex)
                            {
                                builder.AppendLine(ex.Message);
                            }
                            result = builder.Length == 0;
                        }
                    }
                    else
                    {
                        result = !string.IsNullOrEmpty(_studentCourseArrangeRepository.Insert(arrange).Id); //.InsertOrUpdate(arrange);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 24
0
        public ActionResult Index(string message = "")
        {
            ViewBag.ErrorMessage = message;
            ReceiptListModel model = new ReceiptListModel();

            model.SOBId = SessionHelper.SOBId;

            if (model.Periods == null)
            {
                model.Periods  = ReceivablePeriodHelper.GetPeriodList(Convert.ToInt64(SessionHelper.SOBId));
                model.PeriodId = model.Periods.Any() ?
                                 Convert.ToInt32(model.Periods.First().Value) : 0;
            }
            else if (model.Periods == null)
            {
                model.Periods = new List <SelectListItem>();
            }

            CalendarViewModel calendar = CalendarHelper.GetCalendar(ReceivablePeriodHelper.GetReceivablePeriod(model.PeriodId.ToString()).CalendarId.ToString());

            if (calendar == null)
            {
                SessionHelper.Calendar.StartDate = DateTime.Now;
                SessionHelper.Calendar.EndDate   = DateTime.Now;
            }
            else
            {
                SessionHelper.Calendar = CalendarHelper.GetCalendar(ReceivablePeriodHelper.GetReceivablePeriod(model.PeriodId.ToString()).CalendarId.ToString());
            }

            if (model.Customers == null)
            {
                model.Customers = customerService.GetAll(AuthenticationHelper.CompanyId.Value, SessionHelper.SOBId,
                                                         SessionHelper.Calendar.StartDate, SessionHelper.Calendar.EndDate).
                                  Select(a => new SelectListItem
                {
                    Text  = a.CustomerName.ToString(),
                    Value = a.Id.ToString()
                }).ToList();
            }
            model.CustomerId = model.Customers.Count() > 0 ? Convert.ToInt64(model.Customers.FirstOrDefault().Value) : 0;

            if (model.Currency == null)
            {
                model.Currency = CurrencyHelper.GetCurrencies(Convert.ToInt32(SessionHelper.SOBId))
                                 .Select(x => new SelectListItem
                {
                    Text  = x.Name,
                    Value = x.Id.ToString()
                }).ToList();
                model.CurrencyId = model.Currency.Any() ? Convert.ToInt32(model.Currency.First().Value) : 0;
            }
            else if (model.Currency == null)
            {
                model.Currency = new List <SelectListItem>();
            }

            return(View(model));
        }
Exemplo n.º 25
0
        public TotalWeeksViewModel GetTotalWeeks()
        {
            var result = new TotalWeeksViewModel();

            result.TotalWeeks  = CalendarHelper.GetTotalWeeks();
            result.CurrentWeek = DateTime.UtcNow.GetWeekNumber();
            return(result);
        }
Exemplo n.º 26
0
        public YearWeeksViewModel GetWeeksModel(int year)
        {
            var result = new YearWeeksViewModel();

            result.Year       = year;
            result.MonthWeeks = CalendarHelper.GetYearWeeks(year);
            return(result);
        }
        public ActionResult GetCalendarList()
        {
            CalendarListModel model = new CalendarListModel();

            model.SOBId     = SessionHelper.SOBId;
            model.Calendars = CalendarHelper.GetCalendars(SessionHelper.SOBId);
            return(PartialView("_List", model));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Calculates start date, end date, updates collection of dates with barriers and calendar's template
        /// </summary>
        private void _UpdateCalendarView()
        {
            DateTime startDate = CalendarHelper.GetStartRangeDate(DisplayDate); // -1 week date
            DateTime endDate   = CalendarHelper.GetEndRangeDate(DisplayDate);   // + 2 weeks date

            BarriersDayStatusesManager.Instance.UpdateDayStatuses(startDate, endDate);
            _UpdateCalendarDayButtonStyle();
        }
Exemplo n.º 29
0
        public PopupDatePicker()
        {
            Orientation       = ScrollOrientation.Horizontal;
            HorizontalOptions = LayoutOptions.Center;
            Padding           = 0;
            BackgroundColor   = StyleManager.DarkAccentColor;

            var now = DateTime.Now;

            monthTiles = new List <TopPanelItem>();

            for (int i = 1; i <= 12; i++)
            {
                IEnumerable <DateTime> days = CalendarHelper.GetDaysInMonth(i, now.Year);
                var dayPicker = new DayPicker(CalendarHelper.CreateDayLayouts(days));
                dayPicker.DateChanged += (sender, e) => {
                    SelectedDay = dayPicker.SelectedItem;
                    DateChanged(sender, e);
                };

                var month = new DateTime(now.Year, i, 1, 0, 0, 0, DateTimeKind.Local);
                var tab   = new TopPanelItem(month.ToString("MMMM", new CultureInfo("en-US")), dayPicker)
                {
                    WidthRequest = 100
                };

                if (month.Month == now.Month)
                {
                    tab.IsSelected   = true;
                    currentMonthTile = tab;
                }
                monthTiles.Add(tab);
            }

            monthPicker = new PopupTopPanel(monthTiles);

            monthPicker.DefaultView = currentMonthTile.ContentView;
            DefaultView             = monthPicker.DefaultView;
            Content = monthPicker;

            ScrollEnded += (sender, args) => {
                var position = (int)Math.Round(ScrollX / 115);

                if (position >= 0 && position < monthTiles.Count)
                {
                    SelectMonthTile(monthTiles[position]);
                }
            };

            Scrolled += (sender, args) => {
                var position = (int)Math.Round(args.ScrollX / 115);

                if (position >= 0 && position < monthTiles.Count)
                {
                    HighlightItem(position);
                }
            };
        }
Exemplo n.º 30
0
        public ActionResult Create()
        {
            PayableInvoiceModel model = SessionHelper.PayableInvoice;

            if (model == null)
            {
                model = new PayableInvoiceModel
                {
                    CompanyId     = AuthenticationHelper.CompanyId.Value,
                    InvoiceDetail = new List <PayableInvoiceDetailModel>(),
                    Periods       = new List <SelectListItem>(),
                    Vendors       = new List <SelectListItem>(),
                    VendorSites   = new List <SelectListItem>(),
                    WHTaxes       = new List <SelectListItem>(),
                    InvoiceTypes  = new List <SelectListItem>(),
                    InvoiceNo     = "New",
                    SOBId         = SessionHelper.SOBId
                };
            }

            model.Periods = PayablePeriodHelper.GetPeriodList(SessionHelper.SOBId);

            if (model.Periods != null && model.Periods.Count() > 0)
            {
                model.PeriodId         = Convert.ToInt64(model.Periods.FirstOrDefault().Value);
                SessionHelper.Calendar = CalendarHelper.GetCalendar(model.PeriodId.ToString());
                model.InvoiceDate      = SessionHelper.Calendar.StartDate;

                model.InvoiceTypes = InvoiceTypeHelper.GetInvoiceTypes(SessionHelper.SOBId, SessionHelper.Calendar.StartDate, SessionHelper.Calendar.EndDate);

                if (model.InvoiceTypes != null && model.InvoiceTypes.Count() > 0)
                {
                    model.InvoiceTypeId = Convert.ToInt64(model.InvoiceTypes.FirstOrDefault().Value);
                }

                model.Vendors = VendorHelper.GetVendorList(SessionHelper.Calendar.StartDate, SessionHelper.Calendar.EndDate);

                if (model.Vendors != null && model.Vendors.Count() > 0)
                {
                    model.VendorId    = Convert.ToInt64(model.Vendors.FirstOrDefault().Value);
                    model.VendorSites = VendorHelper.GetVendorSiteList(model.VendorId);

                    if (model.VendorSites != null && model.VendorSites.Count() > 0)
                    {
                        model.VendorSiteId = Convert.ToInt64(model.VendorSites.FirstOrDefault().Value);
                        model.WHTaxes      = WithholdingHelper.GetWithHoldingList(model.VendorId, model.VendorSiteId, SessionHelper.Calendar.StartDate, SessionHelper.Calendar.EndDate);

                        if (model.WHTaxId != null && model.WHTaxes.Count() > 0)
                        {
                            model.WHTaxId = Convert.ToInt64(model.WHTaxes.FirstOrDefault().Value);
                        }
                    }
                }
            }

            SessionHelper.PayableInvoice = model;
            return(View("Edit", model));
        }
Exemplo n.º 31
0
        public async Task TestDirect()
        {
            var authenticationHelper = Auth();

            var c = new CalendarHelper(authenticationHelper);
           
            var events = await c.GetCalendarEvents();
            Assert.IsNotNull(events);
            Assert.IsFalse(!events.Any());
            Debug.WriteLine($"{events.Count()} events found");
        }
Exemplo n.º 32
0
        /// <summary>
        /// UserId, Start, Finish, Type, ObjectId, ObjectTypeId, ObjectName, Duration, PercentCompleted,
        /// PriorityId, StateId, FinishDate, Highlight, IsNewMessage, IsOverdue, AssignmentId, AssignmentName
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="curDate"></param>
        /// <param name="fromDate"></param>
        /// <param name="toDate"></param>
        /// <param name="objectTypes"></param>
        /// <param name="highlightedItems"></param>
        /// <param name="getPastTime"></param>
        /// <param name="getOffTime"></param>
        /// <param name="mergeBreaks"></param>
        /// <param name="strictBorder"></param>
        /// <returns></returns>
        public static DataTable GetResourceUtilization(
			int userId,
			DateTime curDate,
			DateTime fromDate, 
			DateTime toDate,
			ArrayList objectTypes,	/*ArrayList arr = new ArrayList();arr.Add(ObjectTypes.Task);arr.Add(ObjectTypes.ToDo);arr.Add(ObjectTypes.CalendarEntry);arr.Add(ObjectTypes.Document);arr.Add(ObjectTypes.Issue);*/
			List<KeyValuePair<int, int>> highlightedItems,	/* key:ObjectId, value:ObjectTypeId */
			bool getPastTime,
			bool getOffTime,
			bool mergeBreaks,
			bool strictBorder)
        {
            /* �������� �������:
             * 1. �������� ������ � ������������, ������ ���������� ����� ����� �������� ������� � ������ ���������
             *    (��� �������� ����� ��������� ������� ������ �� ������ �������� ��� � �� ����� ���������� ���)
             * 2. ������ ����������� ���������� TimeType.Past (��������� �����) � TimeType.Off.
             *    �.�. �� ��������� �� ����� - ���������.
             * 3. �� ��������� �������� ��������� ���������� � ������� ������� ����� (TimeType.Free)
             * 4. ��������� ���������� � ��������� ������� � �������������� �������.
             * 5. ������ ��� ����������� �� ������, ��������� ������ ���������� TimeType.CalendarEntry
             *    � ������������ ��������� ��������������� ���� � �������������� �������
             * 6. ������ WorkPinnedUp, ��������� ������ ���������� TimeType�.Sticked
             *    � ������������ ��������� ��������������� ���� � �������������� �������
             * 7. ������ ������, ���������, ��������� (��������������� � ������ ��������) �
             *    ������������ ���� � ��� � ������� �� ���������� TimeType.WorkUrgent -
             *    TimeTime.WorkLow (� ����������� �� ����������) � ������������ ���������
             *    ��������������� ���� � �������������� �������.
             *
             * �� ������ ����� ������� � ������� �������.
             * ����� ��� ������������� ����� ����� ������������� �������� �� �����������
             *
             * - �������� "mergeBreaks" ����������, ���� �� ���������� ����������� ��������� ������
             * - �������� "strictBorder" ����������, ��� ����� ��������� � �������������� �������, ����
             *   ������ �������� �� ������� ���������� ���������. ���� true, �� ��������� ����� ������
             *   ����� �������� �� �������� fromDate � toDate. ���� false, �� ����� ������������
             *   �������� ��������� ����� ������
             */

            // round dates to minutes
            fromDate = fromDate.Date.AddHours(fromDate.Hour).AddMinutes(fromDate.Minute);
            toDate = toDate.Date.AddHours(toDate.Hour).AddMinutes(toDate.Minute);
            curDate = curDate.Date.AddHours(curDate.Hour).AddMinutes(curDate.Minute);

            if (fromDate >= toDate)
                throw new ArgumentException("fromDate, toDate");

            DataTable resultTable;	// Resulting table
            int calendarId = -1;	// Calendar Id
            int userCalendarId = -1;	// UserCalendar Id
            List<TimeType> timeList;	// Main array. It contains information about
                                        // every minute allocation from the 00:00 of current date
                                        // to 24:00 of the toDate
            int freeTimeCounter;	// Counter of free time
            DateTime curCalDate;	// Current Date in Calendar timezone
            DateTime fromCalDate;	// FromDate in Calendar timezone
            DateTime toCalDate;		// ToDate in Calendar timezone
            int curMinute;			// Total minutes elapsed from 00:00 of current day
            int fromMinute;			// Total minutes elapsed from 00:00 of current day to fromDate (curDate < fromdate)
                                    // or total minutes elapsed from 00:00 of current day (fromdate > curDate)
            int toMinute;			// Total minutes elapsed from 00:00 of current day to toDate
            TimeSpan ts;			// Auxiliary variable
            CalendarHelper calendarHelper;	// Auxiliary class
            int intervalDuration;	// total minutes from 00:00 of current date to 24:00 of the toDate

            bool getTasks = objectTypes.Contains(ObjectTypes.Task);
            bool getTodo = objectTypes.Contains(ObjectTypes.ToDo);
            bool getIncidents = objectTypes.Contains(ObjectTypes.Issue);
            bool getDocuments = objectTypes.Contains(ObjectTypes.Document);
            DataTable objectTable;

            #region PreStep: initial actions
            // Resulting DataTable definition
            resultTable = new DataTable();
            resultTable.Locale = CultureInfo.InvariantCulture;

            resultTable.Columns.Add("UserId", typeof(int));
            resultTable.Columns.Add("Start", typeof(DateTime));
            resultTable.Columns.Add("Finish", typeof(DateTime));
            resultTable.Columns.Add("Type", typeof(TimeType));
            resultTable.Columns.Add("ObjectId", typeof(int));
            resultTable.Columns.Add("ObjectTypeId", typeof(int));
            resultTable.Columns.Add("ObjectName", typeof(string));
            resultTable.Columns.Add("Duration", typeof(int));
            resultTable.Columns.Add("PercentCompleted", typeof(int));
            resultTable.Columns.Add("PriorityId", typeof(int));
            resultTable.Columns.Add("StateId", typeof(int));
            resultTable.Columns.Add("FinishDate", typeof(DateTime));
            resultTable.Columns.Add("Highlight", typeof(bool));
            resultTable.Columns.Add("IsNewMessage", typeof(bool));	// for incidents
            resultTable.Columns.Add("IsOverdue", typeof(bool));
            resultTable.Columns.Add("AssignmentId", typeof(string));
            resultTable.Columns.Add("AssignmentName", typeof(string));
            resultTable.Columns.Add("ProjectTitle", typeof(string));

            DateTime fromUtcDate = Security.CurrentUser.CurrentTimeZone.ToUniversalTime(fromDate);
            DateTime toUtcDate = Security.CurrentUser.CurrentTimeZone.ToUniversalTime(toDate);
            DateTime curUtcDate = Security.CurrentUser.CurrentTimeZone.ToUniversalTime(curDate);

            // if we have past time
            if (fromDate < curDate)
            {
                if (curDate < toDate)
                {
                    if (getPastTime)
                    {
                        AddRow(resultTable, userId, fromDate, curDate, TimeType.Past);
                    }
                }
                else // all time is past
                {
                    if (getPastTime)
                    {
                        AddRow(resultTable, userId, fromDate, toDate, TimeType.Past);
                    }
                    return resultTable;
                }
            }

            // Get User Calendar info
            using (IDataReader reader = GetUserCalendarByUser(userId))
            {
                if (reader.Read())
                {
                    calendarId = (int)reader["CalendarId"];
                    userCalendarId = (int)reader["UserCalendarId"];
                }
            }

            // Check user calendar existance
            if (calendarId < 0)	// if calendar doesn't exist
            {
                if (getOffTime)
                {
                    if (strictBorder)
                    {
                        AddRow(resultTable,
                            userId,
                            (fromDate > curDate) ? fromDate : curDate,
                            toDate,
                            TimeType.Off);
                    }
                    else
                    {
                        AddRow(resultTable,
                            userId,
                            curDate,
                            toDate.AddDays(1),	// no border in graph
                            TimeType.Off);
                    }

                }

                return resultTable;
            }

            UserLight ul = UserLight.Load(userId);
            int timeZoneId = ul.TimeZoneId;

            // Calendar TimeZone
            McTimeZone timeZoneInfo = McTimeZone.Load(timeZoneId);
            if (timeZoneInfo == null)
                throw new ArgumentException("Unknown TimeZoneId = '" + timeZoneId.ToString() + "'.");
            TimeZone calendarTimeZone = new Mediachase.Ibn.Data.UserTimeZone("Calendar Time Zone",
                timeZoneInfo.Bias,
                timeZoneInfo.DaylightBias,
                timeZoneInfo.DaylightMonth,
                timeZoneInfo.DaylightDayOfWeek,
                timeZoneInfo.DaylightWeek,
                timeZoneInfo.DaylightHour,
                timeZoneInfo.StandardBias,
                timeZoneInfo.StandardMonth,
                timeZoneInfo.StandardDayOfWeek,
                timeZoneInfo.StandardWeek,
                timeZoneInfo.StandardHour);

            curCalDate = calendarTimeZone.ToLocalTime(curUtcDate);
            fromCalDate = calendarTimeZone.ToLocalTime(fromUtcDate);
            toCalDate = calendarTimeZone.ToLocalTime(toUtcDate);

            curMinute = curCalDate.Hour * 60 + curCalDate.Minute;
            if (fromDate < curDate)
            {
                fromMinute = curMinute;
            }
            else
            {
                ts = fromCalDate.Subtract(curCalDate.Date);
                fromMinute = (int)ts.TotalMinutes;
            }
            ts = toCalDate.Subtract(curCalDate.Date);
            toMinute = (int)ts.TotalMinutes;
            #endregion

            #region Step 1: Array creation
            // leveling to the start of date
            if (toCalDate == toCalDate.Date)
                ts = toCalDate.Date.Subtract(curCalDate.Date);
            else
                ts = toCalDate.Date.AddDays(1).Subtract(curCalDate.Date);
            intervalDuration = (int)ts.TotalMinutes;

            if (intervalDuration == 0)
            {
                return resultTable;
            }

            // Calendar Helper
            calendarHelper = new CalendarHelper(curCalDate.Date, calendarTimeZone);
            calendarHelper.FromCalDate = fromCalDate;
            calendarHelper.ToCalDate = toCalDate;
            calendarHelper.IntervalDuration = intervalDuration;
            calendarHelper.HighlightedItems = highlightedItems;

            // array creation
            timeList = new List<TimeType>(intervalDuration);
            #endregion

            #region Step 2: Default array allocation
            for (int i = 0; i < intervalDuration; i++)
            {
                if (i < curMinute)
                    timeList.Add(TimeType.Past);
                else
                    timeList.Add(TimeType.Off);
            }
            #endregion

            #region Step 3: Data from calendar
            ProcessCalendarInfo(timeList, curCalDate, toCalDate, calendarId, userCalendarId, toMinute);
            #endregion

            #region Step 4: Add information about time off to resulting table
            TimeType curType = TimeType.Past;
            int startMinute = 0;
            int endMinute;
            freeTimeCounter = 0;

            for (int i = 0; i < intervalDuration; i++)
            {
                if (timeList[i] == TimeType.Free)
                    freeTimeCounter++;

                if (timeList[i] != curType)	// if type is changed
                {
                    endMinute = i;
                    if (getOffTime && curType == TimeType.Off && startMinute < toMinute && endMinute > fromMinute)
                    {
                        if (strictBorder)
                        {
                            if (startMinute < fromMinute)
                                startMinute = fromMinute;
                            if (endMinute > toMinute)
                                endMinute = toMinute;
                        }
                        if (startMinute < endMinute)
                        {
                            AddRow(resultTable, userId, calendarHelper.GetUserDate(startMinute), calendarHelper.GetUserDate(endMinute), TimeType.Off);
                        }
                    }
                    startMinute = i;
                    curType = timeList[i];
                    continue;
                }
            }

            // Last interval
            if (getOffTime && curType == TimeType.Off && startMinute < toMinute)
            {
                endMinute = intervalDuration + 24*60;	// hide border
                if (strictBorder)
                {
                    if (startMinute < fromMinute)
                        startMinute = fromMinute;
                    if (endMinute > toMinute)
                        endMinute = toMinute;
                }
                if (startMinute < endMinute)
                {
                    AddRow(resultTable, userId, calendarHelper.GetUserDate(startMinute), calendarHelper.GetUserDate(endMinute), TimeType.Off);
                }
            }

            if (freeTimeCounter == 0)
                return resultTable;

            //----------------------
            #endregion

            #region Step 5: Process Events
            if (objectTypes.Contains(ObjectTypes.CalendarEntry))
            {
                int entryType = (int)CalendarView.CalendarFilter.Appointment | (int)CalendarView.CalendarFilter.Event | (int)CalendarView.CalendarFilter.Meeting;
                DataTable events = CalendarView.GetListCalendarEntriesByUser(curDate.Date, (toDate == toDate.Date) ? toDate : toDate.Date.AddDays(1), true, true, false, entryType, userId);

                // ID, Type, Title, Description, StartDate, FinishDate, ShowStartDate, ShowFinishDate, StateId
                foreach (DataRow row in events.Rows)
                {
                    if ((int)row["StateId"] == (int)ObjectStates.Completed || (int)row["StateId"] == (int)ObjectStates.Suspended)
                        continue;

                    DateTime objectStartDate = calendarHelper.GetCalendarDate((DateTime)row["StartDate"]);
                    DateTime objectFinishDate = calendarHelper.GetCalendarDate((DateTime)row["FinishDate"]);

                    if (objectStartDate >= ((toCalDate.Date == toCalDate) ? toCalDate : toCalDate.Date.AddDays(1)) || objectFinishDate <= curCalDate.Date)
                        continue;	// we don't need objects which have dates outside our period

                    // round dates to the diapason boundaries
                    if (objectStartDate < curCalDate.Date)
                        objectStartDate = curCalDate.Date;
                    if (objectFinishDate > ((toCalDate.Date == toCalDate) ? toCalDate : toCalDate.Date.AddDays(1)))
                        objectFinishDate = (toCalDate.Date == toCalDate) ? toCalDate : toCalDate.Date.AddDays(1);

                    // Get number of minutes between objectStartDate/objectFinishDate and curCalDate.Date
                    ts = objectStartDate.Subtract(curCalDate.Date);
                    startMinute = (int)ts.TotalMinutes;
                    ts = objectFinishDate.Subtract(curCalDate.Date);
                    endMinute = (int)ts.TotalMinutes;

                    // feel the array
                    for (int i = startMinute; i < endMinute; i++)
                    {
                        if (timeList[i] != TimeType.Past) // we shouldn't change the past time
                            timeList[i] = TimeType.CalendarEntry;
                    }

                    // Add info to result table
                    if (startMinute < toMinute && endMinute > fromMinute)
                    {
                        int duration = endMinute - startMinute;
                        if (strictBorder)
                        {
                            if (startMinute < fromMinute)
                                startMinute = fromMinute;
                            if (endMinute > toMinute)
                                endMinute = toMinute;
                        }
                        else if (startMinute < curMinute)
                        {
                            startMinute = curMinute;
                        }

                        if (startMinute < endMinute)
                        {
                            AddRow(resultTable, highlightedItems, userId, calendarHelper.GetUserDate(startMinute), calendarHelper.GetUserDate(endMinute), TimeType.CalendarEntry, (int)row["ID"], (int)ObjectTypes.CalendarEntry, row["Title"].ToString(), duration, 0, (int)row["PriorityId"], (int)row["StateId"], (DateTime)row["FinishDate"], null, null, String.Empty, false, false, false);
                        }
                    }
                }

                freeTimeCounter = 0;
                for (int i = 0; i < intervalDuration; i++)
                {
                    if (timeList[i] == TimeType.Free)
                        freeTimeCounter++;
                }
                if (freeTimeCounter == 0)
                    return resultTable;
            }
            #endregion

            #region Step 6: Process WorkPinnedUp
            objectTable = DBCalendar.GetListStickedObjectsUtc(userId, getTasks, getTodo, getIncidents, getDocuments);

            ProcessObjectTable(timeList, curCalDate, userId, objectTable, resultTable, freeTimeCounter, fromMinute, toMinute, calendarHelper, mergeBreaks, strictBorder, true);
            #endregion

            #region Step 7: Process Tasks, Todo, Incidents
            objectTable = DBCalendar.GetListObjectsInPriorityOrderUtc(userId, curUtcDate, toUtcDate, getTasks, getTodo, getIncidents, getDocuments);

            ProcessObjectTable(timeList, curCalDate, userId, objectTable, resultTable, freeTimeCounter, fromMinute, toMinute, calendarHelper, mergeBreaks, strictBorder, false);
            #endregion

            return resultTable;
        }
Exemplo n.º 33
0
        private static int CalculateEndMinute(int endMinute, int toMinute, CalendarHelper calendarHelper, List<TimeType> timeList, int duration, bool mergeBreaks, bool strictBorder)
        {
            if (strictBorder && endMinute > toMinute)
                endMinute = toMinute;

            // if we are going to merge breaks we should extend the right edge in the case if
            // interval is finished, but duration is still not 0
            if (duration > 0 && mergeBreaks)
            {
                // at the right we can have event or another work, so we should check this
                bool anotherWorkFound = false;
                for (int j = endMinute; j < calendarHelper.IntervalDuration; j++)
                {
                    if (timeList[j] != TimeType.Off)
                    {
                        endMinute = j;
                        anotherWorkFound = true;
                        break;
                    }
                }

                if (!anotherWorkFound)
                {
                    if (strictBorder)
                    {
                        endMinute = calendarHelper.IntervalDuration;
                    }
                    else
                    {
                        // it's not a real endMinute, because we do not have information
                        // about time off of the next day. Just imitation for drawing purpose.
                        endMinute = calendarHelper.IntervalDuration + duration;
                    }
                }
            }
            return endMinute;
        }
Exemplo n.º 34
0
        private static int CalculateStartMinute(int startMinute, int realStartMinute, int fromMinute, CalendarHelper calendarHelper, List<TimeType> timeList, ref bool extendToLeft, bool mergeBreaks, bool strictBorder)
        {
            int savedStart = startMinute;
            if (strictBorder && startMinute < fromMinute)
                startMinute = fromMinute;

            if (extendToLeft)
            {
                // at the left we can have events or another work, so we should check this
                bool anotherWorkFound = false;
                bool freeTimeFound = false;
                for (int j = startMinute - 1; j >= 0; j--)
                {
                    if (timeList[j] != TimeType.Off)
                    {
                        if (timeList[j] == TimeType.Free)	// free work time found. We can't extend to left
                        {
                            freeTimeFound = true;
                            break;
                        }

                        if (timeList[j] != timeList[savedStart])	// types are different
                            extendToLeft = false;
                        else
                            startMinute = j + 1;

                        anotherWorkFound = true;
                        break;
                    }
                }

                if (!anotherWorkFound)
                {
                    extendToLeft = false;

                    if (strictBorder)
                        startMinute = fromMinute;
                    else if (!freeTimeFound)
                        startMinute = (realStartMinute < 0) ? 0 : realStartMinute;
                }
            }

            return startMinute;
        }
Exemplo n.º 35
0
        private static void ProcessObjectTable(
			List<TimeType> timeList, 
			DateTime curCalDate, 
			int userId, 
			DataTable objectTable, 
			DataTable resultTable, 
			int freeTimeCounter,
			int fromMinute,
			int toMinute,
			CalendarHelper calendarHelper,
			bool mergeBreaks,
			bool strictBorder,
			bool sticked)
        {
            // we should extend to left the first work item
            bool extendToLeft = (mergeBreaks && curCalDate.Date < calendarHelper.FromCalDate.Date) ? true : false;

            foreach (DataRow row in objectTable.Rows)
            {
                // ObjectId, ObjectTypeId, ObjectName, PriorityId, StartDate (UTC), FinishDate (UTC),
                // CreationDate (UTC), TaskTime, PercentCompleted, TaskTimeLeft, FinishDateLeft (UTC)

                int duration = (int)row["TaskTimeLeft"];
                int originalDuration = duration;
                int objectId = (int)row["ObjectId"];
                int objectTypeId = (int)row["ObjectTypeId"];
                int taskTimeLeft = (int)row["TaskTimeLeft"];
                string objectName = row["ObjectName"].ToString();
                int percentCompleted = (int)row["PercentCompleted"];
                int priorityId = (int)row["PriorityId"];
                int stateId = (int)row["StateId"];
                bool isNewMessage = (bool)row["IsNewMessage"];
                bool isOverdue = (bool)row["IsOverdue"];
                DateTime finishDate = Security.CurrentUser.CurrentTimeZone.ToLocalTime((DateTime)row["FinishDate"]);
                string assignmentId = row["AssignmentId"].ToString();
                string assignmentName = row["AssignmentName"].ToString();
                string projectTitle = string.Empty;
                if (row["ProjectTitle"] != DBNull.Value)
                    projectTitle = row["ProjectTitle"].ToString();

                int realStartMinute = -1;	// the position of the first minute allocation

                TimeType curType;
                if (!sticked)
                {
                    switch (priorityId)
                    {
                        case (int)Priority.Urgent:
                            curType = TimeType.WorkUrgent;
                            break;
                        case (int)Priority.VeryHigh:
                            curType = TimeType.WorkVeryHigh;
                            break;
                        case (int)Priority.High:
                            curType = TimeType.WorkHigh;
                            break;
                        case (int)Priority.Low:
                            curType = TimeType.WorkLow;
                            break;
                        default:
                            curType = TimeType.WorkNormal;
                            break;
                    }
                }
                else
                {
                    curType = TimeType.WorkPinnedUp;
                }

                DateTime objectStartDate = calendarHelper.GetCalendarDateFromUtc((DateTime)row["StartDate"]);
                if (objectStartDate < curCalDate.Date)
                    objectStartDate = curCalDate.Date;
                TimeSpan ts = objectStartDate.Subtract(curCalDate.Date);
                int minStart = (int)ts.TotalMinutes;

                bool continueFlag = false;

                int startMinute = -1;
                int endMinute;
                for (int i = minStart; i < calendarHelper.IntervalDuration; i++)
                {
                    // we should find free time
                    if (timeList[i] == TimeType.Free)
                    {
                        if (realStartMinute == 0)	// total start
                            realStartMinute = i;

                        if (startMinute < 0)	// start after some breaks
                            startMinute = i;

                        if (originalDuration <= 0)	// sticked objects can have 0 duration
                        {
                            AddRow(resultTable, calendarHelper.HighlightedItems, userId, calendarHelper.GetUserDate(startMinute), calendarHelper.GetUserDate(startMinute), curType, objectId, objectTypeId, objectName, taskTimeLeft, percentCompleted, priorityId, stateId, finishDate, assignmentId, assignmentName, projectTitle, mergeBreaks, isNewMessage, isOverdue);
                            continueFlag = true;
                            break;
                        }

                        timeList[i] = curType;
                        duration--;
                        freeTimeCounter--;

                        if (duration == 0 || freeTimeCounter == 0)
                        {
                            endMinute = i + 1;

                            if (startMinute < toMinute && endMinute > fromMinute)
                            {
                                startMinute = CalculateStartMinute(startMinute, realStartMinute, fromMinute, calendarHelper, timeList, ref extendToLeft, mergeBreaks, strictBorder);
                                endMinute = CalculateEndMinute(endMinute, toMinute, calendarHelper, timeList, duration, mergeBreaks, strictBorder);

                                if (startMinute < endMinute)
                                {
                                    AddRow(resultTable, calendarHelper.HighlightedItems, userId, calendarHelper.GetUserDate(startMinute), calendarHelper.GetUserDate(endMinute), curType, objectId, objectTypeId, objectName, taskTimeLeft, percentCompleted, priorityId, stateId, finishDate, assignmentId, assignmentName, projectTitle, mergeBreaks, isNewMessage, isOverdue);
                                }
                            }
                            startMinute = -1;
                            break;
                        }
                    }
                    else // free interval break
                    {
                        if (startMinute >= 0)
                        {
                            endMinute = i;

                            if (startMinute < toMinute && endMinute > fromMinute)
                            {
                                startMinute = CalculateStartMinute(startMinute, realStartMinute, fromMinute, calendarHelper, timeList, ref extendToLeft, mergeBreaks, strictBorder);
                                endMinute = CalculateEndMinute(endMinute, toMinute, calendarHelper, timeList, duration, mergeBreaks, strictBorder);

                                if (startMinute < endMinute)
                                {
                                    AddRow(resultTable, calendarHelper.HighlightedItems, userId, calendarHelper.GetUserDate(startMinute), calendarHelper.GetUserDate(endMinute), curType, objectId, objectTypeId, objectName, taskTimeLeft, percentCompleted, priorityId, stateId, finishDate, assignmentId, assignmentName, projectTitle, mergeBreaks, isNewMessage, isOverdue);
                                }
                            }
                            startMinute = -1;
                        }
                    }
                }

                if (continueFlag)
                    continue;

                // last interval
                if (startMinute >= 0)
                {
                    endMinute = calendarHelper.IntervalDuration;

                    if (startMinute < toMinute && endMinute > fromMinute)
                    {
                        startMinute = CalculateStartMinute(startMinute, realStartMinute, fromMinute, calendarHelper, timeList, ref extendToLeft, mergeBreaks, strictBorder);
                        endMinute = CalculateEndMinute(endMinute, toMinute, calendarHelper, timeList, duration, mergeBreaks, strictBorder);
                        if (startMinute < endMinute)
                        {
                            AddRow(resultTable, calendarHelper.HighlightedItems, userId, calendarHelper.GetUserDate(startMinute), calendarHelper.GetUserDate(endMinute), curType, objectId, objectTypeId, objectName, taskTimeLeft, percentCompleted, priorityId, stateId, finishDate, assignmentId, assignmentName, projectTitle, mergeBreaks, isNewMessage, isOverdue);
                        }
                    }
                }

                if (freeTimeCounter == 0)
                {
                    break;
                }
            }
        }