Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Amélioration populate bib list #416

Merged
merged 2 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 8 additions & 19 deletions apptax/admin/admin_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
from apptax.admin.utils import taxref_media_file_name, get_user_permission
from pypnusershub.utils import get_current_app_id
from apptax.admin.admin import adresses
from apptax.admin.utils import PopulateBibListeException, populate_bib_liste


class FlaskAdminProtectedMixin:
Expand Down Expand Up @@ -136,7 +137,7 @@ def render(self, template, **kwargs):
class PopulateBibListesForm(Form):
delimiter = SelectField(label="Delimiter", choices=[(",", ","), (";", ";")])
with_header = BooleanField(label="With header")
upload = FileUploadField("File")
upload = FileUploadField(label="File", allowed_extensions=("csv",))


class BibListesView(FlaskAdminProtectedMixin, ModelView):
Expand Down Expand Up @@ -172,24 +173,12 @@ def import_cd_nom_view(self, *args, **kwargs):
with_header = request.form.get("with_header", default=False)
file = request.files["upload"]

fstring = file.read().decode()
inputcsv = csv.reader(fstring.splitlines(), delimiter=delimiter)

bibliste = BibListes.query.get(id_list)
# if header skip first line
if with_header:
next(inputcsv, None)
for row in inputcsv:
try:
cd_nom = int(row[0])
except (TypeError, ValueError):
flash(f"Invalid cd_nom value: {row[0]}")
return self.render("admin/populate_biblist.html", form=form)
tax = Taxref.query.get(cd_nom)
if tax:
tax.liste.append(bibliste)

db.session.commit()
try:
populate_bib_liste(id_list, delimiter, with_header, file)
except PopulateBibListeException as e:
flash(e.message, "error")
return self.render("admin/populate_biblist.html", form=form)

return redirect(self.get_url(".index_view"))

return self.render("admin/populate_biblist.html", form=form)
Expand Down
29 changes: 28 additions & 1 deletion apptax/admin/templates/admin/populate_biblist.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,39 @@
{{ super() }}
{% endblock %}

<h1>Populate bib list</h1>
<h1>Peupler la liste</h1>

<div class="bg-light border p-3 mb-3">
<b>Instructions</b>
<p>
Pour ajouter des cd_nom à une liste, il faut avoir un fichier csv contenant une colonne.
Cette colonne doit correspondre à une liste de cd_nom
</p>

<div class="table-responsive col-4">
<table class="table table-sm table-striped table-bordered">
<thead>
<tr>
<th>cd_nom</th>
<th>autres colonnes facultatives et non utilisées</th>
</tr>
</thead>
<tbody>
<tr>
<td>212</td>
<td>...</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="border p-3 mt-3">
{% block edit_form %}
{% call lib.form_tag(action=action) %}
{{ lib.render_form_fields(form, form_opts=form_opts) }}
{{ lib.render_form_buttons(cancel_url, extra, is_modal) }}
{% endcall %}
{% endblock %}
</div>

{% endblock %}
47 changes: 47 additions & 0 deletions apptax/admin/utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import csv
from werkzeug.utils import secure_filename

from pypnusershub.db.models import AppUser, Application
from pypnusershub.utils import get_current_app_id

from apptax.taxonomie.models import BibListes, Taxref
from apptax.database import db


def taxref_media_file_name(obj, file_data):
"""
Expand All @@ -24,3 +28,46 @@ def get_user_permission(id_role):
AppUser.id_role == id_role
)
return query.scalar()


class PopulateBibListeException(Exception):
def __init__(self, message):
self.message = message

def __str__(self):
return self.message


def populate_bib_liste(id_list, delimiter, with_header, file):
if not ("." in file.filename and file.filename.rsplit(".", 1)[1].lower() == "csv"):
raise PopulateBibListeException("Format de fichier requis : CSV")

try:
fstring = file.read().decode()
inputcsv = csv.reader(fstring.splitlines(), delimiter=delimiter)
except Exception:
raise PopulateBibListeException("Lecture du fichier impossible")

bibliste = BibListes.query.get(id_list)

# if header skip first line
if with_header:
next(inputcsv, None)

for row in inputcsv:
try:
cd_nom = int(row[0])
except (TypeError, ValueError):
msg = "Invalid cd_nom value: {row[0]}"
if not row[0].isnumeric():
msg = """
Il semble que votre fichier contienent le nom des colonnes,
sélectionner l'option 'with header'
ou que la première colonne ne corresponde pas à une liste de cd_nom"""
raise PopulateBibListeException(msg)

tax = Taxref.query.get(cd_nom)
if tax:
tax.liste.append(bibliste)

db.session.commit()