8
0
Fork 0
mirror of https://gitlab2.federez.net/re2o/re2o synced 2024-11-25 04:43:10 +00:00

[Printer] Fix major bug. See below for more explanations :

Before, I used request.session to store some information about the current jobs to be printed.
This was because in the very beginning, I had an issue with disappearing files in my model.

I was able to fix this issue in a previous commit, but I still needed the jids.
However, because of this storage system, if someone tried to print a file, then oppened a second tab,
and tried to print anoter file, he/she would pay twice for the second file ....

I decided to add a hidden field to store the job id and deal with it, and it is readonly to avoid
changing it.
This commit is contained in:
Maxime Bombar 2018-10-21 19:48:10 +02:00 committed by root
parent 511eb2d7a1
commit d7233a0845
4 changed files with 121 additions and 42 deletions

View file

@ -47,6 +47,9 @@ class JobWithOptionsForm(FormRevMixin, ModelForm):
class PrintForm(FormRevMixin, ModelForm): class PrintForm(FormRevMixin, ModelForm):
jid = forms.IntegerField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
prefix = kwargs.pop('prefix', self.Meta.model.__name__) prefix = kwargs.pop('prefix', self.Meta.model.__name__)
self.user = kwargs.pop('user') self.user = kwargs.pop('user')
@ -58,6 +61,7 @@ class PrintForm(FormRevMixin, ModelForm):
self.fields['color'].label = 'color' self.fields['color'].label = 'color'
self.fields['count'].label = 'count' self.fields['count'].label = 'count'
self.fields['jid'].widget.attrs['readonly'] = True
self.fields['printAs'].widget.attrs['readonly'] = True self.fields['printAs'].widget.attrs['readonly'] = True
self.fields['filename'].widget.attrs['readonly'] = True self.fields['filename'].widget.attrs['readonly'] = True
self.fields['price'].widget.attrs['readonly'] = True self.fields['price'].widget.attrs['readonly'] = True
@ -71,4 +75,5 @@ class PrintForm(FormRevMixin, ModelForm):
'endtime', 'endtime',
'status', 'status',
'file', 'file',
'paid',
] ]

View file

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2018-10-21 15:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('printer', '0008_auto_20181012_1242'),
]
operations = [
migrations.AddField(
model_name='jobwithoptions',
name='paid',
field=models.BooleanField(default='False'),
),
]

View file

@ -85,6 +85,7 @@ class JobWithOptions(RevMixin, models.Model):
('Finished', 'Finished') ('Finished', 'Finished')
) )
user = models.ForeignKey('users.User', on_delete=models.PROTECT) user = models.ForeignKey('users.User', on_delete=models.PROTECT)
paid = models.BooleanField(default='False')
file = models.FileField(storage=FileSystemStorage(location='/var/impressions'), file = models.FileField(storage=FileSystemStorage(location='/var/impressions'),
upload_to=user_printing_path, upload_to=user_printing_path,
validators=[FileValidator( validators=[FileValidator(

View file

@ -46,23 +46,36 @@ def new_job(request):
View to create a new printing job View to create a new printing job
""" """
if request.method == 'POST': if request.method == 'POST':
# raise Exception('coucou3')
# raise ValidationError("'%(path)s'", code='path', params = {'path': request.FILES})
job_formset = formset_factory(JobWithOptionsForm)( job_formset = formset_factory(JobWithOptionsForm)(
request.POST, request.POST,
request.FILES or None, request.FILES or None,
form_kwargs={'user': request.user}, form_kwargs={'user': request.user},
) )
# raise ValidationError("'%(path)s'", code='path', params = {'path': request.FILES})
tmp_job_formset = job_formset tmp_job_formset = job_formset
if request.FILES: if request.FILES:
# raise Exception("Coucou4")
if job_formset.is_valid(): if job_formset.is_valid():
# raise Exception("Valide !!!")
files = request.FILES files = request.FILES
data = [] data = []
i=0 i=0
for job in job_formset: # request.POST['jids'] = []
# raise ValidationError("'%(path)s'", code='path', params = {'path': job.cleaned_data["file"].name}) jids = []
for job in job_formset.forms:
if job.is_valid():
try:
filename = job.cleaned_data['file'].name filename = job.cleaned_data['file'].name
except KeyError:
raise ValidationError("'%(path)s'", code='path', params = {'path': job})
job = job.save(commit=False) job = job.save(commit=False)
job.filename = filename job.filename = filename
job.user=request.user job.user=request.user
@ -85,15 +98,21 @@ def new_job(request):
job._update_price() job._update_price()
job.save() job.save()
job_data = model_to_dict(job) job_data = model_to_dict(job)
request.session['id-form-%s-file' % i] = job.id jids.append(job.id)
request.session['form-%s-file' % i] = request.FILES['form-%s-file' % i].temporary_file_path() # request.session['id-form-%s-file' % i] = job.id
# raise ValidationError("'%(plop)s'", code='plop', params = {'plop': job_data }) # request.session['form-%s-file' % i] = request.FILES['form-%s-file' % i].temporary_file_path()
job_data['jid'] = job.id
data.append(job_data) data.append(job_data)
i+=1 i+=1
job_formset_filled_in = formset_factory(PrintForm, extra=0)( job_formset_filled_in = formset_factory(PrintForm, extra=0)(
initial=data, initial=data,
form_kwargs={'user': request.user}, # jids=jids,
form_kwargs={'user': request.user,
},
) )
# raise ValidationError("'%(path)s'", code='path', params = {'path': job_formset_filled_in.forms })
# request.POST['job_ids'] = jids
return form( return form(
{ {
'jobform': job_formset_filled_in, 'jobform': job_formset_filled_in,
@ -102,40 +121,70 @@ def new_job(request):
'printer/print.html', 'printer/print.html',
request request
) )
else:
job_formset = tmp_job_formset
return form(
{
'jobform': job_formset,
'action_name': _("Next"),
},
'printer/newjob.html',
request
)
# else:
# job_formset = tmp_job_formset
# return form(
# {
# 'jobform': job_formset,
# 'action_name': _("Next"),
# },
# 'printer/newjob.html',
# request
# )
# else:
# raise Exception("Coucou5")
# elif 'Print' in request.POST: # elif 'Print' in request.POST:
# raise ValidationError("'%(path)s'", code='path', params = {'path': request.POST }) # raise ValidationError("'%(path)s'", code='path', params = {'path': request.POST })
# raise Exception('On a déjà upload !') # raise Exception('On a déjà upload !')
n = int(request.POST['form-TOTAL_FORMS']) # n = int(request.POST['form-TOTAL_FORMS'])
job_formset = formset_factory(PrintForm)( job_formset = formset_factory(PrintForm)(
request.POST, request.POST,
form_kwargs={'user': request.user}, form_kwargs={'user': request.user},
) )
jids = [request.session['id-form-%s-file' % i] for i in range(n)] # raise ValidationError("'%(path)s'", code='path', params = {'path': request.POST })
# raise ValidationError("'%(path)s'", code='path', params = {'path': id_list }) # jids = request.POST['job_ids']
if job_formset.is_valid(): if job_formset.is_valid():
for job_obj in job_formset: for job_form in job_formset:
i=0 i=0
old_job = JobWithOptions.objects.get(id=jids[i]) # old_job = JobWithOptions.objects.get(id=jids[i])
job = job_obj.save(commit=False) jid = job_form.cleaned_data['jid']
# raise ValidationError("'%(path)s'", code='path', params = {'path': job_obj.cleaned_data })
job = JobWithOptions.objects.get(id=jid)
# job = job_obj.save(commit=False)
job.user = request.user job.user = request.user
job.status = 'Printable' job.status = 'Printable'
job.file = old_job.file # raise ValidationError("'%(plop)s'", code='plop', params = {'plop': job.file})
# job.file = old_job.file
job._update_price() job._update_price()
job.save() job.save()
i+=1 i+=1
# raise ValidationError("'%(plop)s'", code='plop', params = {'plop': request.method}) # raise ValidationError("'%(plop)s'", code='plop', params = {'plop': request.method})
# raise ValidationError("'%(path)s'", code='path', params = {'path': str(n) }) # raise ValidationError("'%(path)s'", code='path', params = {'path': str(n) })
request.session['jids']=jids # request.session['jids']=jids
return redirect('printer:payment') return redirect('printer:payment')
job_formset = tmp_job_formset
else: else:
# raise Exception("Coucou2")
job_formset = formset_factory(JobWithOptionsForm)( job_formset = formset_factory(JobWithOptionsForm)(
form_kwargs={'user': request.user} form_kwargs={'user': request.user}
) )
# raise ValidationError("'%(plop)s'", code='plop', params = {'plop': job_formset})
return form( return form(
{ {
'jobform': job_formset, 'jobform': job_formset,
@ -150,15 +199,19 @@ def payment(request):
View used to create a new invoice and make the payment View used to create a new invoice and make the payment
""" """
# user = request.user # user = request.user
jids = request.session['jids'] # jids = request.session['jids']
# raise ValidationError("'%(path)s'", code='path', params = {'path': jids}) # raise ValidationError("'%(path)s'", code='path', params = {'path': jids})
jobs = JobWithOptions.objects.filter(id__in=jids) jobs = JobWithOptions.objects.filter(user=request.user, status='Printable', paid='False')
users = {} users = {}
for job in jobs: for job in jobs:
try: try:
users[job.printAs]+=job.price users[job.printAs]+=job.price
job.paid = True
job.save()
except KeyError: except KeyError:
users[job.printAs]=job.price users[job.printAs]=job.price
job.paid = True
job.save()
for user in users: for user in users:
# If payment_method balance doesn't exist, then you're not allowed to print. # If payment_method balance doesn't exist, then you're not allowed to print.