Skip to content

Commit

Permalink
Utsett levering knapp på index
Browse files Browse the repository at this point in the history
  • Loading branch information
sondregronas committed Sep 15, 2023
1 parent 5b4f51e commit 27367d3
Show file tree
Hide file tree
Showing 5 changed files with 141 additions and 27 deletions.
19 changes: 19 additions & 0 deletions BookingSystem/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,25 @@ def book_equipment() -> flask.Response:
return flask.Response(f'Utstyret ble utlevert til {user.get(userid).get("name")}.', status=200)


@api.route('/book/postpone', methods=['POST'])
@login_required(admin_only=True)
@handle_api_exception
def postpone_due_date() -> flask.Response:
"""Postpone the due date for an item."""
# START: Validation
validation_map = {
'item_id': VALIDATORS.ID,
'days': VALIDATORS.INT,
'days_minmax': MINMAX(MIN_DAYS, MAX_DAYS),
}
form = sanitize(validation_map, flask.request.form)
# END: Validation
item_id = form.get('item_id')
days = int(form.get('days'))
inventory.postpone_due_date(item_id=item_id, days=days)
return flask.Response(f'Fristen for {item_id} ble utsatt med {days} {"dager" if days > 1 else "dag"}.', status=200)


@api.route('/return/<item_id>', methods=['POST'])
@login_required(admin_only=True)
@handle_api_exception
Expand Down
21 changes: 21 additions & 0 deletions BookingSystem/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,3 +305,24 @@ def register_in(item_id: str) -> None:
con.close()
_update_last_seen(item_id)
audits.audit('REG_IN', f'{item_id} er nå tilgjengelig.')


def postpone_due_date(item_id: str, days: int) -> None:
"""Postpone the due date of the item with the given ID by the given number of days."""
item = get(item_id)
if item.available:
raise APIException(f'{item_id} er ikke utlånt.')
due_date = datetime.now() + timedelta(days=days)

con = sqlite3.connect(DATABASE)
try:
sql = 'UPDATE inventory SET order_due_date=:order_due_date WHERE id=:id'
con.execute(sql, {'id': item_id, 'order_due_date': due_date})
con.commit()
logger.info(f'{item_id} har fått utsatt frist til {due_date}.')
except sqlite3.IntegrityError:
logger.error(f'{item_id} eksisterer ikke. (postpone)')
raise APIException(f'{item_id} eksisterer ikke.')
finally:
con.close()
audits.audit('POSTPONE', f'{item_id} har fått utsatt frist til {due_date:%d.%m.%Y} ({item.lender}).')
5 changes: 3 additions & 2 deletions BookingSystem/sanitizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def __str__(self):

def _sanitize_form(sanitization_map: dict[any: VALIDATORS | MINMAX], form, data: dict = dict) -> bool:
"""Sanitize a form based on a sanitization map."""

def id_pattern(fkey: str) -> bool:
# Check if the ID/name is valid
r = re.compile(REGEX_ID)
Expand Down Expand Up @@ -152,8 +153,8 @@ def groupname(text: str) -> bool:
# Check if the value is between the min and max
mn, mx = sanitizer
if not mn <= int(form.get(key[:-7])) <= mx:
logger.debug(f'Invalid minmax for {key} ({form.get(key)})')
raise APIException(f'Tallverdien er ikke mellom {mn} og {mx} ({form.get(key)})')
logger.debug(f'Invalid minmax for {key} ({form.get(key[:-7])})')
raise APIException(f'Tallverdien er ikke mellom {mn} og {mx} ({form.get(key[:-7])})')

# Passed all checks!
logger.debug(f'Validated {key} ({sanitizer}, {form.get(key)})')
Expand Down
6 changes: 6 additions & 0 deletions BookingSystem/templates/audits.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ <h3>Her kan du søke i loggen etter forlatt utstyr, hva skjedde med det?</h3>
</button>
</a>
</li>
<li>
<a href="?search=POSTPONE">
<button>
Utsatt
</button>
</a>
<li>
<a href="?search=REG_OUT">
<button>
Expand Down
117 changes: 92 additions & 25 deletions BookingSystem/templates/index_admin.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,31 +27,38 @@ <h3>Velkommen! Her kan du <a href="{{ url_for('app.innlevering') }}">levere inn<
</a>

{% if overdue_items %}
<br><br>
<center>
<h4>
Overskredet utstyr:
</h4>
</center>
<table id="active">
<thead>
<tr>
<th>Løpenummer</th>
<th>Utstyr</th>
<th>Utlånt til</th>
<th>Frist for levering</th>
</thead>
<tbody>
{% for item in overdue_items %}
<tr class="item-row item-row--overdue">
<td>{{ item.id }}</td>
<td>{{ item.name }} ({{ item.category }})</td>
<td>{{ item.lender_name }} <small> ({{ item.classroom }}{% if item.teacher %},
{{ item.teacher }}{% endif %})</small></td>
<td>{{ item.order_due_date|strftime }}</td>
</tr>
{% endfor %}
</table>
<div id="overdue_items">
<br><br>
<center>
<h4>
Overskredet utstyr:
</h4>
</center>
<table id="active">
<thead>
<tr>
<th>Løpenummer</th>
<th>Utstyr</th>
<th>Utlånt til</th>
<th>Frist for levering</th>
<th>Alternativer</th>
</thead>
<tbody>
{% for item in overdue_items %}
<tr class="item-row item-row--overdue">
<td>{{ item.id }}</td>
<td>{{ item.name }} ({{ item.category }})</td>
<td>{{ item.lender_name }} <small> ({{ item.classroom }}{% if item.teacher %},
{{ item.teacher }}{% endif %})</small></td>
<td>{{ item.order_due_date|strftime }}</td>
<td>
<a onclick="postpone('{{ item.id }}', '{{ item.lender }}', this.parentNode.parentNode)">Utsett
frist</a>
</td>
</tr>
{% endfor %}
</table>
</div>
{% endif %}

<script>
Expand All @@ -77,6 +84,66 @@ <h4>
"lengthMenu": [[25, 50, -1], [25, 50, "Alle"]],
});
});

function postpone(id, lender, node) {
$.confirm({
title: `Utsett levering av '${id}'`,
type: 'blue',
icon: 'fa fa-calendar-plus-o',
content: `<i>Lånt til ${lender}</i>` +
'<br><br>Utlånsfristen kan utsettes opp til 7 dager, kontaktlærer bør varsles om utsettelsen før den gjennomføres.',
buttons: {
oneDay: {
text: '1 dag',
btnClass: 'btn-blue',
action: function () {
submitPostpone(id, lender, node, 1)
}
},
threeDays: {
text: '3 dager',
btnClass: 'btn-blue',
action: function () {
submitPostpone(id, lender, node, 3)
}
},
sevenDays: {
text: '1 uke',
btnClass: 'btn-blue',
action: function () {
submitPostpone(id, lender, node, 7)
}
},
},
})
}

function submitPostpone(id, lender, tr, days) {
$.ajax({
url: "{{ url_for('api.postpone_due_date') }}",
data: {
item_id: id,
days: days
},
type: 'POST',
success: function (response, status) {
iziToast.success({
title: 'Utsetter levering',
message: response
});
tr.remove();
if ($('.item-row').length === 0) {
$('#overdue_items').remove();
}
},
error: function (response, status) {
iziToast.error({
title: 'Feil',
message: response.responseText,
});
}
})
}
</script>

{% endblock %}

0 comments on commit 27367d3

Please sign in to comment.