Exemplo n.º 1
0
        // POST: odata/Jobs
        public IActionResult Post([FromBody] Job job)
        {
            var currentUser = CurrentUser();

            // Ensure user is an administrator.
            if (!currentUser.CanCreateProjects)
            {
                return(Forbid());
            }

            var customer = _context.Customers
                           .Where(c => c.OrganizationId == currentUser.OrganizationId)
                           .Where(c => c.Id == job.CustomerId)
                           .FirstOrDefault();

            if (customer == null)
            {
                return(BadRequest());
            }

            // Auto-generated.
            job.CreatedAt  = DateTime.UtcNow;
            job.CustomerId = customer.Id;

            // Prepare to create tasks automatically.
            var taskTemplateId = job.TaskTemplateId;

            // Validate the model.
            ModelState.ClearValidationState(nameof(job));
            if (!TryValidateModel(job, nameof(job)))
            {
                var errors = new List <string>();

                foreach (var modelStateKey in ModelState.Keys)
                {
                    var value = ModelState[modelStateKey];

                    if (value == null)
                    {
                        continue;
                    }

                    foreach (var error in value.Errors)
                    {
                        errors.Add(error.ErrorMessage);
                    }
                }

                var message = string.Join(", ", errors);
                return(BadRequest(message));
            }

            _context.Jobs.Add(job);

            _context.SaveChanges();

            if (taskTemplateId.HasValue)
            {
                var taskTemplate = _context.TaskTemplates
                                   .Where(c => c.OrganizationId == currentUser.OrganizationId)
                                   .Where(c => c.Id == taskTemplateId.Value)
                                   .FirstOrDefault();

                if (taskTemplate != null)
                {
                    var service = new SecurityService();

                    var items = JsonSerializer.Deserialize <TemplateItem[]>(taskTemplate.Template);

                    // Start ordering.
                    var order = 10;

                    foreach (var item in items)
                    {
                        // Get the next task number.
                        var maxSql = @"
                            SELECT
	                            MAX(CAST([T].[Number] AS INT))
                            FROM
                                [Tasks] AS [T]
                            JOIN
	                            [Jobs] AS [J] ON [J].[Id] = [T].[JobId]
                            JOIN
	                            [Customers] AS [C] ON [C].[Id] = [J].[CustomerId]
                            WHERE
	                            [C].[OrganizationId] = @OrganizationId;"    ;
                        var max    = _context.Database.GetDbConnection().QuerySingle <int?>(maxSql, new { OrganizationId = currentUser.OrganizationId });

                        // Either start at the default or increment.
                        var number = !max.HasValue ? "1000" : (max.Value + 1).ToString(); //service.NxtKeyCode(max);

                        // Find the base payroll rate for the new task.
                        var basePayrollRate = _context.Rates
                                              .Where(r => r.OrganizationId == currentUser.OrganizationId)
                                              .Where(r => r.Type == "Payroll")
                                              .Where(r => r.Name == item.BasePayrollRate)
                                              .Where(r => r.IsDeleted == false)
                                              .FirstOrDefault();

                        // Find the base service rate for the new task.
                        var baseServiceRate = _context.Rates
                                              .Where(r => r.OrganizationId == currentUser.OrganizationId)
                                              .Where(r => r.Type == "Service")
                                              .Where(r => r.Name == item.BaseServiceRate)
                                              .Where(r => r.IsDeleted == false)
                                              .FirstOrDefault();

                        // Populate the new task.
                        var task = new Brizbee.Core.Models.Task()
                        {
                            Name              = item.Name,
                            CreatedAt         = DateTime.UtcNow,
                            JobId             = job.Id,
                            Group             = item.Group,
                            Order             = order,
                            Number            = number,
                            BasePayrollRateId = basePayrollRate == null ? (int?)null : basePayrollRate.Id,
                            BaseServiceRateId = baseServiceRate == null ? (int?)null : baseServiceRate.Id
                        };

                        _context.Tasks.Add(task);
                        _context.SaveChanges();

                        // Increment the order.
                        order = order + 10;
                    }
                }
            }

            // Attempt to send notifications.
            try
            {
                var mobileNumbers = _context.Users
                                    .Where(u => u.IsDeleted == false)
                                    .Where(u => u.OrganizationId == currentUser.OrganizationId)
                                    .Where(u => !string.IsNullOrEmpty(u.NotificationMobileNumbers))
                                    .Select(u => u.NotificationMobileNumbers)
                                    .ToArray();

                var accountSid       = _configuration["TwilioNotificationsAccountSid"];
                var authToken        = _configuration["TwilioNotificationsAccountToken"];
                var fromMobileNumber = _configuration["TwilioNotificationsMobileNumber"];

                TwilioClient.Init(accountSid, authToken);

                foreach (var mobileNumber in mobileNumbers)
                {
                    var message = MessageResource.Create(
                        body: $"Project Added {job.Number} - {job.Name} for Customer {job.Customer.Name}",
                        from: new Twilio.Types.PhoneNumber(fromMobileNumber),
                        to: new Twilio.Types.PhoneNumber(mobileNumber)
                        );
                }
            }
            catch (Exception ex)
            {
                Trace.TraceWarning(ex.ToString());
            }

            return(Created("", job));
        }
Exemplo n.º 2
0
        // POST: odata/Tasks
        public IActionResult Post([FromBody] Brizbee.Core.Models.Task task)
        {
            var currentUser = CurrentUser();

            var job = _context.Jobs
                      .Include(j => j.Customer)
                      .Where(j => j.Id == task.JobId)
                      .FirstOrDefault();

            // Ensure that user is authorized.
            if (!currentUser.CanCreateTasks ||
                job.Customer.OrganizationId != currentUser.OrganizationId)
            {
                return(Forbid());
            }

            // Check for duplicate task numbers in the organization.
            var isNumberDuplicated = _context.Tasks
                                     .Include(t => t.Job.Customer)
                                     .Where(t => t.Job.Customer.OrganizationId == currentUser.OrganizationId)
                                     .Where(t => t.Number == task.Number)
                                     .Any();

            if (isNumberDuplicated)
            {
                return(BadRequest());
            }

            // Determine the order of this task.
            var lastOrder = _context.Tasks
                            .Where(t => t.JobId == job.Id)
                            .Max(t => (int?)t.Order);

            // Auto-generated
            task.CreatedAt = DateTime.UtcNow;
            task.JobId     = job.Id;
            task.Order     = lastOrder.HasValue ? lastOrder.Value + 10 : 0;

            // Validate the model.
            ModelState.ClearValidationState(nameof(task));
            if (!TryValidateModel(task, nameof(task)))
            {
                var errors = new List <string>();

                foreach (var modelStateKey in ModelState.Keys)
                {
                    var value = ModelState[modelStateKey];

                    if (value == null)
                    {
                        continue;
                    }

                    foreach (var error in value.Errors)
                    {
                        errors.Add(error.ErrorMessage);
                    }
                }

                var message = string.Join(", ", errors);
                return(BadRequest(message));
            }

            _context.Tasks.Add(task);

            _context.SaveChanges();

            return(Created("", task));
        }