public int SaveComplaint(complaintItem complaint)
 {
     asynSaveImage = new SaveImageBytes(ImageController.SavePicture);
     try
     {
         context = new SocialCopsEntities();
         // Add Log
         logger.LogMethod("ENTER","SaveComplaint","Userid/" + complaint.userId.ToString()+ "/ started SaveComplaint", null);
         // New Complaint
         Complaint temp = new Complaint();
         temp = complaintItem.convertComplaint(complaint);
         //Add a new Complaint
         context.Complaints.Add(temp);
         context.SaveChanges();
         //Image Upload Async
         byte[] image = complaint.ImageByte;
         if (image.Length > 0)
         {
             IAsyncResult result = asynSaveImage.BeginInvoke(image, temp.complaintId.ToString(), new AsyncCallback(FinishImageUpload), asynSaveImage);
         }
         // Exit Log
         logger.LogMethod("EXIT", "SaveComplaint", "Userid/" + complaint.userId.ToString() + "/ finished SaveComplaint", null);
         return temp.complaintId;
     }
     catch (Exception ex)
     {
         logger.LogMethod("ERROR", "SaveComplaint", "Userid/" + complaint.userId.ToString() + "/ " + ex.ToString(), null);
         error.Result = false;
         error.ErrorMessage = "unforeseen error occured. Please try later.";
         error.ErrorDetails = ex.ToString();
         throw new FaultException<Bug>(error, ex.ToString());
     }
 }
Exemple #2
0
 public void DeleteComplaint(int id)
 {
     //unitOfWork.StartTransaction();
     ComplaintRepository repo = new ComplaintRepository(unitOfWork);
     ComplaintModel complaintModel = new ComplaintModel();
     Complaint complaint = new Complaint();
     complaint = repo.GetAll().Where(x => x.ComplaintId == id).SingleOrDefault();
     repo.Delete(x => x.ComplaintId == complaint.ComplaintId);
     //unitOfWork.Commit();
 }
Exemple #3
0
 public ComplaintModel GetComplaintByComplaintId(int complaintId)
 {
     //unitOfWork.StartTransaction();
     ComplaintRepository repo = new ComplaintRepository(unitOfWork);
     ComplaintModel complaintModel = new ComplaintModel();
     Complaint complaint = new Complaint();
     complaint = repo.GetAll().Where(x => x.ComplaintId == complaintId).FirstOrDefault();
     //unitOfWork.Commit();
     AutoMapper.Mapper.Map(complaint, complaintModel);
     return complaintModel;
 }
Exemple #4
0
        public ComplaintModel GetComplaintDetailByComplaintId(int compliantId)
        {
            //unitOfWork.StartTransaction();
            ComplaintRepository repo = new ComplaintRepository(unitOfWork);
            ComplaintModel complaintModelList = new ComplaintModel();
            Complaint complaintlist = new Complaint();
            var complaints = (from data in db.Complaint
                              join e in db.Employee on data.EmployeeId equals e.EmployeeId
                              join cl in db.Client on data.ClientId equals cl.ClientId
                              join ul in db.UserLocation on cl.ClientId equals ul.UserId
                              join u in db.Users on cl.ClientId equals u.Id
                              join sp in db.ServiceProvider on data.ServiceProviderId equals sp.ServiceProviderId
                              join j in db.Job on data.JobId equals j.JobId
                              select new
                              {
                                  ComplainId = data.ComplaintId,
                                  Description = data.Description,
                                  ServiceProviderId = data.ServiceProviderId,
                                  EmployeeName = e.FirstName,
                                  ClientName = cl.FirstName,
                                  ClientAddress = ul.Address,
                                  ClientPhoneNumber = u.PhoneNumber,
                                  ServiceProviderName = sp.CompanyName,
                                  Status = data.Status,
                                  jobDescription = j.Description,
                                  JobAddress = j.JobAddress
                              }).Where(x => x.ComplainId == compliantId).FirstOrDefault();

                ComplaintModel model = new ComplaintModel();
                model.ComplaintId = complaints.ComplainId;
                model.Description = complaints.Description;
                model.EmployeeName = complaints.EmployeeName;
                model.ClientName = complaints.ClientName;
                model.ServiceProviderName = complaints.ServiceProviderName;
                model.Status = complaints.Status;
                model.JobDescription = complaints.jobDescription;
                model.JobAddress = complaints.JobAddress;
                model.ClientAddress = complaints.ClientAddress;
                model.ClientPhoneNumber = complaints.ClientPhoneNumber;

            //unitOfWork.Commit();
            return model;
        }
Exemple #5
0
 public ComplaintModel UpdateComplaint(ComplaintModel model)
 {
     //unitOfWork.StartTransaction();
     ComplaintRepository repo = new ComplaintRepository(unitOfWork);
     ComplaintModel complaintModel = new ComplaintModel();
     Complaint complaint = new Complaint();
     complaint = repo.GetAll().Where(x => x.ComplaintId == model.ComplaintId).FirstOrDefault();
     AutoMapper.Mapper.Map(model, complaint);
     repo.Update(complaint);
     //unitOfWork.Commit();
     return complaintModel;
 }
Exemple #6
0
 public ComplaintList(Complaint e)
 {
     Id                  = e.Id;
     DateReceived        = e.DateReceived;
     DateComplaintClosed = e.DateComplaintClosed;
 }
Exemple #7
0
        public async Task <List <Complaint> > FetchUserComplaint(int raisedBy)
        {
            List <Complaint> complaints = new List <Complaint>();

            using (SqlConnection connection = new SqlConnection(this._connectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("FETCH_USER_COMPLAINT", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.Add("@raisedBy", SqlDbType.Int).Value = raisedBy;
                    try
                    {
                        using (SqlDataReader reader = await command.ExecuteReaderAsync())
                        {
                            while (reader.Read())
                            {
                                var complaint = new Complaint
                                {
                                    CID               = Convert.ToInt32(reader["cid"].ToString()),
                                    TID               = Convert.ToInt32(reader["tid"].ToString()),
                                    CPriority         = Convert.ToInt32(reader["cpriority"].ToString()),
                                    UserContactNumber = reader["user_contact"].ToString(),
                                    UserComment       = reader["user_comment"].ToString(),
                                    CStatus           = Convert.ToInt32(reader["cstatus"].ToString()),
                                    ResolverComment   = reader["resolver_comment"].ToString(),
                                    AssignedToName    = reader["user_name"].ToString(),
                                };
                                switch (Convert.ToInt32(reader["cpriority"].ToString()))
                                {
                                case 1: complaint.CPriorityText = "Low";
                                    break;

                                case 2: complaint.CPriorityText = "Medium";
                                    break;

                                case 3:
                                    complaint.CPriorityText = "High";
                                    break;
                                }
                                switch (Convert.ToInt32(reader["cstatus"].ToString()))
                                {
                                case 1:
                                    complaint.CStatusText = "Acknowledged";
                                    break;

                                case 2:
                                    complaint.CStatusText = "Assigned";
                                    break;

                                case 3:
                                    complaint.CStatusText = "Work In Progress";
                                    break;

                                case 4:
                                    complaint.CStatusText = "Resolved";
                                    break;
                                }
                                complaints.Add(complaint);
                            }
                        }
                        return(complaints);
                    }
                    catch (Exception ex)
                    {
                        return(null);
                    }
                }
            }
        }
Exemple #8
0
 public void ComplaintDisputePendingTrial(Complaint complaint)
 {
 }
Exemple #9
0
 public void ComplaintConfirmed(Complaint complaint)
 {
 }
 public ComplaintsComponent(Complaint complaint)
 {
     InitializeComponent();
     Refresh(complaint);
 }
Exemple #11
0
 public void ComplaintCreated(Complaint complaint)
 {
 }
Exemple #12
0
    protected void btnAddcomplaintsubmit_Click(object sender, EventArgs e)
    {
        if (btnAddcomplaintsubmit.Text == "Reset")
        {
            lblCompstatus.Text         = "";
            btnAddcomplaintsubmit.Text = "Submit";
        }

        else
        {
            try
            {
                Complaint newComp = new Complaint();

                newComp.CompTypeID = Convert.ToInt32(drpComplaintcategory.SelectedItem.Value);
                newComp.Assignedto = GetAvailableEmployee(newComp.CompTypeID);


                //newComp.Assignedto = 4;

                newComp.SeverityID    = 2;
                newComp.FlatNumber    = txtAddcompFlat.Text;
                newComp.CurrentStatus = 1;
                newComp.Descrption    = txtComplaintdescription.Text;

                if (muser.currentResident.UserType == "Admin")
                {
                    newComp.ResidentID = muser.currentResident.ResID;
                }
                else
                {
                    newComp.ResidentID = muser.currentResident.ResID;
                }
                bool result = newComp.AddNewComplaint();


                if (result == true)
                {
                    drpComplaintcategory.SelectedIndex = 0;
                    txtComplaintdescription.Text       = "";

                    //Added by Aarshi on 11-Sept-2017 for bug fix
                    drpAddcomAssign.Items.Clear();
                    drpAddcomAssign.Items.Insert(0, new ListItem("Select", "NA"));
                    txtAddcompFlat.Text     = string.Empty;
                    txtComplaintername.Text = string.Empty;
                    LoadComplaintsDataList();
                    ClientScript.RegisterStartupScript(GetType(), "SetFocusScript", "<Script>self.close();</Script>");    //code to close window
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('Complaint Submitted Sucessfully')", true);
                    //FillComplaintData();
                }
                else
                {
                    lblCompstatus.ForeColor  = System.Drawing.Color.Red;
                    lblCompstatus.Text       = " Add complaint failed try later. ";
                    lblEmptyDataText.Visible = true;
                    lblEmptyDataText.Text    = "Add complaint failed try later";
                }
            }
            catch (Exception ex)
            {
            }

            finally
            {
            }
        }
    }
        public void CompleteOrderDelivery(
            Employee driver,
            int orderId,
            int bottlesReturnCount,
            int rating,
            int driverComplaintReasonId,
            string otherDriverComplaintReasonComment,
            string driverComment,
            DateTime recievedTime)
        {
            var vodovozOrder     = _orderRepository.GetOrder(_unitOfWork, orderId);
            var routeList        = _routeListRepository.GetActualRouteListByOrder(_unitOfWork, vodovozOrder);
            var routeListAddress = routeList.Addresses.Where(x => x.Order.Id == orderId).SingleOrDefault();

            if (vodovozOrder is null)
            {
                var error = $"Заказ не найден: { orderId }";
                _logger.LogWarning(error);
                throw new ArgumentOutOfRangeException(nameof(orderId), error);
            }

            if (routeList is null)
            {
                var error = $"МЛ для заказа: { orderId } не найден";
                _logger.LogWarning(error);
                throw new ArgumentOutOfRangeException(nameof(orderId), error);
            }

            if (routeListAddress is null)
            {
                var error = $"адрес МЛ для заказа: { orderId } не найден";
                _logger.LogWarning(error);
                throw new ArgumentOutOfRangeException(nameof(orderId), error);
            }

            if (routeList.Driver.Id != driver.Id)
            {
                _logger.LogWarning($"Водитель {driver.Id} попытался завершить заказ {orderId} водителя {routeList.Driver.Id}");
                throw new InvalidOperationException("Нельзя завершить заказ другого водителя");
            }

            if (routeList.Status != RouteListStatus.EnRoute)
            {
                var error = $"Нельзя завершить заказ: { orderId }, МЛ не в пути";
                _logger.LogWarning(error);
                throw new ArgumentOutOfRangeException(nameof(orderId), error);
            }

            if (routeListAddress.Status != RouteListItemStatus.EnRoute)
            {
                var error = $"Нельзя завершить заказ: { orderId }, адрес МЛ не в пути";
                _logger.LogWarning(error);
                throw new ArgumentOutOfRangeException(nameof(orderId), error);
            }

            routeListAddress.DriverBottlesReturned = bottlesReturnCount;

            routeList.ChangeAddressStatus(_unitOfWork, routeListAddress.Id, RouteListItemStatus.Completed);

            if (rating < _maxClosingRating)
            {
                var complaintReason = _complaintsRepository.GetDriverComplaintReasonById(_unitOfWork, driverComplaintReasonId);
                var complaintSource = _complaintsRepository.GetComplaintSourceById(_unitOfWork, _webApiParametersProvider.ComplaintSourceId);
                var reason          = complaintReason?.Name ?? otherDriverComplaintReasonComment;

                var complaint = new Complaint
                {
                    ComplaintSource = complaintSource,
                    ComplaintType   = ComplaintType.Driver,
                    Order           = vodovozOrder,
                    DriverRating    = rating,
                    DeliveryPoint   = vodovozOrder.DeliveryPoint,
                    CreationDate    = recievedTime,
                    ChangedDate     = recievedTime,
                    CreatedBy       = driver,
                    ChangedBy       = driver,
                    ComplaintText   = $"Заказ номер { orderId }\n" +
                                      $"По причине { reason }"
                };

                _unitOfWork.Save(complaint);
            }

            if (bottlesReturnCount != vodovozOrder.BottlesReturn)
            {
                if (!string.IsNullOrWhiteSpace(driverComment))
                {
                    vodovozOrder.DriverMobileAppComment     = driverComment;
                    vodovozOrder.DriverMobileAppCommentTime = recievedTime;
                }

                vodovozOrder.DriverCallType = DriverCallType.CommentFromMobileApp;

                _unitOfWork.Save(vodovozOrder);
            }

            _unitOfWork.Save(routeListAddress);
            _unitOfWork.Save(routeList);

            _unitOfWork.Commit();
        }
Exemple #14
0
        public override void GetById(ObjectId id)
        {
            Collection = Connection.GetCollection(collectionName);
            var filter = Builders <BsonDocument> .Filter.Eq("_id", id);

            var document = Collection.Find(filter).First();

            _id = id;

            Description = document.GetValue("Description").AsString;

            Doctor = new Doctor();
            Doctor.GetById(document.GetValue("Doctor").AsInt32, sqlConnection);

            Article = new Article();
            Article.GetById(document.GetValue("Article").AsBsonDocument.GetValue("$id").AsObjectId, Connection);

            foreach (BsonDocument doc in document.GetValue("Tags").AsBsonArray)
            {
                Tag tag = new Tag();
                tag.GetById(doc.GetValue("$id").AsObjectId, Connection);
                Tags.Add(tag);
            }

            foreach (BsonDocument doc in document.GetValue("MedicineObjects").AsBsonArray)
            {
                switch (doc.GetValue("Table").AsString)
                {
                case "Complaint":
                    Complaint complaint = new Complaint();
                    complaint.GetById(doc.GetValue("Id").AsInt32, sqlConnection);
                    MedicineObjects.Add(complaint);
                    break;

                case "Diagnosis":
                    Diagnosis diagnosis = new Diagnosis();
                    diagnosis.GetById(doc.GetValue("Id").AsInt32, sqlConnection);
                    MedicineObjects.Add(diagnosis);
                    break;

                case "Doctor":
                    Doctor doctor = new Doctor();
                    doctor.GetById(doc.GetValue("Id").AsInt32, sqlConnection);
                    MedicineObjects.Add(doctor);
                    break;

                case "Medicament":
                    Medicament medicament = new Medicament();
                    medicament.GetById(doc.GetValue("Id").AsInt32, sqlConnection);
                    MedicineObjects.Add(medicament);
                    break;

                case "Patient":
                    Patient patient = new Patient();
                    patient.GetById(doc.GetValue("Id").AsInt32, sqlConnection);
                    MedicineObjects.Add(patient);
                    break;

                case "Problem":
                    Problem problem = new Problem();
                    problem.GetById(doc.GetValue("Id").AsInt32, sqlConnection);
                    MedicineObjects.Add(problem);
                    break;

                case "Symptom":
                    Symptom symptom = new Symptom();
                    symptom.GetById(doc.GetValue("Id").AsInt32, sqlConnection);
                    MedicineObjects.Add(symptom);
                    break;
                }
            }

            foreach (BsonDocument doc in document.GetValue("Changes").AsBsonArray)
            {
                Change change = new Change()
                {
                    ChangeTime = doc.GetValue("ChangeTime").ToUniversalTime(),
                    Content    = doc.GetValue("Content").AsString
                };
                Changes.Add(change);
            }
        }
Exemple #15
0
        // GET api/complaintapi/5
        public String Get(int id)
        {
            Complaint Complaint = _db.Complaints.Find(id);

            return(Json.Encode(Complaint));
        }
Exemple #16
0
        public async Task <IActionResult> Create(CreateComplaintViewModel model)
        {
            var currentUser = await GetCurrentUserAsync();

            if (currentUser == null)
            {
                throw new Exception("Current user not found");
            }

            string msg = null;

            if (!ModelState.IsValid)
            {
                msg = $"The Complaint was not created. Please fix the errors shown below.";
                ViewData["AlertMessage"] = new AlertViewModel(msg, AlertStatus.Error, "Error");

                // Populate the select lists before returning the model
                model.SelectLists = await _dal.GetCommonSelectListsAsync(model.CurrentOfficeId);

                model.DisableCurrentOwnerSelect = !(model.CurrentOfficeId == currentUser.OfficeId ||
                                                    User.IsInRole(CtsRole.DivisionManager.ToString()));

                return(View(model));
            }

            if ((!User.IsInRole(CtsRole.DivisionManager.ToString()) &&
                 model.CurrentOfficeId != currentUser.OfficeId) ||
                model.CurrentOwnerId == CTS.SelectUserMasterText)
            {
                model.CurrentOwnerId = null;
            }

            var complaint = new Complaint(model)
            {
                Status      = ComplaintStatus.New,
                DateEntered = DateTime.Now,
                EnteredBy   = currentUser,
                DateCurrentOwnerAssigned = (model.CurrentOwnerId != null) ? (DateTime?)DateTime.Now : null,
                DateCurrentOwnerAccepted = (model.CurrentOwnerId != null && model.CurrentOwnerId == currentUser.Id) ? (DateTime?)DateTime.Now : null,
            };

            // Save main complaint details
            try
            {
                _context.Add(complaint);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                ex.Data.Add("Action", "Saving Complaint");
                ex.Data.Add("ViewModel", model);
                await _errorLogger.LogErrorAsync(ex, (User == null)? "Unknown" : User.Identity.Name, MethodBase.GetCurrentMethod().Name);

                msg = "There was an error saving the complaint. Please try again or contact support.";
                ViewData["AlertMessage"] = new AlertViewModel(msg, AlertStatus.Error, "Error");

                // Populate the select lists before returning the model
                model.SelectLists = await _dal.GetCommonSelectListsAsync(model.CurrentOfficeId);

                model.DisableCurrentOwnerSelect = !(model.CurrentOfficeId == currentUser.OfficeId ||
                                                    User.IsInRole(CtsRole.DivisionManager.ToString()));
                return(View(model));
            }

            // The complaint was successfully saved. Now start tracking any subsequent errors.
            var saveStatus = AlertStatus.Success;

            // Save initial complaint transitions
            bool transitionSaveError = false;
            Guid transitionId        = Guid.Empty;

            try
            {
                transitionId = await AddComplaintTransition(new ComplaintTransition()
                {
                    ComplaintId           = complaint.Id,
                    TransferredByUserId   = currentUser.Id,
                    TransferredToOfficeId = model.CurrentOfficeId,
                    TransitionType        = TransitionType.New,
                });

                if (model.CurrentOwnerId != null)
                {
                    complaint.CurrentAssignmentTransitionId = await AddComplaintTransition(new ComplaintTransition()
                    {
                        ComplaintId           = complaint.Id,
                        TransferredByUserId   = currentUser.Id,
                        TransferredToUserId   = model.CurrentOwnerId,
                        TransferredToOfficeId = model.CurrentOfficeId,
                        DateAccepted          = (currentUser.Id == model.CurrentOwnerId) ? (DateTime?)DateTime.Now : null,
                        TransitionType        = TransitionType.Assigned,
                    });

                    if (model.CurrentOwnerId == currentUser.Id)
                    {
                        complaint.Status = ComplaintStatus.UnderInvestigation;
                    }

                    _context.Update(complaint);
                    await _context.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("Action", "Saving Transitions");
                ex.Data.Add("Complaint ID", complaint.Id);
                ex.Data.Add("ViewModel", model);
                ex.Data.Add("Complaint Model", complaint);
                ex.Data.Add("Transition ID", transitionId);
                await _errorLogger.LogErrorAsync(ex, (User == null)? "Unknown" : User.Identity.Name, MethodBase.GetCurrentMethod().Name);

                saveStatus          = AlertStatus.Warning;
                transitionSaveError = true;
            }

            // Email appropriate recipients
            bool emailError = false;

            try
            {
                var complaintUrl = Url.Action("Details", "Complaints", new { id = complaint.Id }, protocol: HttpContext.Request.Scheme);
                if (complaint.CurrentOwnerId == null)
                {
                    // Email Master of current Office
                    var currentOffice = await _context.LookupOffices.FindAsync(complaint.CurrentOfficeId);

                    var officeMaster = await _userManager.FindByIdAsync(currentOffice.MasterUserId);

                    var masterEmail = await _userManager.GetEmailAsync(officeMaster);

                    await _emailSender.SendEmailAsync(
                        masterEmail,
                        string.Format(EmailTemplates.ComplaintOpenedToMaster.Subject, complaint.Id),
                        string.Format(EmailTemplates.ComplaintOpenedToMaster.PlainBody, complaint.Id, complaintUrl, currentOffice.Name),
                        string.Format(EmailTemplates.ComplaintOpenedToMaster.HtmlBody, complaint.Id, complaintUrl, currentOffice.Name),
                        !officeMaster.Active || !officeMaster.EmailConfirmed,
                        replyTo : currentUser.Email);
                }
                else
                {
                    // Email new owner
                    var currentOwner = await _userManager.FindByIdAsync(complaint.CurrentOwnerId);

                    var currentOwnerEmail = await _userManager.GetEmailAsync(currentOwner);

                    bool isValidUser = currentOwner.Active && currentOwner.EmailConfirmed;
                    await _emailSender.SendEmailAsync(
                        currentOwnerEmail,
                        string.Format(EmailTemplates.ComplaintAssigned.Subject, complaint.Id),
                        string.Format(EmailTemplates.ComplaintAssigned.PlainBody, complaint.Id, complaintUrl),
                        string.Format(EmailTemplates.ComplaintAssigned.HtmlBody, complaint.Id, complaintUrl),
                        !isValidUser,
                        replyTo : currentUser.Email);
                }
            }
            catch (Exception ex)
            {
                ex.Data.Add("Action", "Emailing recipients");
                ex.Data.Add("Complaint ID", complaint.Id);
                ex.Data.Add("ViewModel", model);
                ex.Data.Add("Complaint Model", complaint);
                await _errorLogger.LogErrorAsync(ex, (User == null)? "Unknown" : User.Identity.Name, MethodBase.GetCurrentMethod().Name);

                saveStatus = AlertStatus.Warning;
                emailError = true;
            }

            // Save attachments
            bool   attachmentsError       = false;
            int    fileCount              = 0;
            string attachmentErrorMessage = null;

            if (model.Attachments != null && model.Attachments.Count > 0)
            {
                switch (_fileService.ValidateUploadedFiles(model.Attachments))
                {
                case FilesValidationResult.TooMany:
                    saveStatus             = AlertStatus.Warning;
                    attachmentsError       = true;
                    attachmentErrorMessage = "No more than 10 files can be uploaded at a time. ";
                    break;

                case FilesValidationResult.WrongType:
                    saveStatus             = AlertStatus.Warning;
                    attachmentsError       = true;
                    attachmentErrorMessage = "An invalid file type was selected. (Supported file types are images, documents, and spreadsheets.) ";
                    break;

                case FilesValidationResult.Valid:
                    var savedFileList = new List <Attachment>();

                    try
                    {
                        foreach (var file in model.Attachments)
                        {
                            var attachment = await _fileService.SaveAttachmentAsync(file);

                            if (attachment != null)
                            {
                                attachment.ComplaintId  = complaint.Id;
                                attachment.UploadedById = currentUser.Id;
                                _context.Add(attachment);
                                savedFileList.Add(attachment);
                                fileCount++;
                            }
                        }

                        await _context.SaveChangesAsync();
                    }
                    catch (Exception ex)
                    {
                        ex.Data.Add("Action", "Saving Attachments");
                        ex.Data.Add("Complaint ID", complaint.Id);
                        ex.Data.Add("ViewModel", model);
                        ex.Data.Add("Complaint Model", complaint);
                        await _errorLogger.LogErrorAsync(ex, (User == null)? "Unknown" : User.Identity.Name, MethodBase.GetCurrentMethod().Name);

                        foreach (var attachment in savedFileList)
                        {
                            await _fileService.TryDeleteFileAsync(attachment.FilePath);

                            if (attachment.IsImage)
                            {
                                await _fileService.TryDeleteFileAsync(attachment.ThumbnailPath);
                            }
                        }

                        fileCount              = 0;
                        saveStatus             = AlertStatus.Warning;
                        attachmentsError       = true;
                        attachmentErrorMessage = "An unknown database error occurred. ";
                    }
                    break;
                }
            }

            // Compile response message
            if (fileCount == 0)
            {
                msg = "The Complaint has been created. ";
            }
            else if (fileCount == 1)
            {
                msg = "The Complaint has been created and one file was attached. ";
            }
            else if (fileCount > 1)
            {
                msg = $"The Complaint has been created and {fileCount} files were attached. ";
            }

            if (saveStatus != AlertStatus.Success)
            {
                if (transitionSaveError)
                {
                    msg += "There were errors saving some of the complaint details. Please contact support. ";
                }

                if (emailError)
                {
                    msg += "There was an error emailing the recipients. Please contact support. ";
                }

                if (attachmentsError)
                {
                    msg += "There was a problem saving the attachments: " + attachmentErrorMessage + "No files were saved. ";
                }

                TempData.SaveAlertForSession(msg, AlertStatus.Warning, "Warning");
            }

            TempData.SaveAlertForSession(msg, saveStatus, saveStatus.GetDisplayName());
            return(RedirectToAction("Details", new { id = complaint.Id }));
        }
 public async Task <bool> UpdateComplaint(Complaint complaint)
 {
     return(await this._rechargeApiDAL.UpdateComplaint(complaint));
 }
Exemple #18
0
 public string AddComplaint(Complaint complaint)
 {
     return(complaint.Id);
 }
Exemple #19
0
        public async Task <ActionResult> New(NewImprovementViewModel model)
        {
            if (ModelState.IsValid && (model.ComplaintSource == "order" || model.ComplaintSource == "direct" || model.ComplaintSource == "invoice"))
            {
                var           complaintsDAL = new ROLWeb.Models.Improvements.ImproventsDAL();
                var           rentalsDAL    = new ROLWeb.Models.Rentals.RentalsDAL();
                Customer      custId        = new Customer();
                StringBuilder sb            = new StringBuilder();

                List <Attachment> attachments = new List <Attachment>();
                byte[]            file        = null;
                if (model.file != null)
                {
                    var inputFile = new MemoryStream();
                    await model.file.InputStream.CopyToAsync(inputFile);

                    inputFile.Seek(0, 0);
                    attachments.Add(new Attachment(inputFile, model.file.FileName));
                    inputFile.Seek(0, 0);
                    file = inputFile.ToArray();
                }

                if (model.ComplaintSource == "order")
                {
                    var orderDetails = rentalsDAL.GetRentalOrderDetails(this.ActiveCustomer, model.ReferenceId);

                    if (orderDetails == null)
                    {
                        return(View("FormSubmitted", new FormSubmittedViewModel {
                            Title = Resources.Error, Message = Resources.DataProvidedNotValid
                        }));
                    }

                    custId.DatabaseName = this.ActiveCustomer.DatabaseName;
                    custId.CompanyId    = this.ActiveCustomer.CompanyId;
                    custId.CustomerId   = this.ActiveCustomer.CustomerId;
                    custId.Name         = orderDetails.AccountName;

                    //Register complaint
                    var complaint = new Complaint
                    {
                        UserId            = User.Identity.GetUserId(),
                        DatabaseName      = custId.DatabaseName,
                        CompanyId         = custId.CompanyId,
                        CustomerId        = custId.CustomerId,
                        Description       = model.Description ?? "",
                        SuggestedSolution = model.SuggestedSolution ?? "",
                        ComplaintSource   = "order",
                        ReferenceId       = orderDetails.InventTransId,
                        StatusId          = "10",
                        Answer            = "",
                        Attachment        = file
                    };

                    complaint.ComplaintId = await complaintsDAL.InsertComplaint(complaint);

                    sb.AppendFormat("<h2>MyRiwal {0}</h2>", Resources.NewImprovementForm);
                    sb.AppendLine("<table>");
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1:dd-MM-yyyy HH:mm}</td></tr>\n", Resources.DateTime, DateTime.Now);
                    sb.AppendFormat("<tr><td>MyRiwal {0}:</td><td>{1}</td></tr>\n", Resources.UserName, ((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("FullName").Value);
                    sb.AppendFormat("<tr><td></td><td></td></tr>\n");
                    sb.AppendFormat("<tr><td>{0}:</td><td></td></tr>\n", Resources.FormDetails);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CompanyNumber, this.ActiveCustomer.CompanyId);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CustomerNumber, orderDetails.CustAccount);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CustomerName, orderDetails.AccountName);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.ImprovementNumber, complaint.ComplaintKey);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.RentalOrder, orderDetails.SalesId);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.MachineSerialNumber, orderDetails.ObjectId);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.FleetNumber, orderDetails.AssetId);
                    sb.AppendLine("</table>");
                    sb.AppendLine("<br /><br />");
                    sb.AppendFormat("{0}: <br />", Resources.ImprovementDescription);
                    sb.AppendLine(model.Description);
                    sb.AppendLine("<br /><br />");
                    sb.AppendFormat("{0}: <br />", Resources.SuggestedSolution);
                    sb.AppendLine(model.SuggestedSolution);
                } // end source="order"
                else if (model.ComplaintSource == "invoice")
                {
                    var invoice = (await db.GetInvoiceDetails(this.ActiveCustomer, model.ReferenceId));

                    if (invoice == null)
                    {
                        return(View("FormSubmitted", new FormSubmittedViewModel {
                            Title = Resources.Error, Message = Resources.DataProvidedNotValid
                        }));
                    }

                    custId.DatabaseName = this.ActiveCustomer.DatabaseName;
                    custId.CompanyId    = this.ActiveCustomer.CompanyId;
                    custId.CustomerId   = invoice.InvoiceAccount;
                    custId.Name         = invoice.AccountName;

                    //Register complaint
                    var complaint = new Complaint
                    {
                        UserId            = User.Identity.GetUserId(),
                        DatabaseName      = custId.DatabaseName,
                        CompanyId         = custId.CompanyId,
                        CustomerId        = custId.CustomerId,
                        Description       = model.Description ?? "",
                        SuggestedSolution = model.SuggestedSolution ?? "",
                        ComplaintSource   = "invoice",
                        ReferenceId       = invoice.InvoiceId,
                        StatusId          = "10",
                        Answer            = "",
                        Attachment        = file
                    };

                    complaint.ComplaintId = await complaintsDAL.InsertComplaint(complaint);

                    sb.AppendFormat("<h2>MyRiwal {0}</h2>", Resources.NewImprovementForm);
                    sb.AppendLine("<table>");
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1:dd-MM-yyyy HH:mm}</td></tr>\n", Resources.DateTime, DateTime.Now);
                    sb.AppendFormat("<tr><td>MyRiwal {0}:</td><td>{1}</td></tr>\n", Resources.UserName, ((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("FullName").Value);
                    sb.AppendFormat("<tr><td></td><td></td></tr>\n");
                    sb.AppendFormat("<tr><td>{0}:</td><td></td></tr>\n", Resources.FormDetails);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CompanyNumber, this.ActiveCustomer.CompanyId);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CustomerNumber, invoice.InvoiceAccount);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CustomerName, invoice.AccountName);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.ImprovementNumber, complaint.ComplaintKey);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.InvoiceNumber, invoice.InvoiceId);
                    sb.AppendLine("</table>");
                    sb.AppendLine("<br /><br />");
                    sb.AppendFormat("{0}: <br />", Resources.ImprovementDescription);
                    sb.AppendLine(model.Description);
                    sb.AppendLine("<br /><br />");
                    sb.AppendFormat("{0}: <br />", Resources.SuggestedSolution);
                    sb.AppendLine(model.SuggestedSolution);
                } // end source="invoice"
                else if (model.ComplaintSource == "direct")
                {
                    custId.DatabaseName = this.ActiveCustomer.DatabaseName;
                    custId.CompanyId    = this.ActiveCustomer.CompanyId;
                    custId.CustomerId   = this.ActiveCustomer.CustomerId;
                    custId.Name         = this.ActiveCustomer.Name;

                    //Register complaint
                    var complaint = new Complaint
                    {
                        UserId            = User.Identity.GetUserId(),
                        DatabaseName      = custId.DatabaseName,
                        CompanyId         = custId.CompanyId,
                        CustomerId        = custId.CustomerId,
                        Description       = model.Description ?? "",
                        SuggestedSolution = model.SuggestedSolution ?? "",
                        ComplaintSource   = "direct",
                        ReferenceId       = "",
                        StatusId          = "10",
                        Answer            = "",
                        Attachment        = file
                    };

                    complaint.ComplaintId = await complaintsDAL.InsertComplaint(complaint);

                    sb.AppendFormat("<h2>MyRiwal {0}</h2>", Resources.NewImprovementForm);
                    sb.AppendLine("<table>");
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1:dd-MM-yyyy HH:mm}</td></tr>\n", Resources.DateTime, DateTime.Now);
                    sb.AppendFormat("<tr><td>MyRiwal {0}:</td><td>{1}</td></tr>\n", Resources.UserName, ((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("FullName").Value);
                    sb.AppendFormat("<tr><td></td><td></td></tr>\n");
                    sb.AppendFormat("<tr><td>{0}:</td><td></td></tr>\n", Resources.FormDetails);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CompanyNumber, this.ActiveCustomer.CompanyId);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CustomerNumber, custId.CustomerId);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.CustomerName, custId.Name);
                    sb.AppendFormat("<tr><td>{0}:</td><td>{1}</td></tr>\n", Resources.ImprovementNumber, complaint.ComplaintKey);
                    sb.AppendLine("</table>");
                    sb.AppendLine("<br /><br />");
                    sb.AppendFormat("{0}: <br />", Resources.ImprovementDescription);
                    sb.AppendLine(model.Description);
                    sb.AppendLine("<br /><br />");
                    sb.AppendFormat("{0}: <br />", Resources.SuggestedSolution);
                    sb.AppendLine(model.SuggestedSolution);
                } // end source="direct"

                string userEmail   = ((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("Email").Value;
                string onRentEmail = await rentalsDAL.GetOnRentEmailAddress(custId);

                if (MailClient.SendEmail(custId, Resources.NewImprovementForm, sb.ToString(), null, userEmail, onRentEmail, null, attachments))
                {
                    return(View("FormSubmitted", new FormSubmittedViewModel {
                        Title = Resources.FormSubmitted, Message = Resources.RequestSubmitted
                    }));
                }

                return(View("FormSubmitted", new FormSubmittedViewModel {
                    Title = Resources.Error, Message = Resources.RequestNotSent
                }));
            } // modelstate.isvalid


            return(View("FormSubmitted", new FormSubmittedViewModel {
                Title = Resources.Error, Message = Resources.DataProvidedNotValid
            }));
        }
 public ComplaintViewModel()
 {
     complaint     = new Complaint();
     DataService   = new ComplaintService();
     AcceptCommand = new RelayCommand(AcceptExecute);
 }
Exemple #21
0
        private IQueryOver <Complaint> GetComplaintQuery(IUnitOfWork uow)
        {
            ComplaintJournalNode resultAlias = null;

            Complaint           complaintAlias           = null;
            Employee            authorAlias              = null;
            Counterparty        counterpartyAlias        = null;
            DeliveryPoint       deliveryPointAlias       = null;
            ComplaintGuiltyItem complaintGuiltyItemAlias = null;
            Employee            guiltyEmployeeAlias      = null;
            Subdivision         guiltySubdivisionAlias   = null;
            Fine  fineAlias  = null;
            Order orderAlias = null;
            ComplaintDiscussion discussionAlias      = null;
            Subdivision         subdivisionAlias     = null;
            ComplaintKind       complaintKindAlias   = null;
            Subdivision         superspecialAlias    = null;
            ComplaintObject     complaintObjectAlias = null;

            var authorProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.String, "GET_PERSON_NAME_WITH_INITIALS(?1, ?2, ?3)"),
                NHibernateUtil.String,
                Projections.Property(() => authorAlias.LastName),
                Projections.Property(() => authorAlias.Name),
                Projections.Property(() => authorAlias.Patronymic)
                );

            var workInSubdivisionsSubQuery = QueryOver.Of <Subdivision>(() => subdivisionAlias)
                                             .Where(() => subdivisionAlias.Id == discussionAlias.Subdivision.Id)
                                             .Where(() => discussionAlias.Status == ComplaintStatuses.InProcess)
                                             .Select(Projections.Conditional(
                                                         Restrictions.IsNotNull(Projections.Property(() => subdivisionAlias.ShortName)),
                                                         Projections.Property(() => subdivisionAlias.ShortName),
                                                         Projections.Constant("?")
                                                         )
                                                     );

            var subdivisionsSubqueryProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.String, "GROUP_CONCAT(DISTINCT ?1 SEPARATOR ?2)"),
                NHibernateUtil.String,
                Projections.SubQuery(workInSubdivisionsSubQuery),
                Projections.Constant(", "));

            string okkSubdivision = uow.GetById <Subdivision>(_subdivisionParametersProvider.GetOkkId()).ShortName ?? "?";

            var workInSubdivisionsProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.String, "CONCAT_WS(',', ?1, IF(?2 = 'Checking',?3, ''))"),
                NHibernateUtil.String,
                subdivisionsSubqueryProjection,
                Projections.Property(() => complaintAlias.Status),
                Projections.Constant(okkSubdivision)
                );

            var plannedCompletionDateProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.String, "GROUP_CONCAT(DISTINCT DATE_FORMAT(?1, \"%d.%m.%Y\") SEPARATOR ?2)"),
                NHibernateUtil.String,
                Projections.Property(() => discussionAlias.PlannedCompletionDate),
                Projections.Constant("\n"));

            var lastPlannedCompletionDateProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.DateTime, "MAX(DISTINCT ?1)"),
                NHibernateUtil.DateTime,
                Projections.Property(() => discussionAlias.PlannedCompletionDate));

            var counterpartyWithAddressProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.String, "CONCAT_WS('\n', ?1, COMPILE_ADDRESS(?2))"),
                NHibernateUtil.String,
                Projections.Property(() => counterpartyAlias.Name),
                Projections.Property(() => deliveryPointAlias.Id));

            var guiltyEmployeeProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.String, "GET_PERSON_NAME_WITH_INITIALS(?1, ?2, ?3)"),
                NHibernateUtil.String,
                Projections.Property(() => guiltyEmployeeAlias.LastName),
                Projections.Property(() => guiltyEmployeeAlias.Name),
                Projections.Property(() => guiltyEmployeeAlias.Patronymic)
                );

            var guiltiesProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.String, "GROUP_CONCAT(DISTINCT " +
                                        "CASE ?1 " +
                                        $"WHEN '{nameof(ComplaintGuiltyTypes.Client)}' THEN 'Клиент' " +
                                        $"WHEN '{nameof(ComplaintGuiltyTypes.Depreciation )}' THEN 'Износ' " +
                                        $"WHEN '{nameof(ComplaintGuiltyTypes.None)}' THEN 'Нет' " +
                                        $"WHEN '{nameof(ComplaintGuiltyTypes.Employee)}' THEN CONCAT('(',?5,')', ?2)" +
                                        $"WHEN '{nameof(ComplaintGuiltyTypes.Subdivision)}' THEN ?3 " +
                                        $"WHEN '{nameof(ComplaintGuiltyTypes.Supplier)}' THEN 'Поставщик' " +
                                        "ELSE '' " +
                                        "END" +
                                        " SEPARATOR ?4)"),
                NHibernateUtil.String,
                Projections.Property(() => complaintGuiltyItemAlias.GuiltyType),
                guiltyEmployeeProjection,
                Projections.Property(() => guiltySubdivisionAlias.ShortName),
                Projections.Constant("\n"),
                Projections.Property(() => superspecialAlias.ShortName));

            var finesProjection = Projections.SqlFunction(
                new SQLFunctionTemplate(NHibernateUtil.String, "GROUP_CONCAT(DISTINCT CONCAT(ROUND(?1, 2), ' р.')  SEPARATOR ?2)"),
                NHibernateUtil.String,
                Projections.Property(() => fineAlias.TotalMoney),
                Projections.Constant("\n"));

            var query = uow.Session.QueryOver(() => complaintAlias)
                        .Left.JoinAlias(() => complaintAlias.CreatedBy, () => authorAlias)
                        .Left.JoinAlias(() => complaintAlias.Counterparty, () => counterpartyAlias)
                        .Left.JoinAlias(() => complaintAlias.Order, () => orderAlias)
                        .Left.JoinAlias(() => complaintAlias.DeliveryPoint, () => deliveryPointAlias)
                        .Left.JoinAlias(() => complaintAlias.Guilties, () => complaintGuiltyItemAlias)
                        .Left.JoinAlias(() => complaintAlias.ComplaintKind, () => complaintKindAlias)
                        .Left.JoinAlias(() => complaintAlias.Fines, () => fineAlias)
                        .Left.JoinAlias(() => complaintAlias.ComplaintDiscussions, () => discussionAlias)
                        .Left.JoinAlias(() => discussionAlias.Subdivision, () => subdivisionAlias)
                        .Left.JoinAlias(() => complaintGuiltyItemAlias.Employee, () => guiltyEmployeeAlias)
                        .Left.JoinAlias(() => guiltyEmployeeAlias.Subdivision, () => superspecialAlias)
                        .Left.JoinAlias(() => complaintGuiltyItemAlias.Subdivision, () => guiltySubdivisionAlias)
                        .Left.JoinAlias(() => complaintKindAlias.ComplaintObject, () => complaintObjectAlias);

            #region Filter

            if (FilterViewModel != null)
            {
                if (FilterViewModel.IsForRetail != null)
                {
                    query.Where(() => counterpartyAlias.IsForRetail == FilterViewModel.IsForRetail);
                }

                FilterViewModel.EndDate = FilterViewModel.EndDate.Date.AddHours(23).AddMinutes(59);
                if (FilterViewModel.StartDate.HasValue)
                {
                    FilterViewModel.StartDate = FilterViewModel.StartDate.Value.Date;
                }

                QueryOver <ComplaintDiscussion, ComplaintDiscussion> dicussionQuery = null;

                if (FilterViewModel.Subdivision != null)
                {
                    dicussionQuery = QueryOver.Of(() => discussionAlias)
                                     .Select(Projections.Property <ComplaintDiscussion>(p => p.Id))
                                     .Where(() => discussionAlias.Subdivision.Id == FilterViewModel.Subdivision.Id)
                                     .And(() => discussionAlias.Complaint.Id == complaintAlias.Id);
                }

                if (FilterViewModel.StartDate.HasValue)
                {
                    switch (FilterViewModel.FilterDateType)
                    {
                    case DateFilterType.PlannedCompletionDate:
                        if (dicussionQuery == null)
                        {
                            query = query.Where(() => complaintAlias.PlannedCompletionDate <= FilterViewModel.EndDate)
                                    .And(() => FilterViewModel.StartDate == null || complaintAlias.PlannedCompletionDate >= FilterViewModel.StartDate.Value);
                        }
                        else
                        {
                            dicussionQuery = dicussionQuery
                                             .And(() => FilterViewModel.StartDate == null || discussionAlias.PlannedCompletionDate >= FilterViewModel.StartDate.Value)
                                             .And(() => discussionAlias.PlannedCompletionDate <= FilterViewModel.EndDate);
                        }
                        break;

                    case DateFilterType.ActualCompletionDate:
                        query = query.Where(() => complaintAlias.ActualCompletionDate <= FilterViewModel.EndDate)
                                .And(() => FilterViewModel.StartDate == null || complaintAlias.ActualCompletionDate >= FilterViewModel.StartDate.Value);
                        break;

                    case DateFilterType.CreationDate:
                        query = query.Where(() => complaintAlias.CreationDate <= FilterViewModel.EndDate)
                                .And(() => FilterViewModel.StartDate == null || complaintAlias.CreationDate >= FilterViewModel.StartDate.Value);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                if (dicussionQuery != null)
                {
                    query.WithSubquery.WhereExists(dicussionQuery);
                }
                if (FilterViewModel.ComplaintType != null)
                {
                    query = query.Where(() => complaintAlias.ComplaintType == FilterViewModel.ComplaintType);
                }
                if (FilterViewModel.ComplaintStatus != null)
                {
                    query = query.Where(() => complaintAlias.Status == FilterViewModel.ComplaintStatus);
                }
                if (FilterViewModel.Employee != null)
                {
                    query = query.Where(() => complaintAlias.CreatedBy.Id == FilterViewModel.Employee.Id);
                }
                if (FilterViewModel.Counterparty != null)
                {
                    query = query.Where(() => complaintAlias.Counterparty.Id == FilterViewModel.Counterparty.Id);
                }

                if (FilterViewModel.CurrentUserSubdivision != null &&
                    FilterViewModel.ComplaintDiscussionStatus != null)
                {
                    query = query.Where(() => discussionAlias.Subdivision.Id == FilterViewModel.CurrentUserSubdivision.Id)
                            .And(() => discussionAlias.Status == FilterViewModel.ComplaintDiscussionStatus);
                }

                if (FilterViewModel.GuiltyItemVM?.Entity?.GuiltyType != null)
                {
                    var subquery = QueryOver.Of <ComplaintGuiltyItem>()
                                   .Where(g => g.GuiltyType == FilterViewModel.GuiltyItemVM.Entity.GuiltyType.Value);
                    switch (FilterViewModel.GuiltyItemVM.Entity.GuiltyType)
                    {
                    case ComplaintGuiltyTypes.None:
                    case ComplaintGuiltyTypes.Client:
                    case ComplaintGuiltyTypes.Depreciation:
                    case ComplaintGuiltyTypes.Supplier:
                        break;

                    case ComplaintGuiltyTypes.Employee:
                        if (FilterViewModel.GuiltyItemVM.Entity.Employee != null)
                        {
                            subquery.Where(g => g.Employee.Id == FilterViewModel.GuiltyItemVM.Entity.Employee.Id);
                        }
                        break;

                    case ComplaintGuiltyTypes.Subdivision:
                        if (FilterViewModel.GuiltyItemVM.Entity.Subdivision != null)
                        {
                            subquery.Where(g => g.Subdivision.Id == FilterViewModel.GuiltyItemVM.Entity.Subdivision.Id);
                        }
                        break;

                    default:
                        break;
                    }
                    query.WithSubquery.WhereProperty(x => x.Id).In(subquery.Select(x => x.Complaint));
                }

                if (FilterViewModel.ComplaintKind != null)
                {
                    query.Where(() => complaintAlias.ComplaintKind.Id == FilterViewModel.ComplaintKind.Id);
                }

                if (FilterViewModel.ComplaintObject != null)
                {
                    query.Where(() => complaintObjectAlias.Id == FilterViewModel.ComplaintObject.Id);
                }
            }

            #endregion Filter

            query.Where(
                GetSearchCriterion(
                    () => complaintAlias.Id,
                    () => complaintAlias.ComplaintText,
                    () => complaintAlias.ResultText,
                    () => counterpartyAlias.Name,
                    () => deliveryPointAlias.CompiledAddress
                    )
                );

            query.SelectList(list => list
                             .SelectGroup(() => complaintAlias.Id).WithAlias(() => resultAlias.Id)
                             .Select(() => complaintAlias.CreationDate).WithAlias(() => resultAlias.Date)
                             .Select(() => complaintAlias.ComplaintType).WithAlias(() => resultAlias.Type)
                             .Select(() => complaintAlias.Status).WithAlias(() => resultAlias.Status)
                             .Select(workInSubdivisionsProjection).WithAlias(() => resultAlias.WorkInSubdivision)
                             .Select(plannedCompletionDateProjection).WithAlias(() => resultAlias.PlannedCompletionDate)
                             .Select(lastPlannedCompletionDateProjection).WithAlias(() => resultAlias.LastPlannedCompletionDate)
                             .Select(counterpartyWithAddressProjection).WithAlias(() => resultAlias.ClientNameWithAddress)
                             .Select(guiltiesProjection).WithAlias(() => resultAlias.Guilties)
                             .Select(authorProjection).WithAlias(() => resultAlias.Author)
                             .Select(finesProjection).WithAlias(() => resultAlias.Fines)
                             .Select(() => complaintAlias.ComplaintText).WithAlias(() => resultAlias.ComplaintText)
                             .Select(() => complaintKindAlias.Name).WithAlias(() => resultAlias.ComplaintKindString)
                             .Select(() => complaintKindAlias.IsArchive).WithAlias(() => resultAlias.ComplaintKindIsArchive)
                             .Select(() => complaintAlias.ResultText).WithAlias(() => resultAlias.ResultText)
                             .Select(() => complaintAlias.ActualCompletionDate).WithAlias(() => resultAlias.ActualCompletionDate)
                             .Select(() => complaintObjectAlias.Name).WithAlias(() => resultAlias.ComplaintObjectString)
                             );

            query.TransformUsing(Transformers.AliasToBean <ComplaintJournalNode>())
            .OrderBy(n => n.Id)
            .Desc();

            return(query);
        }
Exemple #22
0
        public Complaint UpdateComplaintStarStatus(int id, bool star)
        {
            using (var connection = SqlConnectionManager.GetConnection())
                using (var command = new NpgsqlCommand()) {
                    command.Connection  = connection;
                    command.CommandText = "select * from updateComplaintStarStatus(@id, @star)";
                    command.Parameters.AddWithValue("@id", id);
                    command.Parameters.Add("@star", NpgsqlDbType.Bit).Value = star;

                    var reader = command.ExecuteReader();
                    if (reader.Read())
                    {
                        var c = new Complaint()
                        {
                            Id      = int.Parse(reader["c_id"].ToString()),
                            Title   = reader["title"].ToString(),
                            Student = new Student()
                            {
                                Id = int.Parse(reader["student_id"].ToString())
                            },
                            ComplaintCategory = new ComplaintCategory()
                            {
                                Id   = int.Parse(reader["complaint_category_id"].ToString()),
                                Name = reader["complaint_category_name"].ToString(),
                                Code = reader["complaint_category_code"].ToString()
                            },
                            DateTime    = DateTime.Parse(reader["datetime"].ToString()),
                            Description = reader["description"].ToString(),
                            Starred     = ((BitArray)reader["c_starred"]).Get(0),
                            Feedback    = reader["feedback"].ToString()
                        };
                        var status = int.Parse(reader["status"].ToString());

                        switch (status)
                        {
                        case 0:
                            c.ComplaintStatus = ComplaintStatus.Pending;
                            break;

                        case 1:
                            c.ComplaintStatus = ComplaintStatus.Scheduled;
                            break;

                        default:
                            c.ComplaintStatus = ComplaintStatus.Resolved;
                            break;
                        }

                        var appDate = reader["appointment_date_pref"].ToString();
                        if (!string.IsNullOrEmpty(appDate) || !string.IsNullOrWhiteSpace(appDate))
                        {
                            appDate = appDate.Substring(0, 10);
                            c.AppointmentDatePreference =
                                DateTime.ParseExact(appDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            c.AppointmentDatePreference = null;
                        }

                        var appFromTime = reader["appointment_from_time_pref"].ToString();
                        var appToTime   = reader["appointment_to_time_pref"].ToString();

                        if (!string.IsNullOrEmpty(appFromTime) || !string.IsNullOrWhiteSpace(appFromTime))
                        {
                            appFromTime = $"1970-01-01T{appFromTime}";
                            c.AppointmentFromTimePreference = DateTime.Parse(appFromTime);
                        }
                        else
                        {
                            c.AppointmentFromTimePreference = null;
                        }

                        if (!string.IsNullOrEmpty(appToTime) || !string.IsNullOrWhiteSpace(appToTime))
                        {
                            appToTime = $"1970-01-01T{appToTime}";
                            c.AppointmentToTimePreference = DateTime.Parse(appToTime);
                        }
                        else
                        {
                            c.AppointmentToTimePreference = null;
                        }

                        return(c);
                    }

                    return(null);
                }
        }
Exemple #23
0
        private async Task AddComplaint()
        {
            this.Activity.RunOnUiThread(() => progressBar.Visibility = ViewStates.Visible);
            List <string> photos = new List <string>();

            foreach (Bitmap b in images)
            {
                photos.Add(ImageToBase64String(b));
            }
            Complaint complaint = new Complaint()
            {
                furnitureId = furniture.id,
                description = problemDesc.Text,
                photo       = photos,
                senderName  = GlobalVars.login,
                madeBy      = furniture.madeBy
            };

            if (complaint.Correct() && photoDefault != photoPreview.Drawable)
            {
                FireBaseConnector connector = new FireBaseConnector();
                var res = connector.dataInsert(complaint);
                if (res == 0)
                {
                    if (photos.Count != 0)
                    {
                        Android.Support.V7.App.AlertDialog.Builder alertDialog = new Android.Support.V7.App.AlertDialog.Builder(this.Activity);
                        alertDialog.SetTitle(GetString(Resource.String.dataError));
                        alertDialog.SetIcon(Resource.Drawable.ic4c_192x192);
                        alertDialog.SetMessage(GetString(Resource.String.addCorrect));
                        alertDialog.SetNeutralButton(GetString(Resource.String.OKbutton), delegate
                        {
                            alertDialog.Dispose();
                        });
                        alertDialog.Show();
                    }
                    else
                    {
                        Android.Support.V7.App.AlertDialog.Builder alertDialog = new Android.Support.V7.App.AlertDialog.Builder(this.Activity);
                        alertDialog.SetTitle(GetString(Resource.String.photoError));
                        alertDialog.SetIcon(Resource.Drawable.ic4c_192x192);
                        alertDialog.SetMessage(GetString(Resource.String.photoErrorMsg));
                        alertDialog.SetNeutralButton(GetString(Resource.String.OKbutton), delegate
                        {
                            alertDialog.Dispose();
                        });
                        alertDialog.Show();
                    }
                }
                if (res == -1)
                {
                    Android.Support.V7.App.AlertDialog.Builder alertDialog = new Android.Support.V7.App.AlertDialog.Builder(this.Activity);
                    alertDialog.SetTitle(GetString(Resource.String.noInternetConnection));
                    alertDialog.SetIcon(Resource.Drawable.ic5c_192x192);
                    alertDialog.SetMessage(GetString(Resource.String.checkConnection));
                    alertDialog.SetNeutralButton(GetString(Resource.String.OKbutton), delegate
                    {
                        alertDialog.Dispose();
                    });
                    alertDialog.Show();
                }
                if (res == 1)
                {
                    Android.Support.V7.App.AlertDialog.Builder alertDialog = new Android.Support.V7.App.AlertDialog.Builder(this.Activity);
                    alertDialog.SetTitle(GetString(Resource.String.complaintCorrect));
                    alertDialog.SetIcon(Resource.Drawable.ok2a_192x192);
                    alertDialog.SetMessage(GetString(Resource.String.complaintMessage));
                    alertDialog.SetNeutralButton(GetString(Resource.String.OKbutton), delegate
                    {
                        alertDialog.Dispose();
                        this.OnComplaintCreated();
                        this.Dismiss();
                    });
                    alertDialog.Show();
                }
            }
            else
            {
                Android.Support.V7.App.AlertDialog.Builder alertDialog = new Android.Support.V7.App.AlertDialog.Builder(this.Activity);
                alertDialog.SetTitle(GetString(Resource.String.dataError));
                alertDialog.SetIcon(Resource.Drawable.ic4c_192x192);
                alertDialog.SetMessage(GetString(Resource.String.addCorrect));
                alertDialog.SetNeutralButton(GetString(Resource.String.OKbutton), delegate
                {
                    alertDialog.Dispose();
                });
                alertDialog.Show();
            }
            this.Activity.RunOnUiThread(() => btn2Complaint.Enabled  = true);
            this.Activity.RunOnUiThread(() => progressBar.Visibility = ViewStates.Invisible);
        }
Exemple #24
0
        public Complaint CreateComplaint(Complaint complaint)
        {
            using (var connection = SqlConnectionManager.GetConnection())
                using (var command = new NpgsqlCommand()) {
                    command.Connection  = connection;
                    command.CommandText =
                        "select * from createComplaint(@title, @studentId, @complaintCategoryId, @datetime, @description, @datePref, @fromTimePref, @toTimePref, @pictures)";

                    command.Parameters.AddWithValue("@title", complaint.Title);
                    command.Parameters.AddWithValue("@studentId", complaint.Student.Id);
                    command.Parameters.AddWithValue("@complaintCategoryId", complaint.ComplaintCategory.Id);
                    command.Parameters.AddWithValue("@description", complaint.Description);
                    command.Parameters.Add("@datetime", NpgsqlDbType.TimestampTz).Value = complaint.DateTime;
                    command.Parameters.Add("@datePref", NpgsqlDbType.Date).Value        = complaint.AppointmentDatePreference;
                    command.Parameters.Add("@pictures", NpgsqlDbType.Array | NpgsqlDbType.Text).Value = complaint.Pictures;

                    if (complaint.AppointmentFromTimePreference != null)
                    {
                        var fromTimeString =
                            complaint.AppointmentFromTimePreference.Value.ToString("HH:mm:ss",
                                                                                   CultureInfo.InvariantCulture);
                        var fromTime = TimeSpan.Parse(fromTimeString);
                        command.Parameters.Add("@fromTimePref", NpgsqlDbType.Time).Value = fromTime;
                    }
                    else
                    {
                        command.Parameters.Add("@fromTimePref", NpgsqlDbType.Time).Value = null;
                    }

                    if (complaint.AppointmentToTimePreference != null)
                    {
                        var toTimeString =
                            complaint.AppointmentToTimePreference.Value.ToString("HH:mm:ss", CultureInfo.InvariantCulture);
                        var toTime = TimeSpan.Parse(toTimeString);
                        command.Parameters.Add("@toTimePref", NpgsqlDbType.Time).Value = toTime;
                    }
                    else
                    {
                        command.Parameters.Add("@toTimePref", NpgsqlDbType.Time).Value = null;
                    }

                    var reader = command.ExecuteReader();
                    if (reader.Read())
                    {
                        var c = new Complaint()
                        {
                            Id      = int.Parse(reader["c_id"].ToString()),
                            Title   = reader["c_title"].ToString(),
                            Student = new Student()
                            {
                                Id = int.Parse(reader["c_student_id"].ToString())
                            },
                            ComplaintCategory = new ComplaintCategory()
                            {
                                Id   = int.Parse(reader["c_complaint_category_id"].ToString()),
                                Name = reader["c_complaint_category_name"].ToString(),
                                Code = reader["c_complaint_category_code"].ToString()
                            },
                            DateTime    = DateTime.Parse(reader["c_datetime"].ToString()),
                            Description = reader["c_description"].ToString(),
                            Starred     = ((BitArray)reader["c_starred"]).Get(0),
                            Feedback    = reader["c_feedback"].ToString()
                        };
                        var status = int.Parse(reader["c_status"].ToString());

                        switch (status)
                        {
                        case 0:
                            c.ComplaintStatus = ComplaintStatus.Pending;
                            break;

                        case 1:
                            c.ComplaintStatus = ComplaintStatus.Scheduled;
                            break;

                        default:
                            c.ComplaintStatus = ComplaintStatus.Resolved;
                            break;
                        }

                        var appDate = reader["c_appointment_date_pref"].ToString();
                        if (!string.IsNullOrEmpty(appDate) || !string.IsNullOrWhiteSpace(appDate))
                        {
                            appDate = appDate.Substring(0, 10);
                            c.AppointmentDatePreference =
                                DateTime.ParseExact(appDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            c.AppointmentDatePreference = null;
                        }

                        var appFromTime = reader["c_appointment_from_time_pref"].ToString();
                        var appToTime   = reader["c_appointment_to_time_pref"].ToString();

                        if (!string.IsNullOrEmpty(appFromTime) || !string.IsNullOrWhiteSpace(appFromTime))
                        {
                            appFromTime = $"1970-01-01T{appFromTime}";
                            c.AppointmentFromTimePreference = DateTime.Parse(appFromTime);
                        }
                        else
                        {
                            c.AppointmentFromTimePreference = null;
                        }

                        if (!string.IsNullOrEmpty(appToTime) || !string.IsNullOrWhiteSpace(appToTime))
                        {
                            appToTime = $"1970-01-01T{appToTime}";
                            c.AppointmentToTimePreference = DateTime.Parse(appToTime);
                        }
                        else
                        {
                            c.AppointmentToTimePreference = null;
                        }

                        return(c);
                    }

                    return(null);
                }
        }
Exemple #25
0
 public void ComplaintDisputed(Complaint complaint)
 {
 }
Exemple #26
0
        public List <Complaint> GetComplaintsByCaretaker(int cid, int len)
        {
            using (var connection = SqlConnectionManager.GetConnection())
                using (var command = new NpgsqlCommand()) {
                    var complaints = new List <Complaint>();
                    command.Connection  = connection;
                    command.CommandText = "select * from getComplaintsByCaretaker(@cid, @len)";
                    command.Parameters.AddWithValue("@cid", cid);
                    command.Parameters.AddWithValue("@len", len);
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        var c = new Complaint()
                        {
                            Id      = int.Parse(reader["id"].ToString()),
                            Title   = reader["title"].ToString(),
                            Student = new Student()
                            {
                                Id              = int.Parse(reader["student_id"].ToString()),
                                Name            = reader["student_name"].ToString(),
                                Rollno          = reader["student_rollno"].ToString(),
                                PersonalContact = reader["student_personal_contact"].ToString(),
                                ParentContact   = reader["student_parent_contact"].ToString(),
                                Email           = reader["student_email"].ToString(),
                                Gender          = ((BitArray)reader["student_gender"]).Get(0) ? 'M' : 'F',
                                Hostel          = new Hostel()
                                {
                                    Id         = int.Parse(reader["hostel_id"].ToString()),
                                    RoomNumber = reader["room_no"].ToString()
                                }
                            },
                            ComplaintCategory = new ComplaintCategory()
                            {
                                Id   = int.Parse(reader["complaint_category_id"].ToString()),
                                Name = reader["complaint_category_name"].ToString(),
                                Code = reader["complaint_category_code"].ToString()
                            },
                            DateTime    = DateTime.Parse(reader["datetime"].ToString()),
                            Description = reader["description"].ToString(),
                            Starred     = ((BitArray)reader["starred"]).Get(0),
                            Feedback    = reader["feedback"].ToString()
                        };
                        var status = int.Parse(reader["status"].ToString());

                        switch (status)
                        {
                        case 0:
                            c.ComplaintStatus = ComplaintStatus.Pending;
                            break;

                        case 1:
                            c.ComplaintStatus = ComplaintStatus.Scheduled;
                            break;

                        default:
                            c.ComplaintStatus = ComplaintStatus.Resolved;
                            break;
                        }

                        var appDate = reader["appointment_date_pref"].ToString();
                        if (!string.IsNullOrEmpty(appDate) || !string.IsNullOrWhiteSpace(appDate))
                        {
                            appDate = appDate.Substring(0, 10);
                            c.AppointmentDatePreference =
                                DateTime.ParseExact(appDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            c.AppointmentDatePreference = null;
                        }

                        var appFromTime = reader["appointment_from_time_pref"].ToString();
                        var appToTime   = reader["appointment_to_time_pref"].ToString();

                        if (!string.IsNullOrEmpty(appFromTime) || !string.IsNullOrWhiteSpace(appFromTime))
                        {
                            appFromTime = $"1970-01-01T{appFromTime}";
                            c.AppointmentFromTimePreference = DateTime.Parse(appFromTime);
                        }
                        else
                        {
                            c.AppointmentFromTimePreference = null;
                        }

                        if (!string.IsNullOrEmpty(appToTime) || !string.IsNullOrWhiteSpace(appToTime))
                        {
                            appToTime = $"1970-01-01T{appToTime}";
                            c.AppointmentToTimePreference = DateTime.Parse(appToTime);
                        }
                        else
                        {
                            c.AppointmentToTimePreference = null;
                        }

                        c.Pictures = GetComplaintPictures(c.Id);

                        complaints.Add(c);
                    }

                    return(complaints);
                }
        }
Exemple #27
0
 public void ComplaintTerminatedAsDisputeAccepted(Complaint complaint)
 {
 }
        public ActionResult <Complaint> CreateComplaint([FromBody] Complaint complaint)
        {
            var dao = new ComplaintsDao();

            return(dao.CreateComplaint(complaint));
        }
Exemple #29
0
        public async Task <Response <Member> > DeleteMember(int communityID, int userID)
        {
            //Remove Alerts
            List <Alert> Alerts = new List <Alert>();

            Alerts = db.Alerts.Where(x => x.communityID == communityID && x.userID == userID).ToList();
            if (Alerts.Count != 0)
            {
                foreach (var item in Alerts)
                {
                    Alert Alert = await db.Alerts.FindAsync(item.id);

                    db.Alerts.Remove(Alert);
                }
                await db.SaveChangesAsync();
            }


            List <Chat> ChatsTo   = new List <Chat>();
            List <Chat> ChatsFrom = new List <Chat>();

            ChatsTo   = db.Chats.Where(x => x.communityID == communityID && x.to == userID).ToList();
            ChatsFrom = db.Chats.Where(x => x.communityID == communityID && x.from == userID).ToList();

            if (ChatsTo.Count != 0)
            {
                foreach (var item in ChatsTo)
                {
                    Chat chat = await db.Chats.FindAsync(item.chatMessageID);

                    db.Chats.Remove(chat);
                }
                await db.SaveChangesAsync();
            }
            if (ChatsFrom.Count != 0)
            {
                foreach (var item in ChatsFrom)
                {
                    Chat chat = await db.Chats.FindAsync(item.chatMessageID);

                    db.Chats.Remove(chat);
                }
                await db.SaveChangesAsync();
            }


            List <Complaint> Complaints = new List <Complaint>();

            Complaints = db.Complaints.Where(x => x.communityID == communityID && x.userID == userID).ToList();
            if (Complaints.Count != 0)
            {
                foreach (var item in Complaints)
                {
                    Complaint Complaint = await db.Complaints.FindAsync(item.complaintID);

                    db.Complaints.Remove(Complaint);
                }
                await db.SaveChangesAsync();
            }



            Response <Member> responceMember = new Response <Member>();
            Member            member         = new Member();

            member = await(from l in db.Members
                           where l.communityID == communityID && l.userId == userID
                           select l).FirstOrDefaultAsync();
            if (member == null)
            {
                responceMember.status = "Failed: Incorrect CommunityID or UserID";
                responceMember.model  = null;
                return(responceMember);
            }

            db.Members.Remove(member);
            await db.SaveChangesAsync();

            responceMember.status = "Success";
            responceMember.model  = member;
            return(responceMember);
        }
Exemple #30
0
        public async Task <List <Complaint> > FetchUserComplaintAdmin()
        {
            List <Complaint> complaints = new List <Complaint>();

            using (SqlConnection connection = new SqlConnection(this._connectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("FETCH_USER_COMPLAINT_ADMIN", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    try
                    {
                        using (SqlDataReader reader = await command.ExecuteReaderAsync())
                        {
                            while (reader.Read())
                            {
                                var complaint = new Complaint
                                {
                                    CID               = Convert.ToInt32(reader["cid"].ToString()),
                                    RaisedBy          = Convert.ToInt32(reader["raisedby"].ToString()),
                                    RaisedByText      = reader["raisedBy"].ToString(),
                                    TID               = Convert.ToInt32(reader["tid"].ToString()),
                                    CPriority         = Convert.ToInt32(reader["cpriority"].ToString()),
                                    UserContactNumber = reader["user_contact"].ToString(),
                                    UserComment       = reader["user_comment"].ToString(),
                                    CStatus           = Convert.ToInt32(reader["cstatus"].ToString()),
                                    ResolverComment   = reader["resolver_comment"].ToString(),
                                    AssignedToName    = reader["user_name"].ToString(),
                                };
                                var transaction = new RechargeTransaction
                                {
                                    TransactionMessage = reader["errorMessage"].ToString(),
                                    TransactionAmount  = Convert.ToDecimal(reader["rechargeAmount"].ToString()),
                                    TransactionDate    = Convert.ToDateTime(reader["transactionDate"].ToString()).Date,
                                    TransactionMode    = reader["rechargeMode"].ToString(),
                                    TransactionStatus  = reader["transactionStatus"].ToString()
                                };
                                complaint.Transaction = transaction;
                                switch (Convert.ToInt32(reader["cpriority"].ToString()))
                                {
                                case 1:
                                    complaint.CPriorityText = "Low";
                                    break;

                                case 2:
                                    complaint.CPriorityText = "Medium";
                                    break;

                                case 3:
                                    complaint.CPriorityText = "High";
                                    break;
                                }
                                switch (Convert.ToInt32(reader["cstatus"].ToString()))
                                {
                                case 1:
                                    complaint.CStatusText = "Acknowledged";
                                    break;

                                case 2:
                                    complaint.CStatusText = "Assigned";
                                    break;

                                case 3:
                                    complaint.CStatusText = "Work In Progress";
                                    break;

                                case 4:
                                    complaint.CStatusText = "Resolved";
                                    break;
                                }
                                complaints.Add(complaint);
                            }
                        }
                        return(complaints);
                    }
                    catch (Exception ex)
                    {
                        return(null);
                    }
                }
            }
        }
Exemple #31
0
        public async Task <string> AcceptAlertAsync(int id)
        {
            var notification = await _context.Notifications
                               .Include(n => n.NotificationType)
                               .FirstOrDefaultAsync(n => n.Id == id);

            var notificationType = notification.NotificationType.Type;

            switch (notificationType)
            {
            case "TierChange":
                var tempTable = await _context.ChangeClientsTierTemp
                                .Include(cc => cc.Client)
                                .ThenInclude(c => c.ProgramTier)
                                .Include(cc => cc.ProgramTier)
                                .FirstOrDefaultAsync(cc => cc.Id == notification.TempTableId);

                if (tempTable == null)
                {
                    return("Client tier not changed because the change has already been confirmed or denied");
                }

                var client      = tempTable.Client;
                var programTier = tempTable.ProgramTier;

                client.ProgramTier = programTier;

                _context.Clients.Update(client);
                _context.ChangeClientsTierTemp.Remove(tempTable);
                await _context.SaveChangesAsync();

                return("Client tier changed successfully");

            case "Complaint":
                var tempTableComplaint = await _context.ComplaintTemps
                                         .FirstOrDefaultAsync(cm => cm.Id == notification.TempTableId);

                if (tempTableComplaint == null)
                {
                    return("Complaint not changed because the change has already been confirmed or denied");
                }

                var complaint = new Complaint {
                    Subject            = tempTableComplaint.Subject,
                    Description        = tempTableComplaint.Description,
                    MilesProgramNumber = tempTableComplaint.MilesProgramNumber,
                    ComplaintDate      = tempTableComplaint.ComplaintDate
                };

                _context.Complaints.Add(complaint);
                _context.ComplaintTemps.Remove(tempTableComplaint);
                await _context.SaveChangesAsync();

                return("Complaint filed successfully");

            case "SeatAvailability":
                //TODO Pending
                break;

            case "PartnerReference":
                var tempPartner = await _context.AddPartnersTemp
                                  .FirstOrDefaultAsync(pt => pt.Id == notification.TempTableId);

                if (tempPartner == null)
                {
                    return("Partner was not created because its creation has already been confirmed or denied.");
                }

                var newPartner = new Partner
                {
                    Name        = tempPartner.Name,
                    Description = tempPartner.Description
                };

                _context.Partners.Add(newPartner);
                _context.AddPartnersTemp.Remove(tempPartner);
                await _context.SaveChangesAsync();

                return("Partner added successfully.");

            case "AdInsertion":
                //TODO Pending
                break;
            }

            return("An unknown error occurred");
        }
 public static complaintItem convertComplaint(Complaint temp)
 {
     complaintItem complaint = new complaintItem();
     complaint.complaintId = temp.complaintId;
     complaint.userId = temp.userId;
     complaint.title = temp.title;
     complaint.details = temp.details;
     complaint.numLikes = (int)temp.numLikes;
     complaint.numComments = (int)temp.numComments;
     complaint.picture = temp.picture;
     complaint.complaintDate = (DateTime)temp.complaintDate;
     complaint.location = temp.location;
     complaint.latitude = (float)temp.latitude;
     complaint.longitude = (float)temp.longitude;
     complaint.category = temp.category;
     complaint.complaintStatus = temp.complaintStatus;
     complaint.date = temp.date;
     complaint.isAnonymous = temp.isAnonymous;
     complaint.city = temp.city;
     complaint.state = temp.state;
     complaint.country = temp.country;
     complaint.pincode = temp.pincode;
     complaint.thumbImage1 = temp.thumbImage1;
     complaint.thumbImage2 = temp.thumbImage2;
     return complaint;
 }
Exemple #33
0
 public ComplaintModel InsertComplaint(ComplaintModel model)
 {
     //unitOfWork.StartTransaction();
     ComplaintRepository repo = new ComplaintRepository(unitOfWork);
     Complaint complaint = new Complaint();
     AutoMapper.Mapper.Map(model, complaint);
     repo.Insert(complaint);
     AutoMapper.Mapper.Map(complaint,model);
     //unitOfWork.Commit();
     return model;
 }
Exemple #34
0
 public ComplaintController()
 {
     complaint = new Complaint();
 }
        public ActionResult NewComplaint(NewComplaint model)
        {
            try
            {
                ViewBag.ComplaintType = _complaintType.GetAll();
                //ViewBag.SolutionType = _slnType.GetAll();
                //ViewBag.SolutionStatus = _slnStatus.GetAll();
                var user = _user.GetUser(User.Identity.Name);
                ViewBag.Complaints = _vComplaint.FilterComplaint(DateTime.Now.Date, DateTime.Now.Date, 0, 0, 0, user.UserId);

                if (model.Details != "" && model.ComplaintTypeId > 0)
                {
                    if (model.Title.Trim().Contains(" "))
                    {
                        ViewBag.Msg = _help.getMsg(AlertType.danger.ToString(), "Empty space is not allowed in Title, you can replace empty space with character like - or _");
                        return(View(model));
                    }
                    //if (!string.IsNullOrEmpty(model.ComplaintOwnerEmail))
                    //{
                    //    if (!_help.IsValidEmail(model.ComplaintOwnerEmail))
                    //    {
                    //        ViewBag.Msg = _help.getMsg(AlertType.danger.ToString(), "Invalid email address!");
                    //        return View(model);
                    //    }
                    //}
                    //if (!_help.IsValidPhone(model.MobileNo))
                    //{
                    //    ViewBag.Msg = _help.getMsg(AlertType.danger.ToString(), "Invalid phone number!");
                    //    return View(model);
                    //}
                    var compType = _complaintType.GetRecordById(model.ComplaintTypeId);
                    model.Title = compType.Name.Replace(" ", "_") + "_" + model.Title + "_" + model.MobileNo;
                    var cmp = _complaint.GetComplaintByTitle(model.Title);
                    if (cmp == null)
                    {
                        var soln = _slnStatus.GetRecordById(1);
                        if (soln.Name.ToUpper() == "RESOLVED FULLY")
                        {
                            model.StatusId = 4;
                        }
                        else
                        {
                            if (soln.Name.ToUpper() == "REQUIRED TECHNICAL SKILL")
                            {
                                model.StatusId = 3;
                            }
                            else
                            {
                                model.StatusId = 2;
                            }
                        }

                        Complaint nc = new Complaint();
                        nc.Code = model.Code;
                        nc.ComplaintOwnerEmail = null;
                        nc.ComplaintOwnerName  = null;
                        nc.ComplaintTypeId     = model.ComplaintTypeId;
                        nc.Date             = DateTime.Now;
                        nc.Details          = model.Details;
                        nc.Location         = null;
                        nc.MobileNo         = "08066666666";
                        nc.RegisteredBy     = user.UserId;
                        nc.SolutionStatusId = 1;
                        nc.StatusId         = model.StatusId;
                        nc.Title            = model.Title;

                        using (var cmd = new TransactionScope())
                        {
                            try
                            {
                                _complaint.Create(nc);
                                //ComplaintActivity ca = new ComplaintActivity();
                                //ca.ComplaintId = nc.ComplaintId;
                                //ca.Date = DateTime.Now;
                                //ca.RecordedBy = -1;
                                //ca.SolutionDetails = "No Solution Yet";
                                //ca.SolutionStatusId = 1;
                                ////ca.SolutionTypeId = model.SolutionTypeId;
                                //_complaintActivity.Create(ca);
                                cmd.Complete();
                                ViewBag.Msg = _help.getMsg(AlertType.success.ToString(), "Complaint added successful!");
                                return(View(new NewComplaint()));
                            }
                            catch (Exception er)
                            {
                                cmd.Dispose();
                                ViewBag.Msg = _help.getMsg(AlertType.danger.ToString(), er.Message);
                                return(View(model));
                            }
                        }
                    }
                    else
                    {
                        ViewBag.Msg = _help.getMsg(AlertType.danger.ToString(), "Complaint title already exist!");
                        return(View(model));
                    }
                }
                else
                {
                    ViewBag.Msg = _help.getMsg(AlertType.danger.ToString(), "All fields with * are required!");
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                ViewBag.Msg = _help.getMsg(AlertType.danger.ToString(), ex.Message);
                return(View(model));
            }
        }
Exemple #36
0
        static void Main(string[] args)
        {
            Console.Write("Имя пользователя SQL Server: ");
            string sqlUser = Console.ReadLine();

            Console.Write("Пароль SQL Server: ");
            string sqlPassword = Console.ReadLine();

            Console.Write("Имя пользователя MongoDB: ");
            string mongoUser = Console.ReadLine();

            Console.Write("Пароль MongoDB: ");
            string mongoPassword = Console.ReadLine();

            try
            {
                MongoConnection mongoConnection = new MongoConnection("ds229008.mlab.com", "29008", mongoUser, mongoPassword);
                mongoConnection.Connect();

                SqlConnection sqlConnection = new SqlConnection("ELISEY", /*"1433",*/ sqlUser, sqlPassword);
                sqlConnection.Connect();

                Console.Clear();

                #region Заполнение БД
                Doctor doctor = new Doctor("Иванова", "Людмила", "Ивановна", sqlConnection);
                doctor.Save(sqlConnection);

                doctor.SignUp("doctor", "hello", "hello");
                doctor.SignIn("doctor", "hello", sqlConnection);

                Patient patient = new Patient("Карапузов", "Иван", "Андреевич");
                patient.Save(sqlConnection);

                Problem problem = new Problem("Не могу больше держаться", new DateTime(2018, 4, 17), patient, doctor, sqlConnection);
                problem.Save();
                Console.WriteLine(problem);

                Complaint complaint1 = new Complaint("Мне больно", problem, sqlConnection);
                complaint1.Save();

                Complaint complaint2 = new Complaint("Очень", problem, sqlConnection);
                complaint2.Save();

                Diagnosis diagnosis = new Diagnosis("Простуда", problem, doctor, sqlConnection);
                diagnosis.Save();
                Console.WriteLine(diagnosis);

                Archetype pulse = new Archetype("Пульс");
                pulse.Save(sqlConnection);

                Archetype pressure = new Archetype("Давление");
                pressure.Save(sqlConnection);

                Console.WriteLine(pressure);

                Symptom symptom1 = new Symptom(diagnosis, pulse, "60", sqlConnection);
                symptom1.Save();

                Symptom symptom2 = new Symptom(diagnosis, pressure, "120/80", sqlConnection);
                symptom2.Save();

                Console.WriteLine(symptom1);
                Console.WriteLine(symptom2);

                Medicament medicament = new Medicament("Мезим");
                medicament.Save(sqlConnection);

                Medicament medicament2 = new Medicament("Терафлю");
                medicament2.Save(sqlConnection);

                Medicament medicament3 = new Medicament("Нурофен");
                medicament3.Save(sqlConnection);

                Prescription prescription = new Prescription(medicament, diagnosis, sqlConnection);
                prescription.Save();

                Prescription prescription2 = new Prescription(medicament2, diagnosis, sqlConnection);
                prescription2.Save();

                Prescription prescription3 = new Prescription(medicament3, diagnosis, sqlConnection);
                prescription3.Save();

                Console.WriteLine(prescription3);

                Article article1 = new Article("Повышенная вязкость крови – один из факторов развития кардиоваскулярных осложнений у больных с истинной полицитемией",
                                               "https://research-journal.org/medical/povyshennaya-vyazkost-krovi-odin-iz-faktorov-razvitiya-kardiovaskulyarnyx-oslozhnenij-u-bolnyx-s-istinnoj-policitemiej/",
                                               "Разнообразие клинических проявлений и высокий процент развития осложнений, отличающихся по характеру и тяжести, у больных эритремией продолжает создавать трудности как в лечении, так и в повышении качества жизни больных [6, С. 32]. Изменение реологических свойств и повышение вязкости крови, по результатам наших исследований, оказывают большее влияние на сердечно-сосудистую систему с развитием целого ряда синдромов и симптомов – гипертоническая болезнь, ишемическая болезнь сердца, симптоматическая артериальная гипертензия в 53,4% случаев. Возрастной пик заболеваемости, приходящий на пациентов среднего и пожилого возраста, делает их более уязвимыми в отношении развития тромботических осложнений. В рамках нашего исследования истинной полицитемии более подвержены мужчины  от 40 до 70 лет.",
                                               mongoConnection);
                Article article2 = new Article("Центральная гемодинамика, тиреоидный статус и дисфункции эндотелия у больных артериальной гипертонией в условиях высокогорья",
                                               "https://research-journal.org/medical/centralnaya-gemodinamika-tireoidnyj-status-i-disfunkcii-endoteliya-u-bolnyx-arterialnoj-gipertoniej-v-usloviyax-vysokogorya/",
                                               "Установлено, что снижение продукции NO с одновременным снижением концентрации тиреоидных гормонов вызывают нарушения интракардиальной гемодинамики, изменения структурно-функционального состояния ЛЖ и утяжеляют течение артериальной гипертонии.",
                                               mongoConnection);
                Article article3 = new Article("Сочетанные изменения экспрессии генов cstb и acap3 при симптоматической эпилепсии и болезни паркинсона",
                                               "https://research-journal.org/medical/sochetannye-izmeneniya-ekspressii-genov-cstb-i-acap3-pri-simptomaticheskoj-epilepsii-i-bolezni-parkinsona/",
                                               "Кроме того, у женщин наблюдалось снижение уровня мРНК гена CSTB при эпилепсии(примерно в 3 раза) и при болезни Паркинсона(примерно в 2.5 раза).Полученные данные указывают на возможное участие исследованных генов в патогенезе симптоматической эпилепсии и болезни Паркинсона.",
                                               mongoConnection);
                Tag tag1 = new Tag("Карапузов", mongoConnection);
                Tag tag2 = new Tag("Эритремия", mongoConnection);
                Tag tag3 = new Tag("Гипертония", mongoConnection);
                Tag tag4 = new Tag("Карапузовдержись", mongoConnection);

                article1.Save();
                article2.Save();
                article3.Save();

                tag1.Save();
                tag2.Save();
                tag3.Save();
                tag4.Save();

                Association association1 = new Association("Ассоциация с наибольшим количеством тегов", mongoConnection, sqlConnection);
                association1.Tags.AddRange(new Tag[]
                {
                    tag1,
                    tag2,
                    tag3
                });
                association1.Article = article1;
                association1.MedicineObjects.AddRange(new IEhrObject[]
                {
                    patient,
                    problem,
                    medicament2,
                    medicament3
                });
                association1.Save();

                Association association2 = new Association("Ассоциация про Карапузова", mongoConnection, sqlConnection);
                association2.Tags.AddRange(new Tag[]
                {
                    tag1,
                    tag3
                });
                association2.Article = article2;
                association2.MedicineObjects.AddRange(new IEhrObject[]
                {
                    patient,
                    medicament
                });
                association2.Save();

                Association association3 = new Association("Ассоциация с наименьшим количеством тегов", mongoConnection, sqlConnection);
                association3.Tags.AddRange(new Tag[]
                {
                    tag1,
                    tag4
                });
                association3.Article = article3;
                association3.MedicineObjects.AddRange(new IEhrObject[]
                {
                    medicament,
                    medicament3
                });
                association3.Save();
                #endregion

                #region Поиск по тегам
                Tag findTag1 = new Tag();
                Tag findTag2 = new Tag();
                Tag findTag3 = new Tag();
                Tag findTag4 = new Tag();
                Tag findTag5 = new Tag();

                try
                {
                    Console.Write("Введите тег: ");
                    findTag1.GetByContent(Console.ReadLine(), mongoConnection); //"Карапузов"
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                try
                {
                    Console.Write("Введите тег: ");
                    findTag2.GetByContent(Console.ReadLine(), mongoConnection); //"Эритремия"
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                try
                {
                    Console.Write("Введите тег: ");
                    findTag3.GetByContent(Console.ReadLine(), mongoConnection); //"Гипертония"
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                try
                {
                    Console.Write("Введите тег: ");
                    findTag4.GetByContent(Console.ReadLine(), mongoConnection); //"Грипп"
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Console.WriteLine();

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                List <KeyValuePair <int, Association> > associations = Association.GetAssociationListByTag(new Tag[]
                {
                    findTag1,
                    findTag2,
                    findTag3,
                    findTag4
                }, sqlConnection, mongoConnection);
                stopwatch.Stop();

                foreach (KeyValuePair <int, Association> association in associations)
                {
                    Console.WriteLine(association.Value);
                    Console.WriteLine("Число совпадений: " + association.Key);
                    Console.WriteLine();
                }
                Console.WriteLine("Затрачено времени: " + stopwatch.Elapsed);
                #endregion
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }
Exemple #37
0
 public void AddComplaint(Complaint complaint)
 {
     _dbContext.Complaints.Add(complaint);
     _dbContext.SaveChanges();
 }
 public static Complaint convertComplaint(complaintItem item)
 {
     Complaint temp = new Complaint();
     temp.userId = item.userId;
     temp.title = item.title;
     temp.details = item.details;
     temp.numLikes = (int)item.numLikes;
     temp.numComments = (int)item.numComments;
     temp.picture = item.picture;
     temp.complaintDate = (DateTime)item.complaintDate;
     temp.location = item.location;
     temp.latitude = (float)item.latitude;
     temp.longitude = (float)item.longitude;
     temp.category = item.category;
     temp.complaintStatus = item.complaintStatus;
     temp.date = item.date;
     temp.isAnonymous = item.isAnonymous;
     temp.city = item.city;
     temp.state = item.state;
     temp.country = item.country;
     temp.pincode = item.pincode;
     return temp;
 }