Ajout du frontend et branchement sur l'API axione #9

Merged
felix.baylac merged 21 commits from johan/frontend into master 2022-02-13 19:39:12 +01:00
3 changed files with 116 additions and 23 deletions
Showing only changes of commit 202fda826f - Show all commits

View file

@ -54,7 +54,7 @@ class AddressFinder:
print("Error querying DB : {0}".format(err), file=sys.stderr) print("Error querying DB : {0}".format(err), file=sys.stderr)
return [] return []
communesMap=dict() communesMap = dict()
for row in cur.fetchall(): for row in cur.fetchall():
row_obj = dict(row) row_obj = dict(row)
commune = Commune( commune = Commune(
@ -62,12 +62,12 @@ class AddressFinder:
nom=row_obj[DB_COL_COMMUNE_NAME], nom=row_obj[DB_COL_COMMUNE_NAME],
codeZip=row_obj[DB_COL_COMMUNE_POSTE]) codeZip=row_obj[DB_COL_COMMUNE_POSTE])
# This way we avoid duplicates # This way we avoid duplicates
communesMap[commune["codeInsee"]]= commune communesMap[commune["codeInsee"]] = commune
con.close() con.close()
return list(communesMap.values()) return list(communesMap.values())
def getCommuneFantoirVoies(self, communeInseeCode: str) -> list[FantoirVoie]: def getCommuneFantoirVoies(self, communeInseeCode: str, voieSearch: str = None) -> list[FantoirVoie]:
# Extract data from DB # Extract data from DB
con = sqlite3.connect(self.dbPath) con = sqlite3.connect(self.dbPath)
@ -92,6 +92,19 @@ class AddressFinder:
data_dict = json.loads(data.get("value")) data_dict = json.loads(data.get("value"))
# In extracted JSON data, the interesting payload is behind "value" key # In extracted JSON data, the interesting payload is behind "value" key
fantoir_dict = data_dict.get("value") fantoir_dict = data_dict.get("value")
if voieSearch is not None:
regexSearch = r".*"
for expr in voieSearch.split(' '):
regexSearch += r"(?=" + expr + r").*"
regexSearch += r".*"
fantoir_voies_filtered = []
for voie in fantoir_dict:
for libelle in voie['libelle']:
if re.search(regexSearch, libelle, re.IGNORECASE):
fantoir_voies_filtered.append(voie)
break
fantoir_dict = fantoir_voies_filtered
else: else:
print("Did not found any data matching Insee code " + print("Did not found any data matching Insee code " +
str(communeInseeCode)) str(communeInseeCode))

View file

@ -25,10 +25,10 @@
<div id="methodPto" class="collapse show testMethods"> <div id="methodPto" class="collapse show testMethods">
<h2 class="text-center form-title">Test d'éligibilité par PTO</h1> <h2 class="text-center form-title">Test d'éligibilité par PTO</h1>
<form> <form method="post" action="/test/pto">
<div class="form-group" id="ptoForm"> <div class="form-group" id="ptoForm">
<label class="form-label" for="pto-number">Numéro PTO</label> <label class="form-label" for="pto-number">Numéro PTO</label>
<input required type="text" class="form-control" id="pto-number" aria-describedby="ptoHelp" placeholder="OOOO-XXXX-XXXX" oninvalid="this.setCustomValidity('Veuillez renseigner le PTO')" oninput="setCustomValidity('')"> <input required type="text" class="form-control" name="pto" id="pto-number" aria-describedby="ptoHelp" placeholder="OOOO-XXXX-XXXX" oninvalid="this.setCustomValidity('Veuillez renseigner le PTO')" oninput="setCustomValidity('')">
<small id="ptoHelp" class="form-text btn btn-link" data-toggle="collapse" data-target="#ptoInfo" aria-expanded="true" aria-controls="ptoInfo">Où trouver mon numéro de PTO ?</small> <small id="ptoHelp" class="form-text btn btn-link" data-toggle="collapse" data-target="#ptoInfo" aria-expanded="true" aria-controls="ptoInfo">Où trouver mon numéro de PTO ?</small>
<div id="ptoInfo" class="collapse" aria-labelledby="ptoForm" data-parent="#ptoForm"> <div id="ptoInfo" class="collapse" aria-labelledby="ptoForm" data-parent="#ptoForm">
@ -49,25 +49,27 @@
<div id="methodAddress" class="collapse testMethods"> <div id="methodAddress" class="collapse testMethods">
<h2 class="text-center form-title">Test d'éligibilité par adresse</h1> <h2 class="text-center form-title">Test d'éligibilité par adresse</h1>
<form> <form method="post" action="/test/address">
<div class="form-group" id="communeForm"> <div class="form-group" id="communeForm">
<label class="form-label" for="communeInput">Commune</label> <label class="form-label" for="communeInput">Commune</label>
<input type="text" list="communes" class="form-control" id="communeInput" ondblclick="this.focus();this.select()" aria-describedby="communeHelp" placeholder="Nom de la commune ou code postal"> <input type="text" list="communes" name="commune" class="form-control" id="communeInput" ondblclick="this.focus();this.select()" aria-describedby="communeHelp" placeholder="Nom de la commune ou code postal">
<datalist id="communes"> <datalist id="communes">
</datalist> </datalist>
</div> </div>
<div class="form-row collapse waitCommune" id="voieForm"> <div class="form-row collapse" id="voieForm">
<div class="col-sm-3 my-1"> <div class="col-sm-3 my-1">
<label class="form-label" for="numeroVoieInput">Numéro de voie</label> <label class="form-label" for="numeroVoieInput">Numéro de voie</label>
<input type="text" class="form-control" id="numeroVoieInput" aria-describedby="numeroVoieHelp" placeholder="Numéro de voie"> <input required type="text" name="numeroVoie" class="form-control" id="numeroVoieInput" aria-describedby="numeroVoieHelp" placeholder="Numéro de voie" oninvalid="this.setCustomValidity('Veuillez renseigner le numéro de voie')" oninput="setCustomValidity('')">
</div> </div>
<div class="col-sm-9 my-1"> <div class="col-sm-9 my-1">
<label class="form-label" for="voieInput">Nom de voie</label> <label class="form-label" for="voieInput">Nom de voie</label>
<input type="text" class="form-control" id="voieInput" aria-describedby="voieHelp" placeholder="Nom de voie"> <input type="text" name="voie" list="voies" class="form-control" id="voieInput" aria-describedby="voieHelp" placeholder="Nom de voie">
<datalist id="voies">
</datalist>
</div> </div>
</div> </div>
<br> <br>
<button id="btnTestAdresse" type="button" class="btn btn-sable collapse waitCommune">Tester l'adresse</button> <button id="btnTestAdresse" type="submit" class="btn btn-sable collapse">Tester l'adresse</button>
</form> </form>
<br> <br>
<button id="buttonReturnPto" type="button" data-toggle="collapse" data-target=".testMethods" class="btn btn-link" aria-expanded="false" aria-controls="methodPto methodAddress">Revenir au test par PTO</button> <button id="buttonReturnPto" type="button" data-toggle="collapse" data-target=".testMethods" class="btn btn-link" aria-expanded="false" aria-controls="methodPto methodAddress">Revenir au test par PTO</button>
@ -79,6 +81,9 @@
<script> <script>
$(document).ready(function(){ $(document).ready(function(){
var communes=[] var communes=[]
var codeInsee=0
var voies=[]
var voie=""
function fillCommunes(search='') { function fillCommunes(search='') {
var api="addresses/communes"; var api="addresses/communes";
if (search != '') { if (search != '') {
@ -99,32 +104,91 @@
$("#communes").append("<option codeInsee=" + communes[i].codeInsee + " value='" + $("#communes").append("<option codeInsee=" + communes[i].codeInsee + " value='" +
communes[i].codeZip + ' ' + communes[i].nom + "'></option>"); communes[i].codeZip + ' ' + communes[i].nom + "'></option>");
} }
if (communes.length == 1) { }
$('.waitCommune').addClass('show'); if (communes.length == 1) {
codeInsee=communes[0].codeInsee
console.log("fillCommunes show voieForm")
$('#voieForm').collapse('show');
console.log("fillCommunes shown voieForm")
} else {
console.log("fillCommunes hide voieForm")
console.log("voieInput to empty")
$('#voieInput').val('');
$('#voieForm').collapse('hide');
}
}
});
}
var voies=[]
function fillVoies(codeInsee,search='') {
var api="addresses/fantoirvoies/" + codeInsee;
if (search != '') {
api+="?s="+search;
}
$.ajax({
type: 'GET',
dataType:"json",
url: api,
success: function (data, status, xhr) {
if (JSON.stringify(data) !== JSON.stringify(voies)){
$("#voies").empty();
voies=data
for (let i = 0; i < 20; i++) {
if (! voies[i]) {
break;
}
$("#voies").append("<option id=" + voies[i].id + " value='" +
voies[i].libelle[0] + "'></option>");
}
if (voies.length == 1) {
console.log("fillVoies show btnTestAdresse")
$('#btnTestAdresse').collapse('show');
voie=voies[0].libelle[0]
} else { } else {
$('.waitCommune').removeClass('show'); console.log("fillVoies hide btnTestAdresse")
$('#btnTestAdresse').collapse('hide');
} }
} }
} }
}); });
} }
$('#methodAddress').on('shown.bs.collapse', function () { $('#methodAddress').on('show.bs.collapse', function () {
fillCommunes(); console.log("SHOW methodAddress")
$('#communeInput').trigger('input')
$('#communeInput').trigger('keyup')
}); });
$('#voieForm').on('show.bs.collapse', function () {
console.log("SHOW voieForm")
$('#voieInput').trigger('input')
$('#voieInput').trigger('keyup')
});
$('#communeInput').on('keyup', function () { $('#communeInput').on('keyup', function () {
console.log("communes keyup, call fillCommunes")
fillCommunes($(this).val()); fillCommunes($(this).val());
}); });
$('#communeInput').on('input', function() { $('#communeInput').on('input', function() {
console.log("val ", $(this).val())
if ($(this).val() === '') { if ($(this).val() === '') {
$('.waitCommune').removeClass('show'); console.log("on empty input hide voieForm")
$('#voieForm').collapse('hide');
} }
}); });
$('#buttonReturnPto').on('click', function() { $('#voieInput').on('keyup', function () {
console.log("click") fillVoies(codeInsee,$(this).val());
$('#communeInput').val('');
$('.waitCommune').removeClass('show');
}); });
$('#voieInput').on('input', function () {
console.log("voie val ", $(this).val())
if ($(this).val() === '') {
console.log("on empty input hide btnTestAdresse")
$('#btnTestAdresse').collapse('hide');
}
});
}); });
</script> </script>
</body> </body>

View file

@ -48,9 +48,25 @@ def get_communes():
@app.route("/addresses/fantoirvoies/<codeInsee>", methods=['GET']) @app.route("/addresses/fantoirvoies/<codeInsee>", methods=['GET'])
def get_fantoir_voies(codeInsee): def get_fantoir_voies(codeInsee):
fantoirVoies=addressFinder.getCommuneFantoirVoies(codeInsee) to_search=request.args.get('s')
fantoirVoies=addressFinder.getCommuneFantoirVoies(codeInsee,to_search)
response = app.response_class( response = app.response_class(
response=json.dumps(fantoirVoies), response=json.dumps(fantoirVoies),
mimetype='application/json' mimetype='application/json'
) )
return response return response
@app.route("/test/address", methods=['POST'])
def test_address():
print(request.form)
# pto = escape(request.form['pto'])
# result = parse_response(query_axione_pto(cfg, pto))
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
@app.route("/test/pto", methods=['POST'])
def test_pto():
print(request.form)
# pto = escape(request.form['pto'])
# result = parse_response(query_axione_pto(cfg, pto))
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}