Пример #1
0
 public TimeReportUpdateStrategy(
     IEnumerable <TimeReport> dateTimeReports,
     TimeReport newTimeReport)
 {
     this.dateTimeReports = dateTimeReports.ToList();
     this.newTimeReport   = newTimeReport;
 }
Пример #2
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,TimeReportName,Description,DateTimeCreated,DateTimeFrom,DateTimeTo,PersonId,PersonId1")] TimeReport timeReport)
        {
            if (id != timeReport.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(timeReport);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TimeReportExists(timeReport.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(IndexSearch)));
            }
            ViewData["PersonId"]  = new SelectList(_context.Person, "Id", "FullName", timeReport.PersonId);
            ViewData["PersonId1"] = new SelectList(_context.Person, "Id", "FullName", timeReport.PersonId1);
            return(View(timeReport));
        }
Пример #3
0
        public async Task Update(DayTimeReportViewModel viewModel)
        {
            TimeReport newTimeReport = viewModel.ToTimeReport(await GetUserId());
            TimeReportUpdateStrategy timeReportUpdateStrategy = await GetTimeReportUpdateStrategy(newTimeReport);

            timeReportUpdateStrategy.Update();
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,SiteId,IncidentNumber,ShiftStarted,ShiftEnded,WorkedHours,FeeHour,TotalFee,Notes")] TimeReport timeReport)
        {
            if (id != timeReport.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(timeReport);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TimeReportExists(timeReport.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["SiteId"] = new SelectList(_context.Site, "Id", "SiteName", timeReport.SiteId);
            return(View(timeReport));
        }
Пример #5
0
        public TimeReport GetTimeReport(string filePath)
        {
            var        table            = GetTimeReportTable(GetDataTableCollection(filePath, 11));
            TimeReport timeReportResult = new TimeReport();

            ///Костыль тк мы не знаем
            if (!table.Columns.Contains("#"))
            {
                table = GetTimeReportTable(GetDataTableCollection(filePath, 14));
            }

            timeReportResult.TimeReportRows = new List <TimeReportRow>();
            timeReportResult.SetName(filePath);

            foreach (DataRow row in table.Rows)
            {
                TimeReportRow timeReportRow = new TimeReportRow();

                foreach (DataColumn column in table.Columns)
                {
                    PutValueByTheCaptionTimeReport(row, column, timeReportRow);
                }

                timeReportResult.TimeReportRows.Add(timeReportRow);
            }

            /// удаляем последнюю строку с Total и все которые не заполнены в полях Task и Description
            RemoveEmptyAndTotalRows(timeReportResult);

            return(timeReportResult);
        }
Пример #6
0
        private string ProcessReplacements(string content, TimeReport timeReport)
        {
            var properties = timeReport.GetType().GetProperties();

            foreach (var property in properties)
            {
                var itemKey = $"@Model.{property.Name}";
                if (property.PropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
                {
                    var startPosition = content.IndexOf(itemKey, StringComparison.Ordinal);
                    if (startPosition >= 0)
                    {
                        var blockStart    = content.IndexOf('{', startPosition);
                        var blockEnd      = content.IndexOf('}', blockStart);
                        var template      = content.Substring(blockStart + 1, blockEnd - blockStart - 1);
                        var stringBuilder = new StringBuilder();

                        var values = property.GetValue(timeReport) as IEnumerable;
                        foreach (var row in values)
                        {
                            var rowProperties = row.GetType().GetProperties();
                            var rowContent    = "" + template;
                            foreach (var rowProp in rowProperties)
                            {
                                var rowItemKey = $"@row.{rowProp.Name}";
                                var propValue  = rowProp.GetValue(row);
                                rowContent = rowContent.Replace(rowItemKey, GetFormatterPropertyValue(rowProp, propValue));

                                if (rowProp.Name.Contains("offset", StringComparison.OrdinalIgnoreCase))
                                {
                                    var offset = (double)propValue;
                                    var color  = "#ffffff";
                                    if (offset > .25 && offset <= .75)
                                    {
                                        color = "#ffffe6";
                                    }
                                    else if (offset > .75)
                                    {
                                        color = "#ffcccc";
                                    }
                                    rowContent = rowContent.Replace("@row.Color", color);
                                }
                            }
                            stringBuilder.AppendLine(rowContent);
                        }

                        var newRowContent = stringBuilder.ToString();
                        content = content.Remove(startPosition, blockEnd - startPosition + 1);
                        content = content.Insert(startPosition, newRowContent);
                    }
                }
                else
                {
                    content = content.Replace(itemKey, GetFormatterPropertyValue(property, property.GetValue(timeReport)));
                }
            }

            return(content);
        }
Пример #7
0
        public IActionResult AddTimeReport(TimeReport time, [FromBody] TimeReport Time)
        {
            time.Id = Guid.NewGuid().ToString();

            _context.TimeReport.Add(Time);
            _context.SaveChanges();
            return(Ok("ok"));
        }
Пример #8
0
        public async Task <int> AddTimeReportFromIOT(IOTViewModel viewModel)
        {
            TimeReport timeReport = viewModel.ToTimeReport(viewModel.UserId);
            CreateTimeReportUpdateStrategy timeReportUpdateStrategy = (CreateTimeReportUpdateStrategy)(await GetTimeReportUpdateStrategy(timeReport));

            timeReportUpdateStrategy.Update();
            return(timeReportUpdateStrategy.NewTimeReportId);
        }
Пример #9
0
        public async Task SendDetailedTimeReport(Subscriber subscriber, TimeReport timeReport, double offsetThreshold, bool includeSummary = true)
        {
            await _bot.SendTextMessageAsync(subscriber.TelegramId,
                                            $"Your stats since {timeReport.StartDate.Date:yyyy-MM-dd}");

            const int maxTitleLength = 50;

            //Support threshold values from decimal or percentage
            if (offsetThreshold > 1)
            {
                offsetThreshold /= 100;
            }

            var baseUrl = new Url(_devOpsAddress).AppendPathSegment("/_workitems/edit/");
            var builder = new StringBuilder();

            foreach (var item in timeReport.WorkItemTimes.OrderBy(x => x.Date))
            {
                var title = item.Title;
                if (title.Length > maxTitleLength)
                {
                    title = title.Substring(0, maxTitleLength);
                }
                title = title.PadRight(maxTitleLength);

                var offset = Math.Abs(item.Active - item.Completed) / item.Active;

                if (offset > offsetThreshold)
                {
                    var message =
                        $"{item.Date:dd-MM} <a href=\"{baseUrl + item.Id}\">{item.Id}</a> - {title} C:{item.Completed:F2} A:{item.Active:F2} E:{item.Estimated:F2} Off:{offset:P}";

                    if (builder.Length + message.Length >= maxMessageLength)
                    {
                        await _bot.SendTextMessageAsync(subscriber.TelegramId, $"{builder}", ParseMode.Html);

                        builder = new StringBuilder();
                    }

                    builder.AppendLine($"{message}");
                }
            }

            if (builder.Length > 0)
            {
                await _bot.SendTextMessageAsync(subscriber.TelegramId, $"{builder}", ParseMode.Html);
            }

            if (includeSummary)
            {
                await _bot.SendTextMessageAsync(subscriber.TelegramId,
                                                $"Estimated Hours: {timeReport.TotalEstimated:0.##}{Environment.NewLine}" +
                                                $"Completed Hours: {timeReport.TotalCompleted:0.##}{Environment.NewLine}" +
                                                $"Active Hours: {timeReport.TotalActive:0.##}{Environment.NewLine}" +
                                                $"Expected Hours: {timeReport.Expected:0.##}", ParseMode.Markdown);
            }
        }
Пример #10
0
 public ChangedActivityUpdateTimeReportStrategy(
     IUnitOfWork unitOfWork,
     IEnumerable <TimeReport> dateTimeReports,
     TimeReport newTimeReport,
     TimeReport oldActivityTimeReport)
     : base(dateTimeReports, newTimeReport)
 {
     this.unitOfWork            = unitOfWork;
     this.oldActivityTimeReport = oldActivityTimeReport;
 }
 public CreateTimeReportUpdateStrategy(
     ITimeReportRepository timeReportRepository,
     IEnumerable <TimeReport> dateTimeReports,
     TimeReport newTimeReport)
     : base(
         timeReportRepository,
         dateTimeReports,
         newTimeReport)
 {
 }
Пример #12
0
        public void StartRide(DateTime startRideTime)
        {
            if (Status != TaxiOrderStatus.WaitingCarArrival)
            {
                throw new InvalidOperationException($"Недопустимая операция для статуса {Status}");
            }

            Status = TaxiOrderStatus.InProgress;
            TimeReport.Report(startRideTime);
        }
Пример #13
0
        public void FinishRide(DateTime finishRideTime)
        {
            if (Status != TaxiOrderStatus.InProgress)
            {
                throw new InvalidOperationException($"Недопустимая операция для статуса {Status}");
            }

            Status = TaxiOrderStatus.Finished;
            TimeReport.Report(finishRideTime);
        }
 public NewActivityUpdateTimeReportStrategy(
     ITimeReportRepository timeReportRepository,
     IEnumerable <TimeReport> dateTimeReports,
     TimeReport newTimeReport)
     : base(
         dateTimeReports,
         newTimeReport)
 {
     this.timeReportRepository = timeReportRepository;
 }
Пример #15
0
        public async Task <int> AddTimeReport(DayTimeReportViewModel viewModel)
        {
            TimeReport timeReport = viewModel.ToTimeReport(await GetUserId());

            timeReport.Id = GlobalConstants.NullId;
            CreateTimeReportUpdateStrategy timeReportUpdateStrategy = (CreateTimeReportUpdateStrategy)(await GetTimeReportUpdateStrategy(timeReport));

            timeReportUpdateStrategy.Update();
            return(timeReportUpdateStrategy.NewTimeReportId);
        }
Пример #16
0
        private async Task <TimeReport> GetTimeReport(Subscriber subscriber, string url, string token, DateTime startDate, ILogger log)
        {
            var orgUrl = new Uri(url);
            var personalAccessToken = token;

            var connection   = new VssConnection(orgUrl, new VssBasicCredential(string.Empty, personalAccessToken));
            var workItemsIds = await _backlogAccessor.GetWorkItemsForPeriod(connection, subscriber.Email, startDate, log);

            var workItems = await _backlogAccessor.GetWorkItemsById(connection, workItemsIds);

            var report = new TimeReport();

            foreach (var workItem in workItems)
            {
                if (workItem.Id != null)
                {
                    var workItemId = workItem.Id.Value;
                    var activeTime = await GetWorkItemActiveTime(connection, workItemId);

                    if (!workItem.Fields.TryGetValue <double>("Microsoft.VSTS.Scheduling.OriginalEstimate", out var estimated))
                    {
                        estimated = 0;
                    }

                    if (!workItem.Fields.TryGetValue <double>("Microsoft.VSTS.Scheduling.CompletedWork", out var completed))
                    {
                        completed = 0;
                    }

                    var workItemDate = workItem.Fields.Keys.Contains("Microsoft.VSTS.Common.ClosedDate")
                        ? (DateTime)workItem.Fields["Microsoft.VSTS.Common.ClosedDate"]
                        : (DateTime)workItem.Fields["System.ChangedDate"];


                    var item = new WorkItemTime
                    {
                        Id        = workItem.Id.GetValueOrDefault(),
                        Date      = workItemDate,
                        Title     = workItem.Fields["System.Title"].ToString(),
                        Active    = activeTime.TotalHours,
                        Estimated = estimated,
                        Completed = completed
                    };
                    report.AddWorkItem(item);

                    log.LogInformation($"{item.Title} {item.Estimated:F2} {item.Completed:F2} {item.Active:F2}");
                }
            }

            report.StartDate = startDate;
            report.EndDate   = DateTime.UtcNow.Date;
            report.Expected  = GetBusinessDays(startDate, DateTime.UtcNow.Date) * (subscriber.HoursPerDay == 0 ? HoursPerDay : subscriber.HoursPerDay);
            report.HoursOff  = GetHoursOff(subscriber, startDate);
            return(report);
        }
Пример #17
0
        public static DayTimeReportViewModel ToViewTimeReport(this TimeReport timeReport)
        {
            string stringDate = TimeConverter.ToJSONString(timeReport.Date);

            return(new DayTimeReportViewModel(
                       timeReport.Id,
                       timeReport.Duration,
                       timeReport.ActivityId,
                       timeReport.Activity,
                       stringDate));
        }
Пример #18
0
 public string GetShortOrderInfo()
 {
     return(string.Join(" ",
                        "OrderId: " + Id,
                        "Status: " + Status,
                        "ClientName: " + FormatName(ClientName),
                        "Driver: " + FormatName(Driver?.Name),
                        "From: " + FormatAddress(Start),
                        "To: " + FormatAddress(Destination),
                        "LastProgressTime: " + TimeReport.GetLastProgressTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)));
 }
        public async Task <IActionResult> Create([Bind("Id,SiteId,IncidentNumber,ShiftStarted,ShiftEnded,WorkedHours,FeeHour,TotalFee,Notes")] TimeReport timeReport)
        {
            if (ModelState.IsValid)
            {
                _context.Add(timeReport);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["SiteId"] = new SelectList(_context.Site, "Id", "SiteName", timeReport.SiteId);
            return(View(timeReport));
        }
 public CreateExistingActivityUpdateTimeReportStrtegy(
     ITimeReportRepository timeReportRepository,
     IEnumerable <TimeReport> dateTimeReports,
     TimeReport newTimeReport,
     TimeReport oldActivityTimeReport)
     : base(
         timeReportRepository,
         dateTimeReports,
         newTimeReport)
 {
     this.oldActivityTimeReport = oldActivityTimeReport;
 }
Пример #21
0
        public async Task <IActionResult> Create([Bind("Id,TimeReportName,Description,DateTimeCreated,DateTimeFrom,DateTimeTo,ApplicationUserId,PersonId")] TimeReport timeReport)
        {
            if (ModelState.IsValid)
            {
                _context.Add(timeReport);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(IndexSearch)));
            }
            ViewData["ApplicationUserId"] = new SelectList(_context.Users, "Id", "Email", timeReport.ApplicationUserId);
            ViewData["PersonId"]          = new SelectList(_context.Person, "Id", "FullName", timeReport.PersonId);
            return(View(timeReport));
        }
        public void Update(TimeReport entity)
        {
            string query = $"UPDATE TimeReports SET Date=@date, Duration=@duration, ActivityId=@activityId WHERE Id=@id";

            var dbArgs = new DynamicParameters();

            dbArgs.Add("id", entity.Id);
            dbArgs.Add("date", entity.Date);
            dbArgs.Add("duration", entity.Duration);
            dbArgs.Add("activityId", entity.ActivityId);

            queryExecuter.Execute(query, dbArgs);
        }
Пример #23
0
        public string GenerateReport(TimeReport timeReport)
        {
            var assembly     = Assembly.GetExecutingAssembly();
            var resourceName = "UnTaskAlert.Reports.DetailReport.cshtml";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                {
                    var content = reader.ReadToEnd();

                    return(ProcessReplacements(content, timeReport));
                }
            ;
        }
Пример #24
0
        public TimeReport Create(TimeReport timeReport, HttpContext accesor)
        {
            var validation = this.validateToken(accesor);

            if (!validation)
            {
                return(null);
            }


            timeReport.date = DateTime.Now;
            _context.TimeReports.Add(timeReport);
            _context.SaveChanges();
            return(timeReport);
        }
Пример #25
0
        private async Task SaveTimeReport(TimeReport report)
        {
            try
            {
                string connectionString            = ConfigurationManager.AppSettings["TableStorage"];
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
                CloudTableClient    tableClient    = storageAccount.CreateCloudTableClient();
                CloudTable          table          = tableClient.GetTableReference("TimeReport");
                table.CreateIfNotExists();

                await table.ExecuteAsync(TableOperation.Insert(report));
            }
            catch (Exception ex)
            { }
        }
Пример #26
0
        public void Cancel(DateTime cancelTime)
        {
            switch (Status)
            {
            case TaxiOrderStatus.InProgress:
            case TaxiOrderStatus.Finished:
                throw new InvalidOperationException($"Недопустимая операция для статуса {Status}");

            case TaxiOrderStatus.Canceled:
                throw new InvalidOperationException("Заказ уже отменен");
            }

            Status = TaxiOrderStatus.Canceled;
            TimeReport.Report(cancelTime);
        }
Пример #27
0
        protected void Button2_Click(object sencer, EventArgs e)
        {
            try
            {
                webtimeclockEntities db = new webtimeclockEntities();

                String userID = Session["UserID"].ToString().Split(' ')[0];
                var    user   = (from use in db.users
                                 where use.UserID == userID
                                 select use).Single();

                TimeReport s = new TimeReport();

                if (!radio_month.Checked && !radio_week.Checked)
                {
                    //say some stuff about needing to check it
                }
                else if (radio_month.Checked)
                {
                    DateTime time       = DateTime.Now;
                    DateTime monthStart = new DateTime(time.Year, time.Month, 1);
                    DateTime monthEnd   = new DateTime(time.Year, time.Month, DateTime.DaysInMonth(time.Year, time.Month));

                    //incorporates all the functions of report generation
                    s = new TimeReport(user.UserID, user.FirstName, user.LastName,
                                       TimeSpanString(monthStart, monthEnd), GenerateHoursTable(monthStart, monthEnd, userID));

                    DisplayReport(s);
                }
                else if (radio_week.Checked)
                {
                    DateTime time   = DateTime.Today;
                    int      offset = time.DayOfWeek - DayOfWeek.Sunday;

                    //last sunday
                    DateTime start = time.AddDays(-offset);
                    //this saturday
                    DateTime end = start.AddDays(6);

                    s = new TimeReport(user.UserID, user.FirstName, user.LastName,
                                       TimeSpanString(start, end), GenerateHoursTable(start, end, userID));

                    DisplayReport(s);
                }
            } catch (Exception ex)
            {
            }
        }
Пример #28
0
        public async Task SendTimeReport(Subscriber subscriber, TimeReport timeReport)
        {
            var content       = new StpdReportGenerator(_devOpsAddress).GenerateReport(timeReport);
            var byteArray     = Encoding.UTF8.GetBytes(content);
            var contentStream = new MemoryStream(byteArray);
            var file          = new InputOnlineFile(contentStream)
            {
                FileName = "report.html"
            };

            await _bot.SendDocumentAsync(subscriber.TelegramId, file, caption : "Your report.");

            await _bot.SendTextMessageAsync(subscriber.TelegramId,
                                            $"Your stats since {timeReport.StartDate.Date:yyyy-MM-dd}{Environment.NewLine}{Environment.NewLine}" +
                                            $"Estimated Hours: {timeReport.TotalEstimated:0.##}{Environment.NewLine}" +
                                            $"Completed Hours: {timeReport.TotalCompleted:0.##}{Environment.NewLine}" +
                                            $"Active Hours: {timeReport.TotalActive:0.##}{Environment.NewLine}" +
                                            $"Expected Hours: {timeReport.Expected - timeReport.HoursOff:0.##}{Environment.NewLine}" +
                                            $"Hours off: {timeReport.HoursOff}");
        }
Пример #29
0
        public void AssignDriver(int driverId, DateTime driverAssignmentTime)
        {
            if (Status != TaxiOrderStatus.WaitingForDriver)
            {
                throw new InvalidOperationException($"Недопустимая операция для статуса {Status}");
            }

            if (driverId == 15)
            {
                Driver = new Driver(driverId, new PersonName("Drive", "Driverson"));
                Car    = new TaxiCar("Lada sedan", "Baklazhan", "A123BT 66");
            }
            else
            {
                throw new Exception("Unknown driver id " + driverId);
            }

            Status = TaxiOrderStatus.WaitingCarArrival;
            TimeReport.Report(driverAssignmentTime);
        }
        public int Add(TimeReport entity)
        {
            try
            {
                string query = $"INSERT INTO TimeReports(Date,Duration,ActivityId, UserId) " +
                               $"VALUES (@date, @duration, @activity, @userId); SELECT CAST(SCOPE_IDENTITY() AS INT)";

                var dbArgs = new DynamicParameters();
                dbArgs.Add("date", entity.Date);
                dbArgs.Add("duration", entity.Duration);
                dbArgs.Add("activity", entity.ActivityId);
                dbArgs.Add("userId", entity.UserId);

                int newtimeReportId = queryExecuter.Connection.Query <int>(query, dbArgs).Single();
                return(newtimeReportId);
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }