Skip to content

Commit

Permalink
Merge pull request #14 from DevCapu/migrando-refeicoes
Browse files Browse the repository at this point in the history
Migrando refeicoes
  • Loading branch information
Morkhusz authored May 20, 2020
2 parents 026db24 + 02f5840 commit b6fe52c
Show file tree
Hide file tree
Showing 12 changed files with 297 additions and 20 deletions.
26 changes: 26 additions & 0 deletions app/Http/Controllers/MealController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php


namespace App\Http\Controllers;


use App\Services\IngestedFood;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MealController extends Controller
{
public function index()
{
return view('meals.create', ['id' => Auth::id()]);
}

public function store(Request $request, IngestedFood $ingestedFood)
{
foreach ($request->ingestedFoods as $food) {
$food = json_decode(json_encode($food));
$ingestedFood->saveIngestedFood($food, $request->id);
}
}

}
22 changes: 22 additions & 0 deletions app/Services/IngestedFood.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
namespace App\Services;


use App\Models\Food;
use App\Models\Ingested;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class IngestedFood
Expand Down Expand Up @@ -94,4 +97,23 @@ public function getRows()
}
return $max;
}

public function saveIngestedFood($food, int $userId): void
{
$ingested = new Ingested();


$ingested->food_id = $food->id;
$ingested->quantity = $food->quantity;

$ingested->user_id = $userId;
$ingested->period = $food->period;

$ingested->calories = (Food::find($ingested->food_id))
->calories * $ingested->quantity;

$ingested->date = Carbon::now('America/Sao_Paulo')->format('d/m/y');

$ingested->saveOrFail();
}
}
41 changes: 41 additions & 0 deletions public/js/HttpClient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class HttpClient {
constructor() {
this.baseUrl = "http://localhost:8000/api";
}

/**
* @param {string} resource
*/
get(resource) {
return fetch(this.baseUrl + resource)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Não foi possível buscar o alimento')
})
.catch(error => console.log(error))
}

/**
* @param {string} resource
* @param {json} requestBody
*/
post(resource, requestBody) {
const body = JSON.stringify(requestBody)
console.log(body)
return fetch(this.baseUrl + resource,
{
method: 'POST',
body,
headers: new Headers({"Content-Type": "application/json"})
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Não foi possível buscar o alimento')
})
.catch(error => console.log(error))
}
}
28 changes: 28 additions & 0 deletions public/js/ingested-food/TableManager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class TableManager {
addFood(food, selectedMeal) {
const table = $(`#tabela-${selectedMeal}`)
const tableRow = $('<tr></tr>')
const tableCellId = $('<td></td>')
const tableCellName = $('<td></td>')
const tableCellQuantity = $('<td></td>')

this.insertCellTexts(tableCellId, tableCellName, tableCellQuantity, food);

tableRow.append(tableCellId, tableCellName, tableCellQuantity)
table.append(tableRow);
}

/**
* @private
* @param tableCellId
* @param food
* @param tableCellName
* @param tableCellQuantity
*/
insertCellTexts(tableCellId, tableCellName, tableCellQuantity, food) {
tableCellId.text(food.id);
tableCellId.addClass('hidden');
tableCellName.text(food.name)
tableCellQuantity.text(food.quantity)
}
}
11 changes: 11 additions & 0 deletions public/js/ingested-food/getFieldValues.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class GetFieldValues {
static getFieldsValues() {
const selectedFoodId = $('#alimentos').val();

return {
id: selectedFoodId,
name: $(`option[value="${selectedFoodId}"]`).text(),
quantity: $('#quantidade').val()
};
}
}
11 changes: 11 additions & 0 deletions public/js/ingested-food/initializeFields.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
(function () {
$(document).ready(function () {
$('#refeicao').formSelect();
$('#alimentos').formSelect();
$('.tabs').tabs();
});

$('#alimentos').on('contentChanged', function () {
$(this).formSelect();
});
})()
8 changes: 8 additions & 0 deletions public/js/ingested-food/initializeInsertButton.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
(function () {
const formAlimento = document.querySelector('#adicionaAlimento');
formAlimento.addEventListener('submit', event => {
event.preventDefault();
const food = GetFieldValues.getFieldsValues();
new TableManager().addFood(food, $('#refeicao').val())
})
})()
20 changes: 20 additions & 0 deletions public/js/ingested-food/insertIngestedFoods.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
(function () {
$('#insertIngestedFoods').click(function () {
let foods = [];
let periods = ['BREAKFAST', 'LUNCH', 'AFTERNOON_COFFEE', 'DINNER'];

$('table').each(function (index) {
const rows = $(this).children('tbody').children('tr');
period = periods[index];
rows.each(function () {
const id = $(this).children('td').eq(0).text();
const quantity = $(this).children('td').eq(2).text();
const ingestedFood = {id, quantity, period};
foods = [...foods, ingestedFood];
})
})
const requestBody = {ingestedFoods: foods, id};
var httpClient = new HttpClient();
httpClient.post('/meal', requestBody);
});
})();
13 changes: 13 additions & 0 deletions public/js/ingested-food/searchFoods.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
(function () {
const httpClient = new HttpClient();
httpClient.get('/alimento')
.then(json => {
const foodOptions = json.map(food => (
`<option value="${food.id}">${food.nome}</option>`
))

const foodDropdown = $('#alimentos');
foodDropdown.append(foodOptions.join(''))
$("#alimentos").trigger('contentChanged');
});
})()
1 change: 1 addition & 0 deletions public/js/refeicao/busca-alimentos.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
);
});
selectAlimentos.innerHTML = opcoesDeAlimentos.join('');
$("#alimentos").trigger('contentChanged');
})
.catch(error => console.error(error));
})();
26 changes: 6 additions & 20 deletions public/js/refeicao/salva-refeicoes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,20 @@
tabelas.each(function (index) {
let alimentos = [];
let periodo;
console.log(index);
switch (index) {
case 0:
periodo = 'CAFÉ DA MANHÃ';
break;
case 1:
periodo = 'ALMOÇO';
break;
case 2:
periodo = 'CAFÉ DA TARDE';
break;
case 3:
periodo = 'JANTAR';
break;
}

meals = ['BREAKFAST', 'LUNCH', 'AFTERNOON_COFFEE', 'DINNER'];
periodo = meals[index];
const tr = $(this).children('tbody').children('tr');
tr.each(function () {
const tdId = $(this).children('td').eq(0);
const tdQuantidade = $(this).children('td').eq(2);
const alimento = {id: tdId.text(), quantidade: tdQuantidade.text()};
const alimento = {id: tdId.text(), quantity: tdQuantidade.text()};
alimentos = [...alimentos, alimento];
});
requestBody = {"periodo": periodo, "alimentos": alimentos, "id": id};
requestBody = {"period": periodo, "foods": alimentos, "id": id};
const body = JSON.stringify(requestBody);
console.log(body);
console.log(body);
fetch('/api/refeicao',
fetch('/api/meal',
{
method: 'POST',
body: body,
Expand All @@ -45,7 +32,6 @@
if (response.ok) {
return response.json();
}
console.log(response);
throw new Error("Não foi possível buscar os alimentos");
})
.then(json => {
Expand Down
110 changes: 110 additions & 0 deletions resources/views/meals/create.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
@extends("template")

@section("conteudo")
<div class="row">
<section class="col s12 m4">
<form action="#" id="adicionaAlimento">
<div class="input-field col s12">
<select name="refeicao" id="refeicao" required>
<option value="cafeDaManha" selected>Café da manhã</option>
<option value="almoco">Almoço</option>
<option value="cafeDaTarde">Café da tarde</option>
<option value="jantar">Jantar</option>
</select>
<label for="refeicao">Em qual refeição você deseja adicionar?</label>
</div>

<div class="input-field col s12">
<select name="alimento" id="alimentos" required>
</select>
<label for="alimentos">Qual alimento você ingeriu?</label>
</div>
<div class="input-field col s12">
<input id="quantidade" type="number" name="quantidade" step="1" min="1" max="100">
<label for="quantidade">Quantidade em unidades</label>
</div>
<button class="btn" type="submit">Adicionar</button>
</form>
</section>


<div class="col s12 m8">
<button id="insertIngestedFoods" class="btn right">Salvar refeições</button>
<br><br>
<ul class="tabs">
<li class="tab col s3"><a class="active" href="#cafeDaManha">Café da manhã</a></li>
<li class="tab col s3"><a href="#almoco">Almoço</a></li>
<li class="tab col s3"><a href="#cafeDaTarde">Café da tarde</a></li>
<li class="tab col s3"><a href="#jantar">Jantar</a></li>
</ul>

<div class="row" id="cafeDaManha">
<table class="centered col s12" id="tabela-cafeDaManha">
<thead>
<tr>
<th colspan="2">Café da manhã</th>
</tr>
<tr>
<th>Nome</th>
<th>Quantidade</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="row" id="almoco">
<table class="centered col s12" id="tabela-almoco">
<thead>
<tr>
<th colspan="2">Almoço</th>
</tr>
<tr>
<th>Nome</th>
<th>Quantidade</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="row" id="cafeDaTarde">
<table class="centered col s12" id="tabela-cafeDaTarde">
<thead>
<tr>
<th colspan="2">Café da tarde</th>
</tr>
<tr>
<th>Nome</th>
<th>Quantidade</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="row" id="jantar">
<table class="centered col s12" id="tabela-jantar">
<thead>
<tr>
<th colspan="2">Janta</th>
</tr>
<tr>
<th>Nome</th>
<th>Quantidade</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
@endsection

@section("scripts")
<script>const id = {{__($id)}};</script>
<script src="{{asset('js/HttpClient.js')}}"></script>
<script src="{{asset('js/ingested-food/initializeFields.js')}}"></script>
<script src="{{asset('js/ingested-food/TableManager.js')}}"></script>
<script src="{{asset('js/ingested-food/initializeInsertButton.js')}}"></script>
<script src="{{asset('js/ingested-food/searchFoods.js')}}"></script>
<script src="{{asset('js/ingested-food/getFieldValues.js')}}"></script>
<script src="{{asset('js/ingested-food/insertIngestedFoods.js')}}"></script>
@endsection

0 comments on commit b6fe52c

Please sign in to comment.