Exemplo n.º 1
0
        public async Task <IHttpActionResult> UpdateDefaultAlloc(int defaultAllocId)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;

                    DefaultAllocation defaultAlloc = db.DefaultAllocations.Find(defaultAllocId);

                    defaultAlloc.Client_Id    = Convert.ToInt32(form.Get("Client"));
                    defaultAlloc.Doctor_Id    = Convert.ToInt32(form.Get("Doctor"));
                    defaultAlloc.Employee_Id  = Convert.ToInt32(form.Get("Employee"));
                    defaultAlloc.JobLevel     = form.Get("JobLevel");
                    defaultAlloc.Pages        = Convert.ToInt32(form.Get("NoOfPages"));
                    defaultAlloc.Accuracy     = Convert.ToInt32(form.Get("Accuracy"));
                    defaultAlloc.LastModified = DateTime.Now;
                    defaultAlloc.Inactive     = Convert.ToBoolean(form.Get("IsInActive"));

                    db.Entry(defaultAlloc).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();

                    return(Ok());
                }
            }

            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 2
0
        public IHttpActionResult AddDefaultAllocation()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;

                    DefaultAllocation alloc = new DefaultAllocation();
                    alloc.Client_Id    = Convert.ToInt32(form.Get("Client"));
                    alloc.Doctor_Id    = Convert.ToInt32(form.Get("Doctor"));
                    alloc.Employee_Id  = Convert.ToInt32(form.Get("Employee"));
                    alloc.JobLevel     = form.Get("JobLevel");
                    alloc.LastModified = DateTime.Now;
                    alloc.Accuracy     = Convert.ToInt32(form.Get("Accuracy"));
                    alloc.Pages        = Convert.ToInt32(form.Get("NoOfPages"));
                    alloc.Inactive     = false;

                    db.DefaultAllocations.Add(alloc);
                    db.SaveChanges();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 3
0
        public IHttpActionResult UpdateEmployeeLeave()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;

                    LeaveRecord leave = new LeaveRecord();
                    leave.EmpId     = form.Get("empId");
                    leave.LeaveDate = Convert.ToDateTime(form.Get("leaveDate"));
                    leave.UpdatedBy = User.Identity.GetUserId();
                    leave.LeaveType = form.Get("leaveType");

                    db.LeaveRecords.Add(leave);
                    db.SaveChanges();
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An errorr occured, please try again later"));
            }
        }
Exemplo n.º 4
0
        public IHttpActionResult AddEmpPayScale(int EmpId)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;

                    EmployeePayscale emp = db.EmployeePayscales.Where(x => x.Emp_Id == EmpId).FirstOrDefault();

                    //EmployeePayscale empPayScale = new EmployeePayscale();
                    emp.BankAccNo   = form.Get("AccountNumber");
                    emp.BankAccName = form.Get("AccountName");
                    emp.BankBranch  = form.Get("BranchName");
                    emp.BankName    = form.Get("BankName");
                    emp.Gross       = Convert.ToInt32(form.Get("CTC"));

                    db.Entry(emp).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occureed, please try again later"));
            }
        }
        public IHttpActionResult AddClientTicketResponse()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;

                    ActivitiesLog actLog = new ActivitiesLog();
                    actLog.AssignedBy  = User.Identity.GetUserId();
                    actLog.AssignedTo  = form.Get("assignedTo");
                    actLog.Status      = "Pending";
                    actLog.Description = form.Get("description");
                    actLog.TaskDate    = MasterDataController.GetIndianTime(DateTime.Now);
                    actLog.TaskId      = form.Get("taskId");

                    db.ActivitiesLogs.Add(actLog);
                    db.SaveChanges();
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 6
0
        public IHttpActionResult AddDocument()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form     = HttpContext.Current.Request.Form;
                    var docDate  = form.Get("DocDate");
                    var files    = HttpContext.Current.Request.Files;
                    var Document = files["Documents"];

                    var fileExtension   = Path.GetExtension(Document.FileName);
                    var validExtensions = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".doc", ".docx", ".pdf", ".txt", ".xls", ".xlsx" };
                    if (!validExtensions.Contains(fileExtension))
                    {
                        return(Content(HttpStatusCode.InternalServerError, "Invalid file type for detailed estimate!!"));
                    }

                    Document doc = new Document();

                    if (!string.IsNullOrEmpty(docDate))
                    {
                        doc.DocumentDate = DateTime.Parse(docDate);
                    }
                    doc.Category = form.Get("Category");

                    doc.Notes = form.Get("Notes");

                    doc.Keywords    = form.Get("KeyWords");
                    doc.UploadDate  = DateTime.Now;
                    doc.Employee_Id = Convert.ToInt32(form.Get("EmployeeId"));

                    var fileDirecory = HttpContext.Current.Server.MapPath("~/Employees/Document");
                    if (!Directory.Exists(fileDirecory))
                    {
                        Directory.CreateDirectory(fileDirecory);
                    }
                    var fileName = DateTime.Now.Ticks + "_" + Document.FileName;
                    var filepath = Path.Combine(fileDirecory, fileName);
                    Document.SaveAs(filepath);
                    doc.DocumentURL = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "Employee", "Documents", fileName);

                    db.Documents.Add(doc);
                    db.SaveChanges();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 7
0
        public IHttpActionResult UpdateItemModel(int id)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;

                    ItemsMaster im = db.ItemsMasters.Find(id);
                    im.Brand        = form.Get("Brand");
                    im.ModelNumber  = form.Get("ModelNumber");
                    im.ItemName     = form.Get("ItemName");
                    im.HSNCode      = form.Get("HsnCode");
                    im.UPC          = form.Get("Upc");
                    im.EAN          = form.Get("Ean");
                    im.Description  = form.Get("Description");
                    im.ItemContents = form.Get("Contents");
                    im.MadeIn       = Convert.ToInt32(form.Get("Country"));
                    im.Manufacturer = form.Get("Manufacturer");
                    // im.PowerInput = Convert.ToInt32(form.Get("PowerInput"));
                    int?powerUnit = im.PowerInput;
                    if (form.Get("PowerInput") != "")
                    {
                        im.PowerInput      = Convert.ToInt32(form.Get("PowerInput"));
                        im.PowerInputUnits = form.Get("PowerUnits");
                    }
                    else
                    {
                        im.PowerInput      = null;
                        im.PowerInputUnits = null;
                    }

                    im.ThresholdQuantity = Convert.ToInt32(form.Get("ThresholdValue"));
                    im.UpdatedBy         = User.Identity.GetUserId();
                    im.LastUpdated       = MasterDataController.GetIndianTime(DateTime.Now);
                    im.Units             = form.Get("Units");
                    im.GST             = Convert.ToDecimal(form.Get("Gst")) / 2;
                    im.CGST            = Convert.ToDecimal(form.Get("Gst")) / 2;
                    im.SrlNoExists     = Convert.ToBoolean(form.Get("SrlNoExits"));
                    db.Entry(im).State = EntityState.Modified;
                    db.SaveChanges();

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 8
0
        public IHttpActionResult LogLocationData(object myObject)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var root     = JObject.Parse(myObject.ToString()).First.First;
                    var location = JsonConvert.DeserializeObject <LocationInfo>(root.ToString());
                    if (db.EmployeeAttendanceLogs.Any(x => x.Emp_Id == location.EmployeeId && location.Time == x.Time))
                    {
                        return(Ok());
                    }
                    string Address = null;
                    try
                    {
                        string      latlon = location.Latitude + "," + location.Longitude;
                        XmlDocument xDoc   = new XmlDocument();
                        xDoc.Load("https://maps.googleapis.com/maps/api/geocode/xml?latlng=" + latlon + "&key=AIzaSyCPbyemMRyuWmR7yiD-nIwXaaeZaw-jK9o");
                        XmlNodeList xNodelst = xDoc.GetElementsByTagName("result");
                        XmlNode     xNode    = xNodelst.Item(0);
                        Address = xNode.SelectSingleNode("formatted_address").InnerText;
                    }
                    catch
                    {
                    }

                    EmployeeAttendanceLog eal = new EmployeeAttendanceLog()
                    {
                        Emp_Id       = location.EmployeeId,
                        Latitude     = location.Latitude,
                        Longitude    = location.Longitude,
                        IsClockIn    = location.IsClockIn,
                        IsClockOut   = location.IsClockOut,
                        Time         = MasterDataController.GetIndianTime(location.Time),
                        Address      = Address,
                        InsertedTime = MasterDataController.GetIndianTime(DateTime.UtcNow)
                    };
                    db.EmployeeAttendanceLogs.Add(eal);
                    db.SaveChanges();

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
        public IHttpActionResult AddCategory()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form          = HttpContext.Current.Request.Form;
                    var subCategories = JsonConvert.DeserializeObject <List <SubCat> >(form.Get("subCategories")).ToList();

                    Category category = new Category();
                    category.Dept_Id = Convert.ToInt32(form.Get("deptId"));
                    category.Name    = form.Get("category");

                    if (subCategories.Count() > 0)
                    {
                        foreach (var subCat in subCategories)
                        {
                            SubCategory subCategory = new SubCategory();
                            PointsLog   pointslog   = new PointsLog();

                            subCategory.Name   = subCat.Name;
                            subCategory.Points = subCat.Points;

                            pointslog.Points   = subCat.Points;
                            pointslog.FromDate = DateTime.Now;

                            category.SubCategories.Add(subCategory);
                            subCategory.PointsLogs.Add(pointslog);
                        }
                    }
                    db.Categories.Add(category);
                    db.SaveChanges();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 10
0
 public void logAPIError(string Method, string Message, string StackTrace)
 {
     try
     {
         using (MaxMasterDbEntities db = new MaxMasterDbEntities())
         {
             ExceptionLog el = new ExceptionLog();
             el.Method     = Method;
             el.Message    = Message;
             el.StackTrace = StackTrace;
             el.Time       = DateTime.Now;
             db.ExceptionLogs.Add(el);
             db.SaveChanges();
         }
         return;
     }
     catch (Exception ex)
     {
         return;
     }
 }
Exemplo n.º 11
0
        public IHttpActionResult AddDoctorGroup()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form      = HttpContext.Current.Request.Form;
                    var groupName = form.Get("GroupName");

                    DoctorGroup docGroup = new DoctorGroup();
                    docGroup.Name = groupName;
                    db.DoctorGroups.Add(docGroup);
                    db.SaveChanges();
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
        public IHttpActionResult EditOpportunity(int oppId)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var         form         = HttpContext.Current.Request.Form;
                    var         assingedTo   = form.Get("assignee");
                    var         status       = form.Get("status");
                    var         followupDate = form.Get("followupon");
                    Opportunity opportunity  = db.Opportunities.Where(x => x.Id == oppId).FirstOrDefault();

                    var userId = User.Identity.GetUserId();
                    //  int UserId = db.Employees.Where(x => x.AspNetUserId == userId).FirstOrDefault().Id;
                    opportunity.Status        = status;
                    opportunity.LastUpdated   = MasterDataController.GetIndianTime(DateTime.Now);
                    opportunity.LastUpdatedBy = User.Identity.GetUserId();
                    if (followupDate != "")
                    {
                        opportunity.FollowUpOn = Convert.ToDateTime(form.Get("followupon"));
                    }
                    OpportunitiesLog oppLog = new OpportunitiesLog();

                    if (assingedTo != null)
                    {
                        oppLog.AssignedTo     = (assingedTo);
                        opportunity.TaskOwner = (assingedTo);
                    }
                    else
                    {
                        oppLog.AssignedTo = opportunity.TaskOwner;
                    }

                    oppLog.CreatedDate   = MasterDataController.GetIndianTime(DateTime.UtcNow);
                    oppLog.OpportunityId = oppId;
                    oppLog.Status        = form.Get("status");
                    oppLog.CreatedBy     = User.Identity.GetUserId();
                    oppLog.Comments      = form.Get("Comments");

                    if (oppLog.Status == "Accepted")
                    {
                        opportunity.EDOC = DateTime.Parse(form.Get("edoc"));
                        opportunity.EDOS = DateTime.Parse(form.Get("edos"));
                    }
                    else if (oppLog.Status == "Completed")
                    {
                        opportunity.ActualCompletedDate = Convert.ToDateTime(form.Get("completedDate"));
                    }

                    var files           = HttpContext.Current.Request.Files;
                    var fileAttachments = new List <HttpPostedFile>();

                    if (files.Count > 0)
                    {
                        for (int i = 0; i < files.Count; i++)
                        {
                            fileAttachments.Add(files[i]);
                        }
                        foreach (var file in fileAttachments)
                        {
                            var fileDirecory = HttpContext.Current.Server.MapPath("~/CommentAttachments");

                            if (!Directory.Exists(fileDirecory))
                            {
                                Directory.CreateDirectory(fileDirecory);
                            }

                            var fileName = file.FileName;
                            var filePath = Path.Combine(fileDirecory, fileName);
                            file.SaveAs(filePath);

                            OpportunityAttachment attachment = new OpportunityAttachment();

                            attachment.FileName       = Path.GetFileNameWithoutExtension(file.FileName);
                            attachment.FileAttachment = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "CommentAttachments", fileName);
                            oppLog.OpportunityAttachments.Add(attachment);
                        }
                    }

                    // opportunity.OpportunitiesLogs.Add(oppLog);
                    db.OpportunitiesLogs.Add(oppLog);
                    db.Entry(opportunity).State = System.Data.Entity.EntityState.Modified;

                    db.SaveChanges();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 13
0
        public async Task <IHttpActionResult> AddEmployee()
        {
            try
            {
                /* get data from form */
                var form              = HttpContext.Current.Request.Form;
                var email             = form.Get("Email");
                var firstName         = form.Get("FirstName");
                var role              = form.Get("RoleId");
                var doj               = form.Get("DOJ");
                var provisionalPeriod = form.Get("ProvisionalPeriod");
                var managerId         = form.Get("Manager");

                /* Register to AspNet Users */

                UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));

                var user1 = userManager.FindByEmail(email);
                if (user1 != null)
                {
                    return(Content(HttpStatusCode.InternalServerError, "User with email " + email + " already exists"));
                }

                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var roleName = db.AspNetRoles.Where(x => x.Id == role).FirstOrDefault().Name;

                    Employee emp = new Employee();
                    emp.FirstName      = firstName;
                    emp.MiddleName     = form.Get("MiddleName");
                    emp.LastName       = form.Get("LastName");
                    emp.Email          = form.Get("Email");
                    emp.PrimaryPhone   = form.Get("PrimaryNum");
                    emp.SecondaryPhone = form.Get("SecondaryNum");
                    emp.Gender         = form.Get("Gender");
                    emp.DOB            = DateTime.Parse(form.Get("DOB"));
                    emp.BloodGroup     = form.Get("BloodGroup");
                    emp.Aadhar         = form.Get("Aadhar");
                    emp.PAN            = form.Get("Pan");
                    emp.AddressLine1   = form.Get("AddressLine1");
                    emp.AddressLine2   = form.Get("AddressLine2");
                    emp.Country_Id     = Convert.ToInt32(form.Get("CountryId"));
                    emp.State_Id       = Convert.ToInt32(form.Get("StateId"));
                    emp.City_Id        = Convert.ToInt32(form.Get("CityId"));
                    emp.ZIP            = form.Get("Zip");
                    emp.Role_Id        = (form.Get("RoleId"));
                    emp.Department_Id  = Convert.ToInt32(form.Get("DepartmentId"));
                    emp.Designation_Id = Convert.ToInt32(form.Get("DesignationId"));
                    emp.OrgId          = Convert.ToInt32(form.Get("OrgId"));
                    emp.Shift_Id       = Convert.ToInt32(form.Get("Shift"));

                    if (provisionalPeriod != "")
                    {
                        emp.ProvisionalPeriod = Convert.ToByte(provisionalPeriod);
                    }
                    else
                    {
                        emp.ProvisionalPeriod = 0;
                    }

                    if (!string.IsNullOrEmpty(managerId))
                    {
                        emp.Manager_Id = Convert.ToInt32(form.Get("Manager"));
                    }

                    emp.EmploymentType = form.Get("EmpType");

                    if (!string.IsNullOrEmpty(doj))
                    {
                        emp.DOJ = DateTime.Parse(form.Get("DOJ"));
                    }

                    emp.UpdatedBy   = User.Identity.GetUserId();
                    emp.LastUpdated = DateTime.Now;
                    emp.Active      = true;

                    var prefix = db.Organisations.Where(x => x.Id == emp.OrgId).FirstOrDefault().EmpPrefix;

                    if (emp.EmploymentType == "Consultant")
                    {
                        int Count = db.Employees.Where(x => x.EmploymentType == "Consultant" && x.OrgId == emp.OrgId).Count();

                        if (Count > 0)
                        {
                            var LastEmployeeNumber = db.Employees.Where(x => x.EmploymentType == "Consultant" && x.OrgId == emp.OrgId).OrderByDescending(x => x.LastUpdated).FirstOrDefault().EmployeeNumber;
                            if (LastEmployeeNumber != null)
                            {
                                int count = Convert.ToInt32(LastEmployeeNumber.Split('V')[1]);
GenerateNewNumber:
                                var employeeNumber = prefix + "V" + (count + 1).ToString("00");
                                var empExists  = db.Employees.Where(x => x.EmployeeNumber == employeeNumber).FirstOrDefault();
                                var userexists = await _userManager.FindByNameAsync(employeeNumber);

                                if (empExists != null || userexists != null)
                                {
                                    count++;
                                    goto GenerateNewNumber;
                                }
                                emp.EmployeeNumber = employeeNumber;
                            }
                        }
                        else
                        {
                            emp.EmployeeNumber = prefix + "V01";
                        }
                    }
                    if (emp.EmploymentType == "Permanent")
                    {
                        int Count = db.Employees.Where(x => x.EmploymentType == "Permanent" && x.OrgId == emp.OrgId).Count();

                        if (Count > 0)
                        {
                            var LastEmployeeNumber = db.Employees.Where(x => x.EmploymentType == "Permanent" && x.OrgId == emp.OrgId).OrderByDescending(x => x.EmployeeNumber).FirstOrDefault().EmployeeNumber;
                            if (LastEmployeeNumber != null)
                            {
                                int count = Convert.ToInt32(LastEmployeeNumber.Split('-')[1]);
GenerateNewNumber:
                                var employeeNumber = prefix + (count + 1).ToString("000");
                                if (db.Employees.Any(x => x.EmployeeNumber == employeeNumber))
                                {
                                    count++;
                                    goto GenerateNewNumber;
                                }
                                emp.EmployeeNumber = employeeNumber;
                            }
                        }

                        else
                        {
                            emp.EmployeeNumber = prefix + "001";
                        }
                    }

                    var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                    if (file != null && file.ContentLength > 0)
                    {
                        var fileDirectory = HttpContext.Current.Server.MapPath("~/Employee_Images");
                        if (!Directory.Exists(fileDirectory))
                        {
                            Directory.CreateDirectory(fileDirectory);
                        }

                        var physicalPath = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], emp.EmployeeNumber + Path.GetExtension(file.FileName));
                        file.SaveAs(physicalPath);
                        var path = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "Employee_Images", emp.EmployeeNumber + Path.GetExtension(file.FileName));
                        emp.PhotoURL = path;
                    }
                    string organisation = db.Organisations.Where(x => x.Id == emp.OrgId).FirstOrDefault().OrgName;
                    bool   UserCreated  = new UserController().CreateUser(emp.EmployeeNumber, email, roleName, organisation);
                    var    user         = userManager.FindByEmail(email);

                    if (user != null)
                    {
                        emp.AspNetUserId = user.Id;
                    }
                    db.Employees.Add(emp);

                    EmployeePayscale empPayScale = new EmployeePayscale();
                    empPayScale.Gross  = 0;
                    empPayScale.Emp_Id = emp.Id;

                    db.EmployeePayscales.Add(empPayScale);
                    db.SaveChanges();

                    return(Ok());
                }
            }

            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occoured, please try again!"));
            }
        }
Exemplo n.º 14
0
        public async Task <IHttpActionResult> UpdateEmployee(int EmpId)
        {
            try
            {
                _userManager.UserValidator = new UserValidator <ApplicationUser>(_userManager)
                {
                    AllowOnlyAlphanumericUserNames = false
                };

                var form              = HttpContext.Current.Request.Form;
                var firstName         = form.Get("FirstName");
                var role              = form.Get("RoleId");
                var oldMail           = form.Get("OldEmail");
                var newMail           = form.Get("Email");
                var managerId         = form.Get("Manager");
                var provisionalPeriod = form.Get("ProvisionalPeriod");
                var doj = form.Get("DOJ");
                var dor = form.Get("DOR");

                /* Register to AspNet Users */

                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var      roleName = db.AspNetRoles.Where(x => x.Id == (role)).FirstOrDefault().Name;
                    Employee emp      = await db.Employees.FindAsync(EmpId);

                    /* remove existing user from AspNetUserRoles table and add the new role to the user */
                    var userName = _userManager.FindByEmail(oldMail);
                    var userId   = userName.Id;
                    var roles    = await _userManager.GetRolesAsync(userId);

                    if (userName != null)
                    {
                        var result = await _userManager.RemoveFromRolesAsync(userId, roles.ToArray());

                        var addToRole = await _userManager.AddToRoleAsync(userId, roleName);
                    }

                    /* update AspNetUser with new mail if edited */

                    if (oldMail.ToLower() != newMail.ToLower())
                    {
                        var exists = await _userManager.FindByEmailAsync(newMail);

                        if (exists != null)
                        {
                            return(Content(HttpStatusCode.InternalServerError, "User with email " + newMail + " already exists"));
                        }

                        var res = await _userManager.SetEmailAsync(userId, newMail);
                    }

                    emp.FirstName      = firstName;
                    emp.MiddleName     = form.Get("MiddleName");
                    emp.LastName       = form.Get("LastName");
                    emp.Email          = form.Get("Email");
                    emp.PrimaryPhone   = form.Get("PrimaryNum");
                    emp.SecondaryPhone = form.Get("SecondaryNum");
                    emp.Gender         = form.Get("Gender");
                    emp.DOB            = DateTime.Parse(form.Get("DOB"));
                    emp.BloodGroup     = form.Get("BloodGroup");
                    emp.Aadhar         = form.Get("Aadhar");
                    emp.PAN            = form.Get("Pan");
                    emp.AddressLine1   = form.Get("AddressLine1");
                    emp.AddressLine2   = form.Get("AddressLine2");
                    emp.Country_Id     = Convert.ToInt32(form.Get("CountryId"));
                    emp.State_Id       = Convert.ToInt32(form.Get("StateId"));
                    emp.City_Id        = Convert.ToInt32(form.Get("CityId"));
                    emp.ZIP            = form.Get("Zip");
                    emp.Role_Id        = (form.Get("RoleId"));
                    emp.Department_Id  = Convert.ToInt32(form.Get("DepartmentId"));
                    emp.Designation_Id = Convert.ToInt32(form.Get("DesignationId"));
                    emp.OrgId          = Convert.ToInt32(form.Get("OrgId"));
                    emp.Shift_Id       = Convert.ToInt32(form.Get("Shift"));

                    if (!string.IsNullOrEmpty(managerId))
                    {
                        emp.Manager_Id = Convert.ToInt32(form.Get("Manager"));
                    }

                    emp.EmploymentType = form.Get("EmpType");
                    // emp.DOJ = DateTime.Parse(form.Get("DOJ"));
                    if (!string.IsNullOrEmpty(doj))
                    {
                        emp.DOJ = DateTime.Parse(form.Get("DOJ"));
                    }
                    if (!string.IsNullOrEmpty(dor))
                    {
                        emp.DOR    = DateTime.Parse(form.Get("DOR"));
                        emp.Active = false;
                    }

                    emp.UpdatedBy   = User.Identity.GetUserId();
                    emp.LastUpdated = DateTime.Now;

                    if (provisionalPeriod != "")
                    {
                        emp.ProvisionalPeriod = Convert.ToByte(provisionalPeriod);
                    }
                    else
                    {
                        emp.ProvisionalPeriod = 0;
                    }

                    var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;
                    if (file != null && file.ContentLength > 0)
                    {
                        var fileDirectory = HttpContext.Current.Server.MapPath("~/Employee_Images");
                        if (!Directory.Exists(fileDirectory))
                        {
                            Directory.CreateDirectory(fileDirectory);
                        }

                        var filename     = emp.EmployeeNumber + file.FileName;
                        var physicalPath = Path.Combine(fileDirectory, filename);

                        file.SaveAs(physicalPath);

                        var path = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "Employee_Images", filename);
                        emp.PhotoURL = path;
                    }


                    db.Entry(emp).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occoured, please try again!"));
            }
        }
Exemplo n.º 15
0
        public async Task <IHttpActionResult> UpdateClient()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form            = HttpContext.Current.Request.Form;
                    var id              = form.Get("ClientId");
                    var clientLocations = JsonConvert.DeserializeObject <List <ClientLocationModel> >(form.Get("ClientLocations"));
                    var verticals       = JsonConvert.DeserializeObject <List <ClientVerticalsModel> >(form.Get("ClientVerticals"));
                    var oldMail         = form.Get("OldEmail");
                    var email           = form.Get("Email");
                    var count           = 0;
                    var currency        = form.Get("Currency");
                    var paymentType     = form.Get("PaymentType");
                    var paymentAmount   = form.Get("PaymentAmount");
                    var gst             = form.Get("gst");
                    var pan             = form.Get("pan");
                    var creditPeriod    = form.Get("creditPeriod");

                    //locationId

                    Client client = db.Clients.Find(Convert.ToInt32(id));

                    if (oldMail.ToLower() != email.ToLower())
                    {
                        var userName = _userManager.FindByEmail(oldMail);
                        var userId   = userName.Id;

                        var exists = _userManager.FindByEmailAsync(email);
                        if (exists != null)
                        {
                            //   return Content(HttpStatusCode.InternalServerError, "User with email " + email + "already exists");
                        }

                        var res = await _userManager.SetEmailAsync(userId, email);
                    }

                    if (client == null)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "Invalid Data"));
                    }

                    var clientVerticalList = client.ClientVerticals.ToList();

                    if (clientVerticalList.Count > 0)
                    {
                        foreach (var vertical in client.ClientVerticals.ToList())
                        {
                            client.ClientVerticals.Remove(vertical);
                        }
                    }

                    client.Name           = form.Get("Name");
                    client.ShortName      = form.Get("ShortName");
                    client.Email          = form.Get("Email");
                    client.PrimaryPhone   = form.Get("PrimaryPhone");
                    client.SecondaryPhone = form.Get("SecondaryPhone");
                    client.Fax            = form.Get("Fax");
                    client.ClientType     = form.Get("ClientType");
                    client.Active         = Convert.ToBoolean(form.Get("IsActive"));
                    client.OrgId          = Convert.ToInt32(form.Get("Organisation"));
                    client.ClientStatus   = form.Get("ClientStatus");

                    for (int i = 0; i < verticals.Count(); i++)
                    {
                        var clientVertical = await db.ClientVerticals.FindAsync(verticals[i].value);

                        client.ClientVerticals.Add(clientVertical);
                    }

                    for (int i = 0; i < clientLocations.Count; i++)
                    {
                        var loc = clientLocations[i].LocationId;

                        if (loc != null)
                        {
                            var clientLoc = db.ClientLocations.Find(clientLocations[i].LocationId);
                            clientLoc.AddressLine1     = clientLocations[i].AddressLine1;
                            clientLoc.AddressLine2     = clientLocations[i].AddressLine2;
                            clientLoc.Landmark         = clientLocations[i].Landmark;
                            clientLoc.Country_Id       = clientLocations[i].Country;
                            clientLoc.State_Id         = clientLocations[i].State;
                            clientLoc.City_Id          = clientLocations[i].City;
                            clientLoc.ZIP              = clientLocations[i].zip;
                            clientLoc.TimeZone_Id      = clientLocations[i].TimeZone;
                            clientLoc.IsInvoiceAddress = clientLocations[i].IsInvoice;

                            //if (clientLoc.Country_Id == 101)
                            //{
                            //    count++;
                            //}

                            db.Entry(clientLoc).State = System.Data.Entity.EntityState.Modified;
                        }
                        else
                        {
                            ClientLocation clientloc = new ClientLocation();
                            clientloc.AddressLine1     = clientLocations[i].AddressLine1;
                            clientloc.AddressLine2     = clientLocations[i].AddressLine2;
                            clientloc.Landmark         = clientLocations[i].Landmark;
                            clientloc.Country_Id       = clientLocations[i].Country;
                            clientloc.State_Id         = clientLocations[i].State;
                            clientloc.City_Id          = clientLocations[i].City;
                            clientloc.ZIP              = clientLocations[i].zip;
                            clientloc.TimeZone_Id      = clientLocations[i].TimeZone;
                            clientloc.IsInvoiceAddress = clientLocations[i].IsInvoice;
                            client.ClientLocations.Add(clientloc);
                            db.SaveChanges();
                        }
                    }

                    if (form.Get("ClientType") == "Supplier")
                    {
                        client.AccountName   = form.Get("accountName");
                        client.AccountNumber = form.Get("accountNumber");
                        client.BankName      = form.Get("bankName");
                        client.BranchName    = form.Get("branchName");
                        client.IFSCCode      = form.Get("ifscCode");
                    }

                    if (gst != null)
                    {
                        client.GST = gst;
                    }

                    else
                    {
                        client.GST = null;
                    }

                    if (pan != null)
                    {
                        client.PAN = pan;
                    }
                    if (creditPeriod != "")
                    {
                        client.CreditPeriod = Convert.ToInt32(form.Get("creditPeriod"));
                    }

                    else
                    {
                        client.GST          = null;
                        client.PAN          = null;
                        client.CreditPeriod = null;
                    }

                    if (client.ClientType != "Supplier" && client.ClientType != "Vendor")
                    {
                        if (paymentType != null)
                        {
                            client.PaymentType = form.Get("PaymentType");
                        }
                        else
                        {
                            client.PaymentType = null;
                        }

                        var Amount = (form.Get("PaymentAmount"));
                        if (Amount != "")
                        {
                            client.PaymentAmount = Convert.ToDecimal(form.Get("PaymentAmount"));
                        }
                        else
                        {
                            client.PaymentAmount = null;
                        }

                        if (currency != null)
                        {
                            client.Currency = form.Get("Currency");
                        }
                        else
                        {
                            client.Currency = null;
                        }
                    }
                    else
                    {
                        client.PaymentType   = null;
                        client.Currency      = null;
                        client.PaymentAmount = null;
                    }

                    db.Entry(client).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, Please try again later"));
            }
        }
Exemplo n.º 16
0
        public IHttpActionResult EditStockRequest(int StockId)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form                     = HttpContext.Current.Request.Form;
                    var ItemsRequired            = JsonConvert.DeserializeObject <List <BilledItemsModel> >(form.Get("items"));
                    var status                   = form.Get("status");
                    var task                     = form.Get("taskId");
                    var previouslyRequestedItems = db.StockRequestMappings.Where(x => x.StockReqId == StockId).ToList();
                    /* Get the stock through id */
                    StockRequest stockRequest = db.StockRequests.Find(StockId);

                    stockRequest.Client            = form.Get("Client");
                    stockRequest.ExpectedStockDate = Convert.ToDateTime(form.Get("expectedDate"));
                    stockRequest.Project           = Convert.ToInt32(form.Get("project"));
                    stockRequest.Status            = form.Get("status");
                    stockRequest.Notes             = form.Get("notes");
                    stockRequest.LastUpdated       = DateTime.Now;
                    stockRequest.UpdatedBy         = User.Identity.GetUserId();

                    /* Find task with the taskid  */
                    Activity      activity    = db.Activities.Find(task);
                    ActivitiesLog activityLog = new ActivitiesLog();

                    if (status.ToUpper() == "UNDER REVIEW")
                    {
                        foreach (var item in previouslyRequestedItems)
                        {
                            db.StockRequestMappings.Remove(item);
                            db.SaveChanges();
                        }

                        /* Add requested items to stock */
                        for (int i = 0; i < ItemsRequired.Count(); i++)
                        {
                            StockRequestMapping srm = new StockRequestMapping();
                            srm.ItemId    = ItemsRequired[i].ModelId;
                            srm.Quanitity = ItemsRequired[i].Quantity;

                            stockRequest.StockRequestMappings.Add(srm);
                        }

                        activity.CreatedBy       = User.Identity.GetUserId();
                        db.Entry(activity).State = System.Data.Entity.EntityState.Modified;
                    }

                    else if (status == "Approved")
                    {
                        /* Get Stock Manager and assign activity to manager from super admin */
                        var stockManager = db.StockManagers.Where(x => x.IsActive == true).FirstOrDefault();

                        foreach (var item in previouslyRequestedItems)
                        {
                            db.StockRequestMappings.Remove(item);
                            db.SaveChanges();
                        }

                        /* Add requested items to stock */
                        for (int i = 0; i < ItemsRequired.Count(); i++)
                        {
                            StockRequestMapping srm = new StockRequestMapping();
                            srm.ItemId    = ItemsRequired[i].ModelId;
                            srm.Quanitity = ItemsRequired[i].Quantity;

                            stockRequest.StockRequestMappings.Add(srm);
                        }

                        for (int j = 0; j < ItemsRequired.Count(); j++)
                        {
                            int quantity = ItemsRequired[j].Quantity;
                            int modelId  = ItemsRequired[j].ModelId;

                            /* Get items with model id based on manufactured date */

                            var itemsAvailable = db.Items.Where(x => x.ItemModelId == modelId && x.IsAvailable == true).OrderBy(x => x.StockInDate).ToList();
                            if (itemsAvailable.Count() >= ItemsRequired[j].Quantity)
                            {
                                for (int k = 0; k < ItemsRequired[j].Quantity; k++)
                                {
                                    Item item = db.Items.Find(itemsAvailable[k].Id);

                                    item.ProjectId   = Convert.ToInt32(form.Get("project"));
                                    item.IsAvailable = false;

                                    db.Entry(item).State = System.Data.Entity.EntityState.Modified;
                                }
                            }
                        }

                        if (stockManager != null)
                        {
                            activity.Status    = "Pending";
                            activity.TaskOwner = stockManager.AspNetUserId;

                            activityLog.TaskDate    = DateTime.Now;
                            activityLog.AssignedBy  = User.Identity.GetUserId();
                            activityLog.AssignedTo  = stockManager.AspNetUserId;
                            activityLog.Description = "Items for the project is approved. Dispatch stock as early as possible";
                            activityLog.Status      = "Pending";

                            activity.ActivitiesLogs.Add(activityLog);
                            db.Entry(activity).State = System.Data.Entity.EntityState.Modified;
                        }
                    }

                    else if (status == "Declined")
                    {
                        activity.Status    = "Resolved";
                        activity.TaskOwner = stockRequest.Employee;

                        activityLog.TaskDate    = DateTime.Now;
                        activityLog.AssignedBy  = User.Identity.GetUserId();
                        activityLog.AssignedTo  = activity.CreatedBy;
                        activityLog.Status      = "Resolved";
                        activityLog.Description = "Your request for stock is declined";

                        activity.ActivitiesLogs.Add(activityLog);
                        db.Entry(activity).State = System.Data.Entity.EntityState.Modified;
                    }

                    else if (status == "Dispatched")
                    {
                        for (int j = 0; j < ItemsRequired.Count(); j++)
                        {
                            int quantity = ItemsRequired[j].Quantity;
                            int modelId  = ItemsRequired[j].ModelId;
                            var stock    = db.Items.Where(x => x.IsAvailable == false && x.StockOutDate == null).OrderBy(x => x.StockInDate).ToList();
                            if (stock.Count() >= ItemsRequired[j].Quantity)
                            {
                                for (int k = 0; k < ItemsRequired[j].Quantity; k++)
                                {
                                    Item item = db.Items.Find(stock[k].Id);

                                    item.ProjectId    = Convert.ToInt32(form.Get("project"));
                                    item.IsAvailable  = false;
                                    item.StockOutDate = DateTime.Now;

                                    db.Entry(item).State = System.Data.Entity.EntityState.Modified;
                                }

                                activity.TaskOwner = activity.CreatedBy;
                                activity.Status    = "Resolved";

                                activityLog.TaskDate    = DateTime.Now;
                                activityLog.AssignedBy  = User.Identity.GetUserId();
                                activityLog.AssignedTo  = activity.CreatedBy;
                                activityLog.Status      = "Resolved";
                                activityLog.Description = "Your items were dispatched successfully ";
                                activityLog.HoursWorked = Convert.ToInt32(form.Get("hoursWorked"));

                                activity.ActivitiesLogs.Add(activityLog);
                                db.Entry(activity).State = System.Data.Entity.EntityState.Modified;
                            }
                            else
                            {
                                stockRequest.Status = form.Get("status");
                                return(Content(HttpStatusCode.InternalServerError, "Requested stock is not available to dispatch"));
                            }
                        }
                    }

                    db.Entry(stockRequest).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 17
0
        public IHttpActionResult UpdateBill(int billId)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form            = HttpContext.Current.Request.Form;
                    var BilledItemsList = JsonConvert.DeserializeObject <List <BilledItemsModel> >(form.Get("items"));

                    Bill bill = db.Bills.Find(billId);

                    bill.BillDate   = Convert.ToDateTime(form.Get("billDate"));
                    bill.BillNumber = form.Get("billNum");
                    bill.PoNumber   = form.Get("poNum");
                    if (form.Get("paymentTerms") != null)
                    {
                        bill.PaymentTerms = form.Get("paymentTerms");
                    }

                    bill.Notes      = form.Get("notes");
                    bill.SupplierId = (form.Get("supplierId"));
                    if (form.Get("dueDate") != "")
                    {
                        bill.DueDate = Convert.ToDateTime(form.Get("dueDate"));
                    }

                    bill.Subtotal = Convert.ToDecimal(form.Get("subtotal"));
                    var tds = form.Get("tdsId");
                    if (tds != null)
                    {
                        bill.TDSAmount = Convert.ToDecimal(form.Get("tdsAmount"));
                        bill.TDSId     = Convert.ToInt32(form.Get("tdsId"));
                    }
                    else
                    {
                        bill.TDSId     = null;
                        bill.TDSAmount = null;
                    }
                    bill.Total = Convert.ToDecimal(form.Get("total"));

                    //if (form.Get("taxAmount") != "")
                    //{
                    //    bill.TotalTaxAmount = Convert.ToDecimal(form.Get("taxAmount"));
                    //}
                    //else
                    //{
                    //    bill.TotalTaxAmount = null;
                    //}

                    if (form.Get("discountAmount") != "")
                    {
                        bill.Discount = Convert.ToDecimal(form.Get("discountAmount"));
                    }
                    else
                    {
                        bill.Discount = null;
                    }
                    if (form.Get("discountType") != null)
                    {
                        bill.DiscountType = form.Get("discountType");
                    }
                    else
                    {
                        bill.DiscountType = null;
                    }

                    if (form.Get("courierCharges") != "")
                    {
                        bill.CourierCharges = Convert.ToDecimal(form.Get("courierCharges"));
                    }
                    else
                    {
                        bill.CourierCharges = null;
                    }
                    if (form.Get("roundOffNumber") != "")
                    {
                        bill.RoundOffNumber = Convert.ToDecimal(form.Get("roundOffNumber"));
                    }
                    else
                    {
                        bill.RoundOffNumber = null;
                    }

                    bill.BalanceDue = Convert.ToDecimal(form.Get("total"));
                    if (DateTime.Now < bill.DueDate)
                    {
                        bill.Status = "Due";
                    }
                    else
                    {
                        bill.Status = "OverDue";
                    }


                    var files           = HttpContext.Current.Request.Files;
                    var fileAttachments = new List <HttpPostedFile>();
                    if (files.Count > 0)
                    {
                        for (int i = 0; i < files.Count; i++)
                        {
                            fileAttachments.Add(files[i]);
                        }

                        foreach (var file in fileAttachments)
                        {
                            var fileDirecory = HttpContext.Current.Server.MapPath("~/BillAttachments");

                            if (!Directory.Exists(fileDirecory))
                            {
                                Directory.CreateDirectory(fileDirecory);
                            }

                            var fileName = file.FileName;
                            var filePath = Path.Combine(fileDirecory, fileName);
                            file.SaveAs(filePath);

                            BillAttachment Billatt = new BillAttachment();
                            Billatt.FileName      = Path.GetFileNameWithoutExtension(file.FileName);
                            Billatt.AttachmentUrl = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "BillAttachments", fileName);

                            bill.BillAttachments.Add(Billatt);
                        }
                    }

                    // update items list

                    var previouslyBilledItems = db.ItemsBillMappings.Where(x => x.BillId == bill.Id).ToList();

                    for (int i = 0; i < previouslyBilledItems.Count(); i++)
                    {
                        ItemsBillMapping item = db.ItemsBillMappings.Find(previouslyBilledItems[i].Id);
                        db.ItemsBillMappings.Remove(item);
                        //  db.SaveChanges();
                    }

                    for (int i = 0; i < BilledItemsList.Count(); i++)
                    {
                        ItemsBillMapping ibm = new ItemsBillMapping();
                        ibm.ModelId      = BilledItemsList[i].ModelId;
                        ibm.PricePerUnit = Convert.ToDecimal(BilledItemsList[i].Price);
                        ibm.Quantity     = BilledItemsList[i].Quantity;
                        ibm.GST          = Convert.ToDecimal(BilledItemsList[i].Tax) / 2;
                        ibm.CGST         = Convert.ToDecimal(BilledItemsList[i].Tax) / 2;
                        ibm.Description  = BilledItemsList[i].Description;

                        bill.ItemsBillMappings.Add(ibm);

                        //   db.ItemsBillMappings.Add(ibm);
                    }
                    db.Entry(bill).State = EntityState.Modified;
                    db.SaveChanges();
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 18
0
        //public IHttpActionResult GetClientWithAspNetUserId(string clientId)
        //{
        //    try
        //    {
        //        using (MaxMasterDbEntities db = new MaxMasterDbEntities())
        //        {
        //            var client = db.Clients.Where(x => x.AspNetUserId == clientId).Select(x => new { value = x.AspNetUserId, label = x.ShortName }).FirstOrDefault();
        //            return Content(HttpStatusCode.OK, new { client });
        //        }
        //    }
        //    catch(Exception ex)
        //    {
        //        return Content(HttpStatusCode.InternalServerError, "An error occured, please try again later");
        //    }
        //}

        public async Task <IHttpActionResult> AddClientWithPwd()
        {
            try
            {
                UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form            = HttpContext.Current.Request.Form;
                    var clientLocations = JsonConvert.DeserializeObject <List <ClientLocationModel> >(form.Get("ClientLocations"));
                    var email           = form.Get("Email");
                    var password        = form.Get("password");
                    var userName        = form.Get("userName");

                    var user1 = userManager.FindByEmail(email);
                    if (user1 != null)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "User with email " + email + " already exists"));
                    }

                    var exsistingUser = await _userManager.FindByNameAsync(userName);

                    if (exsistingUser != null)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "User with user name " + userName + " already exists"));
                    }

                    Client client = new Client();

                    client.OrgId        = Convert.ToInt32(form.Get("Organisation"));
                    client.Name         = form.Get("Name");
                    client.ShortName    = form.Get("ShortName");
                    client.Email        = email;
                    client.PrimaryPhone = form.Get("PrimaryPhone");

                    for (int i = 0; i < clientLocations.Count; i++)
                    {
                        ClientLocation clientloc = new ClientLocation();
                        clientloc.AddressLine1     = clientLocations[i].AddressLine1;
                        clientloc.AddressLine2     = clientLocations[i].AddressLine2;
                        clientloc.Landmark         = clientLocations[i].Landmark;
                        clientloc.Country_Id       = clientLocations[i].Country;
                        clientloc.State_Id         = clientLocations[i].State;
                        clientloc.City_Id          = clientLocations[i].City;
                        clientloc.ZIP              = clientLocations[i].zip;
                        clientloc.TimeZone_Id      = clientLocations[i].TimeZone;
                        clientloc.IsInvoiceAddress = clientLocations[i].IsInvoice;
                        clientloc.Client_Id        = client.Id;

                        client.ClientLocations.Add(clientloc);
                    }

                    ApplicationUser user = new ApplicationUser()
                    {
                        UserName = userName, Email = email
                    };

                    _userManager.UserValidator = new UserValidator <ApplicationUser>(_userManager)
                    {
                        AllowOnlyAlphanumericUserNames = false,
                        RequireUniqueEmail             = true
                    };
                    IdentityResult result = _userManager.Create(user, password);

                    if (!result.Succeeded)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
                    }

                    var roleStore   = new RoleStore <IdentityRole>(appDb);
                    var roleManager = new RoleManager <IdentityRole>(roleStore);

                    _userManager.AddToRole(user.Id, "Client");

                    string to      = email;
                    string subject = "Welcome to Max Trans Systems";
                    string body    = "Hi,Welcome to Max Trans Systems. Following are the credentials for your account" +
                                     Environment.NewLine + "Username : "******"Password : "******"*****@*****.**";

                    var sendMail = new EmailController().SendEmail(from, "Max", email, subject, body);

                    client.AspNetUserId = user.Id;
                    client.Active       = true;
                    client.LastUpdated  = DateTime.Now;
                    client.UpdatedBy    = User.Identity.GetUserId();
                    client.ClientType   = "Direct Client";

                    db.Clients.Add(client);
                    db.SaveChanges();
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occoured, please try again!"));
            }
        }
Exemplo n.º 19
0
        public bool AddChildTask(Activity activity, Assignee assignee, List <ActivityLog> parentLog)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var u    = User.Identity.GetUserId();
                    var user = db.Employees.Where(x => x.AspNetUserId == u).FirstOrDefault();

                    Activity      task        = new Activity();
                    ActivitiesLog activityLog = new ActivitiesLog();

                    task.AssignedTo     = assignee.AssigneeId;
                    task.Category_Id    = activity.Category_Id;
                    task.SubCategory_Id = activity.SubCategory_Id;
                    if (assignee.Quantity != null)
                    {
                        task.Subject = activity.Subject + " Quanity - " + assignee.Quantity;
                    }
                    else
                    {
                        task.Subject = activity.Subject;
                    }

                    task.TaskOwner     = assignee.AssigneeId;
                    task.Description   = activity.Description;
                    task.EDOC          = Convert.ToDateTime(activity.EDOC);
                    task.Status        = "Open";
                    task.TaskType      = activity.TaskType;
                    task.Client_Id     = activity.Client_Id;
                    task.Project_Id    = activity.Project_Id;
                    task.Priority      = activity.Priority;
                    task.CreatedBy     = User.Identity.GetUserId();
                    task.CreatedDate   = MasterDataController.GetIndianTime(DateTime.UtcNow);
                    task.ParentTask_Id = activity.TaskId;
                    if (assignee.Quantity != null)
                    {
                        task.Quantity = assignee.Quantity;
                    }
                    //else
                    //{
                    //    task.Quantity = null;
                    //}

                    task.TaskId = GenerateTaskId();

                    db.Activities.Add(task);
                    if (parentLog.Count() > 0)
                    {
                        for (int i = 0; i < parentLog.Count(); i++)
                        {
                            ActivitiesLog Log = new ActivitiesLog();

                            Log.Status         = parentLog[i].Status;
                            Log.Description    = parentLog[i].Description;
                            Log.TaskDate       = Convert.ToDateTime(parentLog[i].TaskDate);
                            Log.AssignedBy     = parentLog[i].AssignedById;
                            Log.AssignedTo     = parentLog[i].AssignedToId;
                            Log.HoursWorked    = parentLog[i].HoursWorked;
                            Log.QuantityWorked = parentLog[i].QuantityWorked;

                            task.ActivitiesLogs.Add(Log);
                        }
                    }

                    activityLog.Status      = task.Status;
                    activityLog.Description = task.Description;
                    activityLog.TaskDate    = MasterDataController.GetIndianTime(DateTime.UtcNow);
                    activityLog.AssignedBy  = task.CreatedBy;
                    activityLog.AssignedTo  = assignee.AssigneeId;
                    activityLog.TaskId      = activity.TaskId;

                    task.ActivitiesLogs.Add(activityLog);
                    db.SaveChanges();
                }
                return(true);
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(false);
            }
        }
        public IHttpActionResult EditCategory()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form          = HttpContext.Current.Request.Form;
                    int catId         = Convert.ToInt32(form.Get("catId"));
                    var subCategories = JsonConvert.DeserializeObject <List <NewSubCategory> >(form.Get("subCategories")).ToList();
                    var category      = db.Categories.Find(catId);

                    foreach (var subCategory in subCategories)
                    {
                        SubCategory subCat    = new SubCategory();
                        PointsLog   pointsLog = new PointsLog();

                        if (subCategory.SubCategoryId != null)
                        {
                            var subcat = db.SubCategories.Find(subCategory.SubCategoryId);
                            if (subcat.Points != subCategory.Points)
                            {
                                subcat.Points = subCategory.Points;
                                var subcatPointsLog = db.PointsLogs.Find(subCategory.PointsLogId);

                                if (subcatPointsLog != null)
                                {
                                    subcatPointsLog.ToDate          = MasterDataController.GetIndianTime(DateTime.Now);
                                    db.Entry(subcatPointsLog).State = System.Data.Entity.EntityState.Modified;
                                }
                                pointsLog.FromDate = MasterDataController.GetIndianTime(DateTime.Now);
                                pointsLog.Points   = subCategory.Points;
                                subcat.PointsLogs.Add(pointsLog);
                                db.Entry(subcat).State = System.Data.Entity.EntityState.Modified;
                            }
                            else
                            {
                                subcat.Name            = subCategory.Name;
                                subcat.Points          = subCategory.Points;
                                db.Entry(subcat).State = System.Data.Entity.EntityState.Modified;
                            }
                        }
                        else
                        {
                            subCat.Name   = subCategory.Name;
                            subCat.Points = subCategory.Points;

                            pointsLog.Points   = subCategory.Points;
                            pointsLog.FromDate = MasterDataController.GetIndianTime(DateTime.Now);

                            category.SubCategories.Add(subCat);
                            subCat.PointsLogs.Add(pointsLog);
                        }
                    }
                    db.SaveChanges();
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 21
0
        public async Task <IHttpActionResult> UpdateDoctor(int doctor_Id)
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form         = HttpContext.Current.Request.Form;
                    var specialities = JsonConvert.DeserializeObject <List <keyValueModel> >(form.Get("specialities"));
                    var newMail      = form.Get("email");
                    var oldMail      = form.Get("OldMail");
                    var macropercent = form.Get("macroPercent");

                    if (newMail.ToLower() != oldMail.ToLower())
                    {
                        var userName = _userManager.FindByEmail(oldMail);
                        var userId   = userName.Id;

                        var exists = await _userManager.FindByEmailAsync(newMail);

                        if (exists != null)
                        {
                            return(Content(HttpStatusCode.InternalServerError, "User with email " + newMail + " already exists"));
                        }

                        var res = await _userManager.SetEmailAsync(userId, newMail);
                    }

                    Doctor doc = db.Doctors.Find(Convert.ToInt32(doctor_Id));

                    doc.Salutation       = form.Get("salutation");
                    doc.FirstName        = form.Get("firstName");
                    doc.MiddleName       = form.Get("middleName");
                    doc.LastName         = form.Get("lastName");
                    doc.Email            = newMail;
                    doc.PrimaryPhone     = form.Get("primaryPhoneNum");
                    doc.SecondaryPhone   = form.Get("secondaryPhoneNum");
                    doc.Client_Id        = Convert.ToInt32(form.Get("clientId"));
                    doc.AddressLine1     = form.Get("addressLine1");
                    doc.AddressLine2     = form.Get("addressLin2");
                    doc.Country_Id       = Convert.ToInt32(form.Get("countryId"));
                    doc.State_Id         = Convert.ToInt32(form.Get("stateId"));
                    doc.City_Id          = Convert.ToInt32(form.Get("cityId"));
                    doc.ZIP              = form.Get("zip");
                    doc.IdigitalId       = form.Get("idigitalId");
                    doc.IdigitalAuthorId = form.Get("idigitalAuthId");
                    doc.JobLevel         = form.Get("jobLevel");
                    doc.DictationMode    = form.Get("dictationMode");
                    if (macropercent != "")
                    {
                        doc.MacroPercent = Convert.ToByte(form.Get("macroPercent"));
                    }
                    else
                    {
                        doc.MacroPercent = 0;
                    }

                    doc.VoiceGrade     = form.Get("voiceGrade");
                    doc.DoctorGroup_Id = Convert.ToInt32(form.Get("doctorGroup"));
                    doc.Active         = true;
                    doc.LastUpdated    = DateTime.Now;
                    doc.UpdatedBy      = User.Identity.GetUserId();
                    doc.Active         = Convert.ToBoolean(form.Get("IsActive"));


                    /* Remove previous specialities of this doctor */
                    foreach (var speciality in doc.Specialties.ToList())
                    {
                        doc.Specialties.Remove(speciality);
                    }

                    /* Iterate through the list of specialitites and insert into doctorSpecialities table */
                    for (int i = 0; i < specialities.Count; i++)
                    {
                        var speciality = await db.Specialties.FindAsync(specialities[i].value);

                        if (speciality == null)
                        {
                            continue;
                        }
                        doc.Specialties.Add(speciality);
                    }

                    db.Entry(doc).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
        public IHttpActionResult AddOpportunity()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;
                    var opportunityCategories = JsonConvert.DeserializeObject <List <keyValueModel> >(form.Get("Categories"));

                    Opportunity opp = new Opportunity();
                    opp.Client_Id   = form.Get("client");
                    opp.CreatedDate = MasterDataController.GetIndianTime(DateTime.UtcNow);
                    opp.CreatedBy   = User.Identity.GetUserId();

                    if (form.Get("assignTo") != null)
                    {
                        opp.TaskOwner  = form.Get("assignTo");
                        opp.AssignedTo = form.Get("assignTo");
                    }
                    else
                    {
                        opp.TaskOwner  = User.Identity.GetUserId();
                        opp.AssignedTo = User.Identity.GetUserId();
                    }

                    opp.OpportunityName = form.Get("opportunity");
                    opp.RefferedBy      = form.Get("refferedBy");
                    opp.Org_Id          = Convert.ToInt32(form.Get("orgId"));
                    opp.Status          = form.Get("Status");

                    opp.Description = form.Get("comments");
                    opp.Location_Id = Convert.ToInt32(form.Get("Location"));

                    if (opp.Status == "Accepted")
                    {
                        opp.EDOC = DateTime.Parse(form.Get("edoc"));
                        opp.EDOS = DateTime.Parse(form.Get("edos"));
                    }
                    else if (opp.Status == "Completed")
                    {
                        opp.ActualCompletedDate = Convert.ToDateTime(form.Get("CompletedDate"));
                    }
                    db.Opportunities.Add(opp);

                    for (int i = 0; i < opportunityCategories.Count; i++)
                    {
                        OpportunityCategoryMapping oppCat = new OpportunityCategoryMapping();
                        oppCat.Category_Id = Convert.ToInt32(opportunityCategories[i].value);

                        opp.OpportunityCategoryMappings.Add(oppCat);
                    }

                    if (form.Get("contactPersons") != null)
                    {
                        var checkedContacts = JsonConvert.DeserializeObject <List <string> >(form.Get("contactPersons"));
                        for (int j = 0; j < checkedContacts.Count; j++)
                        {
                            OpportunityContactMapping oppContact = new OpportunityContactMapping();
                            oppContact.Contact_Id = Convert.ToInt32(checkedContacts[j]);

                            opp.OpportunityContactMappings.Add(oppContact);
                        }
                    }

                    OpportunitiesLog oppLog = new OpportunitiesLog();

                    oppLog.CreatedBy   = User.Identity.GetUserId();
                    oppLog.CreatedDate = MasterDataController.GetIndianTime(DateTime.UtcNow);
                    oppLog.AssignedTo  = opp.TaskOwner;
                    oppLog.Status      = form.Get("Status");
                    oppLog.Comments    = form.Get("comments");

                    opp.OpportunitiesLogs.Add(oppLog);

                    var files           = HttpContext.Current.Request.Files;
                    var fileAttachments = new List <HttpPostedFile>();

                    for (int i = 0; i < files.Count; i++)
                    {
                        fileAttachments.Add(files[i]);
                    }
                    foreach (var file in fileAttachments)
                    {
                        var fileDirecory = HttpContext.Current.Server.MapPath("~/CommentAttachments");

                        if (!Directory.Exists(fileDirecory))
                        {
                            Directory.CreateDirectory(fileDirecory);
                        }

                        var fileName = file.FileName;
                        var filePath = Path.Combine(fileDirecory, fileName);
                        file.SaveAs(filePath);

                        OpportunityAttachment attachment = new OpportunityAttachment();

                        attachment.FileName       = Path.GetFileNameWithoutExtension(file.FileName);
                        attachment.FileAttachment = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "CommentAttachments", fileName);
                        oppLog.OpportunityAttachments.Add(attachment);
                    }
                    db.Opportunities.Add(opp);
                    db.SaveChanges();
                }

                return(Ok());
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured , please try again later"));
            }
        }
Exemplo n.º 23
0
        public async Task <IHttpActionResult> AddDoctor()
        {
            try
            {
                var form         = HttpContext.Current.Request.Form;
                var specialities = JsonConvert.DeserializeObject <List <keyValueModel> >(form.Get("specialities"));
                var email        = form.Get("email");
                var doctorGroup  = form.Get("doctorGroup");
                var macropercent = form.Get("macroPercent");

                UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));

                var user1 = userManager.FindByEmail(email);
                if (user1 != null)
                {
                    return(Content(HttpStatusCode.InternalServerError, "User with email " + email + " already exists"));
                }

                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    /* Get the values from form and add to database thorugh Entity Framework */

                    Doctor doc = new Doctor();

                    doc.Salutation       = form.Get("salutation");
                    doc.FirstName        = form.Get("firstName");
                    doc.MiddleName       = form.Get("middleName");
                    doc.LastName         = form.Get("lastName");
                    doc.Email            = form.Get("email");
                    doc.PrimaryPhone     = form.Get("primaryPhoneNum");
                    doc.SecondaryPhone   = form.Get("secondaryPhoneNum");
                    doc.Client_Id        = Convert.ToInt32(form.Get("clientId"));
                    doc.AddressLine1     = form.Get("addressLine1");
                    doc.AddressLine2     = form.Get("addressLin2");
                    doc.Country_Id       = Convert.ToInt32(form.Get("countryId"));
                    doc.State_Id         = Convert.ToInt32(form.Get("stateId"));
                    doc.City_Id          = Convert.ToInt32(form.Get("cityId"));
                    doc.ZIP              = form.Get("zip");
                    doc.IdigitalId       = form.Get("idigitalId");
                    doc.IdigitalAuthorId = form.Get("idigitalAuthId");
                    doc.JobLevel         = form.Get("jobLevel");
                    doc.DictationMode    = form.Get("dictationMode");

                    if (macropercent != "")
                    {
                        doc.MacroPercent = Convert.ToByte(form.Get("macroPercent"));
                    }
                    else
                    {
                        doc.MacroPercent = 0;
                    }

                    doc.VoiceGrade = form.Get("voiceGrade");
                    if (doctorGroup != null)
                    {
                        doc.DoctorGroup_Id = Convert.ToInt32(form.Get("doctorGroup"));
                    }

                    doc.Active      = true;
                    doc.LastUpdated = DateTime.Now;
                    doc.UpdatedBy   = User.Identity.GetUserId();

                    /* Iterate through the list of specialitites and insert into doctorSpecialities table */
                    for (int i = 0; i < specialities.Count; i++)
                    {
                        var speciality = await db.Specialties.FindAsync(specialities[i].value);

                        if (speciality == null)
                        {
                            continue;
                        }
                        doc.Specialties.Add(speciality);
                    }

                    var idigitalAuthIdExists = db.Doctors.Where(x => x.IdigitalAuthorId == doc.IdigitalAuthorId).FirstOrDefault();
                    if (idigitalAuthIdExists != null)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "User with IDigital AuthorId already exists"));
                    }
                    int    orgId        = db.Clients.Where(x => x.Id == doc.Client_Id).FirstOrDefault().OrgId;
                    string organisation = db.Organisations.Where(x => x.Id == orgId).FirstOrDefault().OrgName;
                    var    userCreated  = new UserController().CreateUser(email, email, "Doctor", organisation);
                    var    user         = userManager.FindByEmail(email);

                    if (user != null)
                    {
                        doc.AspNetUserId = user.Id;
                    }

                    if (userCreated)
                    {
                        db.Doctors.Add(doc);
                        db.SaveChanges();
                        return(Ok());
                    }
                    else
                    {
                        return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
                    }
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
        public IHttpActionResult AddOrganisation()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;
                    var OrganisationLocations = JsonConvert.DeserializeObject <List <ViewModels.OrganisationLocation> >(form.Get("OrgLocations"));

                    Organisation org = new Organisation();
                    org.OrgName        = form.Get("orgName");
                    org.WebSite        = form.Get("website");
                    org.Email          = form.Get("Email");
                    org.PrimaryPhone   = form.Get("primaryPhoneNum");
                    org.SecondaryPhone = form.Get("secondaryPhoneNum");
                    org.EmpPrefix      = form.Get("empPrefix").ToUpper();
                    org.PAN            = form.Get("pan");
                    org.GST            = form.Get("gst");
                    org.TIN            = form.Get("tin");
                    org.UpdatedBy      = User.Identity.GetUserId();
                    org.LastUpdated    = MasterDataController.GetIndianTime(DateTime.Now);

                    var EmpPrefixExists = db.Organisations.Where(x => x.EmpPrefix == org.EmpPrefix).FirstOrDefault();

                    if (EmpPrefixExists != null)
                    {
                        return(Content(HttpStatusCode.InternalServerError, "Organisation with the same employee prefix already exists "));
                    }

                    var file = HttpContext.Current.Request.Files;

                    if (file.Count > 0)
                    {
                        var image         = file["OrgLogo"];
                        var fileExtension = Path.GetExtension(image.FileName);

                        var fileDirecory = HttpContext.Current.Server.MapPath("~/OrgLogos");
                        if (!Directory.Exists(fileDirecory))
                        {
                            Directory.CreateDirectory(fileDirecory);
                        }
                        var fileName = DateTime.Now.Ticks + "_" + image.FileName;
                        var filepath = Path.Combine(fileDirecory, fileName);
                        image.SaveAs(filepath);
                        org.Logo = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "OrgLogos", fileName);
                    }

                    for (int i = 0; i < OrganisationLocations.Count(); i++)
                    {
                        OrgansationLocation orgLoc = new OrgansationLocation();

                        orgLoc.AddressLine1 = OrganisationLocations[i].AddressLine1;
                        orgLoc.AddressLine2 = OrganisationLocations[i].AddressLine2;
                        orgLoc.CountryId    = Convert.ToInt32(OrganisationLocations[i].Country);
                        orgLoc.StateId      = OrganisationLocations[i].State;
                        orgLoc.CityId       = OrganisationLocations[i].City;
                        orgLoc.ZIP          = OrganisationLocations[i].ZIP;

                        org.OrgansationLocations.Add(orgLoc);
                    }

                    db.Organisations.Add(org);
                    db.SaveChanges();
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 25
0
        public IHttpActionResult AddItem()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;

                    var items     = JsonConvert.DeserializeObject <List <ItemModel> >(form.Get("items"));
                    var warrenty  = form.Get("warrenty");
                    var serialNum = form.Get("serialNumberExists");

                    for (int i = 0; i < items.Count; i++)
                    {
                        Item item;
                        if (items[i].Id == "")
                        {
                            item = new Item();
                        }
                        else
                        {
                            int itemId = Convert.ToInt32(items[i].Id);
                            var it     = db.Items.Where(x => x.Id == itemId).FirstOrDefault();
                            item = it;
                        }

                        item.ItemModelId     = Convert.ToInt32(form.Get("modelNo"));
                        item.BatchNumber     = form.Get("batchNumber");
                        item.StockLocationId = Convert.ToInt32(form.Get("stockLocation"));
                        item.StockInDate     = Convert.ToDateTime(form.Get("stockInDate"));
                        item.CostPrice       = Convert.ToDecimal(form.Get("cp"));
                        item.MinimumSP       = Convert.ToDecimal(form.Get("minSp"));
                        item.MRP             = Convert.ToDecimal(form.Get("mrp"));
                        item.PONumber        = form.Get("poNumber");
                        item.HardwareVersion = form.Get("hardwareVersion");
                        item.SellingPrice    = Convert.ToDecimal(form.Get("sp"));
                        item.SupplierId      = form.Get("supplierId");

                        item.MACAddress          = items[i].MacAddress;
                        item.StockReceiverUserId = User.Identity.GetUserId();
                        item.UpdatedBy           = User.Identity.GetUserId();
                        if (items[i].ManufacturedDate != null)
                        {
                            item.ManufacturedDate = Convert.ToDateTime(items[i].ManufacturedDate);
                        }

                        item.LastUpdated = DateTime.Now;
                        item.IsAvailable = true;
                        item.BillNumber  = form.Get("billNumber");

                        if (serialNum == "true")
                        {
                            item.SerialNumber = items[i].SerialNo;
                        }
                        else
                        {
                            if (items[i].SerialNo == "")
                            {
                                item.SerialNumber = GenerateRandomNumber(5);
                            }
                            else
                            {
                                item.SerialNumber = items[i].SerialNo;
                            }
                        }

                        decimal itemTaxRate = Convert.ToDecimal(form.Get("gst"));

                        item.GST  = Convert.ToDecimal(itemTaxRate / 2);
                        item.CGST = Convert.ToDecimal(itemTaxRate / 2);

                        if (warrenty != null)
                        {
                            int duration = Convert.ToInt32(form.Get("warrenty"));
                            var type     = form.Get("warrentyDuration");
                            item.Warrenty       = duration;
                            item.WarrentyPeriod = form.Get("warrentyDuration");
                        }

                        var itemPrice = db.ItemPrices.Where(x => x.ItemModelId == item.ItemModelId && x.ToDate == null).FirstOrDefault();

                        if (itemPrice != null)
                        {
                            if (item.SellingPrice != itemPrice.SellingPrice)
                            {
                                itemPrice.ToDate          = DateTime.Now;
                                db.Entry(itemPrice).State = EntityState.Modified;

                                ItemPrice ip = new ItemPrice();

                                ip.ItemModelId  = item.ItemModelId;
                                ip.FromDate     = DateTime.Now;
                                ip.SellingPrice = item.SellingPrice;
                                ip.DealerPrice  = item.CostPrice;

                                db.ItemPrices.Add(ip);
                            }
                        }
                        else
                        {
                            ItemPrice ip = new ItemPrice();
                            ip.FromDate     = DateTime.Now;
                            ip.SellingPrice = item.SellingPrice;
                            ip.ItemModelId  = item.ItemModelId;
                            ip.DealerPrice  = item.CostPrice;
                            db.ItemPrices.Add(ip);
                        }

                        if (items[i].Id == "")
                        {
                            db.Items.Add(item);
                        }
                        else
                        {
                            db.Entry(item).State = EntityState.Modified;
                        }

                        db.SaveChanges();
                    }

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
        public IHttpActionResult AddClientRequest()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form         = HttpContext.Current.Request.Form;
                    var clientId     = form.Get("clientId");
                    var departmentId = form.Get("departmentId");
                    int orgId        = Convert.ToInt32(form.Get("OrgId"));
                    var categoryId   = form.Get("categoryId");
                    var u            = User.Identity.GetUserId();

                    Activity activity = new Activity();

                    var user      = db.Clients.Where(x => x.AspNetUserId == u && x.Active == true).FirstOrDefault();
                    var createdby = user.Id;

                    var clientOrg = user.OrgId;

                    var emp = db.Employees.Where(x => x.Role_Id == "8").FirstOrDefault();
                    if (emp != null)
                    {
                        activity.AssignedTo = emp.AspNetUserId;
                        activity.TaskOwner  = emp.AspNetUserId;
                    }

                    activity.CreatedBy  = User.Identity.GetUserId();
                    activity.TaskType   = "Client";
                    activity.Client_Id  = user.AspNetUserId;
                    activity.Project_Id = Convert.ToInt32(form.Get("projectId"));
                    activity.EDOC       = DateTime.Now.AddDays(2);

                    activity.TaskId = RandomString(4, orgId, createdby, true);
                    db.Activities.Add(activity);

                    ActivitiesLog activityLog = new ActivitiesLog();

                    activityLog.Status      = activity.Status;
                    activityLog.Description = activity.Description;
                    activityLog.TaskDate    = MasterDataController.GetIndianTime(DateTime.UtcNow);
                    activityLog.AssignedBy  = activity.CreatedBy;
                    activityLog.AssignedTo  = activity.TaskOwner;

                    activity.ActivitiesLogs.Add(activityLog);

                    var files = HttpContext.Current.Request.Files;

                    var fileAttachments = new List <HttpPostedFile>();

                    for (int i = 0; i < files.Count; i++)
                    {
                        fileAttachments.Add(files[i]);
                    }

                    foreach (var file in fileAttachments)
                    {
                        var fileDirecory = HttpContext.Current.Server.MapPath("~/Task");

                        if (!Directory.Exists(fileDirecory))
                        {
                            Directory.CreateDirectory(fileDirecory);
                        }

                        var fileName = file.FileName;
                        var filePath = Path.Combine(fileDirecory, fileName);
                        file.SaveAs(filePath);

                        ActivityAttachment actAttachments = new ActivityAttachment();

                        actAttachments.AttachmentURL = Path.Combine(ConfigurationManager.AppSettings["ApiUrl"], "Task", fileName);
                        actAttachments.Name          = Path.GetFileNameWithoutExtension(file.FileName);
                        activityLog.ActivityAttachments.Add(actAttachments);
                    }


                    var    from   = "";
                    var    to     = "";
                    string name   = "";
                    var    taskId = activity.TaskId;

                    var client = db.Clients.Where(x => x.AspNetUserId == activity.CreatedBy && x.Active == true).FirstOrDefault();
                    to   = client.Email;
                    name = client.Name;


                    var empl = db.Employees.Where(x => x.AspNetUserId == activity.AssignedTo && x.Active == true).FirstOrDefault();
                    to   = empl.Email;
                    name = empl.FirstName + " " + empl.LastName;

                    string subject = "You have created a new ticket with ticket Id #" + taskId;

                    var body = @"<div style=""border: 1px solid gray;margin-top:2px; margin-right: 2px;padding: 9px;"" > 
                                     <p> Dear " + name + ", </p>" +
                               "<p> Greetings! Thank you for contacting our support team. We received your request in our system and we have started working on priority.</p>" +
                               "<p> We will approach you soon if we require any further details to probe and expedite on the issue. Please allow us some time to give you an update on the progress on resolution.Your patience till then is much appreciated.</p> " +
                               "<p> We encourage you to kindly use our support portal http://ourclientSupport.azurewebsites.net for reporting issues/Service Requests with support team or to seek any further updates on your ticket. </p>" +
                               "<p> If you are experiencing any delays or for any further assistance you are feel free to contact on below numbers:</p>" +
                               "<p> CUSTOMER SERVICE: 9 66 67 24 365 </p>" +
                               " </div>";
                    bool sendmail = new EmailController().SendEmail(from, "Task Management System", to, subject, body);

                    db.SaveChanges();
                }
                return(Ok());
            }
            catch (Exception ex)
            {
                return(Content(System.Net.HttpStatusCode.InternalServerError, "An error occured please try again later"));
            }
        }
        public IHttpActionResult AddInvoice()
        {
            try
            {
                var form = HttpContext.Current.Request.Form;
                var clientAddress = form.Get("ClientAddress");
                var dueAmount = form.Get("UnpaidBalance");
                var month = form.Get("InvoiceMonth");
                var clientToAddress = form.Get("ClientToAddress");

                if (dueAmount == "null")
                {
                    dueAmount = 0.ToString();
                }
                var CurrentAmount = form.Get("CurrentAmount");
                var serviceId = form.Get("ClientService");
                var createdBy = form.Get("CreatedBy");
                var invoiceSer = JsonConvert.DeserializeObject<List<string>>(form.Get("InvoiceServices"));

                using (MaxMasterDbEntities db = new MaxMasterDbEntities())

                {
                    Invoice inData = new Invoice();
                    InvoiceService inService = new InvoiceService();

                    inData.Client_Id = Convert.ToInt32(form.Get("Client_Id"));
                    inData.Id = form.Get("InvoiceId"); ;
                    inData.CompanyAddress = form.Get("CompanyAddress");
                    inData.ClientAddress = clientAddress;
                    inData.InvoiceCreatedBy = (from Emp in db.Employees where Emp.EmployeeNumber == createdBy select Emp.Id).FirstOrDefault();
                    inData.InvoiceCreatedDate = DateTime.Now;
                    inData.InvoiceMonth = month;
                    inData.InvoiceYear = Convert.ToInt32(form.Get("invoiceYear"));

                    string currency = (from client in db.Clients where client.Id == inData.Client_Id select client.Currency).FirstOrDefault();
                    inData.CurrencyType = currency;

                    inData.CurrentBillAmount = Convert.ToDecimal(CurrentAmount);
                    inData.TotalDueAmount = Convert.ToDecimal(dueAmount);
                    var totalInvoice = Convert.ToDecimal(CurrentAmount) + Convert.ToDecimal(dueAmount);
                    inData.TotalInvoiceAmount = Convert.ToDecimal(totalInvoice);
                    inData.Status = "Generated";

                    foreach (string id in invoiceSer)
                    {
                        string unitprice = (from client in db.Clients where client.Id == inData.Client_Id select client.PaymentAmount).FirstOrDefault().ToString();
                        inService.InvoiceId = inData.Id;
                        inService.ClientId = Convert.ToInt32(form.Get("Client_Id"));
                        inService.ServiceId = Convert.ToInt32(serviceId);
                        inService.UnitPrice = Convert.ToDecimal(form.Get("UnitPrice"));
                        inService.TotalLines = Convert.ToInt32(form.Get("TotalLines"));
                        inService.BillAmount = Convert.ToDecimal(CurrentAmount);
                        inService.DueAmount = inService.BillAmount;
                    }
                    db.Invoices.Add(inData);
                    db.InvoiceServices.Add(inService);
                    db.SaveChanges();
                }
                return Ok();
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return InternalServerError();
            }
        }
        public IHttpActionResult FeedBackFromClient()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form = HttpContext.Current.Request.Form;

                    var    ticketId = form.Get("TicketId");
                    string status   = form.Get("Status");

                    Activity      activity = db.Activities.Where(x => x.TaskId == ticketId).FirstOrDefault();
                    ActivitiesLog actLog   = new ActivitiesLog();
                    if (activity != null)
                    {
                        if (status == "true")
                        {
                            activity.Status        = "Closed";
                            activity.CompletedDate = MasterDataController.GetIndianTime(DateTime.Now);

                            actLog.TaskDate    = MasterDataController.GetIndianTime(DateTime.Now);
                            actLog.TaskId      = ticketId;
                            actLog.AssignedBy  = activity.TaskOwner;
                            actLog.AssignedTo  = activity.CreatedBy;
                            actLog.Status      = "Closed by assignee";
                            actLog.Description = "Satisfactory";

                            db.ActivitiesLogs.Add(actLog);
                            db.Entry(activity).State = System.Data.Entity.EntityState.Modified;

                            var taskCreator = db.Employees.Where(x => x.AspNetUserId == activity.CreatedBy && x.Active == true).FirstOrDefault();

                            db.SaveChanges();
                        }

                        else
                        {
                            if (activity.Status == "Resolved")
                            {
                                activity.Status        = "Reopened";
                                activity.CompletedDate = null;

                                var lastWorked = db.ActivitiesLogs.Where(x => x.TaskId == ticketId).OrderByDescending(x => x.TaskDate).FirstOrDefault();

                                activity.Status        = "Reopened";
                                activity.TaskOwner     = lastWorked.AssignedBy;
                                activity.CompletedDate = null;

                                actLog.TaskDate    = MasterDataController.GetIndianTime(DateTime.Now);
                                actLog.TaskId      = ticketId;
                                actLog.AssignedTo  = lastWorked.AssignedBy;
                                actLog.AssignedBy  = User.Identity.GetUserId();
                                actLog.Status      = "Reopened";
                                actLog.Description = "Ticket Reopened ";

                                db.ActivitiesLogs.Add(actLog);
                                db.Entry(activity).State = System.Data.Entity.EntityState.Modified;

                                var taskCreator = db.Employees.Where(x => x.AspNetUserId == activity.CreatedBy && x.Active == true).FirstOrDefault();

                                if (taskCreator != null)
                                {
                                }
                                else
                                {
                                    var Client = db.Clients.Where(x => x.AspNetUserId == activity.CreatedBy).FirstOrDefault();
                                    if (Client != null)
                                    {
                                        string subject = "Your Ticket Id #" + activity.TaskId + " ( " + activity.Subject + " ) is reopened. ";
                                        string from    = "";
                                        string to      = Client.Email;
                                        var    body    = @"<div style=""border: 1px solid gray;margin-top:2px; margin-right: 2px;padding: 9px;"" > 
                                     <p> Dear " + Client.Name + ", </p>" +
                                                         "<p> your ticket with Id " + activity.TaskId + " ( " + activity.Subject + " ) is reopened and the support team will contact you soon.  " + "</p>" +
                                                         "<p> We encourage you to kindly use our support portal http://ourclientSupport.azurewebsites.net for reporting issues/Service Requests with support team or to seek any further updates on your ticket. </p>" +
                                                         "<p> CUSTOMER SERVICE: 9 66 67 24 635 </p>" +
                                                         " </div>";
                                        bool sendEmail = new EmailController().SendEmail(from, "Task Management System", to, subject, body);
                                    }
                                }

                                db.SaveChanges();
                            }
                        }
                    }
                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 29
0
        public IHttpActionResult AddMaterialRequest()
        {
            try
            {
                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    var form        = HttpContext.Current.Request.Form;
                    var items       = JsonConvert.DeserializeObject <List <BilledItemsModel> >(form.Get("items"));
                    var emp         = db.Employees.Where(x => x.Role_Id == "8").FirstOrDefault();
                    var category    = db.Categories.Where(x => x.Name == "Stock").FirstOrDefault().Id;
                    var subCategory = db.SubCategories.Where(x => x.Name == "Stock").FirstOrDefault().Id;


                    StockRequest stockReq = new StockRequest();

                    stockReq.Employee          = User.Identity.GetUserId();
                    stockReq.Client            = form.Get("Client");
                    stockReq.ExpectedStockDate = Convert.ToDateTime(form.Get("expectedDate"));
                    stockReq.Project           = Convert.ToInt32(form.Get("project"));
                    stockReq.Status            = "Under Review";
                    stockReq.Notes             = form.Get("notes");
                    stockReq.RequestDate       = DateTime.Now;
                    stockReq.LastUpdated       = DateTime.Now;
                    stockReq.UpdatedBy         = User.Identity.GetUserId();

                    for (int i = 0; i < items.Count(); i++)
                    {
                        StockRequestMapping srm = new StockRequestMapping();
                        srm.ItemId    = items[i].ModelId;
                        srm.Quanitity = items[i].Quantity;

                        stockReq.StockRequestMappings.Add(srm);
                    }

                    Activity act = new Activity();


                    if (emp != null)
                    {
                        act.AssignedTo = emp.AspNetUserId;
                    }

                    act.CreatedBy      = User.Identity.GetUserId();
                    act.Status         = "Open";
                    act.Subject        = "Material request for project";
                    act.Project_Id     = Convert.ToInt32(form.Get("project"));
                    act.EDOC           = Convert.ToDateTime(form.Get("expectedDate"));
                    act.Client_Id      = form.Get("Client");
                    act.Priority       = 0;
                    act.CreatedDate    = DateTime.Now;
                    act.TaskType       = "Client";
                    act.TaskOwner      = act.AssignedTo;
                    act.Description    = form.Get("notes");
                    act.TaskId         = RandomString(4);
                    stockReq.TaskId    = act.TaskId;
                    act.Category_Id    = Convert.ToInt32(category);
                    act.SubCategory_Id = Convert.ToInt32(subCategory);

                    ActivitiesLog activityLog = new ActivitiesLog();
                    activityLog.Status      = act.Status;
                    activityLog.Description = act.Description;
                    activityLog.TaskDate    = MasterDataController.GetIndianTime(DateTime.UtcNow);
                    activityLog.AssignedBy  = act.CreatedBy;
                    activityLog.AssignedTo  = act.TaskOwner;

                    act.ActivitiesLogs.Add(activityLog);

                    db.Activities.Add(act);

                    db.StockRequests.Add(stockReq);
                    db.SaveChanges();

                    return(Ok());
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occured, please try again later"));
            }
        }
Exemplo n.º 30
0
        public async Task <IHttpActionResult> AddClient()
        {
            try
            {
                var form            = HttpContext.Current.Request.Form;
                var clientLocations = JsonConvert.DeserializeObject <List <ClientLocationModel> >(form.Get("ClientLocations"));
                var verticals       = JsonConvert.DeserializeObject <List <ClientVerticalsModel> >(form.Get("ClientVerticals"));
                var v             = form.Get("ClientVerticals");
                var email         = form.Get("Email");
                var currency      = form.Get("Currency");
                var paymentType   = form.Get("PaymentType");
                var paymentAmount = form.Get("PaymentAmount");
                var gst           = form.Get("gst");
                var pan           = form.Get("pan");
                var creditPeriod  = form.Get("creditPeriod");

                var count = 0;

                /* Register to AspNet Users */

                UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext()));


                using (MaxMasterDbEntities db = new MaxMasterDbEntities())
                {
                    Client client = new Client();

                    int organisationId = Convert.ToInt32(form.Get("Organisation"));
                    client.OrgId = Convert.ToInt32(form.Get("Organisation"));

                    var user1 = userManager.FindByEmail(email);
                    if (user1 != null)
                    {
                        //client.AspNetUserId = user1.Id;
                        return(Content(HttpStatusCode.InternalServerError, "User with email " + email + " already exists"));
                    }
                    //else
                    //{
                    //    string organisation = db.Organisations.Where(x => x.Id == client.OrgId).FirstOrDefault().OrgName;

                    //}
                    //bool sendmail = new UserController().CreateUser(email, email, "Client", client.OrgId.ToString());


                    client.Name           = form.Get("Name");
                    client.ShortName      = form.Get("ShortName");
                    client.Email          = email;
                    client.Fax            = form.Get("Fax");
                    client.PrimaryPhone   = form.Get("PrimaryPhone");
                    client.SecondaryPhone = form.Get("SecondaryPhone");
                    client.ClientType     = form.Get("ClientType");

                    client.LastUpdated  = DateTime.Now;
                    client.UpdatedBy    = User.Identity.GetUserId();
                    client.EncrytionKey = RandomString(5);
                    client.Active       = true;
                    client.ClientStatus = form.Get("ClientStatus");

                    if (form.Get("ClientType") == "Supplier")
                    {
                        client.AccountName   = form.Get("accountName");
                        client.AccountNumber = form.Get("accountNumber");
                        client.BankName      = form.Get("bankName");
                        client.BranchName    = form.Get("branchName");
                        client.IFSCCode      = form.Get("ifscCode");
                    }

                    if (gst != null)
                    {
                        client.GST = gst;
                    }

                    if (pan != null)
                    {
                        client.PAN = pan;
                    }
                    if (creditPeriod != "")
                    {
                        client.CreditPeriod = Convert.ToInt32(form.Get("creditPeriod"));
                    }

                    if (paymentType != null)
                    {
                        client.PaymentType = form.Get("PaymentType");
                    }
                    if (paymentAmount != "")
                    {
                        client.PaymentAmount = Convert.ToDecimal(form.Get("PaymentAmount"));
                    }
                    if (currency != null)
                    {
                        client.Currency = form.Get("Currency");
                    }

                    string org         = db.Organisations.Where(x => x.Id == client.OrgId).FirstOrDefault().OrgName;
                    bool   UserCreated = new UserController().CreateUser(email, email, "Client", org);

                    var user = userManager.FindByEmail(email);
                    if (user != null)
                    {
                        client.AspNetUserId = user.Id;
                    }

                    for (int i = 0; i < clientLocations.Count; i++)
                    {
                        ClientLocation clientloc = new ClientLocation();
                        clientloc.AddressLine1     = clientLocations[i].AddressLine1;
                        clientloc.AddressLine2     = clientLocations[i].AddressLine2;
                        clientloc.Landmark         = clientLocations[i].Landmark;
                        clientloc.Country_Id       = clientLocations[i].Country;
                        clientloc.State_Id         = clientLocations[i].State;
                        clientloc.City_Id          = clientLocations[i].City;
                        clientloc.ZIP              = clientLocations[i].zip;
                        clientloc.TimeZone_Id      = clientLocations[i].TimeZone;
                        clientloc.IsInvoiceAddress = clientLocations[i].IsInvoice;
                        clientloc.Client_Id        = client.Id;

                        client.ClientLocations.Add(clientloc);
                    }

                    for (int i = 0; i < verticals.Count; i++)
                    {
                        var vertical = await db.ClientVerticals.FindAsync(verticals[i].value);

                        if (vertical == null)
                        {
                            continue;
                        }
                        client.ClientVerticals.Add(vertical);
                    }

                    db.Clients.Add(client);
                    db.SaveChanges();

                    var clientId = db.Clients.Where(x => x.AspNetUserId == user.Id).FirstOrDefault().Id;
                    return(Content(HttpStatusCode.OK, new { Id = clientId, Name = form.Get("ShortName") }));
                }
            }
            catch (Exception ex)
            {
                new Error().logAPIError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString(), ex.StackTrace);
                return(Content(HttpStatusCode.InternalServerError, "An error occoured, please try again!"));
            }
        }