Skip to content

Commit

Permalink
save
Browse files Browse the repository at this point in the history
  • Loading branch information
nyashaChiza committed Aug 11, 2024
1 parent 33aa779 commit 7668ce3
Show file tree
Hide file tree
Showing 11 changed files with 101 additions and 34 deletions.
1 change: 1 addition & 0 deletions accounts/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
path('site/create/', views.create_site, name='create_site'),
path('site/staff/create/<int:pk>', views.create_staff, name='create_staff_user'),
path('site/details/<uuid:uuid>', views.SiteDetailView.as_view(), name='site_detail'),
path('site/update/<uuid:uuid>', views.update_site, name='site_update'),
path('sites/', views.SiteListView.as_view(), name='site_list'),
path('search/', views.SiteSearchView.as_view(), name='site_search'),
path('filter/', views.SiteStatusFilterView.as_view(), name='site_filter'),
Expand Down
36 changes: 34 additions & 2 deletions accounts/views.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import Any
from django.db.models.query import QuerySet
from django.shortcuts import render, redirect
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages

Expand Down Expand Up @@ -96,7 +96,39 @@ def create_site(request):
else:
messages.warning(request, "You do not have the right role to perform this action")
return redirect('site_list')


@login_required
def update_site(request, uuid):
site = get_object_or_404(Site, uuid=uuid, company=request.user.company)

if request.user.role == "Admin":
if request.method == 'POST':
form = SiteForm(request.POST, instance=site)
if form.is_valid():
site = form.save(commit=False)
# Ensure the site remains associated with the user's company
site.company = request.user.company
site.save()

# Update the stock price if necessary (assuming 'price' is in the form)
stock = Stock.objects.filter(site=site, name='LP Gas').first()
if stock:
stock.price = float(form.data['price'])
stock.save()

messages.success(request, "Site Updated Successfully")
return redirect('site_list')
else:
messages.error(request, "There was an error updating the site.")
return render(request, 'sites/update.html', {'form': form, 'site': site})
else:
form = SiteForm(instance=site)
add_staff_form = StaffUserForm(initial={'status':"Active"})

return render(request, 'sites/update.html', {'form': form, 'site': site, 'add_staff_form': add_staff_form})
else:
messages.warning(request, "You do not have the right role to perform this action")
return redirect('site_list')
class SiteListView(ListView):
model = Site
template_name = 'sites/index.html'
Expand Down
4 changes: 2 additions & 2 deletions dashboard/helpers/dashboard_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def get_site_data(self):
return self.user.operation_site
elif self.user.role == "Manager":
return self.user.managed_site
return self.user.company.site.first()
return None

def get_sales_data(self):
"""Returns a dictionary with sales data."""
Expand Down Expand Up @@ -167,5 +167,5 @@ def calculate_plot_data(self):
def get_stock_sales_table_data(self):
"""Returns a queryset of all transactions for the user's site."""
if self.site:
return Transaction.objects.filter(site=self.site)
return Transaction.objects.filter(site=self.site).order_by('-created')[:6]
return Transaction.objects.none() # Return an empty queryset if no site is assigned
16 changes: 11 additions & 5 deletions stock/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@ class RecieptListView(ListView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
site = get_site(self.request.user)
context['add_reciept_form'] = RecieptForm(initial={"stock":site.stock.first()})
if site:
context['add_reciept_form'] = RecieptForm(initial={"stock":site.stock.first(), "site":site})
else:
context['add_reciept_form'] = RecieptForm()
return context

def get_queryset(self):
Expand All @@ -64,10 +67,13 @@ def post(self, request):
form = RecieptForm(request.POST)
if form.is_valid():
form.save()
Stock_stock = Stock.objects.filter(pk=form.instance.stock.pk).first()
if Stock_stock:
Stock_stock.quantity = form.instance.stock.quantity + form.instance.quantity
Stock_stock.save()
stock = Stock.objects.filter(pk=form.instance.stock.pk).first()
if stock:
stock.quantity = stock.quantity + form.instance.quantity
receipt = form.save(commit=False)
receipt.site = get_site(self.request.user)
stock.save()
receipt.save()
settings.LOGGER.critical(form.instance.stock.quantity)

messages.success(request, "Receipt Saved Successfully") # type: ignore
Expand Down
2 changes: 1 addition & 1 deletion templates/dashboard/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


{% block body %}
<div class="nk-content ">
<div class="nk-content my-4 ">
<div class="container-fluid">
<div class="nk-content-inner">
<div class="nk-content-body">
Expand Down
1 change: 0 additions & 1 deletion templates/layouts/header.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
<span class="lead-text">{{ request.user }}</span>
<span class="sub-text">{{ request.user.role }}</span>
<span class="sub-text">{{ request.user.operation_site }}{{ request.user.managed_site }}</span>
<span class="sub-text">{{ request.user.company }}</span>
</div>

</div>
Expand Down
2 changes: 1 addition & 1 deletion templates/layouts/sidebar.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<div class="nk-sidebar-element nk-sidebar-head">
<div class="nk-sidebar-brand">
<a href="{% url 'dashboard' %}" class="logo-link nk-sidebar-logo">
<span class="nk-menu-text h4 nk-title">{{ request.user.company}}</span>
<span class="nk-menu-text h4 nk-title">{{ request.user.company }}</span>
<span class="sub-text">{{ request.user.operation_site }}{{ request.user.managed_site }}</span>
</a>
</div>
Expand Down
1 change: 1 addition & 0 deletions templates/sites/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
<div class="dropdown-menu dropdown-menu-end">
<ul class="link-list-opt no-bdr">
<li><a href="{% url 'site_detail' site.uuid %}"><em class="icon ni ni-eye"></em><span>View Site</span></a></li>
<li><a href="{% url 'site_update' site.uuid %}"><em class="icon ni ni-pen"></em><span>Update Site</span></a></li>
<li data-bs-toggle="modal" data-bs-target="#addStaffModal{{ site.pk }}"><a ><em class="icon ni ni-user-check"></em><span>Add Staff</span></a></li>
</ul>
</div>
Expand Down
33 changes: 33 additions & 0 deletions templates/sites/update.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

{% extends 'layouts/base.html' %}
{% load custom_tags %}
{% load crispy_forms_tags %}

{% load static %}

{% block body %}
<div class="nk-content my-5">
{% if form.errors %}
{% for error in form.errors %}
<div class="alert alert-pro alert-danger">
{{ error }}: {{error.message}}
</div>
{% endfor %}
{% endif %}

<div class="nk-block">
<div class="card h-100 m-2 p-2">
<form method="post">
{% csrf_token %}
{{ form.as_p }} <!-- Render form fields as paragraphs -->
<p>
<label for="id_price">Price:</label>
<input type="hidden" name="company" value={{ request.user.company}} id="id_company">
<input type="number" name="price" class="form-control" value = "{{form.instance.stock.first.price}}" required step="0.01" id="id_price">
</p>
<button class="btn btn-lg btn-primary btn-block my-1" type="submit">Save</button>
</form>
</div>
</div>
</div>
{% endblock %}
7 changes: 1 addition & 6 deletions transactions/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,4 @@ def __init__(self, *args, **kwargs):

for field_name, field in self.fields.items():
field.widget.attrs["class"] = "form-control"

def clean_quantity(self):
quantity = self.cleaned_data.get("quantity")
if Stock.objects.first().quantity < quantity:
raise forms.ValidationError(f"Purchased quantity is greater than the remaining stock quantity {Stock.objects.first().quantity}kg")
return self.cleaned_data.get("quantity")

32 changes: 16 additions & 16 deletions transactions/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@ class TransactionListView(ListView):

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['add_sale_form'] = TransactionForm(initial={"product":Stock.objects.first()})
context['remaining_quantity'] = Stock.objects.first().quantity
site = get_site(self.request.user)
if site:
context['add_sale_form'] = TransactionForm(initial={"product":site.stock.first()})
context['remaining_quantity'] = site.stock.first().quantity
else:
context['add_sale_form'] = TransactionForm()

return context

def get_queryset(self):
Expand All @@ -33,7 +38,7 @@ class TransactionSearchView(ListView):
model = Transaction
template_name = 'transactions/search.html'
context_object_name = 'sales'

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['add_sale_form'] = TransactionForm(initial={"product":Stock.objects.first()})
Expand All @@ -45,7 +50,6 @@ class TransactionStatusFilterView(ListView):
model = Transaction
template_name = 'transactions/search.html'
context_object_name = 'sales'

def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['add_sale_form'] = TransactionForm(initial={"product":Stock.objects.first()})
Expand All @@ -68,15 +72,18 @@ def post(self, request):
form = TransactionForm(request.POST)

if form.is_valid():
site = self.get_user_site(request.user)
site = get_site(request.user)
if not site:
messages.warning(request, "Invalid user role or site association.")
return redirect(reverse('transaction_list'))

# Decrement the stock quantity
stock = site.stock.first() # Assuming the site has a related stock object
if stock and stock.quantity >= form.cleaned_data['quantity']:
stock.quantity -= form.cleaned_data['quantity']
quantity = form.cleaned_data['quantity']

# Perform the quantity validation
if stock and stock.quantity >= quantity:
# Decrement the stock quantity
stock.quantity -= quantity
stock.save()

# Save the transaction
Expand All @@ -86,20 +93,13 @@ def post(self, request):

messages.success(request, "Sale Saved Successfully")
else:
messages.error(request, "Insufficient stock quantity or stock not found.")
messages.warning(request, f"Insufficient stock quantity. Available quantity: {stock.quantity}kg")
else:
messages.warning(request, "Failed to save the transaction. Please correct the errors below.")
messages.warning(request, form.errors)

return redirect(reverse('transaction_list'))

def get_user_site(self, user):
"""Returns the site associated with the user based on their role."""
if user.role == "Operator":
return user.operation_site
elif user.role == "Manager":
return user.managed_site
return None
class TransactionUpdateStatusView(View):
def get(self, request, pk):
transaction = Transaction.objects.filter(pk=pk).first()
Expand Down

0 comments on commit 7668ce3

Please sign in to comment.