public void UpdateEmployeeShifts_StoresByEmployeeId(int employeeId, int storeId)
        {
            //do inserts
            var insert = new EmployeeShifts_Stores()
            {
                ResourceId  = employeeId,
                WarehouseId = storeId,
            };

            _currentDbContext.EmployeeShifts_Stores.Add(insert);
            _currentDbContext.SaveChanges();
        }
Ejemplo n.º 2
0
        public ActionResult Create(ResourcesViewModel appointmentResources, List <int> JobTypeIds, List <int> RolesList1, List <int> GroupsList1)
        {
            if (!caSession.AuthoriseSession())
            {
                return(Redirect((string)Session["ErrorUrl"]));
            }

            // get properties of current tenant
            var tenant = caCurrent.CurrentTenant();

            // get properties of user
            caUser user = caCurrent.CurrentUser();

            var wareh = _activityServices.GetAllPermittedWarehousesForUser(user.UserId, user.TenantId, user.SuperUser == true, false);

            appointmentResources.TenantId = CurrentTenantId;

            if (ModelState.IsValid)
            {
                //insert contactnumber
                int contacNumbersId = _contactNumbersServices.Insert(Mapper.Map <ContactNumbers>(appointmentResources.ContactNumbers));
                appointmentResources.ContactNumbersId = contacNumbersId;

                //insert address
                int addressId = _addressServices.Insert(Mapper.Map <Address>(appointmentResources.Address));
                appointmentResources.AddressId = addressId;

                //insert employee
                appointmentResources.CreatedBy   = user.UserId;
                appointmentResources.UpdatedBy   = user.UserId;
                appointmentResources.DateCreated = DateTime.UtcNow;
                appointmentResources.DateUpdated = DateTime.UtcNow;
                appointmentResources.TenantId    = tenant.TenantId;
                int employeeId = _employeeServices.InsertEmployee(Mapper.Map <Resources>(appointmentResources));

                appointmentResources.ResourceId = employeeId;

                //insert employeeShifts_Store
                if (appointmentResources.StoresList != null)
                {
                    foreach (var item in appointmentResources.StoresList)
                    {
                        var insert = new EmployeeShifts_Stores()
                        {
                            ResourceId  = employeeId,
                            WarehouseId = item,
                        };

                        _employeeShiftsStoresServices.Insert(insert);
                    }
                }

                //insert employeeRoles
                if (RolesList1 != null)
                {
                    foreach (var item in RolesList1)
                    {
                        if (item != 0)
                        {
                            var insert = new EmployeeRoles()
                            {
                                ResourceId  = employeeId,
                                RolesId     = item,
                                TenantId    = tenant.TenantId,
                                DateCreated = DateTime.UtcNow,
                                DateUpdated = DateTime.UtcNow,
                                CreatedBy   = user.UserId,
                                UpdatedBy   = user.UserId
                            };

                            _employeeRolesServices.Insert(insert);
                        }
                    }
                }

                //insert employeeGroups
                if (GroupsList1 != null)
                {
                    foreach (var item in GroupsList1)
                    {
                        if (item != 0)
                        {
                            var insert = new EmployeeGroups()
                            {
                                ResourceId  = employeeId,
                                GroupsId    = item,
                                TenantId    = tenant.TenantId,
                                DateCreated = DateTime.UtcNow,
                                DateUpdated = DateTime.UtcNow,
                                CreatedBy   = user.UserId,
                                UpdatedBy   = user.UserId
                            };

                            _employeeGroupsServices.Insert(insert);
                        }
                    }
                }

                // insert JobType Ids
                _employeeServices.AddResourceJobTypes(Mapper.Map <Resources>(appointmentResources), JobTypeIds);

                ViewBag.Success = $"Successfully Added";

                return(RedirectToAction("Index"));
            }

            // viewbag data
            var jTypes = LookupServices.GetAllJobTypes(CurrentTenantId).Select(m => new { m.JobTypeId, m.Name }).ToList();

            ViewBag.JobTypes        = new MultiSelectList(jTypes, "JobTypeId", "Name");
            ViewBag.RolesList1      = new SelectList(_rolesServices.GetAllRoles(tenant.TenantId), "Id", "RoleName");
            ViewBag.GroupsList1     = new SelectList(_groupsServices.GetAllGroups(tenant.TenantId), "Id", "GroupName");
            ViewBag.Countries       = new SelectList(LookupServices.GetAllGlobalCountries(), "CountryID", "CountryName");
            ViewBag.TenantLocations = new MultiSelectList(_tenantLocationsServices.GetAllTenantLocations(tenant.TenantId).Where(x => wareh.Any(a => a.WId == x.WarehouseId)), "WarehouseId", "WarehouseName");
            ViewBag.Users           = new SelectList(_userService.GetAllAuthUsers(CurrentTenantId), "UserId", "UserName");
            ViewBag.Warning         = $"There is some problem with entereis, please check and try to save again";

            return(View(appointmentResources));
        }
        /// <summary>
        /// TnA device will send all Time logs and operator logs to this mwthod
        /// </summary>
        /// <returns></returns>
        public async Task <HttpResponseMessage> Post()
        {
            string req  = Request.RequestUri.AbsoluteUri; //http://localhost/iclock/cdata?sn=xxxxxx&table=ATTLOG&Stamp=12345678
            string body = await Request.Content.ReadAsStringAsync();

            var    resp           = new HttpResponseMessage(HttpStatusCode.NotFound);
            var    returnResponse = "";
            string clientIp       = HttpContext.Current.Request.UserHostAddress;
            string ServerIp       = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            var    request        = new Uri(req);

            string table = HttpUtility.ParseQueryString(request.Query).Get("table");
            string sn    = HttpUtility.ParseQueryString(request.Query).Get("sn");
            string stamp = "";

            Terminals terminal = TerminalServices.GetTerminalBySerial(sn);

            if (terminal == null)
            {
                resp = new HttpResponseMessage(HttpStatusCode.NotFound);
                return(resp);
            }
            else
            {
                switch (table.ToLower())
                {
                case "attlog":
                    stamp = HttpUtility.ParseQueryString(request.Query).Get("stamp");

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        //-----possible values (single or multiple packets sent from terminal)-----
                        //body = "1\t2017-03-02 10:48:08\t0\t15\t0\t1\n";
                        //body = "2\t2017-04-02 08:48:08\t0\t15\t0\t1\n2\t2017-04-02 12:16:08\t0\t15\t0\t1\n2\t2017-04-02 13:03:08\t0\t15\t0\t1\n2\t2017-04-02 17:00:08\t0\t15\t0\t1\n"
                        //body = "1\t2017-03-03 00:07:29\t0\t15\t0\t2\n1\t2017-03-03 00:07:31\t0\t15\t0\t2\n1\t2017-03-03 00:07:33\t0\t15\t0\t2\n1\t2017-03-02 17:09:47\t0\t15\t0\t2\n1\t2017-03-02 17:09:51\t0\t15\t0\t2\n1\t2017-03-02 17:09:53\t0\t15\t0\t2\n1\t2017-03-02 17:13:42\t0\t15\t0\t2\n1\t2017-03-02 17:13:44\t0\t15\t0\t2\n1\t2017-03-02 17:13:46\t0\t15\t0\t2\n1\t2017-03-02 17:13:48\t0\t15\t0\t2\n1\t2017-03-02 17:13:58\t0\t15\t0\t2\n1\t2017-03-02 17:14:00\t0\t15\t0\t2\n1\t2017-03-02 17:14:02\t0\t15\t0\t2\n1\t2017-03-02 17:14:11\t0\t15\t0\t2\n1\t2017-03-02 17:14:25\t0\t15\t0\t2\n1\t2017-03-02 17:14:27\t0\t15\t0\t2\n1\t2017-03-02 17:19:53\t0\t4\t0\t2\n1\t2017-03-02 17:19:56\t0\t4\t0\t2\n1\t2017-03-02 17:19:59\t0\t4\t0\t2\n1\t2017-03-02 17:21:09\t0\t15\t0\t2\n"
                        //-------------------------

                        body = body.Replace("\\t", "\t").Replace("\\n", "\n");     //do replace for Debugging purposes, b/c fiddler converts single slash into double slashes

                        char[]   delimiters = { '\n' };
                        string[] fieldValue = { };

                        fieldValue = body.Split(delimiters);

                        //loop through each timestamp
                        foreach (string item in fieldValue)
                        {
                            if (!String.IsNullOrEmpty(item))
                            {
                                char[]   itemDelimiters = { '\t' };
                                string[] itemValue      = item.Split(itemDelimiters);
                                var      userPIN        = itemValue[0];
                                DateTime dateTimeStamp  = DateTimeOffset.Parse(itemValue[1]).UtcDateTime;
                                var      ifaceStatus    = Convert.ToInt32(itemValue[2]); //Clock In, see API Docs Table4
                                var      verify         = Convert.ToInt32(itemValue[3]); //FingerPrint/Face, see API Docs Table4
                                var      eventCode      = "";

                                if (itemValue.Count() > 4)
                                {
                                    eventCode = itemValue[4];
                                }


                                //insert to db for audit purposes
                                int attLogsId = _attLogsServices.Insert(new AttLogs()
                                {
                                    UserPIN        = userPIN,
                                    Time           = dateTimeStamp,
                                    Status         = ifaceStatus,
                                    Verify         = verify,
                                    EventCode      = eventCode,
                                    DeviceSerialNo = sn
                                });

                                //--------insert to EmployeeShifts table-----------
                                CultureInfo cInfo      = CultureInfo.CurrentCulture;
                                int         weekNumber = cInfo.Calendar.GetWeekOfYear(dateTimeStamp.Date, cInfo.DateTimeFormat.CalendarWeekRule, cInfo.DateTimeFormat.FirstDayOfWeek);

                                //check if employeeId exist
                                int employeeId   = Convert.ToInt32(userPIN);
                                var employeeInfo = _employeeServices.GetByEmployeeId(Convert.ToInt32(employeeId));

                                var dupStamp = _employeeShiftsServices.SearchDuplicateStampByDateAndEmployee(Convert.ToInt32(userPIN), dateTimeStamp);

                                //go to next record if same stamp already exist
                                //add it otherwise
                                if (dupStamp != null && dupStamp.TimeStamp == dateTimeStamp)
                                {
                                    continue;
                                }

                                //count employeeId for specific date
                                var lastStamp = _employeeShiftsServices.SearchLastStampByDateAndEmployee(Convert.ToInt32(userPIN), dateTimeStamp);
                                int statusId  = 4;    //4 = Unknown, Note: see Enum "EnumStatusType" for Status reference (of statusId)


                                if (lastStamp == null || lastStamp.StatusType == "Out")
                                {
                                    statusId = 5;
                                }
                                else
                                {
                                    statusId = 6;
                                }

                                if (employeeInfo == null)
                                {
                                    statusId = 4;     //4 = unknown
                                }
                                //get shift status
                                EnumAttStatusType statusType = (EnumAttStatusType)Enum.Parse(typeof(EnumAttStatusType), statusId.ToString());

                                if (employeeInfo != null)
                                {
                                    int employeeShiftsId = _employeeShiftsServices.Insert(new ResourceShifts()
                                    {
                                        EmployeeShiftID = userPIN,
                                        ResourceId      = employeeInfo?.ResourceId,
                                        Date            = dateTimeStamp.Date,
                                        WeekNumber      = weekNumber,
                                        TimeStamp       = dateTimeStamp,
                                        StatusType      = statusType.ToString(),
                                        TerminalId      = terminal.TerminalId,
                                        DateCreated     = DateTime.UtcNow,
                                        TenantId        = terminal.TenantId
                                    });

                                    // insert into EmployeeSHifts_Stores

                                    if (!employeeInfo.EmployeeShifts_Stores.Any(x => x.WarehouseId == terminal.WarehouseId))
                                    {
                                        EmployeeShifts_Stores shift = new EmployeeShifts_Stores();
                                        shift.ResourceId  = Convert.ToInt32(userPIN);
                                        shift.WarehouseId = terminal.WarehouseId;
                                        _shiftStoreServices.Insert(shift);
                                    }
                                }
                            }
                        }

                        //---------insert to AttLogsStamps table-------
                        _attLogsStampsServices.Insert(new AttLogsStamps()
                        {
                            SStamp           = Convert.ToInt32(stamp),
                            TerminalId       = terminal.TerminalId,
                            TnALogsStampType = TnALogsStampType.OperatorLogStamp
                        });
                    }

                    //return response as OK status with message "OK"
                    resp           = new HttpResponseMessage(HttpStatusCode.OK);
                    returnResponse = "OK";
                    resp.Content   = new StringContent(returnResponse, Encoding.UTF8, "text/plain");
                    break;

                case "operlog":
                    stamp = HttpUtility.ParseQueryString(request.Query).Get("opstamp");

                    if (!String.IsNullOrWhiteSpace(body))
                    {
                        if (body.Contains("OPLOG"))
                        {
                            body = body.Replace("\\t", "\t").Replace("\\n", "\n");     //do replace for Debugging purposes, b/c fiddler converts single slash into double slashes

                            string[] fieldValue = { };
                            fieldValue = body.Split(new string[] { "OPLOG" }, StringSplitOptions.None);

                            //loop through each operation log
                            foreach (string item in fieldValue)
                            {
                                if (!String.IsNullOrEmpty(item))
                                {
                                    char[]   itemDelimiters = { '\t' };
                                    string[] itemValue      = item.Replace("\n", String.Empty).Split(itemDelimiters); //removing line ending \n then split
                                    var      operType       = itemValue[0];                                           //operation type
                                    var      adminId        = Convert.ToInt32(itemValue[1]);                          //admin id
                                    DateTime dateTimeStamp  = Convert.ToDateTime(itemValue[2]);                       //operation time
                                                                                                                      //DateTime operTime = dateTimeStamp.ToUniversalTime(); //converts to UTC
                                    int object1 = 0;
                                    int.TryParse(itemValue[3], out object1);

                                    int object2 = 0;
                                    int.TryParse(itemValue[4], out object2);

                                    int object3 = 0;
                                    int.TryParse(itemValue[5], out object3);

                                    int object4 = 0;
                                    int.TryParse(itemValue[6], out object4);

                                    //insert to db for audit purposes
                                    _operLogs.Insert(new OperLogs()
                                    {
                                        OperationType    = operType,
                                        AdminID          = Convert.ToString(adminId),
                                        OperationTime    = dateTimeStamp,
                                        OperationObject1 = object1,
                                        OperationObject2 = object2,
                                        OperationObject3 = object3,
                                        OperationObject4 = object4
                                    });
                                }
                            }
                        }

                        //---------insert to AttLogsStamps table-------
                        _attLogsStampsServices.Insert(new AttLogsStamps()
                        {
                            SStamp           = Convert.ToInt32(stamp),
                            TerminalId       = terminal.TerminalId,
                            TnALogsStampType = TnALogsStampType.OperatorLogStamp
                        });
                    }

                    //return response as OK status with message "OK"
                    resp           = new HttpResponseMessage(HttpStatusCode.OK);
                    returnResponse = "OK";
                    resp.Content   = new StringContent(returnResponse, Encoding.UTF8, "text/plain");
                    break;

                default:

                    resp           = new HttpResponseMessage(HttpStatusCode.OK);
                    returnResponse = "OK";
                    resp.Content   = new StringContent(returnResponse, Encoding.UTF8, "text/plain");
                    break;
                }

                // Create log
                TerminalLogTypeEnum logType = (TerminalLogTypeEnum)Enum.Parse(typeof(TerminalLogTypeEnum), "TnAPostStampsAndLogs");

                TerminalsLog newDeviceLog = new TerminalsLog();
                newDeviceLog.TerminalLogId   = Guid.NewGuid();
                newDeviceLog.TerminalId      = terminal.TerminalId;
                newDeviceLog.TerminalLogType = logType.ToString();
                newDeviceLog.Response        = resp.StatusCode.ToString();
                newDeviceLog.ResponseText    = returnResponse;
                newDeviceLog.DateCreated     = DateTime.UtcNow;
                newDeviceLog.clientIp        = clientIp;
                newDeviceLog.ServerIp        = ServerIp;
                newDeviceLog.TenantId        = terminal.TenantId;
                newDeviceLog.DateRequest     = DateTime.UtcNow;

                TerminalServices.SaveTerminalLog(newDeviceLog, terminal.TenantId);

                //return server response
                resp.Content = new StringContent(returnResponse, Encoding.UTF8, "text/plain");
                return(resp);
            }
        }
 public void Insert(EmployeeShifts_Stores employeeShiftsStores)
 {
     _currentDbContext.EmployeeShifts_Stores.Add(employeeShiftsStores);
     _currentDbContext.SaveChanges();
 }