Пример #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
        public JsonResult OnGetDeleteVendor()
        {
            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);

            Dictionary <string, int> NVPairs = JsonConvert.DeserializeObject <Dictionary <string, int> >(jsonQS);

            if (NVPairs.TryGetValue("vendorId", out int vendorId))
            {
                _Business = _context.Business.Find(vendorId);

                if (_Business != null)
                {
                    try
                    {
                        // Delete Vendor
                        _context.Business.Remove(_Business);
                        _context.SaveChanges();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        return(new JsonResult("ERROR~: Exception : Delete Business/Dept Failed."));
                    }
                    return(new JsonResult("SUCCESS~:Delete Business/Dept Succeeded."));
                }
            }
            return(new JsonResult("ERROR~: Delete Business/Dept Failed."));
        }
Пример #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
        public int?GetBuyTransaction(int buyIdx, string buyUrl)
        {
            if ((buyUrl == null) || (buyUrl.Length == 0))
            {
                return(null);
            }

            int?InvItBuyId = null;

            switch (buyIdx)
            {
            case 1:
                InvItBuyId           = InventoryItem.Buy1Id;
                InventoryItem.Buy1Id = null;     // initially clear
                break;

            case 2:
                InvItBuyId           = InventoryItem.Buy2Id;
                InventoryItem.Buy2Id = null;     // initially clear
                break;

            case 3:
                InvItBuyId           = InventoryItem.Buy3Id;
                InventoryItem.Buy3Id = null;     // initially clear
                break;

            default:
                return(null);
            }

            if (buyUrl == "_.")
            {
                return(InvItBuyId);
            }

            var Trans = _context.Transaction.Where(t => t.Link == buyUrl).FirstOrDefault();

            if (Trans == null)
            {
                Trans      = new Transaction();
                Trans.Link = buyUrl;
                try
                {
                    var uri      = new Uri(buyUrl);
                    var hostStrs = uri.Host.Split('.');

                    var NumHostStrs = hostStrs.Length;
                    if (NumHostStrs > 0)
                    {
                        Trans.Memo = hostStrs[Math.Max(0, NumHostStrs - 2)];
                    }
                    else
                    {
                        throw new InvalidOperationException("No Host Name");
                    }

                    _context.Transaction.Add(Trans);
                    _context.SaveChanges();
                }
                catch { Trans.Memo = "Store #" + buyIdx; }
            }
            switch (buyIdx)
            {
            case 1:
                InventoryItem.Buy1Id = Trans.Id;
                break;

            case 2:
                InventoryItem.Buy2Id = Trans.Id;
                break;

            case 3:
                InventoryItem.Buy3Id = Trans.Id;
                break;

            default:
                return(null);
            }
            return(InvItBuyId);
        }
Пример #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
        // 128=~256=Eli Russo~512=~2048=~8192=Christine Gerkhardt~32768=~65536=~131072=~1048576=~
        public bool UpdateAttendance(int evid, int activeRoles, string staffStr)
        {
            try
            {
                // Check for and delete people assigned to un-needed roles.
                List <int> RoleList = Enum.GetValues(typeof(Attendance.AttendanceRoles)).Cast <int>().Where(r => (int)r >= (int)Attendance.AttendanceRoles.Sch_Host).Select(x => x).ToList();

                foreach (var r in RoleList)
                {
                    if ((r & activeRoles) == 0)
                    {
                        // Staff Role now not needed
                        Attendance delAtt = _context.Attendance.AsNoTracking().FirstOrDefault(a => (a.EventId == evid) && (a.RoleType == r));
                        if (delAtt != null)
                        {
                            _context.Attendance.Remove(delAtt);
                            _context.SaveChanges();
                        }
                    }
                }

                if (!string.IsNullOrEmpty(staffStr))
                {
                    List <KeyValuePair <int, string> > kvpList = new List <KeyValuePair <int, string> >();
                    var pairs = staffStr.Split("~");
                    if (pairs.Length == 0)
                    {
                        return(false);
                    }
                    foreach (var p in pairs)
                    {
                        var flds = p.Split("=");
                        if (flds.Length >= 1)
                        {
                            var keyStr = flds[0].Trim();
                            if (!string.IsNullOrEmpty(keyStr))
                            {
                                if (int.TryParse(keyStr, out int key))
                                {
                                    var val = (flds.Length == 2) ? flds[1].Trim() : "";
                                    var kvp = new KeyValuePair <int, string>(key, val);
                                    kvpList.Add(kvp);
                                }
                            }
                        }
                    }

                    kvpList.ForEach(kv =>
                    {
                        Attendance att = _context.Attendance.AsNoTracking().FirstOrDefault(a => (a.EventId == evid) && (a.RoleType == kv.Key));
                        if (att != null)
                        {
                            if (string.IsNullOrEmpty(kv.Value))
                            {
                                // Delete current
                                _context.Attendance.Remove(att);
                                _context.SaveChanges();
                            }
                            else
                            {
                                // Update Current
                                List <Person> persList = Person.PeopleFromNameHint(_context, kv.Value);
                                if (persList.Count == 1)
                                {
                                    att.PersonId = persList[0].Id;

                                    _context.Attendance.Attach(att);
                                    _context.Entry(att).State = EntityState.Modified;
                                    _context.SaveChanges();
                                }
                            }
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(kv.Value))
                            {
                                // Add new Attendance
                                var newAtt      = new Attendance();
                                newAtt.EventId  = evid;
                                newAtt.RoleType = kv.Key;

                                List <Person> persList = Person.PeopleFromNameHint(_context, kv.Value);
                                newAtt.PersonId        = (persList.Count == 1) ? persList[0].Id : Person.AddPersonFromNameHint(_context, kv.Value);
                                if (newAtt.PersonId > 0)
                                {
                                    _context.Attendance.Add(newAtt);
                                    _context.SaveChanges();
                                }
                            }
                        }
                    });
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Пример #9
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"));
        }
Пример #10
0
        public IActionResult OnGet(int?id)
        {
            int tid = !id.HasValue ? tid = 0 : id.Value;
            int res = 0;

            if (tid <= 0)
            {
                // Create new task
                InitializeTask(tid);
                _context.Task.Add(task);
                res = _context.SaveChanges();
            }
            else
            {
                task = _context.Task.FirstOrDefault(m => m.Id == tid);
                if ((task != null) && (tid == task.Id))
                {
                    IsTemplate = (task.Type & (int)CTask.eTaskType.Template) != 0;
                    taskData   = TaskData.ReadTaskData(hostEnv, tid, task.ParentTaskId.HasValue ? task.ParentTaskId.Value : -1);
                    if ((task.DueDate == null) && !IsTemplate)
                    {
                        task.DueDate = task.EstimatedDoneDate; // temporary for editing purpose
                    }
                    else
                    {
                        taskData.FixedDueDate = true;
                    }

                    task.GetTaskStatus(out eTaskStatus state, out eTaskStatus reason, out int PercentComplete);
                    taskData.state           = (int)state;
                    taskData.reason          = (int)reason;
                    taskData.PercentComplete = PercentComplete;

                    if ((task.Type & (int)CTask.eTaskType.Template) != 0)
                    {
                        // Initialize Template Type members
                        CTask.eTaskType CreateTaskDue;
                        CTask.eTaskType CreateTaskEach;
                        int             CreateTaskDueVal;
                        task.GetTaskType(out CreateTaskDue, out CreateTaskEach, out CreateTaskDueVal);
                        taskData.CreateTaskDue  = (int)CreateTaskDue;
                        taskData.CreateTaskEach = (int)CreateTaskEach;
                        taskData.TillDay        = ((taskData.CreateTaskEach == (int)CTask.eTaskType.Day_from_Due_till) && task.EstimatedDoneDate.HasValue) ?
                                                  task.EstimatedDoneDate.Value.Month + "/" + task.EstimatedDoneDate.Value.Day : "";
                        switch (CreateTaskDue)
                        {
                        case CTask.eTaskType.Day_Of_Week_SunMon:
                            taskData.CreateTaskDueVal = ((CreateTaskDueVal >= 1) && (CreateTaskDueVal <= 7)) ? TaskArrs.weekDays[CreateTaskDueVal] : "";
                            break;

                        //case CTask.eTaskType.At_Date:
                        //    if (CreateTaskDueVal > (1 << 5))
                        //    {
                        //        int day = CreateTaskDueVal & 0x1F;
                        //        int month = CreateTaskDueVal >> 5;
                        //        taskData.CreateTaskDueVal = month.ToString() + "/" + day;
                        //    }
                        //    else
                        //        taskData.CreateTaskDueVal = "";
                        //    break;

                        default:
                            taskData.CreateTaskDueVal = CreateTaskDueVal.ToString();
                            break;
                        }
                    }
                }
                else
                {
                    InitializeTask(tid);
                }
            }

            IList <SelectListItem> sList = Enum.GetValues(typeof(CTask.eTaskStatus)).Cast <CTask.eTaskStatus>().Where(e => (int)e < (int)CTask.eTaskStatus.Need_Funds).Select(x => new SelectListItem {
                Text = x.ToString().Replace("_", " "), Value = ((int)x).ToString()
            }).ToList();

            ViewData["State"] = sList;
            IList <SelectListItem> rList = Enum.GetValues(typeof(CTask.eTaskStatus)).Cast <CTask.eTaskStatus>().Where(e => (int)e >= (int)CTask.eTaskStatus.Need_Funds).Select(x => new SelectListItem {
                Text = x.ToString().Replace("_", " "), Value = ((int)x).ToString()
            }).ToList();

            ViewData["Reason"] = rList;

            IList <SelectListItem> dueList = Enum.GetValues(typeof(CTask.eTaskType)).Cast <CTask.eTaskType>().Where(e => ((int)e >= (int)CTask.eTaskType.Before_Start) && ((int)e <= (int)CTask.eTaskType.Day_Of_Week_SunMon)).Select(x => new SelectListItem {
                Text = x.ToString().Replace("_", " "), Value = ((int)x).ToString()
            }).ToList();

            ViewData["CreateTaskDue"] = dueList;

            IList <SelectListItem> eachList = Enum.GetValues(typeof(CTask.eTaskType)).Cast <CTask.eTaskType>().Where(e => ((int)e >= (int)CTask.eTaskType.Retreat_Event) && ((int)e < (int)CTask.eTaskType.Num_Start_Date)).Select(x => new SelectListItem {
                Text = x.ToString().Replace("_", " ").Replace(" n ", "/"), Value = ((int)x).ToString()
            }).ToList();

            ViewData["CreateTaskEach"] = eachList;

            IList <SelectListItem> pList = Enum.GetValues(typeof(CTask.ePriority)).Cast <CTask.ePriority>().Select(x => new SelectListItem {
                Text = x.ToString().Replace("_", " "), Value = ((int)x).ToString()
            }).ToList();

            ViewData["Priority"] = pList;

            ViewData["Blocking1Id"] = new SelectList(_context.Task, "Id", "Description");
            ViewData["Blocking2Id"] = new SelectList(_context.Task, "Id", "Description");
            ViewData["ChurchId"]    = new SelectList(_context.Church, "Id", "Affiliation");

            IList <SelectListItem> personList = _context.Person.OrderBy(p => p.LastName).ThenBy(p1 => p1.FirstName).Where(p => (p.SkillSets & (long)eSkillsAbbr.WRK) != 0).Select(p2 => new SelectListItem {
                Text = p2.FirstName + " " + p2.LastName, Value = p2.Id.ToString()
            }).ToList <SelectListItem>();

            personList.Insert(0, new SelectListItem(" ", "-1"));
            ViewData["PersonId"] = personList;

            IList <SelectListItem> trList = Enum.GetValues(typeof(Person.TitleRoles)).Cast <Person.TitleRoles>().Select(x => new SelectListItem {
                Text = x.ToString().Replace("_", " "), Value = ((int)x).ToString()
            }).ToList();

            ViewData["TitleRoles"] = new SelectList(trList, "Value", "Text");

            return(Page());
        }