Skip to content

Commit

Permalink
Account name should be unique for each user and not for all users (#141)
Browse files Browse the repository at this point in the history
  • Loading branch information
MHamzaBham authored Jan 17, 2025
1 parent c88790e commit 436824b
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 81 deletions.
23 changes: 20 additions & 3 deletions app/Http/Controllers/AccountController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Models\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class AccountController extends Controller
{
Expand Down Expand Up @@ -64,7 +65,14 @@ public function index(Request $request)
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:35|unique:accounts,name',
'name' => [
'required',
'string',
'max:35',
Rule::unique('accounts', 'name')->where(function ($query) {
return $query->where('user_id', auth()->id());
}),
],
'type' => 'required|in:' . implode(',', array_keys(config('custom.account_types'))),
'balance' => 'required|numeric|min:0',
'currency' => 'required|in:' . implode(',', array_keys(config('custom.currencies'))),
Expand Down Expand Up @@ -123,9 +131,18 @@ public function show(Account $account)
public function update(Request $request, $id)
{
$validatedData = $request->validate([
'name' => 'required|string|max:35|unique:accounts,name,' . $id,
'name' => [
'required',
'string',
'max:35',
Rule::unique('accounts', 'name')
->where(function ($query) {
return $query->where('user_id', auth()->id());
})
->ignore($id), // Ignore the current account's ID
],
'type' => 'required|in:' . implode(',', array_keys(config('custom.account_types'))),
'balance' => 'required|numeric|min:0',
'balance' => 'required|numeric',
'currency' => 'required|in:' . implode(',', array_keys(config('custom.currencies'))),
]);

Expand Down
125 changes: 50 additions & 75 deletions public/assets/js/custom.js
Original file line number Diff line number Diff line change
Expand Up @@ -365,80 +365,63 @@ document.getElementById("accountForm")?.addEventListener("submit", function (e)
});

function addAccount(url, formData) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);

// Set the CSRF token in the headers
xhr.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').getAttribute('content'));

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // Request is completed
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText);

if (data.success) {
// Hide the modal
var modalElement = document.getElementById('modal-default');
var modalInstance = bootstrap.Modal.getInstance(modalElement);
modalInstance.hide();

setToastMessage("Your account has been added successfully!");

// Reload the page
window.location.reload();
} else {
let errorList = '';
for (let field in data.errors) {
if (data.errors.hasOwnProperty(field)) {
data.errors[field].forEach(error => {
errorList += `<p class="mb-0">${error}</p>`;
});
}
}
swalWithBootstrapButtons.fire({
title: "Validation Errors",
html: errorList,
icon: "error",
});
}
fetch(url, {
method: 'POST',
headers: {
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
"Accept": "application/json",
},
body: formData,
})
.then(response => {
if (!response.ok) {
return response.json().then(errData => {
throw errData;
});
}
return response.json(); // Return JSON data for successful responses
})
.then(response => {
if (response.success) {
// Hide the modal
const addAccountModal = document.getElementById('AddAccountModal');
const modalInstance = bootstrap.Modal.getInstance(addAccountModal);
modalInstance?.hide();

setToastMessage("Account successfully created.");
window.location.reload();
} else {
let errorMessage = "An error occurred. Please try again.";
if (xhr.responseJSON && xhr.responseJSON.errors) {
let errorList = '';
for (let field in xhr.responseJSON.errors) {
if (xhr.responseJSON.errors.hasOwnProperty(field)) {
xhr.responseJSON.errors[field].forEach(error => {
errorList += `<p class="mb-0">${error}</p>`;
});
}
}
errorMessage = errorList;
} else if (xhr.responseText) {
errorMessage = xhr.responseText;
}
swalWithBootstrapButtons.fire({
title: "Error",
html: errorMessage,
text: "An error occurred: " + response.message,
icon: "error",
});
}
}
};

xhr.onerror = function () {
swalWithBootstrapButtons.fire({
title: "Error",
text: "An error occurred while processing the request.",
icon: "error",
})
.catch(error => {
let errorMessage = "An error occurred. Please try again.";
if (error.errors) {
let errorList = "";
for (let field in error.errors) {
if (error.errors.hasOwnProperty(field)) {
error.errors[field].forEach((err) => {
errorList += `<p class="mb-0">${err}</p>`;
});
}
}
errorMessage = errorList;
}
swalWithBootstrapButtons.fire({
title: "Error",
html: errorMessage,
icon: "error",
});
});
};

// Send the request with FormData
xhr.send(formData);
}




function fetchAccountData(url) {
fetch(url, {
method: 'GET'
Expand All @@ -464,18 +447,17 @@ function openEditAccountModal(account) {
document.getElementById('editCurrency').value = account.currency;

// Show the modal
var modal = new bootstrap.Modal(document.getElementById('modal-edit'));
var modal = new bootstrap.Modal(document.getElementById('EditAccountModal'));
modal.show();
}


function updateAccount(url, formData) {
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

const options = {
method: 'POST',
headers: {
'X-CSRF-TOKEN': csrfToken,
"X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').getAttribute("content"),
"Accept": "application/json",
},
body: formData,
};
Expand All @@ -486,7 +468,7 @@ function updateAccount(url, formData) {
.then(data => {
if (data.success) {
// Hide the modal
const modalElement = document.getElementById('modal-edit');
const modalElement = document.getElementById('EditAccountModal');
const modalInstance = bootstrap.Modal.getInstance(modalElement);
modalInstance.hide();

Expand Down Expand Up @@ -536,7 +518,6 @@ function updateAccount(url, formData) {
}



function deleteAccount(accountId) {
var deleteUrl = window.accountRoutes.destroy.replace('__ACCOUNT_ID__', accountId);

Expand Down Expand Up @@ -581,13 +562,7 @@ function deleteAccount(accountId) {
title: "Error",
text: "An error occurred. Please try again.",
icon: "error"
});
});
} else if (result.dismiss === Swal.DismissReason.cancel) {
swalWithBootstrapButtons.fire({
title: "Cancelled",
text: "Your account is safe :)",
icon: "error"
});
}
});
Expand Down
2 changes: 1 addition & 1 deletion resources/views/accounts/index.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
<div class="card-header pb-0 d-block d-sm-flex justify-content-between mt-0">
<h6 class="mb-sm-2 mb-md-0 text-center text-sm-start">Accounts Information</h6>
<button type="button" class="btn btn-block bg-gradient-primary mb-3 w-100 w-sm-auto" data-bs-toggle="modal"
data-bs-target="#modal-default">+ Add Account</button>
data-bs-target="#AddAccountModal">+ Add Account</button>
</div>
<div class="card-body pt-4 p-3">
<ul class="list-group">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<div class="modal fade" id="modal-default" tabindex="-1" role="dialog" aria-labelledby="modal-default" aria-hidden="true">
<div class="modal fade" id="AddAccountModal" tabindex="-1" role="dialog" aria-labelledby="AddAccountModal" aria-hidden="true">
<div class="modal-dialog modal- modal-dialog-centered modal-" role="document">
<div class="modal-content">
<div class="modal-header px-5">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<div class="modal fade" id="modal-edit" tabindex="-1" role="dialog" aria-labelledby="modal-edit">
<div class="modal fade" id="EditAccountModal" tabindex="-1" role="dialog" aria-labelledby="EditAccountModal">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header px-5">
Expand Down

0 comments on commit 436824b

Please sign in to comment.