Пример #1
0
        public JsonResult OnGetItemStateChange()
        {
            var rawQS = Uri.UnescapeDataString(Request.QueryString.ToString());
            var idx   = rawQS.IndexOf('{');

            if (idx == -1)
            {
                return(new JsonResult("ERROR~:No Parameters"));
            }
            var          jsonQS = rawQS.Substring(idx);
            InvItemState invIS  = JsonConvert.DeserializeObject <InvItemState>(jsonQS);

            if (invIS != null)
            {
                InventoryItem invItem = (invIS.state == NEEDED_STATE) ?
                                        _context.InventoryItem.Include(i => i.Item).FirstOrDefault(m => m.ItemId == invIS.invItemId) :
                                        _context.InventoryItem.FirstOrDefault(m => m.ItemId == invIS.invItemId);

                if (invItem != null)
                {
                    if (invIS.pid > 0)
                    {
                        invItem.PersonId = invIS.pid;
                    }

                    invItem.State = invIS.state;
                    _context.Attach(invItem).State = EntityState.Modified;
                }

                try
                {
                    _context.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    return(new JsonResult("ERROR~:Update DB Failed")); // TBD
                }

                if ((invItem.State == NEEDED_STATE) && (invItem?.Item != null))
                {
                    // Notify Item is needed
                    var Item = _context.Item.FirstOrDefault(m => m.Id == invIS.invItemId); // TBD optimize with a single
                    if (Item != null)
                    {
                        Task.Run(() => NotifyNeedAsync(_hostEnv, _configuration, _userManager, "CStat:Stock> Needed : " + Item.Name, false)); // no cleaning even async while user is active
                    }
                }

                CurState cs = new CurState
                {
                    invItemState = GetInvItemState(invItem),
                    allState     = GetAllState()
                };
                return(new JsonResult(JsonConvert.SerializeObject(cs)));
            }
            return(new JsonResult("ERROR~:Incorrect Parameters"));
        }
Пример #2
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public IActionResult OnPost()
        {
            try
            {
                if (_Person.ChurchId == -1)
                {
                    _Person.ChurchId = null;
                }

                bool isValidAdr = ((_Address.Street != null) && (_Address.Street.Length > 0) &&
                                   (_Address.Town != null) && (_Address.Town.Length > 0) &&
                                   (_Address.State != null) && (_Address.State.Length > 0));

                if (isValidAdr && (_HandleAdrId == "KeepOld"))
                {
                    _Address.Id       = 0;
                    _Person.AddressId = null;
                }

                _Person.Roles = 0;
                foreach (var i in  _TitleRoles)
                {
                    _Person.Roles |= (long)i;
                }

                if ((_Person.AddressId == null) && isValidAdr)
                {
                    if (_Address.Country == null)
                    {
                        _Address.Country = "USA"; // Assume USA if not specified.
                    }
                    _context.Address.Add(_Address);
                    _context.SaveChanges();
                    _Person.AddressId = _Address.Id;
                }
                else
                {
                    if (isValidAdr)
                    {
                        _context.Attach(_Address).State = EntityState.Modified;
                        _context.SaveChanges();
                    }
                }

                _context.Attach(_Person).State = EntityState.Modified;
                _context.SaveChanges();
            }
            catch (Exception e)
            {
                _ = e;
                return(Page());
            }

            return(RedirectToPage("./Find"));
        }
Пример #3
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Attach(Task).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TaskExists(Task.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(RedirectToPage("./Index"));
        }
Пример #4
0
        public ActionResult OnPostMarkComplete()
        {
            int taskId = int.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskId").Value);

            if (taskId > 0)
            {
                var   taskData = TaskData.ReadTaskData(hostEnv, taskId, -1);
                CTask task     = _context.Task.First(t => (t.Id == taskId));
                if ((task != null) && (taskData != null))
                {
                    taskData.PercentComplete = 100;
                    taskData.Write(hostEnv);
                    task.GetTaskStatus(out CTask.eTaskStatus status, out CTask.eTaskStatus reason, out int pctComp);
                    pctComp = 100;
                    status  = CTask.eTaskStatus.Completed;
                    reason  = CTask.eTaskStatus.Job_Done;
                    task.SetTaskStatus((CTask.eTaskStatus)status, (CTask.eTaskStatus)reason, (int)pctComp);
                    try
                    {
                        taskData.Write(hostEnv);
                        _context.Attach(task).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                        _context.SaveChanges();
                        return(this.Content("Success"));
                    }
                    catch { }
                }
            }
            return(this.Content("Failed"));
        }
Пример #5
0
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (string.IsNullOrEmpty(_Business.Name) || (_Business.Type == (int)Business.EType.Unknown))
            {
                return(Page());
            }

            if (!string.IsNullOrEmpty(_ZipCode))
            {
                _ZipCode = Address.StripZip(_ZipCode);
            }

            Address adr = new Address();

            adr.Street  = _Street;
            adr.Town    = _Town;
            adr.ZipCode = _ZipCode;
            adr.Phone   = _Phone;
            adr.State   = _State;
            adr.Fax     = _Fax;
            adr.Country = "USA";

            if (!string.IsNullOrEmpty(adr.Phone) || !string.IsNullOrEmpty(adr.Fax))
            {
                if (!AddressMgr.Validate(ref adr))
                {
                    if (string.IsNullOrEmpty(adr.Street))
                    {
                        adr.Street = "<missing>";
                    }
                    if (string.IsNullOrEmpty(adr.Town))
                    {
                        adr.Town = "<missing>";
                    }
                    if (string.IsNullOrEmpty(adr.State))
                    {
                        adr.State = "NY";
                    }
                    if (string.IsNullOrEmpty(adr.ZipCode))
                    {
                        adr.ZipCode = "11111";
                    }
                }
            }

            int?id = Address.UpdateAddress(_context, adr);

            if (id.HasValue && (id.Value > 0))
            {
                _Business.AddressId = id;
                _Business.Address   = null;
            }
            else
            {
                _Business.AddressId = null;
                _Business.Address   = null;
            }
            _Business.PocId = !string.IsNullOrEmpty(_poc) ? Person.PersonIdFromExactName(_context, _poc) : null;
            if (!string.IsNullOrEmpty(_Business.UserLink))
            {
                _Business.UserLink = _Business.UserLink.Trim();
            }

            _context.Attach(_Business).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BusinessExists(_Business.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            if (string.IsNullOrEmpty(_RedirectURL))
            {
                return(RedirectToPage("./Index"));
            }
            _RedirectURL = "";
            return(NotFound());
        }
Пример #6
0
        public async Task DoWork(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                DateTime enow     = PropMgr.ESTNow;
                DateTime expected = new DateTime(enow.Year, enow.Month, enow.Day, 3, 0, 0);
                DateTime lastW    = (_csSettings.LastTaskUpdate != null) ? _csSettings.LastTaskUpdate : new DateTime(2020, 1, 1);
#if DEBUG
                double MinWait = 0;                                                                              // for testing
#else
                double MinWait = 720;                                                                            // 12 hrs
#endif
                if (((enow - lastW).TotalMinutes >= MinWait) || (Math.Abs((enow - expected).TotalMinutes) < 65)) // done not more than twice a day and covers DST change with delay/offset
                {
                    // Check Stock for possibly needed items
                    OrderedEvents         ordEvs         = new OrderedEvents(_context);
                    IList <InventoryItem> InventoryItems = _context.InventoryItem.Include(i => i.Inventory).Include(i => i.Item).ToList();
                    foreach (var invIt in InventoryItems)
                    {
                        if (IndexInvModel.MayNeedItem(_context, invIt, ordEvs))
                        {
                            // Item likely needs to be ordered. Mark as needed.
                            if (invIt.State == IndexInvModel.STOCKED_STATE)
                            {
                                invIt.State = IndexInvModel.NEEDED_STATE;
                                _context.Attach(invIt).State = EntityState.Modified;

                                try
                                {
                                    _context.SaveChanges();
                                    _csSettings.LastStockUpdate = PropMgr.ESTNow;
                                    _csSettings.Save();
                                    await Task.Run(() => IndexInvModel.NotifyNeedAsync(_hostEnv, _configuration, _userManager, "CStat:Stock> Needed : " + invIt.Item.Name, true)); // potentially clean Message log
                                }
                                catch (DbUpdateConcurrencyException)
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    // Check for new Tasks
                    AutoGen ag = new AutoGen(_context);
                    _csSettings.LastTaskUpdate = PropMgr.ESTNow;
                    _csSettings.Save();
                    ag.GenTasks(_hostEnv);

                    // Notify users Tasks Due
                    CTask.NotifyUserTaskDue(_hostEnv, _configuration, _userManager, _context, 24, true); // Potentially clean log

                    // Persist Daily Reading and Notify if needed for Propane
                    PropaneMgr pmgr = new PropaneMgr(_hostEnv, _configuration, _userManager);
                    pmgr.CheckValue(pmgr.GetTUTank(true)); // get value, log to file and check

                    // Check for any unexpected propane usage (not potentially impacted from events) from recent daily usage
                    var plList = pmgr.GetAll(3);
                    var plCnt  = plList.Count;
                    if (plCnt > 1)
                    {
                        for (int i = 0; i < plCnt - 1; ++i)
                        {
                            var plStart   = plList[i];
                            var plEnd     = plList[i + 1];
                            var dateRange = new DateRange(plStart.ReadingTime, plEnd.ReadingTime);

                            var evList = ag.GetImpactingEvents(dateRange);
                            if (evList.Count == 0) // no impacting events
                            {
                                var totalHrs = dateRange.TotalHours();
                                if ((totalHrs > 0) && _csSettings.GetPropaneProperties(out double tankGals, out double pricePerGal))
                                {
                                    var totalGals = ((plStart.LevelPct - plEnd.LevelPct) / 100) * tankGals;
                                    if ((totalGals / totalHrs) > ((double)2 / 24)) // averaging more than 2 gals/day?
                                    {
                                        // Send a one time alert (allowResend = false)
                                        CSSMS sms = new CSSMS(_hostEnv, _configuration, _userManager);
                                        sms.NotifyUsers(CSSMS.NotifyType.EquipNT, "CStat:Equip> " + "Non Event Propane Usage was " + totalGals.ToString("0.##") + " gals. during " + totalHrs.ToString("0.#") + " hours starting " +
                                                        plStart.ReadingTime.Month + "/" + plStart.ReadingTime.Day + "/" + plStart.ReadingTime.Year % 100, false, true); // potentially clean Message Log
                                    }
                                }
                            }
                        }
                    }

                    // Check for new EMails to store
                    CSEMail.SaveEMails(_configuration, _userManager);

                    // Check/Truncate Size of Arduino file
                    ArdMgr amgr = new ArdMgr(_hostEnv, _configuration, _userManager);
                    amgr.GetAll(true);

                    // Clean/{Reset to full view} Camera
                    using (var ptz = new PtzCamera())
                    {
                        ptz.Cleanup(_hostEnv);
                    }

                    _logger.LogInformation($"CStat Daily Updates Completed at {PropMgr.ESTNow}");
                }

                // Run again at 3:00 AM
                DateTime now          = PropMgr.ESTNow;
                DateTime tom          = now.AddDays(1);
                DateTime start        = new DateTime(tom.Year, tom.Month, tom.Day, 3, 0, 0); // Restart at 3:00 AM tomorrow
                int      MSecsToStart = (int)Math.Round((start - now).TotalMilliseconds);
                await System.Threading.Tasks.Task.Delay(MSecsToStart, stoppingToken);
            }
        }
Пример #7
0
        public bool GenTasks(IWebHostEnvironment hstEnv, int tmplId = -1)
        {
            // Get a List of Template Tasks for a specific template id(when template task is changed) ...or... ALL template tasks (tmplId = -1) when looking to generate tasks in general.
            var TemplateTasks = (tmplId != -1) ? _context.Task.Include(t => t.Person).Where(t => ((t.Type & (int)CTask.eTaskType.Template) != 0) && (t.Id == tmplId)).ToList() :
                                _context.Task.Include(t => t.Person).Where(t => (t.Type & (int)CTask.eTaskType.Template) != 0).OrderBy(t => t.Priority).ToList();

            // Get the range limit of time to possibly create new tasks and a list of events that fully or partially overlap this range limit of time
            DateTime now       = PropMgr.ESTNow;
            DateTime startTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
            DateTime endTime   = startTime.AddMonths(6);
            //DateTime endTime = new DateTime(startTime.Year+1, 12, 31, 23, 59, 59);
            DateRange    lim    = new DateRange(startTime, endTime);
            List <Event> evList = GetEvents(lim);

            List <CTask> AllNewTaskList = new List <CTask>(); // Create a list for collecting all potentially new tasks created for all templates in TemplateTasks

            // Determine what needs to be Auto generated
            foreach (var tmpl in TemplateTasks)
            {
                // Get a list of existing tasks create from the specific template : tmpl
                List <CTask> curCreatedTasks = _context.Task.Include(t => t.Person).Where(t => t.ParentTaskId.HasValue && ((t.ParentTaskId == tmpl.Id) || (t.Description == tmpl.Description))).ToList();

                // Filter out new, created tasks : n that already exist : Having the {same_task_id ...or... same_description} ...AND... {same Year, Month, Day } ...AND... {newlyCreatedTime >= currExistingTime}
                // Note : to be safe, we keep newlyCreatedTime earlier times than currExistingTime and may add as a duplicate in some special cases.
                List <CTask> newCreatedTasks = GetTemplateTasks(hstEnv, _context, tmpl, evList, lim).Where(n => !curCreatedTasks.Any(c => ((c.ParentTaskId == n.ParentTaskId) || (c.Description == n.Description)) &&
                                                                                                                                     c.DueDate.HasValue && n.DueDate.HasValue && (c.DueDate.Value.Year == n.DueDate.Value.Year) && (c.DueDate.Value.Month == n.DueDate.Value.Month) &&
                                                                                                                                     (c.DueDate.Value.Day == n.DueDate.Value.Day) && n.DueDate >= c.DueDate)).ToList();

                //TBD : Do not regen a task that is already closed

                // Make sure the newly filtered potential tasks are assigned to a person
                // NOTE : we cannot rely on tmpl as the only parent tasks as newCreatedTasks may contain other tasks not having t.ParentTaskId = tmpl.Id
                if (newCreatedTasks.Count > 0)
                {
                    // ensure each newCreatedTask is assigned to someone and that person is avaiable
                    // Cache Task Data by task id
                    var TDCache = new Dictionary <int, TaskData>();
                    var PIDList = new List <int>();
                    foreach (var t in newCreatedTasks)
                    {
                        TaskData taskData;
                        if (!TDCache.TryGetValue(t.Id, out taskData))
                        {
                            taskData      = TaskData.ReadTaskData(hstEnv, t.Id, -1);
                            TDCache[t.Id] = taskData;
                        }

                        // For each newCreatedTask, check for a person who is unavailable and if unavailable, nullify person id and person;
                        if (t.PersonId.HasValue && !PIDList.Contains(t.PersonId.Value))
                        {
                            int pid = t.PersonId.Value;
                            PIDList.Add(pid);
                            Person person = (Person)_context.Person.First(p => p.Id == pid);
                            if ((person != null) && person.Roles.HasValue && (((long)person.Roles & (long)Person.TitleRoles.Unavailable) != 0))
                            {
                                t.PersonId = null;
                                t.Person   = null;
                            }
                        }

                        if (!t.PersonId.HasValue || (t.PersonId <= 0))
                        {
                            // Determine person from roles
                            var pid = CTask.ResolvePersonId(_context, taskData.Role1, taskData.Role2, taskData.Role3);
                            if (pid.HasValue && (pid > 0))
                            {
                                t.PersonId = pid;
                                t.SetType(CTask.eTaskType.AutoPersonID);
                            }
                        }
                    }
                }

                // Filter out tasks (completed or not completed that already exist.
                foreach (var nt in newCreatedTasks) // This loop may be redundant. It was added to fix a problem that ultimately was related to changed Due Dates. TBD : Check if it can be removed.
                {
                    if (nt.ParentTaskId.HasValue && (nt.ParentTaskId.Value > 0) && nt.DueDate.HasValue)
                    {
                        if (_context.Task.Any(t => t.ParentTaskId.HasValue && (t.ParentTaskId.Value == nt.ParentTaskId.Value) && t.DueDate.HasValue && (t.DueDate.Value.Date == nt.DueDate.Value.Date)))
                        {
                            continue;           // Child Task with due date already exist. Skip.
                        }
                        AllNewTaskList.Add(nt); // Add needed new task
                    }
                }
            }

            // Search for any existing tasks that are assigned to a person who is now unavailable
            List <CTask> unavailTasks = _context.Task.Include(t => t.Person).Where(t => t.ParentTaskId.HasValue && (t.ParentTaskId.Value > 0) && t.PersonId.HasValue && t.Person.Roles.HasValue && (((long)t.Person.Roles & (long)Person.TitleRoles.Unavailable) != 0)).ToList();

            foreach (var ut in unavailTasks)
            {
                TaskData utd = TaskData.ReadTaskData(hstEnv, ut.ParentTaskId.Value, -1);
                ut.PersonId = CTask.ResolvePersonId(_context, utd.Role1, utd.Role2, utd.Role3);  // Reassign from the unavailable person to someone else
                _context.Attach(ut).State = EntityState.Modified;
                try
                {
                    _context.SaveChanges();
                }
                catch { }
            }

            // TBD: Maintain AutoPersonID state properly.

            // Check for duplicates by same description and same day before Adding to DB.
            var    OrdTasks = AllNewTaskList.OrderBy(t => t.Description).ThenBy(t => t.DueDate);
            string lastDesc = "";
            int    lastYear = -1, lastMonth = -1, lastDay = -1;

            foreach (var t in OrdTasks)
            {
                bool bSkip = (t.Description == lastDesc) && t.DueDate.HasValue && (t.DueDate.Value.Year == lastYear) && (t.DueDate.Value.Month == lastMonth) && (t.DueDate.Value.Day == lastDay);
                lastDesc  = t.Description;
                lastYear  = t.DueDate.Value.Year;
                lastMonth = t.DueDate.Value.Month;
                lastDay   = t.DueDate.Value.Day;

                if (!bSkip)
                {
                    _context.Task.Add(t);
                    _context.SaveChanges();
                }
            }
            return(true);
        }
Пример #8
0
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            if (!InventoryItem.Units.HasValue || (EditItem.Size <= 0))
            {
                ViewData["ItemErrors"] = "* Must have a non-zero Units/Item.";
                return(Page());
            }

            if (InventoryItem.ReorderThreshold.HasValue && (InventoryItem.ReorderThreshold.Value <= 0))
            {
                InventoryItem.ReorderThreshold = null;
            }

            if (InventoryItem.UnitsPerDay.HasValue && (InventoryItem.UnitsPerDay.Value <= 0))
            {
                InventoryItem.UnitsPerDay = null;
            }

            if (ItemPhoto != null)
            {
                if ((EditItem.Upc == null) || (EditItem.Upc.Trim().Length == 0))
                {
                    ViewData["UPCError"] = "Error : UPC Must be specified with Photo.";
                    return(Page());
                }
                string destFile = Path.Combine(hostEnv.WebRootPath, "items", "ItmImg_" + EditItem.Upc + ".jpg");

                if (System.IO.File.Exists(destFile))
                {
                    System.IO.File.Delete(destFile); // Delete any existing photo for this item
                }
                using (var fs = new FileStream(destFile, FileMode.Create))
                {
                    ItemPhoto.CopyTo(fs);
                }
            }

            if ((EditItem.Name != null) && (EditItem.Name.Length > 0))
            {
                EditItem.Name.Trim();
            }
            if ((EditItem.Upc != null) && (EditItem.Upc.Length > 0))
            {
                EditItem.Upc.Trim();
            }

            List <int?> tidsToDel = new List <int?>();

            tidsToDel.Add(GetBuyTransaction(1, Buy1URL));
            tidsToDel.Add(GetBuyTransaction(2, Buy2URL));
            tidsToDel.Add(GetBuyTransaction(3, Buy3URL));

            _context.Attach(InventoryItem).State = EntityState.Modified;
            _context.Attach(EditItem).State      = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _ = ex;
            }

            // Try to delete unused transactions AFTER updating InventoryItem
            foreach (var tid in tidsToDel)
            {
                try
                {
                    if (tid.HasValue)
                    {
                        var OldTrans = _context.Transaction.Find(tid.Value);
                        if (OldTrans != null)
                        {
                            _context.Transaction.Remove(OldTrans);
                            _context.SaveChanges();
                        }
                    }
                }
                catch { }
            }

            return(RedirectToPage("./Index"));
        }
Пример #9
0
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            if ((_Event.Description == null) || (_Event.Description.Trim().Length == 0) || (_Event.Type <= 0))
            {
                UpdateViewData("Event Type and/or Event Description must be set.");
                return(Page());
            }

            if (!ModelState.IsValid)
            {
                UpdateViewData("One or more fields are not valid.");
                return(Page());
            }

            if (_Event.ChurchId == -1)
            {
                _Event.ChurchId = null;
            }

            if (_Event.StartTime >= _Event.EndTime)
            {
                UpdateViewData("End Date/Time must be later than Start Date/Time.");
                return(Page());
            }

            // Check if Start or End Dates have changed and delete tasks associated with event and generate new ones.
            int NumTasksRemoved = RemoveChangedEventTasks(_context, _Event);

            UpdateAttendance(_Event.Id, _Event.Staff ?? 0, _Staff);

            _context.Attach(_Event).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EventExists(_Event.Id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            if (NumTasksRemoved > 0)
            {
                // Regenerate tasks based on event now
                var autogen = new AutoGen(_context);
                autogen.GenTasks(_hostEnv);
            }

            if (string.IsNullOrEmpty(_RedirectURL))
            {
                return(RedirectToPage("./Index"));
            }
            _RedirectURL = "";
            return(NotFound());
        }
Пример #10
0
        public ActionResult OnPostSave()
        {
            if ((this.Request != null) && (this.Request.Form != null))
            {
                bool IsTemplate = false;

                /******************
                *
                *       public int tid { get; set; }
                *       public int state { get; set; }
                *       [DataMember]
                *       public int reason { get; set; }
                *       [DataMember]
                *       public int PercentComplete { get; set; }
                *       [DataMember]
                *       public string Desc { get; set; }
                *       [DataMember]
                *       public List<Pic> pics { get; set; }
                *       [DataMember]
                *       public List<BOMLine> bom { get; set; }
                *       [DataMember]
                *       public string comments { get; set; }
                *
                ******************/

                string fStr = "% Comp";
                try
                {
                    uint pctComp = uint.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "pctComp").Value);
                    fStr = "Status";
                    ulong status = ulong.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskState").Value);
                    fStr = "Reason";
                    ulong reason = ulong.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskReason").Value);
                    fStr          = "Priority";
                    task.Priority = int.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskPriority").Value);
                    task.SetTaskStatus((CTask.eTaskStatus)status, (CTask.eTaskStatus)reason, (int)pctComp);
                    taskData.state           = (int)status;
                    taskData.reason          = (int)reason;
                    taskData.PercentComplete = (int)pctComp;
                    fStr = "Title must be filled";
                    string title = CCommon.UnencodeQuotes(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskTitle").Value).Trim();
                    if (title.Length == 0)
                    {
                        throw new ArgumentNullException("bad title");
                    }
                    taskData.Title = task.Description = title;
                    fStr           = "Task Id";
                    taskData.tid   = task.Id = int.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskId").Value);
                    fStr           = "Parent Task Id";
                    string ptid = this.Request.Form.FirstOrDefault(kv => kv.Key == "parentTaskId").Value;
                    task.ParentTaskId = ((ptid.Length > 0) ? int.Parse(ptid) : (int?)null);
                    fStr          = "Task Type";
                    task.Type     = int.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskType").Value);
                    fStr          = "Person Id";
                    task.PersonId = int.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskPersonId").Value);
                    if (!task.PersonId.HasValue || (task.PersonId <= 0))
                    {
                        task.PersonId = null;
                    }
                    var oldTask = _context.Task.AsNoTracking().FirstOrDefaultAsync(t => (t.Id == task.Id) && (((int)t.Type & (int)eTaskType.AutoPersonID) != 0)).Result;
                    if (oldTask != null)
                    {
                        if (task.PersonId != oldTask.PersonId)
                        {
                            task.Type &= ~(int)eTaskType.AutoPersonID; // Remove Auto Person state since user change person.
                        }
                    }

                    fStr = "Committed Cost";
                    String ccostStr = this.Request.Form.FirstOrDefault(kv => kv.Key == "taskCommittedCost").Value;
                    if (ccostStr.Trim().Length > 0)
                    {
                        task.CommittedCost = decimal.Parse(ccostStr);
                    }
                    else
                    {
                        task.CommittedCost = 0;
                    }
                    fStr = "Total Cost";
                    String tcostStr = this.Request.Form.FirstOrDefault(kv => kv.Key == "taskTotalCost").Value;
                    if (tcostStr.Trim().Length > 0)
                    {
                        task.TotalCost = decimal.Parse(tcostStr);
                    }
                    else
                    {
                        task.TotalCost = 0;
                    }

                    IsTemplate = (task.Type & (int)CTask.eTaskType.Template) != 0;
                    if (IsTemplate)
                    {
                        fStr = "Template Task";

                        // Make sure to initialize ABOVE and also get these HERE only for a Template Task.
                        int dueType = Int32.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskCreateDue").Value);
                        if (dueType != 0)
                        {
                            // Get Template Type

                            int dueValue = 0;

                            if ((dueType == (int)CTask.eTaskType.Hours_Before_Start) ||
                                (dueType == (int)CTask.eTaskType.Hours_After_Start) ||
                                (dueType == (int)CTask.eTaskType.Hours_Before_End) ||
                                (dueType == (int)CTask.eTaskType.Hours_After_End) ||
                                (dueType == (int)CTask.eTaskType.Days_Before_Start) ||
                                (dueType == (int)CTask.eTaskType.Days_After_Start) ||
                                (dueType == (int)CTask.eTaskType.Days_Before_End) ||
                                (dueType == (int)CTask.eTaskType.Days_After_End) ||
                                (dueType == (int)CTask.eTaskType.Weeks_Before_Start) ||
                                (dueType == (int)CTask.eTaskType.Weeks_After_Start) ||
                                (dueType == (int)CTask.eTaskType.Weeks_Before_End) ||
                                (dueType == (int)CTask.eTaskType.Weeks_After_End) ||
                                (dueType == (int)CTask.eTaskType.Months_Before_Start) ||
                                (dueType == (int)CTask.eTaskType.Months_After_Start) ||
                                (dueType == (int)CTask.eTaskType.Months_Before_End) ||
                                (dueType == (int)CTask.eTaskType.Months_After_End) ||
                                (dueType == (int)CTask.eTaskType.Day_Of_Week_SunMon) ||
                                (dueType == (int)CTask.eTaskType.Every_Num_Years))
                            {
                                dueValue = Int32.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskCreateDueVal").Value);
                            }
                            else if (dueType == (int)CTask.eTaskType.Day_Of_Week_SunMon)
                            {
                                String dueStr = this.Request.Form.FirstOrDefault(kv => kv.Key == "taskCreateDueVal").Value;
                                if (dueStr.Length > 0)
                                {
                                    dueStr = dueStr.Trim().ToLower();
                                    if (dueStr.IndexOf("su") == 0)
                                    {
                                        dueValue = 1;
                                    }
                                    else if ((dueStr.IndexOf("m") == 0))
                                    {
                                        dueValue = 2;
                                    }
                                    else if ((dueStr.IndexOf("tu") == 0))
                                    {
                                        dueValue = 3;
                                    }
                                    else if ((dueStr.IndexOf("w") == 0))
                                    {
                                        dueValue = 4;
                                    }
                                    else if ((dueStr.IndexOf("th") == 0))
                                    {
                                        dueValue = 5;
                                    }
                                    else if ((dueStr.IndexOf("f") == 0))
                                    {
                                        dueValue = 6;
                                    }
                                    else if ((dueStr.IndexOf("sa") == 0))
                                    {
                                        dueValue = 7;
                                    }
                                    else
                                    {
                                        return(this.Content("Fail: Week Day needs to start with M, Tu, W, Th, Fr, Sa or Su")); // Send back results
                                    }
                                }
                            }
                            int eachType = Int32.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskCreateEach").Value);

                            if (eachType == (int)CTask.eTaskType.Day_from_Due_till)
                            {
                                String TillDayStr = this.Request.Form.FirstOrDefault(kv => kv.Key == "TillDay").Value;
                                if (TillDayStr.Trim().Length > 0)
                                {
                                    bool     TillFail = true;
                                    String[] numStr   = TillDayStr.Split('/', '.', '-');
                                    if (numStr.Count() == 2)
                                    {
                                        if (Int32.TryParse(numStr[0], out int TillMo) && Int32.TryParse(numStr[1], out int TillDay))
                                        {
                                            try
                                            {
                                                task.EstimatedDoneDate = new DateTime(2020, TillMo, TillDay);
                                            }
                                            catch { }
                                            TillFail = !task.EstimatedDoneDate.HasValue;
                                        }
                                        if (TillFail)
                                        {
                                            return(this.Content("Fail: Day_from_Due_till needs to have a valid Month/Day with a / . or - separator")); // Send back results
                                        }
                                    }
                                }
                            }

                            if ((eachType == (int)CTask.eTaskType.Due_Day) || (eachType == (int)CTask.eTaskType.Num_Start_Date))
                            {
                                string mdStr = CCommon.UnencodeQuotes(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskDueDate").Value).Trim();
                                if (mdStr.Length >= 10)
                                {
                                    string dateOnly = mdStr.Substring(0, 10);
                                    task.DueDate = DateTime.ParseExact(dateOnly, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture);
                                }
                                else
                                {
                                    return(this.Content("Fail: A valid Due Date must be set with Every : Month n Day")); // Send back results
                                }
                            }
                            task.SetTaskType((CTask.eTaskType)dueType, (CTask.eTaskType)eachType, dueValue);
                        }

                        fStr           = "Role123";
                        taskData.Role1 = long.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskRole1").Value);
                        taskData.Role2 = long.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskRole2").Value);
                        taskData.Role3 = long.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskRole3").Value);
                    }
                    fStr = "Task Doc";

                    task.PlanLink     = CCommon.UnencodeQuotes(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskDoc").Value);
                    fStr              = "Detail Text";
                    taskData.Detail   = CCommon.UnencodeQuotes(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskDetail").Value);
                    fStr              = "Comments";
                    taskData.comments = CCommon.UnencodeQuotes(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskComments").Value);
                    fStr              = "Pics";
                    string[] pics = Newtonsoft.Json.JsonConvert.DeserializeObject <string[]>(this.Request.Form.FirstOrDefault(kv => kv.Key == "pics").Value);
                    fStr = "Pic Titles";
                    string[] picTitles = Newtonsoft.Json.JsonConvert.DeserializeObject <string[]>(this.Request.Form.FirstOrDefault(kv => kv.Key == "picTitles").Value);
                    if (pics.Length == picTitles.Length)
                    {
                        for (int i = 0; i < pics.Length; ++i)
                        {
                            Pic pobj = new Pic(task.Id, i + 1, CCommon.UnencodeQuotes(picTitles[i]), pics[i]);
                            taskData.pics.Add(pobj);
                        }
                    }
                    else
                    {
                        return(this.Content("Fail: Pics=" + pics.Length + " DOES NOT MATCH Pic Titles=" + picTitles.Length)); // Send back results
                    }

                    fStr = "Costs /BOM";
                    var sBOM = this.Request.Form.FirstOrDefault(kv => kv.Key == "bom").Value;
                    taskData.bom = Newtonsoft.Json.JsonConvert.DeserializeObject <List <BOMLine> >(sBOM);

                    fStr = "Due/Est.Done Date";
                    string   msDueStr    = CCommon.UnencodeQuotes(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskDueDate").Value).Trim();
                    DateTime dueDateTime = new DateTime();
                    if (msDueStr.Length > 0)
                    {
                        //dueDateTime = DateTime.ParseExact(msDueStr, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture);
                        dueDateTime = DateTime.Parse(msDueStr, System.Globalization.CultureInfo.CurrentCulture);
                    }
                    taskData.FixedDueDate = bool.Parse(this.Request.Form.FirstOrDefault(kv => kv.Key == "fixedDueDate").Value);
                    if (taskData.FixedDueDate)
                    {
                        if (msDueStr.Length > 0)
                        {
                            task.DueDate = dueDateTime;
                        }
                        else
                        {
                            task.DueDate = null;
                        }
                        if (!IsTemplate)
                        {
                            task.EstimatedDoneDate = null;
                        }
                    }
                    else
                    {
                        if (!IsTemplate)
                        {
                            if (msDueStr.Length > 0)
                            {
                                task.EstimatedDoneDate = dueDateTime;
                            }
                            else
                            {
                                task.EstimatedDoneDate = null;
                            }
                            task.DueDate = null;
                        }
                    }
                    fStr = "Completed Date";
                    string msDoneStr = CCommon.UnencodeQuotes(this.Request.Form.FirstOrDefault(kv => kv.Key == "taskDoneDate").Value).Trim();
                    if (msDoneStr.Length > 0)
                    {
                        int slashIdx = msDoneStr.IndexOf("/");
                        if ((slashIdx > 0) && (slashIdx <= 2))
                        {
                            task.ActualDoneDate = DateTime.ParseExact(msDoneStr, "M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.CurrentCulture);
                        }
                        else
                        {
                            long msSinceUXEpoc = long.Parse(msDoneStr);
                            task.ActualDoneDate = DateTimeOffset.FromUnixTimeMilliseconds(msSinceUXEpoc).DateTime.ToLocalTime();
                        }
                    }
                    else
                    {
                        task.ActualDoneDate = null;
                    }

                    task.EstimatedManHours = 0;
                    task.RequiredSkills    = "";

                    if (IsTemplate)
                    {
                        // Remove exist non-done tasks so new ones can be created without task multiplicity
                        Models.Task.RemoveActiveChildTasks(_context, task.Id);
                    }

                    fStr = "Save File Update";
                    taskData.Write(hostEnv);
                    fStr = "DB Update";
                    _context.Attach(task).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                    _context.SaveChanges();

                    if (IsTemplate)
                    {
                        // Generate possibly new Tasks based on template add/changes
                        AutoGen ag = new AutoGen(_context);
                        ag.GenTasks(hostEnv, task.Id);
                    }

                    if (dueDateTime != DateTime.MinValue)
                    {
                        NotifyUserTaskDue(hostEnv, _config, _userManager, _context, 24); // Send out notications if needed.
                    }
                }
                catch (Exception e)
                {
                    return(this.Content("Fail: " + fStr + " e.msg=" + e.Message)); // Send back results
                }

                return(this.Content("Success:" + task.Id));    // Send back results
            }
            return(this.Content("Fail: Bad/Missing Request")); // Send back results
        }
Пример #11
0
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task <IActionResult> OnPostAsync()
        {
            //if (!ModelState.IsValid)
            //{
            //    return Page();
            //}

            Address adr = new Address();

            adr.Street  = _Street;
            adr.Town    = _Town;
            adr.ZipCode = _ZipCode;
            adr.Phone   = _Phone;
            adr.State   = _State;
            adr.Fax     = _Fax;
            adr.Country = "USA";

            if (!string.IsNullOrEmpty(adr.Phone) || !string.IsNullOrEmpty(adr.Fax))
            {
                if (!AddressMgr.Validate(ref adr))
                {
                    if (string.IsNullOrEmpty(adr.Street))
                    {
                        adr.Street = "<missing>";
                    }
                    if (string.IsNullOrEmpty(adr.Town))
                    {
                        adr.Town = "<missing>";
                    }
                    if (string.IsNullOrEmpty(adr.State))
                    {
                        adr.State = "NY";
                    }
                    if (string.IsNullOrEmpty(adr.ZipCode))
                    {
                        adr.ZipCode = "11111";
                    }
                }
            }

            int?id = Address.UpdateAddress(_context, adr);

            if (id.HasValue && (id.Value > 0))
            {
                _Church.AddressId = id;
                _Church.Address   = null;
            }
            else
            {
                _Church.AddressId = null;
                _Church.Address   = null;
            }

            if (!_Church.SeniorMinisterId.HasValue)
            {
                _Church.SeniorMinisterId = Person.PersonIdFromExactName(_context, _SeniorMinister);
            }
            if (!_Church.YouthMinisterId.HasValue)
            {
                _Church.YouthMinisterId = Person.PersonIdFromExactName(_context, _YouthMinister);
            }
            if (!_Church.Trustee1Id.HasValue)
            {
                _Church.Trustee1Id = Person.PersonIdFromExactName(_context, _Trustee1);
            }
            if (!_Church.Trustee2Id.HasValue)
            {
                _Church.Trustee2Id = Person.PersonIdFromExactName(_context, _Trustee2);
            }
            if (!_Church.Trustee3Id.HasValue)
            {
                _Church.Trustee3Id = Person.PersonIdFromExactName(_context, _Trustee3);
            }
            if (!_Church.Alternate1Id.HasValue)
            {
                _Church.Alternate1Id = Person.PersonIdFromExactName(_context, _Alternate1);
            }
            if (!_Church.Alternate2Id.HasValue)
            {
                _Church.Alternate2Id = Person.PersonIdFromExactName(_context, _Alternate2);
            }
            if (!_Church.Alternate3Id.HasValue)
            {
                _Church.Alternate3Id = Person.PersonIdFromExactName(_context, _Alternate3);
            }

            _Church.Affiliation = ((AffiliationType)_Affiliation).ToString();

            _context.Attach(_Church).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
            }

            return(RedirectToPage("./Index"));
        }