a ton of fun happened, refactored alot

This commit is contained in:
2025-07-03 04:29:43 -05:00
parent 72e060d783
commit 1bbe6e2743
121 changed files with 2315 additions and 900 deletions

View File

@ -0,0 +1,29 @@
# plugins/plant/growlog/forms.py
from flask_wtf import FlaskForm
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'),
('repot', 'Repotted'),
('note', 'Note'),
('pest', 'Pest Observed'),
],
validators=[DataRequired()]
)
title = StringField('Title', validators=[Length(max=255)])
notes = TextAreaField('Notes', validators=[Length(max=1000)])
is_public = BooleanField('Public?')
submit = SubmitField('Save Log')

View File

@ -0,0 +1,40 @@
# plugins/plant/growlog/models.py
from datetime import datetime
from app import db
class GrowLog(db.Model):
__tablename__ = "grow_logs"
__table_args__ = {"extend_existing": True}
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)
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
updated_at = db.Column(
db.DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False
)
# ─── Single “primary” media for this log ───────────────────────────────────
media_id = db.Column(db.Integer, db.ForeignKey("media.id"), nullable=True)
media = db.relationship(
"plugins.media.models.Media",
backref=db.backref("update_images", lazy="dynamic"),
foreign_keys=[media_id],
lazy="joined",
)
# ─── All Media items whose growlog_id points here ─────────────────────────
media_items = db.relationship(
"plugins.media.models.Media",
back_populates="growlog",
foreign_keys="plugins.media.models.Media.growlog_id",
lazy="dynamic",
cascade="all, delete-orphan"
)

View File

@ -0,0 +1,176 @@
# plugins/plant/growlog/routes.py
from uuid import UUID as _UUID
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, PlantCommonName
bp = Blueprint(
'growlog',
__name__,
url_prefix='/growlogs',
template_folder='templates',
)
def _get_plant_by_uuid(uuid_val):
"""
Normalize & validate a UUID (may be a uuid.UUID or a string),
then return the Plant owned by current_user or 404.
"""
# 1) If Flask gave us a real UUID, stringify it
if isinstance(uuid_val, _UUID):
val = str(uuid_val)
else:
# 2) Otherwise try to parse it
try:
val = str(_UUID(uuid_val))
except (ValueError, TypeError):
abort(404)
# 3) Only return plants owned by this user
return (
Plant.query
.filter_by(uuid=val, owner_id=current_user.id)
.first_or_404()
)
def _user_plant_choices():
"""
Return [(uuid, "Common Name uuid"), ...] for all plants
owned by current_user, sorted by common 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 add_log(plant_uuid=None):
form = GrowLogForm()
# always populate the select behind the scenes
form.plant_uuid.choices = _user_plant_choices()
plant = None
hide_select = False
# if URL gave us a plant_uuid, lock to that one
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():
plant = _get_plant_by_uuid(form.plant_uuid.data)
log = GrowLog(
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()
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):
from plugins.utility.celery import celery_app
celery_app.send_task('plugins.utility.tasks.ping')
limit = request.args.get('limit', default=10, type=int)
if plant_uuid:
# logs for one plant
plant = _get_plant_by_uuid(plant_uuid)
query = GrowLog.query.filter_by(plant_id=plant.id)
else:
# logs across all of this users 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 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

@ -0,0 +1,41 @@
{% extends 'core/base.html' %}
{% block title %}Add Grow Log{% endblock %}
{% block content %}
<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

@ -0,0 +1,110 @@
{# plugins/plant/growlog/templates/growlog/log_list.html #}
{% extends 'core/base.html' %}
{% 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>
<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 %}
<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 %}