public async Task <IActionResult> CreateMachineUsage(MachineUsageForCreationDto machineUsageForCreationDto) { // map machineUsage from the DTO recieved with the http call var machineUsage = mapper.Map <MachineUsage>(machineUsageForCreationDto); // check if user, machine and tariff exist in DB var user = await repo.GetUser(machineUsage.UserId); var machine = await repo.GetMachine(machineUsage.MachineId); var tariff = await repo.GetTariff(machineUsage.TariffId); if (user == null || machine == null || tariff == null) { return(NotFound("No user, machine or tariff found for the provided id")); } // check if user has enough credit to make use of this machine var totalPrice = machineUsage.QuantityOfServicesBooked * tariff.Price; if (user.RemainingCredit < totalPrice) { return(BadRequest("User has not enough credit to make this usage")); } // Add machine usage to DB machineUsage.User = user; machineUsage.Machine = machine; machineUsage.Tariff = tariff; machineUsage.Date = DateTime.Now; repo.Add(machineUsage); // Update client's remaining credit in DB user.RemainingCredit -= totalPrice; repo.Update(user); // Activate the desired machine using (var httpClient = new HttpClient()) { var formcontent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("arg", "on") }); var particleAccessToken = this.config.GetSection("AppSettings:ParticleAccessToken").Value; var request = await httpClient.PostAsync("https://api.particle.io/v1/devices/e00fce68ba9a1f5ea4870186/motorToggle?access_token=" + particleAccessToken, formcontent); } if (await repo.SaveAll()) { return(Ok(mapper.Map <UserForListDto>(user))); } throw new Exception("Creating the machine usage failed on save"); }
public async Task <IActionResult> CreateTariff(TariffForCreationDto tariffForCreationDto) { var tariff = mapper.Map <Tariff>(tariffForCreationDto); // Retrieve the object machineGroup this tariff belongs to. // Then store the retrieved object into the tariff var machineGroup = await repo.GetMachineGroup(tariff.MachineGroupId); if (machineGroup == null) { return(NotFound("No machine group found under the provided id")); } tariff.MachineGroup = machineGroup; repo.Add(tariff); if (await repo.SaveAll()) { return(Ok(tariff)); } throw new Exception("Creating the tariff failed on save"); }