public async Task <IActionResult> Edit(string id, [Bind("MalfunctionId,Status,Title,Content,Resources,CreationDate,ModifiedDate")] Malfunction malfunction) { if (id != malfunction.MalfunctionId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(malfunction); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MalfunctionExists(malfunction.MalfunctionId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(malfunction)); }
private void SavePhoto(Malfunction malfunction, IFormFile mFiles) { // Sanity check apartment cant be null if (malfunction == null) { return; } // If there is no defined photo, set the default photo if (mFiles == null) { malfunction.Resources = "/images/malfunctions/default_malfunction_photo.jpg"; return; } var fileName = Path.Combine(he.WebRootPath + "/images/malfunctions", Path.GetFileName(mFiles.FileName)); malfunction.Resources = "/images/malfunctions/" + mFiles.FileName; // If the file does not exist already creating it if (!System.IO.File.Exists(fileName)) { mFiles.CopyTo(new FileStream(fileName, FileMode.Create)); } }
// добавление данных по заявке public void AppendOrder(RepairOrder order) { // создание новой заявки/заказа на ремонт RepairOrder newOrder = new RepairOrder { Client = GetClients().ToList().Find(c => c.Id == order.Client.Id), Car = _db.Cars.ToList().Find(c => c.Id == order.Car.Id), Worker = order.Worker, IsReady = order.IsReady, DateOfTheApplication = order.DateOfTheApplication, }; foreach (var value in order.Malfunctions) { Malfunction templValue = _db.Malfunctions.First(m => m.Id == value.Id); newOrder.Malfunctions.Add(templValue); } _db.RepairOrders.Add(newOrder); _db.SaveChanges(); // изменяем статус работника - работает сейчас ChangeWorker(order.Worker, _db.WorkerStatuses.ToList()[0]); // добавляем клиенту дату обращения AppendClientDate(order.Client); ++_countOfOrders; }
public MalfunctionViewData(Malfunction malfunction, List <Detail> details) { Id = malfunction.Id; Title = malfunction.Title; TimeToFix = malfunction.TimeToFix; Details = details; Price = Details.Sum(d => d.Price); }
public async Task <IActionResult> InsertOrUpdate(MalfunctionEditViewModel model) { var machines = await _databaseRepository.GetAll <Machine>(); model.Machines = machines; bool result; if (ModelState.IsValid) { var machineId = machines.Where(m => m.Name == model.Malfunction.MachineName).Select(m => m.id).FirstOrDefault(); Malfunction malfunction = new Malfunction { id = model.Malfunction.id, Name = model.Malfunction.Name, Description = model.Malfunction.Description, MachineId = machineId, File = model.Malfunction.File, Status = true, Created = model.Malfunction.Created, }; if (model.Malfunction.Files != null) { var zipName = _fileService.CreateZip(model.Malfunction.File, model.Malfunction.Files); if (zipName == null) { ModelState.AddModelError("Malfunction.Files", "Error while uploading zip file"); return(View("Edit", model)); } else { malfunction.File = zipName; } } if (malfunction.id == 0) { malfunction.Created = DateTime.Now; result = await _databaseRepository.Insert <Malfunction>(malfunction) > 0; } else { result = await _databaseRepository.Update <Malfunction>(malfunction) != null; } if (result) { return(RedirectToAction("MalfunctionsTable", "Malfunction")); } } return(View("Edit", model)); }
public void Copy(Malfunction mal) { Malfunction_Closed closed = new Malfunction_Closed(); closed.building = mal.building; closed.date = mal.date; closed.type = mal.type; closed.description = mal.description; items2.Add(closed); }
public async Task <IActionResult> Create([Bind("MalfunctionId,Status,Title,Content,Resources,CreationDate,ModifiedDate,CurrentApartment")] Malfunction malfunction) { if (ModelState.IsValid) { _context.Add(malfunction); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(malfunction)); }
public async Task <IActionResult> FixMalfunction(int id) { if (id > 0) { Malfunction malfunction = await _databaseRepository.Get <Malfunction>(id); malfunction.Status = false; var a = await _databaseRepository.Update <Malfunction>(malfunction); } return(RedirectToAction("MalfunctionsTable", "Malfunction")); }
// выбор конкретной неисправности public MalfunctionViewData GetMalfunctionData(int id) { Malfunction malfunction = _context.Malfunctions .Include(m => m.Details) .FirstOrDefault(m => m.Id == id); if (malfunction == null) { throw new WebApiException("Данная неисправность не была найдена"); } return(new MalfunctionViewData(malfunction, malfunction.Details.ToList())); }
public async Task <IActionResult> Delete(int id) { Malfunction model = await _databaseRepository.Get <Malfunction>(id); var result = await _databaseRepository.Delete <Malfunction>(model); if (model.File != null) { _fileService.DeleteFile(model.File); } return(RedirectToAction("MalfunctionsTable", "Malfunction")); }
public void GetMalfunction_MalfunctionFound_ReturnCorrectMalfunction() { var malfunction = new Malfunction(); var id = 1; unitOfWork.Setup(uow => uow.Malfunctions .GetMalfunctionWithEquipment(m => m.Id == id)) .Returns(malfunction); var response = controller.GetMalfunction(id) as OkNegotiatedContentResult <MalfunctionDto>; var result = response.Content; Assert.IsNotNull(response); Assert.AreEqual(result, Mapper.Map <Malfunction, MalfunctionDto>(malfunction)); }
public void DeleteMalfunction_MalfunctionFound_ReturnOk() { //given var id = 1; var malfunctionInDb = new Malfunction(); unitOfWork.Setup(uow => uow.Malfunctions.SingleOrDefault(m => m.Id == id)) .Returns(new Malfunction()); unitOfWork.Setup(uow => uow.Equipment .SingleOrDefault(e => e.Id == malfunctionInDb.EquipmentId)).Returns(new Equipment()); //when var result = controller.DeleteMalfunction(id); //then Assert.That(result, Is.InstanceOf(typeof(OkResult))); }
public ActionResult Add(MalfunctionViewModel model) { try { var data = new Malfunction() { Message = model.Message, Type = model.Type, BrandType = model.BrandType }; if (model.PostedFile != null && model.PostedFile.ContentLength > 0) { var file = model.PostedFile; string fileName = Path.GetFileNameWithoutExtension(file.FileName); string extName = Path.GetExtension(file.FileName); fileName = StringHelpers.UrlFormatConverter(fileName); fileName += StringHelpers.GetCode(); var klasoryolu = Server.MapPath("~/Upload/"); var dosyayolu = Server.MapPath("~/Upload/") + fileName + extName; if (!Directory.Exists(klasoryolu)) { Directory.CreateDirectory(klasoryolu); } file.SaveAs(dosyayolu); WebImage img = new WebImage(dosyayolu); img.Resize(250, 250, false); img.AddTextWatermark("Wissen"); img.Save(dosyayolu); data.AvatarPath = "/Upload/" + fileName + extName; } var a = new MalfunctionRepo().Insert(data); TempData["Message"] = $"Kaydınız Alınmıştır"; return(RedirectToAction("Index", "Home")); } catch (Exception ex) { return(RedirectToAction("Index")); } }
public void UpdateMalfunction_MalfunctionIsNotRepaired_SetEquipmentAsNonOperational() { //given var id = 1; var malfunctionInDb = new Malfunction(); var equipmentWhoseMalfunctionIsBeingEdited = new Equipment(); unitOfWork.Setup(uow => uow.Malfunctions.SingleOrDefault(m => m.Id == id)) .Returns(malfunctionInDb); unitOfWork.Setup(uow => uow.Equipment .SingleOrDefault(e => e.Id == malfunctionInDb.EquipmentId)) .Returns(equipmentWhoseMalfunctionIsBeingEdited); //when controller.UpdateMalfunction(id, new MalfunctionDto { IsRepaired = false }); //then Assert.IsFalse(equipmentWhoseMalfunctionIsBeingEdited.IsOperational); }
public async Task <IActionResult> Edit(int id) { IEnumerable <Machine> machines = await _databaseRepository.GetAll <Machine>(); MalfunctionEditViewModel model = new MalfunctionEditViewModel { Machines = machines, Malfunction = new MalfunctionViewModel() }; if (ModelState.IsValid) { IEnumerable <Malfunction> malfunctions = new Malfunction[] { await _databaseRepository.Get <Malfunction>(id) }; if (malfunctions.First() != null) { var malfunctionViewModel = malfunctions.Join( machines, malf => malf.MachineId, mach => mach.id, (malfunction, machine) => new MalfunctionViewModel { id = malfunction.id, Name = malfunction.Name, Description = malfunction.Description, MachineId = machine.id, MachineName = machine.Name, Status = malfunction.Status, File = malfunction.File, Created = malfunction.Created }); if (malfunctionViewModel.Any()) { model.Malfunction = malfunctionViewModel.First(); } } } return(View(model)); }
public void DeleteMalfunction_MalfunctionFoundAndUnrepairedMalfunctionsGreaterThanZero_SetEquipmentIsOperationalToFalse() { //given var id = 1; var malfunctionInDb = new Malfunction(); var equipmentWhoseMalfunctionIsBeingDeleted = new Equipment(); unitOfWork.Setup(uow => uow.Malfunctions.SingleOrDefault(m => m.Id == id)) .Returns(new Malfunction()); unitOfWork.Setup(uow => uow.Equipment .SingleOrDefault(e => e.Id == malfunctionInDb.EquipmentId)).Returns(equipmentWhoseMalfunctionIsBeingDeleted); unitOfWork.Setup(uow => uow.Malfunctions .Find(m => m.EquipmentId == malfunctionInDb.EquipmentId && m.Id != malfunctionInDb.Id && !m.IsRepaired)).Returns(GetMalfunctionsList()); //when controller.DeleteMalfunction(id); //then Assert.IsFalse(equipmentWhoseMalfunctionIsBeingDeleted.IsOperational); }
public async Task <IActionResult> Edit(string id, [Bind("MalfunctionId,Status,Title,Content,Resources")] Malfunction malfunction, IFormFile files) { if (id != malfunction.MalfunctionId) { return(RedirectToAction("NotFoundPage")); } if (ModelState.IsValid) { if (files != null) { SavePhoto(malfunction, files); } if (!MalfunctionExists(malfunction.MalfunctionId)) { return(RedirectToAction("NotFoundPage")); } // Getting the malfunction from db var malfunctionToSave = _context.Malfunction.First(mal => mal.MalfunctionId == id); // Setting the new values malfunctionToSave.ModifiedDate = DateTime.Now; malfunctionToSave.Status = malfunction.Status; malfunctionToSave.Title = malfunction.Title; malfunctionToSave.Content = malfunction.Content; malfunctionToSave.Resources = malfunction.Resources; // Updating the new malfunction _context.Update(malfunctionToSave); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(malfunction)); }
// добавление неисправности public async Task AppendMalfunction(MalfunctionViewData malfunctionViewData) { // поиск неисправности. если мы находим неисправность, то ругаемся что данная неисправность уже существует Malfunction malfunction = _context.Malfunctions.FirstOrDefault(m => String.Equals(m.Title, malfunctionViewData.Title, StringComparison.CurrentCultureIgnoreCase)); if (malfunction != null) { throw new WebApiException("Данная неисправность уже существует. Добавить еще одну такую же невозможно"); } // создаем неисправность malfunction = new Malfunction { TimeToFix = malfunctionViewData.TimeToFix, Title = malfunctionViewData.Title, Details = new List <Detail>() }; // создание и добавление (в случае надобности) новой детали for (int i = 0; i < malfunctionViewData.Details.Count; i++) { // поиск детали по наименованию Detail detail = _context.Details.FirstOrDefault(d => d.Title == malfunctionViewData.Details[i].Title); // если мы не находим такую деталь, то мы добавляем ее if (detail == null) { _context.Details.Add(malfunctionViewData.Details[i]); await _context.SaveChangesAsync(); } // после добавления детали при необходимости, добавляем деталь к неисправности malfunction.Details.Add(detail); } // добавляем неисправность _context.Malfunctions.Add(malfunction); await _context.SaveChangesAsync(); }
public static void SeedData(this IApplicationBuilder app, IServiceProvider services) { var context = services.GetRequiredService <TransITDBContext>(); if (context.Location.Any() || context.VehicleType.Any() || context.Vehicle.Any() || context.Post.Any() || context.Employee.Any() || context.Country.Any() || context.Currency.Any() || context.Supplier.Any() || context.Malfunction.Any() || context.MalfunctionGroup.Any() || context.MalfunctionSubgroup.Any() || context.Issue.Any()) { return; } #region Locations var LKP1 = new Location() { Name = "ЛКП \"Львівелектротранс\"", Description = "м. Львів вул. Тролейбусна 1" }; var LKP2 = new Location() { Name = "ЛКП \"Львівелектротранс\"", Description = "м. Львів вул.Сахарова 2а" }; var LK = new Location() { Name = "ЛК АТП-1", Description = "м. Львів вул. Авіаційна 1" }; context.Location.AddRange(LKP1, LKP2, LK); #endregion #region VechileTypes var A185 = new VehicleType() { Name = "Автобус А185" }; var E191 = new VehicleType() { Name = "Електробус Е191" }; var T3L = new VehicleType() { Name = "Трамвай Т3L" }; var T191 = new VehicleType() { Name = "Тролейбус Т191" }; context.VehicleType.AddRange(A185, E191, T3L, T191); #endregion #region Vehicles var electron = new Vehicle() { VehicleType = A185, Brand = "Електрон", Vincode = "WR0DA76963U153381", InventoryId = "12314", RegNum = "AC4131CC", Model = "S10", Location = LKP1, WarrantyEndDate = new DateTime(2019, 12, 10), CommissioningDate = new DateTime(2017, 12, 10) }; var electron2 = new Vehicle() { VehicleType = E191, Brand = "Електрон", Vincode = "WP0CA36863U153382", InventoryId = "124", RegNum = "LV1234VL", Model = "S2", WarrantyEndDate = new DateTime(2019, 05, 09), CommissioningDate = new DateTime(2017, 05, 22) }; context.Vehicle.AddRange(electron, electron2); #endregion #region Posts var engineer = new Post { Name = "Провідний інженер" }; var boss = new Post { Name = "Начальник дільниці" }; var locksmith = new Post { Name = "Слюсар механоскладальних робіт" }; context.Post.AddRange(engineer, boss, locksmith); #endregion #region Employees var Ihora = new Employee() { FirstName = "Ігор", MiddleName = "Олександрович", LastName = "Баб'як", ShortName = "Ігора", BoardNumber = 1, Post = boss }; var Yura = new Employee() { FirstName = "Юрій", MiddleName = "Васильович", LastName = "Медведь", ShortName = "Yurik", BoardNumber = 5, Post = locksmith }; var Sania = new Employee() { FirstName = "Олександр", MiddleName = "Борисович", LastName = "Водзянський", ShortName = "Саня", BoardNumber = 2, Post = engineer }; context.Employee.AddRange(Ihora, Yura, Sania); #endregion #region Countries var Ukraine = new Country() { Name = "Україна" }; var Turkey = new Country() { Name = "Туреччина" }; var Russia = new Country() { Name = "Росія" }; var Polland = new Country() { Name = "Польща" }; var German = new Country() { Name = "Німеччина" }; context.Country.AddRange(Ukraine, Turkey, Russia, Polland, German); #endregion #region Currencies var USD = new Currency { ShortName = "USD", FullName = "Долар" }; var UAH = new Currency { ShortName = "UAH", FullName = "Гривня" }; var RUB = new Currency { ShortName = "RUB", FullName = "Рубль" }; var GBR = new Currency { ShortName = "GBR", FullName = "Great British Pound" }; var EUR = new Currency { ShortName = "EUR", FullName = "Євро" }; context.Currency.AddRange(USD, UAH, RUB, GBR, EUR); #endregion #region Supplier var Yunona = new Supplier { Name = "Юнона", FullName = "ТОВ \"Юнона\"", Country = Ukraine, Currency = UAH, Edrpou = "20841865" }; var Tekhnos = new Supplier { Name = "Технос", FullName = "ООО \"Технос\"", Country = Russia, Currency = RUB, Edrpou = "00703" }; var Elephant = new Supplier { Name = "Elephant", FullName = "Elephant", Country = German, Currency = EUR, Edrpou = "04909" }; context.Supplier.AddRange(Yunona, Tekhnos, Elephant); #endregion #region MalfunctionsWithGroups var body = new MalfunctionGroup() { Name = "Кузов", }; var windows = new MalfunctionSubgroup() { Name = "Скління", MalfunctionGroup = body }; var brokenWindow = new Malfunction { Name = "Розбите вікно", MalfunctionSubgroup = windows }; var waterLeak = new Malfunction { Name = "Вікно протікає", MalfunctionSubgroup = windows }; var handrails = new MalfunctionSubgroup { Name = "Поручні", MalfunctionGroup = body }; var missingHandrail = new Malfunction() { Name = "Зникли поручні", MalfunctionSubgroup = handrails }; var brokenHandrail = new Malfunction() { Name = "Зламані поручні", MalfunctionSubgroup = handrails }; var engine = new MalfunctionGroup() { Name = "Двигун" }; var gasEngine = new MalfunctionSubgroup() { Name = "Карбюраторний двигун", MalfunctionGroup = engine }; var tooMuchGas = new Malfunction() { Name = "Залиті Свічки", MalfunctionSubgroup = gasEngine }; var noGas = new Malfunction() { Name = "Перебитий бензонасос", MalfunctionSubgroup = gasEngine }; var dieselEngine = new MalfunctionSubgroup() { Name = "Дизельний двигун", MalfunctionGroup = engine }; var brokenPump = new Malfunction() { Name = "Зламаний насос великого тиску", MalfunctionSubgroup = dieselEngine }; context.MalfunctionGroup.AddRange(body, engine); context.MalfunctionSubgroup.AddRange(windows, handrails, gasEngine, dieselEngine); context.Malfunction.AddRange( brokenWindow, waterLeak, missingHandrail, brokenHandrail, tooMuchGas, noGas, brokenPump); #endregion #region Issues var userController = services.GetRequiredService <UserManager <User> >(); var findRegister = userController.FindByNameAsync("testRegister"); findRegister.Wait(); var register = findRegister.Result; var imissingHandrail = new Issue() { Malfunction = missingHandrail, Vehicle = electron2, Date = DateTime.Now.Subtract( new TimeSpan(days: 1, hours: 0, minutes: 0, seconds: 0)), Warranty = false, Summary = "ппц шо робити", Priority = 1, Create = register, Number = 1, }; var ibrokenHandrail = new Issue() { Malfunction = brokenHandrail, Vehicle = electron2, Date = DateTime.Now, Warranty = false, Summary = "ппц, спочатку пропали поручні, а тепер їх зламали, шо робити?", Priority = 2, Create = register, Number = 2, }; var iwaterLeak = new Issue() { Malfunction = waterLeak, Vehicle = electron, Date = DateTime.Now, Warranty = true, Summary = "Третє вікно праворуч протікає під час дощу", Priority = 0, Create = register, Number = 3 }; var ibrokenWindows = new Issue() { Malfunction = brokenWindow, Vehicle = electron, Date = DateTime.Now, Warranty = false, Summary = "розбили два вікна в салоні з лівого боку", Priority = 2, Number = 4, }; var inoGas = new Issue() { Malfunction = noGas, Vehicle = electron, Date = DateTime.Now, Warranty = true, Summary = "Автобус не заводиться, видно, що перебитий бензонасос", Priority = 2, Number = 5 }; context.Issue.AddRange(imissingHandrail, ibrokenHandrail, iwaterLeak, ibrokenWindows, inoGas); #endregion context.SaveChanges(); }
public IEnumerable <Malfunction> Get() { Malfunction m = new Malfunction(); return(m.Read()); }
public async Task <IActionResult> Create([Bind("CurrentApartment")] int CurrentApartment, [Bind("RequestedBy")] string RequestedBy, [Bind("MalfunctionId,Status,Title,Content,Resources,CurrentApartmentId,RequestedById")] Malfunction malfunction, IFormFile mFiles) { if (ModelState.IsValid) { // Creating the query of the apartment var queryApt = from apt in _context.Apartment where apt.ApartmentId == CurrentApartment select apt; // Creating the query of the user var queryUsr = from usr in _context.User where usr.Id == RequestedBy select usr; // If the id of the apartment/user does not exist in DB if (!queryApt.Any() || !queryApt.Any()) { return(View(malfunction)); } // Adding the apartment to the malfunction to save var curApartment = queryApt.First(); malfunction.CurrentApartment = curApartment; // Adding the user to the malfunction to save var curUser = queryUsr.First(); malfunction.RequestedBy = curUser; // Adding the creation date and modification date malfunction.CreationDate = DateTime.Now; malfunction.ModifiedDate = DateTime.Now; // Uploading photo describing the malfunction SavePhoto(malfunction, mFiles); _context.Add(malfunction); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(malfunction)); }