This commit is contained in:
LilleBRG 2025-05-13 15:14:54 +02:00
commit 12427a85f8
21 changed files with 234 additions and 131 deletions

View File

@ -45,7 +45,7 @@
android:exported="false" />
<activity
android:name=".ui.dishes.CreateDishAIActivity"
android:name=".ui.dishes.GenerateRecipeActivity"
android:exported="false" />
<activity

View File

@ -18,7 +18,7 @@ fun login(ctx: Context, email: String, password: String) {
val response = requestJson<LoginRequest, LoginResponse>(ctx, "POST", "/api/User/login", request)
with (ctx.getSharedPreferences("easyeat", Context.MODE_PRIVATE).edit()) {
with(ctx.getSharedPreferences("easyeat", Context.MODE_PRIVATE).edit()) {
putInt("user-id", response.id)
putString("username", response.userName)
putString("auth-token", response.token)
@ -28,7 +28,7 @@ fun login(ctx: Context, email: String, password: String) {
}
fun logout(ctx: Context) {
with (ctx.getSharedPreferences("easyeat", Context.MODE_PRIVATE).edit()) {
with(ctx.getSharedPreferences("easyeat", Context.MODE_PRIVATE).edit()) {
remove("user-id")
remove("username")
remove("auth-token")

View File

@ -2,6 +2,7 @@ package tech.mercantec.easyeat.helpers
import android.content.Context
import kotlinx.serialization.Serializable
import tech.mercantec.easyeat.models.Ingredient
import tech.mercantec.easyeat.models.Recipe
@Serializable
@ -10,3 +11,21 @@ data class GenerateRecipeRequest(val dish: String, val language: String, val num
fun generateRecipeWithAI(ctx: Context, title: String, language: String): Recipe {
return requestJson<GenerateRecipeRequest, Recipe>(ctx, "POST", "/api/Recipe/chatbot", GenerateRecipeRequest(title, language, 1, arrayOf()))
}
fun createRecipe(ctx: Context, recipe: Recipe) {
requestJson<Recipe, Boolean>(ctx, "POST", "/api/recipe/create", recipe)
}
@Serializable
data class GetAllRecipesResponse(val id: Int, val name: String, val description: String)
fun getAllRecipes(ctx: Context): List<GetAllRecipesResponse> {
return requestJson<Unit, List<GetAllRecipesResponse>>(ctx, "GET", "/api/Recipe/getall", null)
}
@Serializable
data class RecipeDetailsResponse(val id: Int, val name: String, val description: String, val directions: List<String>, val ingredients: List<Ingredient>)
fun getRecipeDetails(ctx: Context, id: Int): RecipeDetailsResponse {
return requestJson<Unit, RecipeDetailsResponse>(ctx, "GET", "/api/Recipe/get/$id", null)
}

View File

@ -1,18 +0,0 @@
package tech.mercantec.easyeat.models
import kotlinx.serialization.Serializable
@Serializable
data class CreateRecipe(
val name: String,
val description: String,
val directions: List<String>,
val ingredients: List<CreateIngredient>
)
@Serializable
data class CreateIngredient(
val amount: Double?,
val unit: String?,
val name: String
)

View File

@ -2,10 +2,9 @@ package tech.mercantec.easyeat.models
import kotlinx.serialization.Serializable
@Serializable
data class Recipe(
val id: Int,
val id: Int? = null,
val name: String,
val description: String,
val directions: List<String>,
@ -14,7 +13,7 @@ data class Recipe(
@Serializable
data class Ingredient(
val id: Int,
val id: Int? = null,
val amount: Double?,
val unit: String?,
val name: String

View File

@ -2,9 +2,7 @@ package tech.mercantec.easyeat.ui.dishes
import android.app.Activity
import android.app.ProgressDialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.ArrayAdapter
import android.widget.Button
@ -14,14 +12,14 @@ import android.widget.LinearLayout
import android.widget.Spinner
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContentProviderCompat.requireContext
import tech.mercantec.easyeat.R
import tech.mercantec.easyeat.helpers.ApiRequestException
import tech.mercantec.easyeat.helpers.changePassword
import tech.mercantec.easyeat.helpers.createRecipe
import tech.mercantec.easyeat.helpers.request
import tech.mercantec.easyeat.models.CreateIngredient
import tech.mercantec.easyeat.models.CreateRecipe
import tech.mercantec.easyeat.models.Ingredient
import tech.mercantec.easyeat.models.Recipe
import kotlin.concurrent.thread
class CreateDishActivity : AppCompatActivity() {
@ -52,7 +50,7 @@ class CreateDishActivity : AppCompatActivity() {
.map { line -> line.trim() }
.filter { it.isNotEmpty() }
val recipe = CreateRecipe(
val recipe = Recipe(
name = findViewById<EditText>(R.id.dishName).text.toString().trim(),
description = findViewById<EditText>(R.id.dishDescription).text.toString().trim(),
directions = directions,
@ -106,8 +104,8 @@ class CreateDishActivity : AppCompatActivity() {
ingredientContainer.addView(ingredientRow)
}
private fun collectIngredients(): List<CreateIngredient> {
val ingredients = mutableListOf<CreateIngredient>()
private fun collectIngredients(): List<Ingredient> {
val ingredients = mutableListOf<Ingredient>()
for (i in 0 until ingredientContainer.childCount) {
val ingredientView = ingredientContainer.getChildAt(i)
@ -124,7 +122,7 @@ class CreateDishActivity : AppCompatActivity() {
// Optional: Only add non-empty rows
if (element.isNotEmpty() && amount.isNotEmpty()) {
ingredients.add(CreateIngredient(name = element, amount = amount.toDouble(), unit = unit))
ingredients.add(Ingredient(name = element, amount = amount.toDouble(), unit = unit))
}
}

View File

@ -6,7 +6,7 @@ import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.PopupMenu
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
@ -15,7 +15,7 @@ import tech.mercantec.easyeat.R
import tech.mercantec.easyeat.databinding.FragmentDishesBinding
import tech.mercantec.easyeat.helpers.ApiRequestException
import tech.mercantec.easyeat.helpers.GetAllRecipesResponse
import tech.mercantec.easyeat.helpers.getAllRecipies
import tech.mercantec.easyeat.helpers.getAllRecipes
import tech.mercantec.easyeat.models.DishListItem
import kotlin.concurrent.thread
@ -36,28 +36,31 @@ class DishesFragment : Fragment() {
loadRecipes()
binding.addDish.setOnClickListener {
val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.create_dish_modal_dialog, null)
val popup = PopupMenu(requireActivity(), it)
val dialog = android.app.AlertDialog.Builder(requireContext())
.setView(dialogView)
.setCancelable(true) // tap outside to dismiss
.create()
popup.apply {
menuInflater.inflate(R.menu.create_dish_menu, menu)
dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
setOnMenuItemClickListener {
when (it.itemId) {
R.id.create_manually -> {
val intent = Intent(requireContext(), CreateDishActivity::class.java)
createDishLauncher.launch(intent)
dialogView.findViewById<Button>(R.id.createManualBtn).setOnClickListener {
val intent = Intent(requireContext(), CreateDishActivity::class.java)
createDishLauncher.launch(intent)
dialog.dismiss()
true
}
R.id.create_with_ai -> {
val intent = Intent(requireContext(), GenerateRecipeActivity::class.java)
createDishLauncher.launch(intent)
true
}
else -> false
}
}
show()
}
dialogView.findViewById<Button>(R.id.createAIBtn).setOnClickListener {
val intent = Intent(requireContext(), CreateDishAIActivity::class.java)
createDishLauncher.launch(intent)
dialog.dismiss()
}
dialog.show()
}
@ -68,7 +71,7 @@ class DishesFragment : Fragment() {
thread {
val recipes: List<GetAllRecipesResponse>
try {
recipes = getAllRecipies(requireContext())
recipes = getAllRecipes(requireContext())
} catch (e: ApiRequestException) {
activity?.runOnUiThread {
Toast.makeText(requireContext(), e.message, Toast.LENGTH_LONG).show()

View File

@ -4,20 +4,20 @@ import android.app.ProgressDialog
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import tech.mercantec.easyeat.R
import tech.mercantec.easyeat.helpers.ApiRequestException
import tech.mercantec.easyeat.helpers.createRecipe
import tech.mercantec.easyeat.helpers.generateRecipeWithAI
import tech.mercantec.easyeat.models.Recipe
import java.util.Locale
import kotlin.concurrent.thread
class CreateDishAIActivity : AppCompatActivity() {
class GenerateRecipeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.create_dish_ai_form)
setContentView(R.layout.activity_generate_recipe)
findViewById<Button>(R.id.generate).setOnClickListener {
val name = findViewById<EditText>(R.id.dish_title).text.toString()
@ -27,21 +27,25 @@ class CreateDishAIActivity : AppCompatActivity() {
progressDialog.show()
thread {
val response: Recipe
val response: GenerateRecipeResponse
try {
response = generateRecipeWithAI(this, name, Locale.getDefault().displayLanguage)
val recipe = generateRecipeWithAI(this, name, Locale.getDefault().displayLanguage)
runOnUiThread {
progressDialog.setMessage("Saving...")
}
createRecipe(this, recipe)
finish()
} catch (e: ApiRequestException) {
runOnUiThread {
Toast.makeText(this, e.message, Toast.LENGTH_LONG).show()
}
return@thread
} finally {
progressDialog.hide()
}
runOnUiThread {
Toast.makeText(this, response.toString(), Toast.LENGTH_LONG).show()
runOnUiThread {
progressDialog.hide()
}
}
}
}

View File

@ -9,16 +9,16 @@ import android.widget.TextView
import tech.mercantec.easyeat.R
class InstructionsAdapter (context: Context, instructions: List<String>)
: ArrayAdapter<String>(context, 0, instructions) {
: ArrayAdapter<String>(context, R.layout.activity_dish_details_instructions_list_item, instructions) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val ingredient = getItem(position)
val instruction = getItem(position)
val view = convertView ?: LayoutInflater.from(context)
.inflate(R.layout.activity_dish_details_instructions_list_item, parent, false)
val nameView = view.findViewById<TextView>(R.id.instructionText)
nameView.text = ingredient?: ""
nameView.text = instruction
return view
}

View File

@ -0,0 +1,54 @@
package tech.mercantec.easyeat.ui.dishes
import android.os.Bundle
import android.text.Html
import android.text.Html.FROM_HTML_MODE_LEGACY
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import kotlinx.serialization.json.Json
import tech.mercantec.easyeat.R
import tech.mercantec.easyeat.models.Recipe
class RecipeFragment : Fragment() {
private var recipe: Recipe? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let { args ->
recipe = args.getString("RECIPE")?.let { Json.decodeFromString<Recipe>(it) }
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
val binding = inflater.inflate(R.layout.fragment_recipe, container, false)
recipe?.let { recipe ->
binding.findViewById<TextView>(R.id.title).text = recipe.name
binding.findViewById<TextView>(R.id.ingredients).text =
Html.fromHtml(
"<ul>" +
recipe.ingredients.map { "<li>${it.amount} ${it.unit} ${it.name}</li>" } +
"</ul>",
FROM_HTML_MODE_LEGACY
)
binding.findViewById<TextView>(R.id.directions).text =
Html.fromHtml(
"<ul>" +
recipe.directions.map { "<li>${it}</li>" } +
"</ul>",
FROM_HTML_MODE_LEGACY
)
}
return binding
}
}

View File

@ -86,7 +86,9 @@ class ShoppingListFragment : Fragment() {
val popup = PopupMenu(requireActivity(), view)
popup.apply {
menuInflater.inflate(R.menu.shopping_item_context_menu, menu)
setOnMenuItemClickListener {
when (it.itemId) {
R.id.remove_shopping_item -> {
@ -107,6 +109,7 @@ class ShoppingListFragment : Fragment() {
else -> false
}
}
show()
}

View File

@ -1,36 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dialog_root"
android:layout_width="250dp"
android:layout_height="400dp"
android:orientation="vertical"
android:background="@drawable/rounded_background"
android:padding="0dp"
android:gravity="center">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text="@string/create_dish"
android:textAlignment="center"
android:textSize="30sp"/>
<Button
android:id="@+id/createManualBtn"
android:layout_width="200dp"
android:layout_height="0dp"
android:layout_weight="1"
android:text="@string/manually" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#CCCCCC" />
<Button
android:id="@+id/createAIBtn"
android:layout_width="200dp"
android:layout_height="0dp"
android:layout_weight="1"
android:text="@string/search_for_dishes" />
</LinearLayout>

View File

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="30dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/title"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:textSize="24sp"
/>
<TextView
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/ingredients_label"
style="@style/HighContrastText"
/>
<TextView
android:id="@+id/ingredients"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="@string/directions_label"
style="@style/HighContrastText"
/>
<TextView
android:id="@+id/directions"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/create_manually"
android:title="@string/create_manually_label"
/>
<item
android:id="@+id/create_with_ai"
android:title="@string/create_ai_label"
/>
</menu>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="HighContrastText" parent="TextAppearance.AppCompat">
<item name="android:textColor">@color/white</item>
</style>
</resources>

View File

@ -8,5 +8,6 @@
<item name="colorSurface">@color/dark_cyan</item>
<item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
<item name="android:colorBackground">@color/black</item>
<item name="android:windowBackground">@color/black</item>
</style>
</resources>

View File

@ -41,13 +41,15 @@
<string name="checked_desc">Checked</string>
<string name="delete_label">Delete</string>
<string name="empty_shopping_list">Your shopping list is empty</string>
<string name="search_for_dishes">Search For Dishes</string>
<string name="manually">Manually</string>
<string name="create_dish">Create Dish</string>
<string name="ai_generate_recipe_title">Generate recipe with AI</string>
<string name="dish_title_label">Name of dish</string>
<string name="generate_recipe_label">Generate</string>
<string name="add_ingredients_to_shopping_list">Add ingredients to Shopping List</string>
<string name="ingredients_label">Ingredients</string>
<string name="directions_label">Directions</string>
<string name="create_manually_label">Create manually</string>
<string name="create_ai_label">Generate recipe using AI</string>
<string-array name="units">
<item></item>
<item>g</item>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="HighContrastText" parent="TextAppearance.AppCompat">
<item name="android:textColor">@color/black</item>
</style>
</resources>

View File

@ -111,38 +111,41 @@ namespace API.BusinessLogic
}
// Adds an entire recipes ingredients to the shoppinglist
public async Task<IActionResult> AddRecipeToShoppingList(int userId, int recipeId)
public async Task<IActionResult> AddRecipeToShoppingList(int userId, int recipeId, int multiplier)
{
var user = await _dbAccess.ReadShoppingList(userId);
var recipe = await _recipeDBAccess.ReadRecipe(recipeId);
var ingredients = recipe.Ingredients;
foreach (var ingredient in ingredients)
for (int i = 0; i < multiplier; i++)
{
List<ShoppingListItem> shoppingList = user.ShoppingList;
if (shoppingList.Any(s => s.Name == ingredient.Name))
foreach (var ingredient in ingredients)
{
ShoppingListItem item = shoppingList.Where(s => s.Name == ingredient.Name).FirstOrDefault();
shoppingList.Remove(item);
List<ShoppingListItem> shoppingList = user.ShoppingList;
ShoppingListItemDTO listItemDTO = new ShoppingListItemDTO();
listItemDTO.Name = ingredient.Name;
listItemDTO.Amount = ingredient.Amount;
listItemDTO.Unit = ingredient.Unit;
listItemDTO.Checked = false;
if (shoppingList.Any(s => s.Name == ingredient.Name))
{
ShoppingListItem item = shoppingList.Where(s => s.Name == ingredient.Name).FirstOrDefault();
shoppingList.Remove(item);
user.ShoppingList.Add(await UnitAdjustmentSameName(listItemDTO, item));
}
else
{
ShoppingListItem newItem = new ShoppingListItem();
newItem.Name = ingredient.Name;
newItem.Amount = ingredient.Amount;
newItem.Unit = ingredient.Unit;
newItem.Checked = false;
ShoppingListItemDTO listItemDTO = new ShoppingListItemDTO();
listItemDTO.Name = ingredient.Name;
listItemDTO.Amount = ingredient.Amount;
listItemDTO.Unit = ingredient.Unit;
listItemDTO.Checked = false;
user.ShoppingList.Add(await UnitAdjustment(newItem));
user.ShoppingList.Add(await UnitAdjustmentSameName(listItemDTO, item));
}
else
{
ShoppingListItem newItem = new ShoppingListItem();
newItem.Name = ingredient.Name;
newItem.Amount = ingredient.Amount;
newItem.Unit = ingredient.Unit;
newItem.Checked = false;
user.ShoppingList.Add(await UnitAdjustment(newItem));
}
}
}

View File

@ -100,12 +100,12 @@ namespace API.Controllers
/// <returns>returns a okobjectresult with a boolean that is true if it fails it returns a confliftobjectresult with a message of why it failed</returns>
[Authorize]
[HttpPost("recipeadd")]
public async Task<IActionResult> AddARecipesItems(int recipeId)
public async Task<IActionResult> AddARecipesItems(int recipeId, int multiplier = 1)
{
var claims = HttpContext.User.Claims;
string userIdString = claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
int userId = Convert.ToInt32(userIdString);
return await _shoppingListLogic.AddRecipeToShoppingList(userId, recipeId);
return await _shoppingListLogic.AddRecipeToShoppingList(userId, recipeId, multiplier);
}
}
}