This commit is contained in:
2025-06-27 17:43:50 -05:00
parent 00fd49c79b
commit 13d56066ab
22 changed files with 1500 additions and 497 deletions

View File

@ -1,8 +1,16 @@
# plugins/growlog/forms.py
from flask_wtf import FlaskForm
from wtforms import TextAreaField, SelectField, SubmitField
from wtforms import SelectField, StringField, TextAreaField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length
class GrowLogForm(FlaskForm):
plant_uuid = SelectField(
'Plant',
choices=[], # injected in view
validators=[DataRequired()]
)
event_type = SelectField('Event Type', choices=[
('water', 'Watered'),
('fertilizer', 'Fertilized'),
@ -11,5 +19,7 @@ class GrowLogForm(FlaskForm):
('pest', 'Pest Observed')
], validators=[DataRequired()])
note = TextAreaField('Notes', validators=[Length(max=1000)])
submit = SubmitField('Add Log')
title = StringField('Title', validators=[Length(max=255)])
notes = TextAreaField('Notes', validators=[Length(max=1000)])
is_public = BooleanField('Public?')
submit = SubmitField('Add Log')

View File

@ -7,6 +7,7 @@ class GrowLog(db.Model):
id = db.Column(db.Integer, primary_key=True)
plant_id = db.Column(db.Integer, db.ForeignKey("plant.id"), nullable=False)
event_type = db.Column(db.String(50), nullable=False)
title = db.Column(db.String(255), nullable=True)
notes = db.Column(db.Text, nullable=True)
is_public = db.Column(db.Boolean, default=False, nullable=False)

View File

@ -1,31 +1,176 @@
from flask import Blueprint, render_template, redirect, url_for, request
from flask_login import login_required
from uuid import UUID as _UUID
from werkzeug.exceptions import NotFound
from flask import (
Blueprint, render_template, abort, redirect, url_for, request, flash
)
from flask_login import login_required, current_user
from app import db
from .models import GrowLog
from .forms import GrowLogForm
from plugins.plant.models import Plant
from plugins.plant.models import Plant, PlantCommonName
bp = Blueprint('growlog', __name__, template_folder='templates')
@bp.route('/plants/<int:plant_id>/logs')
bp = Blueprint(
'growlog',
__name__,
url_prefix='/growlogs',
template_folder='templates',
)
def _get_plant_by_uuid(uuid_val):
"""
uuid_val may already be a uuid.UUID (from a <uuid:> route converter)
or a string (from form POST). Normalize & validate it, then lookup.
"""
# 1) If Flask route gave us a UUID instance, just stringify it
if isinstance(uuid_val, _UUID):
val = str(uuid_val)
else:
# 2) Otherwise try to parse it as a hex string
try:
val = str(_UUID(uuid_val))
except (ValueError, TypeError):
# invalid format → 404
abort(404)
# 3) Only return plants owned by current_user
return (
Plant.query
.filter_by(uuid=val, owner_id=current_user.id)
.first_or_404()
)
def _user_plant_choices():
# join to the commonname table and sort by its name
plants = (
Plant.query
.filter_by(owner_id=current_user.id)
.join(PlantCommonName, Plant.common_id == PlantCommonName.id)
.order_by(PlantCommonName.name)
.all()
)
return [
(p.uuid, f"{p.common_name.name} {p.uuid}")
for p in plants
]
@bp.route('/add', methods=['GET','POST'])
@bp.route('/<uuid:plant_uuid>/add', methods=['GET','POST'])
@login_required
def view_logs(plant_id):
plant = Plant.query.get_or_404(plant_id)
logs = GrowLog.query.filter_by(plant_id=plant.id).order_by(GrowLog.timestamp.desc()).all()
return render_template('growlog/log_list.html', plant=plant, logs=logs)
@bp.route('/plants/<int:plant_id>/logs/add', methods=['GET', 'POST'])
@login_required
def add_log(plant_id):
plant = Plant.query.get_or_404(plant_id)
def add_log(plant_uuid=None):
form = GrowLogForm()
# 1) always populate the dropdown behind the scenes
form.plant_uuid.choices = _user_plant_choices()
plant = None
hide_select = False
# 2) if URL had a plant_uuid, load & pre-select it, hide dropdown
if plant_uuid:
plant = _get_plant_by_uuid(plant_uuid)
form.plant_uuid.data = str(plant_uuid)
hide_select = True
if form.validate_on_submit():
# 3) on POST, resolve via form.plant_uuid
plant = _get_plant_by_uuid(form.plant_uuid.data)
log = GrowLog(
plant_id=plant.id,
event_type=form.event_type.data,
note=form.note.data
plant_id = plant.id,
event_type = form.event_type.data,
title = form.title.data,
notes = form.notes.data,
is_public = form.is_public.data,
)
db.session.add(log)
db.session.commit()
return redirect(url_for('growlog.view_logs', plant_id=plant.id))
return render_template('growlog/log_form.html', form=form, plant=plant)
flash('Grow log added.', 'success')
return redirect(
url_for('growlog.list_logs', plant_uuid=plant.uuid)
)
return render_template(
'growlog/log_form.html',
form = form,
plant = plant,
hide_plant_select = hide_select
)
@bp.route('/', defaults={'plant_uuid': None})
@bp.route('/<uuid:plant_uuid>')
@login_required
def list_logs(plant_uuid):
# how many to show?
limit = request.args.get('limit', default=10, type=int)
if plant_uuid:
# logs for a single plant
plant = _get_plant_by_uuid(plant_uuid)
query = GrowLog.query.filter_by(plant_id=plant.id)
else:
# logs for all your plants
plant = None
query = (
GrowLog.query
.join(Plant, GrowLog.plant_id == Plant.id)
.filter(Plant.owner_id == current_user.id)
)
logs = (
query
.order_by(GrowLog.created_at.desc())
.limit(limit)
.all()
)
return render_template(
'growlog/log_list.html',
plant=plant,
logs=logs,
limit=limit
)
@bp.route('/<uuid:plant_uuid>/edit/<int:log_id>', methods=['GET', 'POST'])
@login_required
def edit_log(plant_uuid, log_id):
plant = _get_plant_by_uuid(plant_uuid)
log = GrowLog.query.filter_by(id=log_id, plant_id=plant.id).first_or_404()
form = GrowLogForm(obj=log)
# Lock the dropdown to this one plant
form.plant_uuid.choices = [(plant.uuid, plant.common_name.name)]
form.plant_uuid.data = plant.uuid
if form.validate_on_submit():
log.event_type = form.event_type.data
log.title = form.title.data
log.notes = form.notes.data
log.is_public = form.is_public.data
db.session.commit()
flash('Grow log updated.', 'success')
return redirect(url_for('growlog.list_logs', plant_uuid=plant_uuid))
return render_template(
'growlog/log_form.html',
form=form,
plant_uuid=plant_uuid,
plant=plant,
log=log
)
@bp.route('/<uuid:plant_uuid>/delete/<int:log_id>', methods=['POST'])
@login_required
def delete_log(plant_uuid, log_id):
plant = _get_plant_by_uuid(plant_uuid)
log = GrowLog.query.filter_by(id=log_id, plant_id=plant.id).first_or_404()
db.session.delete(log)
db.session.commit()
flash('Grow log deleted.', 'warning')
return redirect(url_for('growlog.list_logs', plant_uuid=plant_uuid))

View File

@ -1,10 +1,41 @@
{% extends 'core_ui/base.html' %}
{% block title %}Add Grow Log{% endblock %}
{% block content %}
<h2>Add Log for Plant #{{ plant.id }}</h2>
<form method="POST">
{{ form.hidden_tag() }}
<p>{{ form.event_type.label }}<br>{{ form.event_type() }}</p>
<p>{{ form.note.label }}<br>{{ form.note(rows=4) }}</p>
<p>{{ form.submit() }}</p>
</form>
{% endblock %}
<h2>Add Grow Log{% if plant %} for {{ plant.common_name.name }}{% endif %}</h2>
<form method="POST">
{{ form.hidden_tag() }}
{# only show this when not pre-selecting via URL #}
{% if not hide_plant_select %}
<div class="mb-3">
{{ form.plant_uuid.label(class="form-label") }}
{{ form.plant_uuid(class="form-select") }}
</div>
{% else %}
{{ form.plant_uuid(type="hidden") }}
{% endif %}
<div class="mb-3">
{{ form.event_type.label(class="form-label") }}
{{ form.event_type(class="form-select") }}
</div>
<div class="mb-3">
{{ form.title.label(class="form-label") }}
{{ form.title(class="form-control") }}
</div>
<div class="mb-3">
{{ form.notes.label(class="form-label") }}
{{ form.notes(class="form-control", rows=4) }}
</div>
<div class="mb-3 form-check">
{{ form.is_public(class="form-check-input") }}
{{ form.is_public.label(class="form-check-label") }}
</div>
<button type="submit" class="btn btn-primary">{{ form.submit.label.text }}</button>
</form>
{% endblock %}

View File

@ -1,36 +1,104 @@
{# plugins/growlog/templates/growlog/log_list.html #}
{% import 'core_ui/_media_macros.html' as media %}
{% extends 'core_ui/base.html' %}
{% block content %}
<h2>Logs for Plant #{{ plant.id }}</h2>
<a href="{{ url_for('growlog.add_log', plant_id=plant.id) }}">Add New Log</a>
<ul>
{% for log in logs %}
<li class="mb-3">
<strong>{{ log.timestamp.strftime('%Y-%m-%d') }}:</strong>
{{ log.event_type }} {{ log.note }}
{% if log.media_items %}
<br><em>Images:</em>
<ul class="list-unstyled ps-3">
{% for image in log.media_items %}
<li class="mb-2">
<img
src="{{ generate_image_url(image) }}"
width="150"
class="img-thumbnail"
alt="Log image"
><br>
{{ image.caption or "No caption" }}
</li>
{% endfor %}
</ul>
{% endif %}
</li>
{% endfor %}
</ul>
{# Use shared macro for any remaining media lists #}
{{ media.render_media_list(logs|map(attribute='media_items')|sum, thumb_width=150, current_user=current_user) }}
{% block title %}
{% if plant %}
Logs for {{ plant.common_name.name }}
{% else %}
Recent Grow Logs
{% endif %}
{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<h2 class="mb-0">
{% if plant %}
Grow Logs for {{ plant.common_name.name }}
{% else %}
Recent Grow Logs
{% endif %}
</h2>
{# “Add” button: carry plant_uuid when in single-plant view #}
<a
href="{% if plant %}{{ url_for('growlog.add_log', plant_uuid=plant.uuid) }}{% else %}{{ url_for('growlog.add_log') }}{% endif %}"
class="btn btn-success">
<i class="bi bi-plus-lg"></i> Add Log
</a>
</div>
{% if logs %}
<div class="list-group">
{% for log in logs %}
<div class="list-group-item mb-3">
<div class="d-flex justify-content-between align-items-start">
<div>
<h5 class="mb-1">{{ log.title or 'Untitled' }}</h5>
<small class="text-muted">
{{ log.created_at.strftime('%Y-%m-%d %H:%M') }}
</small>
</div>
{% if not plant %}
{# Show which plant this log belongs to when listing across all plants #}
<div class="ms-auto text-end">
<small class="text-secondary">Plant:</small><br>
<a href="{{ url_for('growlog.list_logs', plant_uuid=log.plant.uuid) }}">
{{ log.plant.common_name.name }}
</a>
</div>
{% endif %}
</div>
<p class="mt-2 mb-1">{{ log.notes or '—' }}</p>
<span class="badge {% if log.is_public %}bg-info text-dark{% else %}bg-secondary{% endif %}">
{% if log.is_public %}Public{% else %}Private{% endif %}
</span>
{% if log.media_items.count() %}
<div class="mt-3 d-flex flex-wrap gap-2">
{% for media in log.media_items %}
<img
src="{{ generate_image_url(media) }}"
class="img-thumbnail"
style="max-width:100px;"
alt="{{ media.caption or '' }}"
>
{% endfor %}
</div>
{% endif %}
<div class="mt-3">
<a
href="{{ url_for(
'growlog.edit_log',
plant_uuid=plant.uuid if plant else log.plant.uuid,
log_id=log.id
) }}"
class="btn btn-sm btn-outline-primary me-2">
Edit
</a>
<form
method="POST"
action="{{ url_for(
'growlog.delete_log',
plant_uuid=plant.uuid if plant else log.plant.uuid,
log_id=log.id
) }}"
class="d-inline"
onsubmit="return confirm('Delete this log?');">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="btn btn-sm btn-outline-danger">Delete</button>
</form>
</div>
</div>
{% endfor %}
</div>
{% else %}
<p class="text-muted">
No grow logs found{% if plant %} for {{ plant.common_name.name }}{% endif %}.
<a href="{% if plant %}{{ url_for('growlog.add_log', plant_uuid=plant.uuid) }}{% else %}{{ url_for('growlog.add_log') }}{% endif %}">
Add one now
</a>.
</p>
{% endif %}
{% endblock %}