diff --git a/app/assets/stylesheets/_domesticated_animals.scss b/app/assets/stylesheets/_domesticated_animals.scss new file mode 100644 index 0000000000..f84e15835e --- /dev/null +++ b/app/assets/stylesheets/_domesticated_animals.scss @@ -0,0 +1,18 @@ +// Let the page show through the jobs section, while each job stays white. +// Keep these overrides local: gardens and standalone notepads are unchanged. +.domesticated-animal-show { + section#jobs { + background: transparent; + padding: 0; + } + + .notepad { + background: transparent; + border: 0; + box-shadow: none; + } + + .notepad-job { + background: $white; + } +} diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index a409380921..044591433f 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -66,6 +66,7 @@ @import "member_cards"; @import "neighbours"; @import "jobs"; +@import "domesticated_animals"; @import "maps"; @import "admin_climate"; diff --git a/app/controllers/domesticated_animals/prompt_dismissals_controller.rb b/app/controllers/domesticated_animals/prompt_dismissals_controller.rb new file mode 100644 index 0000000000..95154b4f5a --- /dev/null +++ b/app/controllers/domesticated_animals/prompt_dismissals_controller.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module DomesticatedAnimals + class PromptDismissalsController < ApplicationController + include FeatureGated + + before_action :authenticate_member! + require_feature :domesticated_animals + + def create + current_member.dismiss_animals_prompt! + redirect_to member_gardens_path(current_member), notice: t('domesticated_animals.prompt.dismissed') + end + end +end diff --git a/app/controllers/domesticated_animals_controller.rb b/app/controllers/domesticated_animals_controller.rb new file mode 100644 index 0000000000..91ae463095 --- /dev/null +++ b/app/controllers/domesticated_animals_controller.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +class DomesticatedAnimalsController < ApplicationController + include FeatureGated + + require_feature :domesticated_animals + + before_action :authenticate_member!, except: :show + load_and_authorize_resource + respond_to :html, :json + responders :flash + + def show + @notepad = JobsNotepad.new(current_member, animal: @domesticated_animal) + respond_with @domesticated_animal + end + + def new + @domesticated_animal.owner = current_member + return render partial: 'form', locals: { dialog: true } if params[:dialog] == 'true' + + respond_with @domesticated_animal + end + + def edit + respond_with @domesticated_animal + end + + def create + @domesticated_animal.owner = current_member + return render_errors(:new) unless @domesticated_animal.save + + respond_with @domesticated_animal + end + + def update + return render_errors(:edit) unless @domesticated_animal.update(domesticated_animal_params) + + respond_with @domesticated_animal + end + + def destroy + @domesticated_animal.destroy + respond_with @domesticated_animal, location: member_path(@domesticated_animal.owner) + end + + private + + def render_errors(template) + respond_to do |format| + format.html do + if params[:dialog] == 'true' + render partial: 'form', locals: { dialog: true }, status: :unprocessable_content + else + render template, status: :unprocessable_content + end + end + format.json { render json: @domesticated_animal.errors, status: :unprocessable_content } + end + end + + def domesticated_animal_params + params.require(:domesticated_animal).permit( + :name, :species, :category, :description, :date_of_birth, :date_of_death, :biological_sex, :alignment + ) + end +end diff --git a/app/controllers/job_suggestions_controller.rb b/app/controllers/job_suggestions_controller.rb index e12e85fbcf..ff4d55ec44 100644 --- a/app/controllers/job_suggestions_controller.rb +++ b/app/controllers/job_suggestions_controller.rb @@ -15,11 +15,23 @@ def index crops = Crop.popular.where('crops.name ILIKE ?', "#{Crop.sanitize_sql_like(query)}%") crops = crops.where(id: plantings.select(:crop_id)) if garden - render json: crops.limit(MAX_CROPS).flat_map { |crop| suggestions_for(crop) }.first(MAX_SUGGESTIONS) + suggestions = animal_suggestions(query) + crops.limit(MAX_CROPS).flat_map { |crop| suggestions_for(crop) } + render json: suggestions.first(MAX_SUGGESTIONS) end private + def animal_suggestions(query) + return [] if garden || !Feature.enabled?(:domesticated_animals, current_member) + + current_member.domesticated_animals.includes(:photos) + .where('domesticated_animals.name ILIKE ?', "#{DomesticatedAnimal.sanitize_sql_like(query)}%") + .order(:name, :id).limit(MAX_SUGGESTIONS).map do |animal| + { jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id, name: animal.name, label: animal.name, + detail: t("domesticated_animals.categories.#{animal.category}"), icon_url: animal.default_photo&.thumbnail_url } + end + end + # The garden whose to-do list this is for, if it is for one. def garden Garden.find_by(id: params[:garden_id]) if params[:garden_id].present? diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb index 24107da2f6..edeb22517f 100644 --- a/app/controllers/jobs_controller.rb +++ b/app/controllers/jobs_controller.rb @@ -20,7 +20,7 @@ def new @job = Job.new(new_job_params.to_h.reverse_merge(due_date: Time.zone.today)) @job.owner = current_member @job.garden = nil unless @job.garden && current_member.accessible_gardens.exists?(@job.garden.id) - @job.planting = nil unless @job.planting && current_member.accessible_gardens.exists?(@job.planting.garden_id) + @job.planting = nil if @job.planting && !current_member.accessible_gardens.exists?(@job.planting.garden_id) respond_with @job end @@ -93,11 +93,11 @@ def render_notepad(status) def render_groups(status) response.set_header('X-Jobs-Done-This-Week', @done_this_week.to_s) - render partial: 'jobs/notepad_groups', locals: { groups: @job_groups, in_garden: garden.present? }, status: + render partial: 'jobs/notepad_groups', locals: { groups: @job_groups, in_garden: garden.present?, in_animal: animal.present? }, status: end def load_notepad - notepad = JobsNotepad.new(@owner, garden:, pinned: pinned_ids) + notepad = JobsNotepad.new(@owner, garden:, animal:, pinned: pinned_ids) @job_groups = notepad.groups @done_this_week = notepad.done_this_week end @@ -107,6 +107,13 @@ def garden Garden.find_by(id: params[:garden_id]) if params[:garden_id].present? end + def animal + return if params[:animal_id].blank? + raise ActiveRecord::RecordNotFound unless Feature.enabled?(:domesticated_animals, current_member) + + current_member.domesticated_animals.find(params[:animal_id]) + end + # The jobs the page has crossed off since it loaded, which stay where they are # until it is loaded again. def pinned_ids @@ -120,7 +127,7 @@ def job_params # What a link to "new job" can fill in ahead of time, as Copy does. def new_job_params - params.permit(:name, :description, :due_date, :garden_id, :planting_id) + params.permit(:name, :description, :due_date, :garden_id, :planting_id, :jobbable_type, :jobbable_id) end # "Repeat how many times, every how many weeks" on the form: copies of the job diff --git a/app/controllers/photo_associations_controller.rb b/app/controllers/photo_associations_controller.rb index 3008b01bcb..a817b99c3d 100644 --- a/app/controllers/photo_associations_controller.rb +++ b/app/controllers/photo_associations_controller.rb @@ -44,6 +44,10 @@ def item_class def find_item raise ActiveRecord::RecordNotFound unless Photo::PHOTO_CAPABLE.include?(item_class) + if item_class == 'DomesticatedAnimal' && !Feature.enabled?(:domesticated_animals, current_member) + raise ActiveRecord::RecordNotFound + end + item_class.constantize.find(params[:id]) end diff --git a/app/controllers/photos_controller.rb b/app/controllers/photos_controller.rb index 58dbebaf93..8c772baf16 100644 --- a/app/controllers/photos_controller.rb +++ b/app/controllers/photos_controller.rb @@ -195,13 +195,19 @@ def item_to_link_to raise "No item id provided" if params[:id].nil? raise "No item type provided" if params[:type].nil? - item_class = params[:type].capitalize + item_class = params[:type].to_s.classify raise "Photos not supported" unless Photo::PHOTO_CAPABLE.include? item_class + if item_class == 'DomesticatedAnimal' && !Feature.enabled?(:domesticated_animals, current_member) + raise ActiveRecord::RecordNotFound + end + klass = item_class.constantize # A draft post is still its author's to add photos to. klass = klass.with_drafts if klass.respond_to?(:with_drafts) - klass.find(params[:id]) + item = klass.find(params[:id]) + authorize! :update, item if item_class == 'DomesticatedAnimal' + item end # diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index 02f1b42584..7411713367 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -31,11 +31,13 @@ def new def edit; end # What the editor's "link to" list offers besides crops (which it gets from - # /crops/search.json): members, and the plantings of the member writing. + # /crops/search.json): members, and the writer's plantings and animals. def link_suggestions authorize! :create, Post term = params[:term].to_s.strip - render json: { members: member_suggestions(term), plantings: planting_suggestions(term) } + suggestions = { members: member_suggestions(term), plantings: planting_suggestions(term) } + suggestions[:animals] = animal_suggestions(term) if Feature.enabled?(:domesticated_animals, current_member) + render json: suggestions end # The body as it will look when posted, for the editor's Preview tab. @@ -68,6 +70,16 @@ def destroy SUGGESTIONS = 5 + def animal_suggestions(term) + return [] if term.blank? || !Feature.enabled?(:domesticated_animals, current_member) + + current_member.domesticated_animals.where('domesticated_animals.name ILIKE ?', "#{DomesticatedAnimal.sanitize_sql_like(term)}%") + .order(:name, :id).limit(SUGGESTIONS).map do |animal| + { id: animal.id, name: animal.name, group: t('domesticated_animals.title'), + category: t("domesticated_animals.categories.#{animal.category}") } + end + end + def member_suggestions(term) return [] if term.blank? diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 2e7f7586d5..fef3e93332 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -146,10 +146,17 @@ def markdownify(text, figures: false) translator.expand_photos!(text, figures:) translator.expand_crops!(text) translator.expand_plantings!(text) + translator.expand_animals!(text, enabled: domesticated_animals_enabled?) translator.expand_members!(text) text end + def domesticated_animals_enabled? + # Markdown is also rendered outside a signed-in request, for example in mail. + member = current_member if respond_to?(:request) && request&.env&.[]('warden') + Feature.enabled?(:domesticated_animals, member) + end + # A 1x1 transparent GIF, standing in for a real avatar when # config.x.blank_avatars is set, which browser specs do: otherwise they fetch # every avatar from gravatar.com for real, and one arriving mid-test moves diff --git a/app/helpers/buttons_helper.rb b/app/helpers/buttons_helper.rb index 1f0dcc2868..f2af5b2932 100644 --- a/app/helpers/buttons_helper.rb +++ b/app/helpers/buttons_helper.rb @@ -21,6 +21,6 @@ def delete_button(model, message: 'are_you_sure', classes: 'btn btn-danger', ico # The page (or dialog) for adding a photo of this record. # `params` go on the link too, such as the `label` of a seed packet photo. def new_photo_path_for(model, **params) - new_photo_path(id: model.id, type: ActiveModel::Name.new(model.class).to_s.downcase, **params) + new_photo_path(id: model.id, type: model.class.model_name.singular, **params) end end diff --git a/app/helpers/icons_helper.rb b/app/helpers/icons_helper.rb index 3d792250d7..228e5222c1 100644 --- a/app/helpers/icons_helper.rb +++ b/app/helpers/icons_helper.rb @@ -1,6 +1,10 @@ # frozen_string_literal: true module IconsHelper + def domesticated_animal_icon + icon('fas', 'paw') + end + # A Font Awesome icon: `icon 'fas', 'heart'`, optionally followed by text and # HTML options. def icon(style, name, text = nil, html_options = {}) diff --git a/app/helpers/photos_helper.rb b/app/helpers/photos_helper.rb index f210badadb..849b97e57f 100644 --- a/app/helpers/photos_helper.rb +++ b/app/helpers/photos_helper.rb @@ -11,7 +11,8 @@ module PhotosHelper # Everything the photo is attached to, as [type, record] pairs: the type is what # the photo associations route calls it ('planting', 'seed', 'crop'). def photo_records(photo) - RECORD_KINDS.flat_map { |type| photo.public_send(type.pluralize).map { |thing| [type, thing] } } + + kinds = domesticated_animals_enabled? ? RECORD_KINDS + ['domesticated_animal'] : RECORD_KINDS + kinds.flat_map { |type| photo.public_send(type.pluralize).map { |thing| [type, thing] } } + photo.crops.map { |crop| ['crop', crop] } end @@ -135,7 +136,7 @@ def photo_label(model) when Garden then "#{model.name} garden" when Planting then model.display_name when Post then model.subject - when Job then model.name + when Job, DomesticatedAnimal then model.name end end diff --git a/app/javascript/application.js b/app/javascript/application.js index 0b58a0362a..aeae3fde39 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -9,6 +9,7 @@ import 'leaflet.markercluster'; import './site/auto_suggest'; import './site/crop_filters'; import './site/crop_job_season'; +import './site/domesticated_animals'; import './site/copy_credit'; import './site/cropmap'; import './site/ecocrop_link'; diff --git a/app/javascript/components/AnimalDialog.jsx b/app/javascript/components/AnimalDialog.jsx new file mode 100644 index 0000000000..33d53e4ef4 --- /dev/null +++ b/app/javascript/components/AnimalDialog.jsx @@ -0,0 +1,106 @@ +import React, {useEffect, useRef, useState} from 'react'; + +import {initDomesticatedAnimals} from '../site/domesticated_animals'; +import Modal from './Modal'; + +function AnimalForm({html, onClose, onSaved, errorLabel}) { + const root = useRef(null); + const [formHtml, setFormHtml] = useState(html); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(false); + + useEffect(() => { + initDomesticatedAnimals(root.current); + root.current.querySelector('input:not([type="hidden"])')?.focus(); + }, [formHtml]); + + useEffect(() => { + root.current.querySelectorAll('[type="submit"]').forEach((button) => { button.disabled = saving; }); + }, [saving, formHtml]); + + async function submit(event) { + event.preventDefault(); + if (saving) return; + const form = event.target; + const body = new FormData(form); + setSaving(true); + setError(false); + try { + const response = await fetch(form.action, { + method: 'POST', body, credentials: 'same-origin', headers: {Accept: 'text/html'}, + }); + if (response.redirected) { + onSaved(response.url); + return; + } + if (response.status === 422) setFormHtml(await response.text()); + else setError(true); + } catch { + setError(true); + } finally { + setSaving(false); + } + } + + return ( +
{errorLabel}
} +