/// <summary> /// 数据源:申请单 /// </summary> /// <param name="PRContents"></param> /// <param name="PurchaseItemRepository"></param> /// <param name="CostCenterRepository"></param> /// <param name="PartRepository"></param> public PurchaseContentGridViewModel(List <PRContent> PRContents, IPurchaseItemRepository PurchaseItemRepository, ICostCenterRepository CostCenterRepository, IPartRepository PartRepository, ITaskHourRepository TaskHourRepository) { rows = new List <PurchaseContentGridRowModel>(); string state = ""; foreach (PRContent _content in PRContents) { PurchaseItem _purchaseItem = PurchaseItemRepository.QueryByID(_content.PurchaseItemID); try { state = Enum.GetName(typeof(PurchaseItemStatus), _purchaseItem.State); } catch { state = ""; } String _costcenter; CostCenter _centerObj = CostCenterRepository.QueryByID(_purchaseItem.CostCenterID); if (_centerObj != null) { _costcenter = _centerObj.Name; } else { _costcenter = ""; } string ERPNo = string.Empty; //if (_purchaseItem.PartID > 0) //{ // Part _part = PartRepository.QueryByID(_purchaseItem.PartID); // ERPNo = _part.ERPPartID; //} ERPNo = _content.ERPPartID; SetupTaskStart _setupTask = new SetupTaskStart(); #region 外发内容 if (_content.TaskID > 0) { TaskHour _taskhour = TaskHourRepository.TaskHours.Where(h => h.TaskID == _content.TaskID).OrderByDescending(h => h.TaskHourID).FirstOrDefault(); if (_taskhour != null) { _setupTask.TaskID = _taskhour.TaskID; _setupTask.MachinesName = TaskHourRepository.GetMachineByTask(_taskhour.TaskID) ?? ""; _setupTask.TotalTime = TaskHourRepository.GetTotalHourByTaskID(_taskhour.TaskID); _setupTask.UserName = _taskhour.Operater; _setupTask.MachinesCode = _taskhour.MachineCode; } } #endregion rows.Add(new PurchaseContentGridRowModel(_content, state, _costcenter, ERPNo, _setupTask)); } Page = 1; Total = PRContents.Count(); Records = 500; }
protected void btnAddCostCenter_Click(object sender, EventArgs e) { accountManager = new AccountManager(this); costCenter = new CostCenter(); if (treCostCenter.SelectedNode != null) { CostCenter original_costCenter = accountManager.GetCostCenter(Convert.ToInt32(treCostCenter.SelectedNode.Value)); costCenter.CopyPropertiesFrom(original_costCenter); if (!String.IsNullOrEmpty(cboTreeCostCenters.SelectedValue)) costCenter.ParentId = Convert.ToInt32(cboTreeCostCenters.SelectedValue); else costCenter.ParentId = null; costCenter.Name = txtName.Text; accountManager.UpdateCostCenter(original_costCenter, costCenter); } else { costCenter.CompanyId = Company.CompanyId; costCenter.Name = txtName.Text; if (!String.IsNullOrEmpty(cboTreeCostCenters.SelectedValue)) costCenter.ParentId = Convert.ToInt32(cboTreeCostCenters.SelectedValue); else costCenter.ParentId = null; accountManager.InsertCostCenter(costCenter); } BindTree(); }
public IList <CostCenter> GetCostCenter() { IList <CostCenter> list = new List <CostCenter>(); CostCenter costCenter = new CostCenter(); costCenter.Id = 1; costCenter.Code = "0110-94300"; costCenter.Name = "cost center 1"; list.Add(costCenter); costCenter.Id = 2; costCenter.Code = "0110-94301"; costCenter.Name = "cost center 2"; list.Add(costCenter); costCenter.Id = 3; costCenter.Code = "0111-76000"; costCenter.Name = "cost center 3"; list.Add(costCenter); costCenter.Id = 4; costCenter.Code = "0110-84000"; costCenter.Name = "cost center 4"; list.Add(costCenter); return(list); }
public async Task <IActionResult> Edit(string id, [Bind("Code,Name, ManagementId")] CostCenter costCenter) { if (ModelState.IsValid) { var cc = await _context.CostCenters.FindAsync(id); try { _context.CostCenters.Remove(cc); _context.Add(costCenter); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CostCenterExists(costCenter.Code)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index), new { codeCheck = "On", nameCheck = "On", managementIdCheck = "On" })); } return(View(costCenter)); }
public void Execute() { TenantDAO tenantDAO = new TenantDAO(sqlConnection); CostCenterDAO costCenterDAO = new CostCenterDAO(sqlConnection); Tenant storedTenant = tenantDAO.GetTenant(tenant.id); // Se o tenant já existe no banco bem como sua massa de dados, então só altera alguns dados if (storedTenant != null) { // seta identificador e nome amigável tenantDAO.SetTenant(tenant); // seta departamento raiz com o nome do tenant CostCenter mainCostCenter = costCenterDAO.GetMainCostCenter(tenant.id); mainCostCenter.name = tenant.alias; costCenterDAO.SetCostCenter(mainCostCenter); return; } // Cria um novo tenant e sua massa de dados inicial int?tenantId = tenantDAO.SetTenant(tenant); tenant.id = tenantId.Value; SetTenantPreference(); SetTenantAccess(); SetTenantDefaultSmtp(); SetTenantRootCC(); }
private List <ReimbursementDto> GetRBDetail(List <ReimbursementDto> temp) { List <ReimbursementDto> Final = new List <ReimbursementDto>(); foreach (ReimbursementDto dto in temp) { if (!string.IsNullOrEmpty(dto.CC_ID)) { CostCenter cc = _costCenterRepository.GetByID(dto.CC_ID).AsNoTracking().FirstOrDefault(); if (cc != null) { dto.CC_Name = cc.CC_Name; } } if (!string.IsNullOrEmpty(dto.U_ID)) { User u = _userRepository.GetByID(dto.U_ID).AsNoTracking().FirstOrDefault(); if (u != null) { dto.U_Name = u.U_Name; dto.U_Portrait = u.U_Portrait; } } Final.Add(dto); } return(Final); }
public ActionResult Edit(CostCenter model) { try { ViewBag.CostCenterCategory = dbcontext.CostCenterCategory.ToList().Select(m => new { Code = m.CategoryCode + "------[" + m.CategoryDesc + ']', ID = m.ID }); if (model.CategoryCode == "0" || model.CategoryCode == null) { ModelState.AddModelError("", HR.Resource.Payroll.CategoryCodemustenter); return(View(model)); } var record = dbcontext.CostCenter.FirstOrDefault(m => m.ID == model.ID); record.CategoryCode = model.CategoryCode; record.CostCenterCode = model.CostCenterCode; record.CostCenterDesc = model.CostCenterDesc; record.CostCenterAltDesc = model.CostCenterAltDesc; record.CostCenterMask = model.CostCenterMask; record.CostCenterMaskDesc = model.CostCenterMaskDesc; dbcontext.SaveChanges(); return(RedirectToAction("index")); } catch (DbUpdateException) { TempData["Message"] = HR.Resource.Basic.thiscodeIsalreadyexists; return(View(model)); } catch (Exception e) { return(View(model)); } }
public void OnGet(string OrderId) { Order = new Application.Oders.GetOrder(_ctx).Do(OrderId); OrderProductss = _ctx.OrderProducts.Include(x => x.Product).Where(x => x.OrderId == Order.Id); if (Order.LocationId != null) { Location = _ctx.Locations.FirstOrDefault(x => x.Id == Order.LocationId); } if (Order.CostcenterId != null) { CostCenter = _ctx.CostCenters.FirstOrDefault(x => x.Id == Order.CostcenterId); } List <OrderProductForDisplay> ProductListx = new List <OrderProductForDisplay>(); foreach (var p in OrderProductss) { OrderProductForDisplay pp = new OrderProductForDisplay { Name = p.Product.Name, Unit = p.Product.Unit, Colour = p.Product.Colour, Price = p.Product.Price, ImageUrl = p.Product.ImageUrl, QTY = p.Qty }; ProductListx.Add(pp); } ProductList = ProductListx; // ApplicationUser = _ctx.Users.FirstOrDefault(x => x.Id = Order.) }
private void SetInergyLocation() { CostCenter costCenter = new CostCenter(SessionManager.GetSessionValueNoRedirect(this.Page, SessionStrings.CONNECTION_MANAGER)); costCenter.Id = Int32.Parse(cmbCostCenter.SelectedValue); DataSet ds = costCenter.GetAll(true); if (ds.Tables[0].Rows.Count > 1 || ds.Tables[0].Rows.Count == 0) { cmbInergyLocation.SelectedValue = ApplicationConstants.INT_NULL_VALUE.ToString(); cmbInergyLocation.Text = String.Empty; //When SelectedValue property of cmbInergyLocation is set, the SelectedIndexChanged event of cmbInergyLocation is not fired. //This is why we have to manually set the currency when the user selects a cost center which causes the cmbInergyLocation combo to //change its selected value SetCurrency(); return; } int idInergyLocation = ApplicationConstants.INT_NULL_VALUE; idInergyLocation = (int)ds.Tables[0].Rows[0]["IdInergyLocation"]; if (idInergyLocation != ApplicationConstants.INT_NULL_VALUE) { cmbInergyLocation.SelectedValue = idInergyLocation.ToString(); } else { cmbInergyLocation.SelectedValue = ApplicationConstants.INT_NULL_VALUE.ToString(); cmbInergyLocation.Text = String.Empty; } //When SelectedValue property of cmbInergyLocation is set, the SelectedIndexChanged event of cmbInergyLocation is not fired. //This is why we have to manually set the currency when the user selects a cost center which causes the cmbInergyLocation combo to //change its selected value SetCurrency(); }
private List <CostCenter> ReadTextCostCenter_2018() { List <CostCenter> costcenters = new List <CostCenter>(); path = Path.Combine(basepath, @"Data\CostCenter_exclude.txt"); using (StreamReader reader = new StreamReader(path)) { using (TextFieldParser parser = new TextFieldParser(reader)) { parser.TextFieldType = FieldType.Delimited; parser.SetDelimiters("\t"); while (!parser.EndOfData) { string[] fields = parser.ReadFields(); var costcenter = new CostCenter(); //if (!fields[1].ToString().Contains("┬бр┼╘б")) //{ costcenter.CostCenterID = fields[0].ToString(); costcenter.CostCenterName = fields[1].ToString(); costcenter.ShortName = fields[1].ToString().Split(new char[] { '-' })[0]; costcenter.Status = RecordStatus.Active; costcenter.NewCreateTimeStamp("Seed"); costcenters.Add(costcenter); //} } } } return(costcenters); }
CostCenterSubset GetExistingCostCenter() { var result = _costCenterConnector.Find(); CheckForError(_connector); if (result.CostCenterSubset.Any()) { return(result.CostCenterSubset.First()); } var costCenterToCreate = new CostCenter { Code = "101", Description = "101", }; var costCenter = _costCenterConnector.Create(costCenterToCreate); CheckForError(_connector); return(new CostCenterSubset { Code = costCenter.Code, }); }
public async Task <IActionResult> OnPost() { var costCenter = new CostCenter(); if (Input.Id > 0) { costCenter = _ctx.CostCenters .Include(c => c.CostCenterAuth) .FirstOrDefault(c => c.Id == Input.Id); foreach (var item in Input.Users) { if (item.IsChecked) { if (!costCenter.CostCenterAuth.Any(la => la.Userid == item.Id)) { costCenter.CostCenterAuth.Add(new CostCenterAuth() { Userid = item.Id }); } } else { var locationAuth = costCenter.CostCenterAuth.FirstOrDefault(la => la.Userid == item.Id); if (locationAuth != null) { costCenter.CostCenterAuth.Remove(locationAuth); } } } } else { costCenter = new CostCenter() { LocationId = Input.LocationId, CostCenterAuth = new List <CostCenterAuth>() }; foreach (var item in Input.Users) { if (item.IsChecked) { costCenter.CostCenterAuth.Add(new CostCenterAuth() { Userid = item.Id }); } } _ctx.CostCenters.Add(costCenter); } costCenter.Name = Input.Name; costCenter.AuthorizerId = Input.AuthorizerId; await _ctx.SaveChangesAsync(); return(RedirectToPage("/BusinessProfile/Locations/LocationEdit", new { locationId = Input.LocationId })); }
public ActionResult CostCentersGridViewPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] CostCenter item) { var model = db.CostCenters; ViewBag.CostCenter = item; if (ModelState.IsValid) { try { var modelItem = model.FirstOrDefault(it => it.id == item.id); if (modelItem != null) { this.UpdateModel(modelItem); db.SubmitChanges(); Session["CostCenters"] = IWSLookUp.GetCostCenter(); return(PartialView("CostCentersGridViewPartial", Session["CostCenters"])); } } catch (Exception e) { ViewData["GenericError"] = e.Message; IWSLookUp.LogException(e); } } else { ViewData["GenericError"] = IWSLookUp.GetModelSateErrors(ModelState); } return(PartialView("CostCentersGridViewPartial", item)); }
public ActionResult CostCentersGridViewPartialAddNew([ModelBinder(typeof(DevExpressEditorsBinder))] CostCenter item) { var model = db.CostCenters; item.CompanyID = (string)Session["CompanyID"]; item.ModelId = (int)IWSLookUp.MetaModelId.CostCenter; DateTime dateTime = IWSLookUp.GetCurrentDateTime(); item.Posted = dateTime; item.Updated = dateTime; ViewBag.CostCenter = item; if (ModelState.IsValid) { try { model.InsertOnSubmit(item); db.SubmitChanges(); Session["CostCenters"] = IWSLookUp.GetCostCenter(); return(PartialView("CostCentersGridViewPartial", Session["CostCenters"])); } catch (Exception e) { ViewData["GenericError"] = e.Message; IWSLookUp.LogException(e); } } else { ViewData["GenericError"] = IWSLookUp.GetModelSateErrors(ModelState); } return(PartialView("CostCentersGridViewPartial", item)); }
public ActionResult Create(string id) { ViewBag.CostCenterCategory = dbcontext.CostCenterCategory.ToList().Select(m => new { Code = m.CategoryCode + "------[" + m.CategoryDesc + ']', ID = m.ID }); var modell = new CostCenter(); var stru = dbcontext.StructureModels.FirstOrDefault(m => m.All_Models == ChModels.Payroll).Structure_Code; var model = dbcontext.CostCenter.ToList(); if (model.Count() == 0) { modell.CostCenterCode = stru + "1"; } else { modell.CostCenterCode = stru + (model.LastOrDefault().ID + 1).ToString(); } if (id != null) { var ID = int.Parse(id); var country = dbcontext.CostCenterCategory.FirstOrDefault(m => m.ID == ID); var modells = new CostCenter { CostCenterCode = modell.CostCenterCode, CategoryCode = country.ID.ToString() }; return(View(modells)); } return(View(modell)); }
private static void InitCostCenter(PlantManagerContext context) { var id = 1; var rnd = new Random(); foreach (var item in context.Departments.Select(x => x.DepartmentId)) { context.CostCenters.AddRange(3.Times(x => { var costCenter = new CostCenter { CostCenterId = id, DepartmentId = item, Name = $"Cost Center {id}", Description = $"Description of cost center {id}", Cost = rnd.Next(10, 30), AverageCost = rnd.Next(10, 30) }; id++; return(costCenter); })); } context.SaveChanges(); }
public async Task <ActionResult <CostCenter> > PostCostCenter(CostCenter costCenter) { _context.CostCenter.Add(costCenter); await _context.SaveChangesAsync(); return(CreatedAtAction("GetCostCenter", new { id = costCenter.ID }, costCenter)); }
public async Task <IHttpActionResult> PutCostCenter(int id, CostCenter costCenter) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != costCenter.ID) { return(BadRequest()); } db.Entry(costCenter).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CostCenterExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
/// <summary> /// /// </summary> /// <param name="CostCenter"></param> /// <returns></returns> public CostCenter CreateCostCenter(string CostCenter) { CostCenter newCostCenter = new CostCenter(); newCostCenter.Name = CostCenter; return(CreateCostCenter(newCostCenter)); }
/// <summary> /// Metodo para obtener la informacion las cuentas, cursos o permisos de la base de datos /// </summary> /// <returns>Retorna un entero</returns> /// <param name="acpToConsult">Cuenta/Curso/Permiso del cual se obtiene la informacion</param> public AccountCoursePermit GetAccountCoursePermit(AccountCoursePermit acpToConsult) { List <ParameterDB> parameters = new List <ParameterDB>(); AccountCoursePermit accountCoursePermit = null; DataTable dataTable = new DataTable(); try { parameters.Add(new ParameterDB(ACPResources.id, SqlDbType.VarChar, acpToConsult.id.ToString(), false)); dataTable = ExecuteConsultStoredProcedure(ACPResources.GetAccountCoursePermitStoredProcedure, parameters); DataRow row = dataTable.Rows[0]; string typeStringFormat = "No Facturable"; int typeNumeric = Int32.Parse(row["TYPE"].ToString()); if (typeNumeric == 1) { typeStringFormat = "Facturable"; } Employee employee = new Employee(Int32.Parse(row["EID"].ToString()), row["EFIRSTNAME"].ToString(), row["ELASTNAME"].ToString()); accountCoursePermit = new AccountCoursePermit(row["ACPID"].ToString(), row["NAME"].ToString(), typeNumeric, typeStringFormat, Convert.ToDateTime(row["INITDATE"].ToString()), Convert.ToDateTime(row["ENDDATE"].ToString()), Int32.Parse(row["STATUS"].ToString()), employee); List <CostCenter> costCenters = new List <CostCenter>(); foreach (DataRow unitRow in dataTable.Rows) { try { OrganizationalUnit organizationalUnit = new OrganizationalUnit(Int32.Parse(unitRow["OUID"].ToString()), unitRow["OUNAME"].ToString()); CostCenter costCenter = new CostCenter(organizationalUnit, unitRow["ACPID"].ToString()); costCenters.Add(costCenter); } catch (Exception ex) { return(null); } } accountCoursePermit.associatedUnits = costCenters; return(accountCoursePermit); } catch (SqlException ex) { throw ex; } catch (NullReferenceException ex) { throw ex; } catch (ArgumentNullException ex) { throw ex; } catch (Exception ex) { throw ex; } }
public void GetAllCostCentersTest() { CostCenter costCenter = new CostCenter(connManager); DataSet ds = costCenter.GetAll(); Assert.AreEqual(11, ds.Tables[0].Columns.Count); }
/// <summary> /// Metodo para agregar en la base de datos un nuevo ACP /// </summary> /// <returns>Retorna un entero</returns> /// <param name="costCenter">Centro de costo que se va a registrar</param> public int AddCostCenter(CostCenter costCenter) { List <ParameterDB> parameters = new List <ParameterDB>(); try { parameters.Add(new ParameterDB(ACPResources.fk_ou, SqlDbType.Int, costCenter.fk_ou.ToString(), false)); parameters.Add(new ParameterDB(ACPResources.fk_acp, SqlDbType.VarChar, costCenter.fk_acp, false)); parameters.Add(new ParameterDB(ACPResources.exitvalue, SqlDbType.Int, true)); List <ResultDB> results = ExecuteStoredProcedure(ACPResources.CreateCostCenterStoredProcedure, parameters); int result = Int32.Parse(results[0].value); return(result); } catch (SqlException ex) { throw ex; } catch (NullReferenceException ex) { throw ex; } catch (ArgumentNullException ex) { throw ex; } catch (Exception ex) { throw ex; } }
private static async Task <CostCenter> GetCostCenterAsync(string apiBaseURL, string email) { string requestUri = "api/costcenter" + "/" + email; using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(apiBaseURL); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage httpResponse = await client.GetAsync(requestUri); if (httpResponse.IsSuccessStatusCode) { string response = await httpResponse.Content.ReadAsStringAsync(); CostCenter costCenter = JsonConvert.DeserializeObject <CostCenter>(response); if (costCenter != null) { Console.WriteLine("SubmitterEmail: {0} \r\n ApproverEmail: {1} \r\n CostCenterName: {2}", costCenter.SubmitterEmail, costCenter.ApproverEmail, costCenter.CostCenterName); } return(costCenter); } else { Console.WriteLine("Internal server error: " + httpResponse.StatusCode); return(null); } } }
public async Task <ActionResult <CostCenter> > Update([FromBody] CostCenter _CostCenter) { CostCenter _CostCenterq = _CostCenter; try { using (var transaction = _context.Database.BeginTransaction()) { try { _CostCenterq = await(from c in _context.CostCenter .Where(q => q.CostCenterId == _CostCenter.CostCenterId) select c ).FirstOrDefaultAsync(); _context.Entry(_CostCenterq).CurrentValues.SetValues((_CostCenter)); //_context.CostCenter.Update(_CostCenterq); await _context.SaveChangesAsync(); BitacoraWrite _write = new BitacoraWrite(_context, new Bitacora { IdOperacion = _CostCenterq.CostCenterId, DocType = "CostCenter", ClaseInicial = Newtonsoft.Json.JsonConvert.SerializeObject(_CostCenterq, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }), ResultadoSerializado = Newtonsoft.Json.JsonConvert.SerializeObject(_CostCenterq, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }), Accion = "Actualizar", FechaCreacion = DateTime.Now, FechaModificacion = DateTime.Now, UsuarioCreacion = _CostCenterq.UsuarioCreacion, UsuarioModificacion = _CostCenterq.UsuarioModificacion, UsuarioEjecucion = _CostCenterq.UsuarioModificacion, }); await _context.SaveChangesAsync(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); _logger.LogError($"Ocurrio un error: { ex.ToString() }"); throw ex; // return BadRequest($"Ocurrio un error:{ex.Message}"); } } } catch (Exception ex) { _logger.LogError($"Ocurrio un error: { ex.ToString() }"); return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}"))); } return(await Task.Run(() => Ok(_CostCenterq))); }
public static void ChangeWorkingCostcenter(CostCenter costcenter) { var currentSession = GetAuthentication(); currentSession.WorkingCostCenter = costcenter; RegisterSession(currentSession); }
// GET: /ProductMaster/Create public ActionResult Create() { CostCenter vm = new CostCenter(); vm.IsActive = true; return(View("Create", vm)); }
public string InsertCostCenters(CostCenter costCenter) { String result; OracleDataAdapter obj_ORCL = new OracleDataAdapter("crol_dml_costcenter_st", this.GetConnection().ConnectionString); obj_ORCL.SelectCommand.CommandType = CommandType.StoredProcedure; obj_ORCL.SelectCommand.BindByName = true; obj_ORCL.SelectCommand.Parameters.Add("p_cost_id", costCenter.cost_id); obj_ORCL.SelectCommand.Parameters.Add("p_cost_code", costCenter.cost_code); obj_ORCL.SelectCommand.Parameters.Add("p_cost_name", costCenter.cost_name); obj_ORCL.SelectCommand.Parameters.Add("p_user_cd", costCenter.user_cd); obj_ORCL.SelectCommand.Parameters.Add("p_row_id", ""); obj_ORCL.SelectCommand.Parameters.Add("p_upduser_cd", costCenter.updUser_cd); obj_ORCL.SelectCommand.Parameters.Add("p_action", "I"); obj_ORCL.SelectCommand.Parameters.Add("p_dataset", OracleDbType.RefCursor).Direction = ParameterDirection.Output; DataTable cs_dt = new DataTable(); try { obj_ORCL.Fill(cs_dt); result = Newtonsoft.Json.JsonConvert.SerializeObject(cs_dt); } catch (Exception ex) { result = Newtonsoft.Json.JsonConvert.SerializeObject(ex.Message); } finally { obj_ORCL.Dispose(); cs_dt.Dispose(); } return(result); }
public async Task <ActionResult <CostCenterVM> > CreateCostCenter(CostCenterVM costcenterVM) { try { if (costcenterVM == null) { return(BadRequest()); } // Add custom model validation error CostCenter costcenter = await costcenterRepository.GetCostCenterByname(costcenterVM.CostCenter); if (costcenter != null) { ModelState.AddModelError("Name", $"CostCenter name: {costcenterVM.CostCenter.Name} already in use"); return(BadRequest(ModelState)); } await costcenterRepository.CreateCostCenter(costcenterVM); return(CreatedAtAction(nameof(GetCostCenter), new { id = costcenterVM.CostCenter.Id }, costcenterVM)); } catch (DbUpdateException Ex) { return(StatusCode(StatusCodes.Status500InternalServerError, Ex.InnerException.Message)); } }
public async Task <CommandResult> Handle(DeleteCostCenterCommand message) { //Validate using domain models CostCenter costCenterAux = new CostCenter(); costCenterAux = _mapper.Map <DeleteCostCenterCommand, CostCenter>(message); //validate code uniqueness var existingCostCenter = await _costCenterRepository.GetCostCenter(message.CostCenterId); if (existingCostCenter == null) { costCenterAux.AddError("Cost Center Id not found."); } //if is not valid if (costCenterAux.HasErrors) { return(costCenterAux.ToResult()); } _costCenterRepository.Delete(existingCostCenter); await _unitOfWork.CommitAsync(); //Publish bussines Event await _bus.PublishAsync(new CostCenterDeleted() { CostCenterId = existingCostCenter.CostCenterId }); //Return result return(existingCostCenter.ToResult()); }
public async Task <IActionResult> PutCostCenter(int id, CostCenter costCenter) { if (id != costCenter.ID) { return(BadRequest()); } _context.Entry(costCenter).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CostCenterExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public ActionResult AddNewChildAccount(string id) { string UserID = User.Identity.GetUserId(); var UserInfo = _unitOfWork.User.GetMyInfo(UserID); var CoInfo = _unitOfWork.Company.GetMyCompany(UserInfo.fCompanyId); var FatherAccount = _unitOfWork.CostCenter.GetCostCenterById(CoInfo.CompanyID, id); CostCenter Obj = new CostCenter(); Obj.CostChart = CoInfo.CostChart; Obj.CostZero = CoInfo.CostChartZero; Obj.CostLevel = FatherAccount.CostLevel + 1; Obj.CostFather = FatherAccount.CostNumber; Obj.CostFatherName = FatherAccount.ArabicName; Obj.CostNumber = "";// _unitOfWork.NativeSql.GetMaxCostNumberChild(CoInfo.CompanyID, Obj.CostFather).ToString(); Obj.LevelZero = FunctionUnit.GetLevelChart(CoInfo.CostChart, Obj.CostLevel); //Obj.LevelZero = Obj.LevelZero.Count().ToString(); if (String.IsNullOrEmpty(Obj.LevelZero)) { ViewBag.Error = Resources.Resource.LastAccountSub; return(PartialView("Error")); } else { return(PartialView("AddNewChildAccount", Obj)); } }
public static CostCenter CreateCostCenter(string costCenterName, global::System.DateTime addTimestamp) { CostCenter costCenter = new CostCenter(); costCenter.CostCenterName = costCenterName; costCenter.AddTimestamp = addTimestamp; return costCenter; }
public void AddToCostCenters(CostCenter costCenter) { base.AddObject("CostCenters", costCenter); }
public ActionResult CreateCashOut(TypeOut? typeOut, CostCenter? userType) { var cash = new CashOut(); cash.TypeOut = typeOut == null ? TypeOut.Regular : typeOut.Value; cash.CostCenter = userType == null ? CostCenter.Other : userType.Value; // ViewBag.Kendaraan = db.Kendaraan.Select(p => p.NoKendaraan).ToList(); ViewBag.Kendaraan = new SelectList(db.Kendaraan, "NoKendaraan", "NoKendaraan"); if (cash.TypeOut == TypeOut.Irregular) { var data = db.Quizs.Where(p => p.QuizGroup.GroupType == GroupType.Irregularaties).ToList(); //data.Insert(0, new Quiz()); ViewBag.Quiz =new SelectList(data, "Id", "Info"); ViewBag.QuizInfo = from dt in data select new { dt.Id, label1 = dt.Note1Label, label2 = dt.Note2Label, label3 = dt.Note3Label, requiredAll = dt.RequiredAll }; } else { var data = db.Quizs.Where( p => p.CostCenter == cash.CostCenter && p.QuizGroup.GroupType != GroupType.Irregularaties).ToList(); // data.Insert(0, new Quiz()); ViewBag.Quiz = new SelectList(data, "Id", "Info"); ViewBag.QuizInfo = from dt in data select new { dt.Id, label1 = dt.Note1Label, label2 = dt.Note2Label, label3 = dt.Note3Label, requiredAll = dt.RequiredAll }; } return View("CashOut", cash); }
/// <summary> /// this method updates costcenter /// </summary> /// <param name="original_entity"></param> /// <param name="entity"></param> public void UpdateCostCenter(CostCenter original_entity, CostCenter entity) { original_entity.CopyPropertiesFrom(entity); DbContext.SubmitChanges(); }
/// <summary> /// Returns the Cost Center /// </summary> /// <param name="companyId"></param> /// <returns></returns> public void InsertCostCenter(CostCenter costCenter) { DbContext.CostCenters.InsertOnSubmit(costCenter); DbContext.SubmitChanges(); }
protected CostCenter GetObject(DataRow dr) { CostCenter objCostCenter = new CostCenter(); objCostCenter.CostCenterId = (dr["CostCenterId"] == DBNull.Value) ? 0 : (Int32)dr["CostCenterId"]; objCostCenter.CostCenterType = (dr["CostCenterType"] == DBNull.Value) ? "" : (String)dr["CostCenterType"]; objCostCenter.CostCenterName = (dr["CostCenterName"] == DBNull.Value) ? "" : (String)dr["CostCenterName"]; objCostCenter.IsActive = (dr["IsActive"] == DBNull.Value) ? false : (Boolean)dr["IsActive"]; objCostCenter.CompanyId = (dr["CompanyId"] == DBNull.Value) ? 0 : (Int32)dr["CompanyId"]; objCostCenter.UpdateBy = (dr["UpdateBy"] == DBNull.Value) ? 0 : (Int32)dr["UpdateBy"]; objCostCenter.UpdateDate = (dr["UpdateDate"] == DBNull.Value) ? DateTime.MinValue : (DateTime)dr["UpdateDate"]; return objCostCenter; }
/// <summary> /// this method deletes a cost center /// </summary> /// <param name="entity"></param> public void DeleteCostCenter(CostCenter entity) { DbContext.CostCenters.DeleteOnSubmit(entity); DbContext.SubmitChanges(); }
protected void btnDeleteCostCenter_Command(object sender, CommandEventArgs e) { if (e.CommandName == "Select") { var node = treCostCenter.FindNodeByValue(e.CommandArgument.ToString()) ?? new Telerik.Web.UI.RadTreeNode(); cboTreeCostCenters.SelectedValue = String.Empty; if (node.ParentNode != null) cboTreeCostCenters.SelectedValue = node.ParentNode.Value; txtName.Text = node.Text; } else if (e.CommandName == "Delete") { accountManager = new AccountManager(this); costCenter = accountManager.GetCostCenter(Convert.ToInt32(e.CommandArgument)); if (costCenter != null) { if (costCenter.CostCenters.Any() || costCenter.Bills.Any() || costCenter.Invoices.Any()) { ShowError(Resources.Exception.DeletingRegisterWithForeignKey); return; } try { accountManager.DeleteCostCenter(costCenter); } catch { ShowError(Resources.Exception.DeletingRegisterWithForeignKey); return; } } BindTree(); } }