public ActionResult <SuccessMessageModel> Reschedule(int id, DateModel date) { try{ int?employerId = ClaimHelper.GetIdFromClaimIdentity((ClaimsIdentity)this.ControllerContext.HttpContext.User.Identity); if (employerId == null) { return(Unauthorized(new ErrorMessageModel("Utilizador não existe!"))); } WorkDAO workDao = new WorkDAO(_connection); WorkDetailsModel work = workDao.FindById(id, (int)employerId); if (work == null) { return(BadRequest(new ErrorMessageModel("O trabalho não existe ou não está associado ao Employer!"))); } bool updated = workDao.updateDate(id, date); if (updated) { return(Ok(new SuccessMessageModel("Data atualizada com sucesso!"))); } else { return(BadRequest(new ErrorMessageModel("Erro! A data não foi atualizada!"))); } } catch (Exception e) { return(BadRequest(new ErrorMessageModel(e.Message))); } }
/// <summary> /// Método de verificação dos dados do pagamento /// </summary> /// <param name="payment"></param> /// <param name="jobId"></param> /// <param name="employerId"></param> /// <returns>Invoice ou Exception</returns> public Invoice makePayment(Invoice payment, int jobId, int employerId) { WorkDAO workDAO = new WorkDAO(_connection); WorkDetailsModel job = workDAO.FindById(jobId); payment.ConfirmedPayment = false; if (job == null) { throw new Exception("Trabalho não existe!"); } if (job.Employer.Id != employerId) { throw new Exception("Não tem acesso a este trabalho!"); } if (!job.FinishedConfirmedByEmployer || !job.FinishedConfirmedByMate) { throw new Exception("Trabalho não foi confirmado como terminado!"); } bool paymentTypeAllowed = false; for (int i = 0; i < job.JobPost.PaymentMethod.Length; i++) { if (job.JobPost.PaymentMethod[i].Equals(payment.PaymentType)) { paymentTypeAllowed = true; break; } } if (!paymentTypeAllowed) { throw new Exception("Método de pagamento inválido para este trabalho!"); } if (payment.PaymentType.Equals(Payment.PAYPAL)) { payment = MakePaymentWithPayPal(payment, job, jobId); } if (payment.PaymentType.Equals(Payment.CRYPTO)) { Console.WriteLine("Pagamento feito com Crypto!"); } if (payment.PaymentType.Equals(Payment.MBWAY)) { Console.WriteLine("Pagamento feito com MBWay!"); } if (payment.PaymentType.Equals(Payment.MONEY)) { payment = MakePaymentWithMoney(payment, job, jobId); } return(payment); }
/// <summary> /// Método para confirmar o trabalho como realizado, /// removendo-o posteriormente da lista de trabalhos /// pendentes do Mate /// </summary> /// <param name="jobId">Id do trabalho a marcar como concluído</param> /// <param name="userId">Id do utilizador que marca o trabalho como /// concluído</param> /// <returns>Verdadeiro em caso de sucesso, falso caso contrário</returns> public bool MarkJobAsDone(int jobId, int userId) { WorkDAO workDAO = new WorkDAO(_connection); WorkDetailsModel job = workDAO.FindById(jobId); if (job == null) { throw new Exception("ID de trabalho Inválido!"); } EmployerDAO employerDAO = new EmployerDAO(_connection); Employer employer = employerDAO.FindEmployerById(userId); bool foundEmployer = (employer != null); if (foundEmployer) { using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "UPDATE dbo.[Job] SET FinishedConfirmedByEmployer = @fnshdEmployer " + "WHERE Id = @id"; cmd.Parameters.Add("@id", SqlDbType.Int).Value = jobId; cmd.Parameters.Add("@fnshdEmployer", SqlDbType.Bit).Value = true; cmd.ExecuteNonQuery(); } return(true); } MateDAO mateDAO = new MateDAO(_connection); Mate mate = mateDAO.FindMateById(userId); bool foundMate = (mate != null); if (foundMate) { using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "UPDATE dbo.[Job] SET FinishedConfirmedByMate = @fnshdMate " + "WHERE Id = @id"; cmd.Parameters.Add("@id", SqlDbType.Int).Value = jobId; cmd.Parameters.Add("@fnshdMate", SqlDbType.Bit).Value = true; cmd.ExecuteNonQuery(); } return(true); } throw new Exception("ID do utilizador Inválido!"); }
public ActionResult <WorkDetailsModel> FindById(int id) { WorkDAO workDao = new WorkDAO(_connection); WorkDetailsModel work = workDao.FindById(id); if (work == null) { return(NotFound(new ErrorMessageModel("Trabalho não encontrado"))); } return(Ok(work)); }
/// <summary> /// Método para obter um Invoice por Id /// </summary> /// <param name="userId"></param> /// <param name="jobId"></param> /// <returns>Invoice ou Exception</returns> public Invoice GetInvoiceByID(int userId, int jobId) { WorkDAO workDAO = new WorkDAO(_connection); WorkDetailsModel job = workDAO.FindById(jobId); if (job == null) { throw new Exception("Trabalho não existe!"); } if (job.Employer.Id != userId && job.Mate.Id != userId) { throw new Exception("Não tem autorização para aceder a este pagamento!"); } Invoice invoice = null; using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "Select Id, Value, PaymentTypeId, Date, ConfirmedPayment FROM dbo.[Invoice] where Id=@id"; cmd.Parameters.Add("@id", SqlDbType.Int).Value = job.InvoiceId; using SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { invoice = new Invoice(); reader.Read(); invoice.Id = reader.GetInt32(0); invoice.Value = reader.GetDouble(1); invoice.PaymentType = (Payment)reader.GetInt32(2); invoice.Date = reader.GetDateTime(3); invoice.ConfirmedPayment = reader.GetBoolean(4); } } if (invoice == null) { throw new Exception("Pagamento ainda não foi realizado!"); } return(invoice); }
/// <summary> /// Método para realizar o pagamento com Paypal /// </summary> /// <param name="payment"></param> /// <param name="job"></param> /// <param name="jobId"></param> /// <returns>Invoice ou Exception</returns> private Invoice MakePaymentWithPayPal(Invoice payment, WorkDetailsModel job, int jobId) { if (!job.JobPost.Tradable) { if (job.JobPost.InitialPrice.Equals(payment.Value)) { using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandText = "INSERT INTO dbo.[Invoice] (Value, PaymentTypeId, Date, ConfirmedPayment)" + "VALUES (@vl, @ptId, @dt, @cnfrdPmnt); SELECT @@Identity"; cmd.Parameters.Add("@vl", SqlDbType.Float).Value = payment.Value; cmd.Parameters.Add("@ptId", SqlDbType.Int).Value = payment.PaymentType; cmd.Parameters.Add("@dt", SqlDbType.DateTime).Value = DateTime.Now; cmd.Parameters.Add("@cnfrdPmnt", SqlDbType.Bit).Value = payment.ConfirmedPayment; payment.Id = int.Parse(cmd.ExecuteScalar().ToString()); } using (SqlCommand cmdSetInvoice = _connection.Fetch().CreateCommand()) { cmdSetInvoice.CommandText = "UPDATE dbo.[Job]" + "SET InvoiceId = @pId " + "WHERE dbo.[Job].Id = @jid"; cmdSetInvoice.Parameters.Add("@pId", SqlDbType.Int).Value = payment.Id; cmdSetInvoice.Parameters.Add("@jid", SqlDbType.Int).Value = jobId; cmdSetInvoice.ExecuteScalar(); } //Change in production string email = "*****@*****.**"; payment.Link = String.Format("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&amount={0}¤cy_code=EUR&business={1}&item_name={2}&return=Page", job.JobPost.InitialPrice, email, job.JobPost.Title); return(payment); } throw new Exception("Preço diferente do negociado!"); } else { throw new Exception("Preço Negociavel ainda não foi implementado!"); } }
/// <summary> /// Método para realizar o pagamento com Dinheiro vivo /// </summary> /// <param name="payment"></param> /// <param name="job"></param> /// <param name="jobId"></param> /// <returns>Invoice ou Exception</returns> private Invoice MakePaymentWithMoney(Invoice payment, WorkDetailsModel job, int jobId) { if (!job.JobPost.Tradable) { if (job.JobPost.InitialPrice.Equals(payment.Value)) { using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandText = "INSERT INTO dbo.[Invoice] (Value, PaymentTypeId, Date, ConfirmedPayment)" + "VALUES (@vl, @ptId, @dt, @cnfrdPmnt); SELECT @@Identity"; cmd.Parameters.Add("@vl", SqlDbType.Float).Value = payment.Value; cmd.Parameters.Add("@ptId", SqlDbType.Int).Value = payment.PaymentType; cmd.Parameters.Add("@dt", SqlDbType.DateTime).Value = DateTime.Now; cmd.Parameters.Add("@cnfrdPmnt", SqlDbType.Bit).Value = payment.ConfirmedPayment; payment.Id = int.Parse(cmd.ExecuteScalar().ToString()); } using (SqlCommand cmdSetInvoice = _connection.Fetch().CreateCommand()) { cmdSetInvoice.CommandText = "UPDATE dbo.[Job]" + "SET InvoiceId = @pId " + "WHERE dbo.[Job].Id = @jid"; cmdSetInvoice.Parameters.Add("@pId", SqlDbType.Int).Value = payment.Id; cmdSetInvoice.Parameters.Add("@jid", SqlDbType.Int).Value = jobId; cmdSetInvoice.ExecuteScalar(); } return(payment); } throw new Exception("Preço diferente do negociado!"); } else { throw new Exception("Preço Negociavel ainda não foi implementado!"); } }
/// <summary> /// Método para confirmar o pagamento /// </summary> /// <param name="jobId"></param> /// <param name="mateId"></param> /// <returns>bool ou Exception</returns> public bool confirmPayment(int jobId, int mateId) { WorkDAO workDAO = new WorkDAO(_connection); WorkDetailsModel job = workDAO.FindById(jobId); if (job == null) { throw new Exception("Trabalho não existe!"); } if (job.Mate.Id != mateId) { throw new Exception("Não tem acesso a este trabalho!"); } Invoice invoice = this.GetInvoiceByID(mateId, jobId); if (invoice == null) { throw new Exception("Pagamento ainda não foi realizado!"); } using (SqlCommand cmdSetInvoice = _connection.Fetch().CreateCommand()) { cmdSetInvoice.CommandText = "UPDATE dbo.[Invoice]" + "SET ConfirmedPayment = @cfrmdPmnt " + "WHERE dbo.[Invoice].Id = @Id"; cmdSetInvoice.Parameters.Add("@Id", SqlDbType.Int).Value = invoice.Id; cmdSetInvoice.Parameters.Add("@cfrmdPmnt", SqlDbType.Bit).Value = true; cmdSetInvoice.ExecuteScalar(); } return(true); }
public void CanFindWorkByIdTest() { IMateDAO <Mate> MateDAO = new MateDAO(_connection); Mate testMate = new Mate(); testMate.FirstName = "Miguel"; testMate.LastName = "Dev"; testMate.UserName = "******"; testMate.Password = "******"; testMate.Email = "*****@*****.**"; testMate.Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; testMate.Address = "Figueiró"; testMate.Categories = new[] { Categories.CLEANING, Categories.PLUMBING }; testMate.Rank = Ranks.SUPER_MATE; testMate.Range = 20; Mate returned = MateDAO.Create(testMate); IEmployerDAO <Employer> EmployerDAO = new EmployerDAO(_connection); Employer testEmployer = new Employer(); testEmployer.FirstName = "Marcelo"; testEmployer.LastName = "Carvalho"; testEmployer.UserName = "******"; testEmployer.Password = "******"; testEmployer.Email = "*****@*****.**"; testEmployer.Description = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."; testEmployer.Address = "Lixa"; Employer returnedEmp = EmployerDAO.Create(testEmployer); IJobDAO jobPostDAO = new JobDAO(_connection); JobPost testPost = new JobPost(); testPost.Title = "Canalização Estourada"; testPost.Category = Categories.PLUMBING; testPost.ImagePath = "path/image"; testPost.Description = "Grande estouro nos canos da sanita"; testPost.Tradable = true; testPost.InitialPrice = 60.6; testPost.Address = "Rua sem fim"; testPost.PaymentMethod = new[] { Payment.PAYPAL, Payment.MONEY }; JobPost jobReturned = jobPostDAO.Create(returnedEmp.Id, testPost); DateTime date = new DateTime(2020, 01, 16); Job job = new Job(); job.Date = date; job.Mate = returned.Id; job.JobPost = jobReturned.Id; job.FinishedConfirmedByEmployer = false; job.FinishedConfirmedByMate = false; job.Employer = returnedEmp.Id; IWorkDAO workDAO = new WorkDAO(_connection); Job created = workDAO.Create(returnedEmp.Id, job); WorkDetailsModel found = workDAO.FindById(created.Id); Assert.Equal(created.Date, found.Date); Assert.Equal(created.Mate, found.Mate.Id); Assert.Equal(created.JobPost, found.JobPost.Id); Assert.Equal(created.FinishedConfirmedByEmployer, found.FinishedConfirmedByEmployer); Assert.Equal(created.FinishedConfirmedByMate, found.FinishedConfirmedByMate); Assert.Equal(created.Employer, found.Employer.Id); _fixture.Dispose(); }
/// <summary> /// Método para encontrar um trabalho por Id /// </summary> /// <param name="id">Id do trabalho pretendido</param> /// <returns>Retorna o trabalho pretendido, se nao existir /// retorna null </returns> public WorkDetailsModel FindById(int id) { WorkDetailsModel wd = null; bool contains = false; int _mateId = 0; int _employerId = 0; int _postId = 0; int?_invoiceId = 0; using (SqlCommand cmd = _connection.Fetch().CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT Date, MateId, JobPostId, InvoiceId, FinishedConfirmedByEmployer, FinishedConfirmedByMate, EmployerId " + "FROM dbo.[Job] " + "WHERE Id=@id"; cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; using (SqlDataReader reader = cmd.ExecuteReader()) { if (contains = reader.HasRows) { wd = new WorkDetailsModel(); reader.Read(); wd.Date = reader.GetDateTime(0); _mateId = reader.GetInt32(1); _postId = reader.GetInt32(2); //guardar o id do invoice para mais tarde fazer o find if (reader.IsDBNull(3)) { _invoiceId = null; } else { _invoiceId = reader.GetInt32(3); } wd.FinishedConfirmedByEmployer = reader.GetBoolean(4); wd.FinishedConfirmedByMate = reader.GetBoolean(5); _employerId = reader.GetInt32(6); } } } if (contains) { IMateDAO <Mate> mateDAO = new MateDAO(_connection); Mate mate = mateDAO.FindMateById(_mateId); wd.Mate = mate; IJobDAO postDao = new JobDAO(_connection); JobPost post = postDao.FindById(_postId); wd.JobPost = post; if (_invoiceId != null) { wd.InvoiceId = (int)_invoiceId; } IEmployerDAO <Employer> employerDAO = new EmployerDAO(_connection); Employer employer = employerDAO.FindEmployerById(_employerId); wd.Employer = employer; } else { return(null); } return(wd); }