feat: plateaux d'impression section on job detail — live HA progress, multi-plate tracking
Deploy via Portainer / deploy (push) Successful in 0s

This commit is contained in:
Jo
2026-07-07 12:37:53 +02:00
parent 95b8b0277b
commit 221a0d7b8c
2 changed files with 215 additions and 15 deletions
+42 -15
View File
@@ -269,6 +269,7 @@ def init_db():
'ALTER TABLE printers ADD COLUMN ha_entity_prefix TEXT DEFAULT ""',
'ALTER TABLE print_slots ADD COLUMN pieces_ignored INTEGER DEFAULT 0',
'ALTER TABLE print_slots ADD COLUMN pieces_override INTEGER DEFAULT NULL',
'ALTER TABLE calendar_blocks ADD COLUMN date_end TEXT DEFAULT NULL',
]
for sql in migrations:
try:
@@ -516,9 +517,14 @@ def get_schedule_dict():
def get_blocks_dict(from_date=None, to_date=None):
conn = get_db()
if from_date and to_date:
# A block overlaps [from_date, to_date] when:
# block.date <= to_date AND COALESCE(block.date_end, block.date) >= from_date
rows = conn.execute(
'SELECT * FROM calendar_blocks WHERE date BETWEEN ? AND ? ORDER BY date',
(str(from_date), str(to_date))).fetchall()
"""SELECT * FROM calendar_blocks
WHERE date <= ?
AND COALESCE(date_end, date) >= ?
ORDER BY date""",
(str(to_date), str(from_date))).fetchall()
else:
rows = conn.execute('SELECT * FROM calendar_blocks ORDER BY date').fetchall()
conn.close()
@@ -528,7 +534,10 @@ def get_day_launches(check_date, schedule, blocks, cycle_min):
"""Returns number of possible launches on a given date (per machine)."""
date_str = str(check_date)
dow = check_date.weekday()
block = next((b for b in blocks if b['date'] == date_str and b['printer_id'] is None), None)
block = next((b for b in blocks
if b['date'] <= date_str
and (b['date_end'] or b['date']) >= date_str
and b['printer_id'] is None), None)
mode = block['type'] if block else schedule[dow]['mode']
if mode == 'off':
@@ -1282,13 +1291,20 @@ def job_detail(id):
LEFT JOIN pricing_profiles pp ON j.pricing_profile_id=pp.id
WHERE j.id=?''', (id,)).fetchone()
slots = conn.execute('''
SELECT ps.*, p.name as printer_name FROM print_slots ps
SELECT ps.*, p.name as printer_name, p.ha_entity_prefix,
COALESCE(ps.pieces_override, j.pieces_per_plate) as effective_pieces,
COALESCE(ps.pieces_ignored, 0) as pieces_ignored
FROM print_slots ps
LEFT JOIN printers p ON ps.printer_id=p.id
JOIN jobs j ON ps.job_id=j.id
WHERE ps.job_id=? ORDER BY ps.planned_start''', (id,)).fetchall()
conn.close()
if not job:
return redirect(url_for('jobs'))
return render_template('job_detail.html', job=job, slots=slots)
import math as _math
total_plates_needed = _math.ceil((job['order_qty'] or 1) / max(1, job['pieces_per_plate'] or 1))
return render_template('job_detail.html', job=job, slots=slots,
total_plates_needed=total_plates_needed)
@app.route('/jobs/<int:id>/delete', methods=['POST'])
def delete_job(id):
@@ -1309,7 +1325,8 @@ def planning():
WHERE j.id NOT IN (SELECT DISTINCT job_id FROM print_slots WHERE status NOT IN ('cancelled','failed'))
ORDER BY j.created_at DESC LIMIT 20''').fetchall()
blocks = conn.execute(
"SELECT * FROM calendar_blocks WHERE date >= date('now') ORDER BY date LIMIT 60"
"SELECT * FROM calendar_blocks"
" WHERE COALESCE(date_end, date) >= date('now') ORDER BY date LIMIT 60"
).fetchall()
schedule = conn.execute('SELECT * FROM working_schedule ORDER BY day_of_week').fetchall()
conn.close()
@@ -1384,12 +1401,18 @@ def working_schedule():
def calendar_blocks():
conn = get_db()
if request.method == 'POST':
conn.execute('INSERT INTO calendar_blocks(date,type,printer_id,notes) VALUES(?,?,?,?)', (
request.form['date'],
request.form.get('type','off'),
request.form.get('printer_id') or None,
request.form.get('notes','')
))
date_start = request.form['date_start']
date_end = request.form.get('date_end','').strip() or None
# If date_end < date_start, ignore it
if date_end and date_end < date_start:
date_end = None
conn.execute(
'INSERT INTO calendar_blocks(date,date_end,type,printer_id,notes) VALUES(?,?,?,?,?)',
(date_start, date_end,
request.form.get('type','off'),
request.form.get('printer_id') or None,
request.form.get('notes',''))
)
conn.commit()
blocks = conn.execute("SELECT cb.*, p.name as printer_name FROM calendar_blocks cb LEFT JOIN printers p ON cb.printer_id=p.id ORDER BY cb.date DESC LIMIT 50").fetchall()
printers = conn.execute('SELECT * FROM printers ORDER BY id').fetchall()
@@ -1837,7 +1860,10 @@ def api_availability():
for offset in range(28):
d = today + timedelta(days=offset)
date_str = str(d)
block = next((b for b in blocks if b['date'] == date_str and b['printer_id'] is None), None)
block = next((b for b in blocks
if b['date'] <= date_str
and (b.get('date_end') or b['date']) >= date_str
and b['printer_id'] is None), None)
mode = block['type'] if block else schedule[d.weekday()]['mode']
if mode == 'off':
result.append({
@@ -1930,8 +1956,9 @@ def calendar_ics():
# Jours indisponibles / bloqués
for b in blocks:
date_val = b['date'].replace('-', '')
# Date suivante pour DTEND all-day
d_obj = datetime.strptime(b['date'], '%Y-%m-%d') + timedelta(days=1)
# For DTEND: use date_end+1 if set, else date+1 (all-day exclusive end)
end_src = b['date_end'] if b['date_end'] else b['date']
d_obj = datetime.strptime(end_src, '%Y-%m-%d') + timedelta(days=1)
end_val = d_obj.strftime('%Y%m%d')
label_map = {'off': '🔴 Jour off', 'maintenance': '🔧 Maintenance', 'other': '📌 Bloqué'}
label = label_map.get(b['type'], b['type'])
+173
View File
@@ -250,6 +250,141 @@
</div>
</div>
<!-- ── Plateaux d'impression ────────────────────────────────────────────── -->
{% set plates_done = slots | selectattr('status','in',['done']) | list | length %}
{% set plates_running = slots | selectattr('status','equalto','running') | list | length %}
{% set plates_planned = slots | selectattr('status','in',['planned','running']) | list | length %}
{% set plates_total = slots | rejectattr('status','in',['cancelled']) | list | length %}
{% set missing_plates = [total_plates_needed - plates_total, 0] | max %}
<div class="row g-4 mt-0">
<div class="col-12">
<div class="card">
<div class="card-header py-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
<span><i class="bi bi-layers-half me-2"></i>Plateaux d'impression</span>
<div class="d-flex align-items-center gap-2 flex-wrap">
<!-- Progress pill: X/Y plateaux -->
{% if total_plates_needed > 1 %}
<span class="badge rounded-pill
{% if plates_done >= total_plates_needed %}bg-success
{% elif missing_plates > 0 %}bg-warning text-dark
{% else %}bg-primary{% endif %}"
style="font-size:.8rem">
{{ plates_done }}/{{ total_plates_needed }} terminé{{ 's' if plates_done > 1 else '' }}
</span>
{% endif %}
{% if missing_plates > 0 %}
<span class="badge bg-warning text-dark" style="font-size:.75rem">
<i class="bi bi-exclamation-triangle-fill me-1"></i>{{ missing_plates }} plateau{{ 'x' if missing_plates > 1 else '' }} à planifier
</span>
{% endif %}
<a href="{{ url_for('planning') }}" class="btn btn-sm btn-outline-primary py-0">
<i class="bi bi-calendar-plus me-1"></i>Planning
</a>
</div>
</div>
{% if slots %}
<div class="card-body p-0">
<table class="table table-sm table-hover mb-0">
<thead class="table-light">
<tr>
<th class="small ps-3">#</th>
<th class="small">Début</th>
<th class="small">Machine</th>
<th class="small">Pièces</th>
<th class="small">Statut / Progression</th>
</tr>
</thead>
<tbody>
{% for s in slots %}
{% if s.status != 'cancelled' %}
<tr id="slotRow{{ s.id }}">
<td class="ps-3 text-muted small">{{ loop.index }}</td>
<td class="small" style="white-space:nowrap">
{{ s.planned_start[:16].replace('T',' ') }}
</td>
<td class="small fw-semibold">{{ s.printer_name }}</td>
<td class="small">
{% set ep = s.effective_pieces %}
{% set ig = s.pieces_ignored %}
{% if ig > 0 %}
<span class="text-warning fw-semibold">{{ ep - ig }}/{{ ep }}</span>
<span class="text-muted" style="font-size:.7rem"> ({{ ig }} ignorée{{ 's' if ig > 1 }})</span>
{% else %}
{{ ep }}
{% endif %}
</td>
<td>
{% set sc = {'planned':'secondary','running':'primary','done':'success','failed':'danger'} %}
{% set sl = {'planned':'Planifié','running':'En cours','done':'Terminé','failed':'Échec'} %}
<span class="badge bg-{{ sc.get(s.status,'secondary') }}">{{ sl.get(s.status, s.status) }}</span>
{% if s.status == 'running' and s.ha_entity_prefix %}
<!-- Live HA progress injected by JS -->
<span id="haLive{{ s.id }}" class="ms-2 small text-muted">
<span class="spinner-border spinner-border-sm"></span>
</span>
{% endif %}
{% if s.failure_note %}
<br><span class="text-muted" style="font-size:.72rem">{{ s.failure_note }}</span>
{% endif %}
</td>
</tr>
<!-- HA live progress bar row (hidden until JS fills it) -->
{% if s.status == 'running' and s.ha_entity_prefix %}
<tr id="haBar{{ s.id }}" class="table-primary">
<td colspan="5" class="px-3 py-1">
<div class="progress" style="height:6px;border-radius:3px">
<div id="haBarInner{{ s.id }}" class="progress-bar bg-primary" style="width:0%"></div>
</div>
<div id="haBarInfo{{ s.id }}" class="text-muted mt-1" style="font-size:.72rem"></div>
</td>
</tr>
{% endif %}
{% endif %}
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="card-body text-center text-muted py-4 small">
<i class="bi bi-calendar-x fs-3 d-block mb-2"></i>
Aucun créneau planifié pour cette commande.
<br><a href="{{ url_for('planning') }}" class="btn btn-sm btn-outline-primary mt-2">
<i class="bi bi-calendar-plus me-1"></i>Aller au planning
</a>
</div>
{% endif %}
<!-- Global progress bar for multi-plate jobs -->
{% if total_plates_needed > 1 %}
<div class="card-footer py-2 px-3" style="background:#fafafa;border-top:1px solid #f0f0f0">
{% set pct = ((plates_done / total_plates_needed) * 100) | round(0) | int %}
<div class="d-flex justify-content-between align-items-center mb-1">
<small class="text-muted">Progression commande</small>
<small class="fw-semibold">{{ pct }}%</small>
</div>
<div class="progress" style="height:8px;border-radius:4px">
<div class="progress-bar bg-success" style="width:{{ pct }}%"></div>
{% if plates_running > 0 %}
<div class="progress-bar bg-primary progress-bar-striped progress-bar-animated"
style="width:{{ ((plates_running / total_plates_needed) * 100) | round(0) | int }}%"></div>
{% endif %}
</div>
<div class="mt-1 d-flex gap-3" style="font-size:.72rem;color:#6b7280">
<span><i class="bi bi-check-circle-fill text-success me-1"></i>{{ plates_done }} terminé{{ 's' if plates_done > 1 }}</span>
{% if plates_running %}<span><i class="bi bi-arrow-repeat text-primary me-1"></i>{{ plates_running }} en cours</span>{% endif %}
{% set plates_sched = plates_planned - plates_running %}
{% if plates_sched %}<span><i class="bi bi-clock text-secondary me-1"></i>{{ plates_sched }} planifié{{ 's' if plates_sched > 1 }}</span>{% endif %}
{% if missing_plates %}<span class="text-warning"><i class="bi bi-exclamation-triangle-fill me-1"></i>{{ missing_plates }} manquant{{ 's' if missing_plates > 1 }}</span>{% endif %}
</div>
</div>
{% endif %}
</div>
</div>
</div>
<!-- ── Modale viewer 3D ──────────────────────────────────────────────────── -->
<div class="modal fade" id="viewerModal" tabindex="-1">
<div class="modal-dialog modal-xl modal-dialog-centered">
@@ -283,6 +418,44 @@
{% endblock %}
{% block scripts %}
<!-- ── Live HA status for running slots ──────────────────────────────────── -->
{% set running_slots = slots | selectattr('status','equalto','running') | selectattr('ha_entity_prefix') | list %}
{% if running_slots %}
<script>
(async function pollHA() {
const runningPrinters = {
{% for s in running_slots %}
"{{ s.printer_id }}": { slotId: {{ s.id }}, prefix: "{{ s.ha_entity_prefix }}" },
{% endfor %}
};
async function refresh() {
try {
const data = await fetch('/api/ha/status').then(r => r.json());
for (const [printerId, info] of Object.entries(runningPrinters)) {
const p = data[printerId];
if (!p) continue;
const liveEl = document.getElementById('haLive' + info.slotId);
const barEl = document.getElementById('haBarInner' + info.slotId);
const barInfo = document.getElementById('haBarInfo' + info.slotId);
if (!liveEl) continue;
const pct = p.progress || 0;
const layer = p.layer && p.layers_total ? `Couche ${p.layer}/${p.layers_total}` : '';
const fin = p.heure_fin ? `Fin ≈ ${p.heure_fin.slice(11,16)}` : '';
liveEl.innerHTML = `<strong>${pct}%</strong>${layer ? ' · ' + layer : ''}${fin ? ' · ' + fin : ''}`;
if (barEl) barEl.style.width = pct + '%';
if (barInfo) barInfo.textContent = [layer, fin].filter(Boolean).join(' · ');
}
} catch(e) {}
setTimeout(refresh, 30000);
}
refresh();
})();
</script>
{% endif %}
<!-- JSZip pour parser les 3MF Bambu Studio -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script type="importmap">