From e7eedc9c7e373a6a2d922157a2adbb982cc8266f Mon Sep 17 00:00:00 2001 From: Daniel O'Connor Date: Fri, 27 Nov 2026 06:43:26 +0000 Subject: [PATCH 1/5] Chicken fleet management --- .../domesticated_animals_controller.rb | 58 ++++++ app/controllers/job_suggestions_controller.rb | 14 +- app/controllers/jobs_controller.rb | 4 +- .../photo_associations_controller.rb | 4 + app/controllers/photos_controller.rb | 10 +- app/controllers/posts_controller.rb | 16 +- app/helpers/application_helper.rb | 7 + app/helpers/buttons_helper.rb | 2 +- app/helpers/icons_helper.rb | 4 + app/helpers/photos_helper.rb | 5 +- app/javascript/components/PostEditor.test.jsx | 9 + app/javascript/components/linkChip.js | 18 +- app/javascript/menuIcons.json | 1 + app/javascript/site/job_notepad.js | 14 +- app/javascript/site/job_notepad.test.js | 26 ++- app/models/ability.rb | 5 + app/models/animal_tag.rb | 8 + app/models/comment.rb | 2 + app/models/concerns/animal_taggable.rb | 20 +++ app/models/concerns/jobbable.rb | 2 +- app/models/domesticated_animal.rb | 32 ++++ app/models/feature.rb | 3 +- app/models/job.rb | 12 +- app/models/member.rb | 1 + app/models/photo.rb | 4 +- app/models/post.rb | 1 + app/services/job_ideas/past_jobs.rb | 2 +- .../domesticated_animals/_form.html.haml | 16 ++ .../domesticated_animals/_profile.html.haml | 20 +++ app/views/domesticated_animals/edit.html.haml | 3 + app/views/domesticated_animals/new.html.haml | 3 + app/views/domesticated_animals/show.html.haml | 45 +++++ app/views/jobs/_card.html.haml | 5 +- app/views/jobs/_form.html.haml | 4 + app/views/jobs/_notepad.html.haml | 2 +- app/views/jobs/_notepad_row.html.haml | 5 + app/views/members/show.html.haml | 2 + app/views/shared/_markdown_help.html.haml | 3 + config/locales/en.yml | 40 +++++ config/routes.rb | 1 + ...61127000000_create_domesticated_animals.rb | 23 +++ db/schema.rb | 27 ++- lib/haml/filters/growstuff_markdown.rb | 10 ++ spec/factories/domesticated_animals.rb | 10 ++ .../haml/filters/growstuff_markdown_spec.rb | 36 ++++ spec/models/animal_tag_spec.rb | 58 ++++++ spec/models/domesticated_animal_spec.rb | 80 +++++++++ .../domesticated_animals_controller_spec.rb | 165 ++++++++++++++++++ .../requests/photos_controller_create_spec.rb | 43 ++++- spec/services/job_ideas/past_jobs_spec.rb | 8 + 50 files changed, 858 insertions(+), 35 deletions(-) create mode 100644 app/controllers/domesticated_animals_controller.rb create mode 100644 app/models/animal_tag.rb create mode 100644 app/models/concerns/animal_taggable.rb create mode 100644 app/models/domesticated_animal.rb create mode 100644 app/views/domesticated_animals/_form.html.haml create mode 100644 app/views/domesticated_animals/_profile.html.haml create mode 100644 app/views/domesticated_animals/edit.html.haml create mode 100644 app/views/domesticated_animals/new.html.haml create mode 100644 app/views/domesticated_animals/show.html.haml create mode 100644 db/migrate/20261127000000_create_domesticated_animals.rb create mode 100644 spec/factories/domesticated_animals.rb create mode 100644 spec/models/animal_tag_spec.rb create mode 100644 spec/models/domesticated_animal_spec.rb create mode 100644 spec/requests/domesticated_animals_controller_spec.rb diff --git a/app/controllers/domesticated_animals_controller.rb b/app/controllers/domesticated_animals_controller.rb new file mode 100644 index 0000000000..6b53dd1caf --- /dev/null +++ b/app/controllers/domesticated_animals_controller.rb @@ -0,0 +1,58 @@ +# 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 + respond_with @domesticated_animal + end + + def new + @domesticated_animal.owner = current_member + 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 { render template, status: :unprocessable_content } + 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 + ) + 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..5b8c1f53b9 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 @@ -120,7 +120,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/components/PostEditor.test.jsx b/app/javascript/components/PostEditor.test.jsx index e88a99d427..0eab7bb07e 100644 --- a/app/javascript/components/PostEditor.test.jsx +++ b/app/javascript/components/PostEditor.test.jsx @@ -241,6 +241,15 @@ describe('PostEditor', () => { expect(await screen.findByText('@my tomato')).toHaveClass('link-chip-planting'); }); + it('shows an animal link as a chip', async () => { + await setup({value: 'Meet [Henrietta](animal:42)'}); + expect(await screen.findByText('@Henrietta')).toHaveClass('link-chip-animal'); + }); + + it('keeps an animal link as written', async () => { + expect(await roundTrip('Meet [Henrietta](animal:42)')).toHaveValue('Meet [Henrietta](animal:42)'); + }); + it('keeps a member link as written', async () => { expect(await roundTrip('Thanks [jane](member)')).toHaveValue('Thanks [jane](member)'); }); diff --git a/app/javascript/components/linkChip.js b/app/javascript/components/linkChip.js index 866d4dc9da..58550f62bf 100644 --- a/app/javascript/components/linkChip.js +++ b/app/javascript/components/linkChip.js @@ -5,20 +5,21 @@ import Suggestion from '@tiptap/suggestion'; import {getJson} from '../api'; // How each kind of link is written in a post's markdown. Crops and members are -// found by name, plantings by slug, as the server expands them (see +// found by name, plantings by slug and animals by ID, as the server expands them (see // Haml::Filters::GrowstuffMarkdown). const WRITTEN = { crop: () => 'crop', member: () => 'member', planting: ({slug}) => `planting:${slug}`, + animal: ({slug}) => `animal:${slug}`, }; -const PATTERN = /^\[([^[\]]+)\]\((crop|member|planting:([\w-]+))\)/; +const PATTERN = /^\[([^[\]]+)\]\((crop|member|planting:([\w-]+)|animal:(\d+))\)/; const clean = (label) => String(label).replace(/[[\]]/g, ''); -// A link to a crop, a member or one of your plantings, shown in the text as a -// chip, and written as [name](crop), [name](member) or [name](planting:slug). +// A link to a crop, a member, a planting or an animal, shown in the text as a +// chip, and written as [name](crop), [name](member), [name](planting:slug) or [name](animal:id). // It is added by typing @ and choosing from the list (see `suggestion`). export function createLinkChip({suggestion}) { return Node.create({ @@ -61,12 +62,12 @@ export function createLinkChip({suggestion}) { markdownTokenizer: { name: 'linkChip', level: 'inline', - start: (src) => src.search(/\[[^[\]]+\]\((?:crop|member|planting:[\w-]+)\)/), + start: (src) => src.search(/\[[^[\]]+\]\((?:crop|member|planting:[\w-]+|animal:\d+)\)/), tokenize(src) { const match = PATTERN.exec(src); if (!match) return undefined; const kind = match[2].split(':')[0]; - return {type: 'linkChip', raw: match[0], kind, label: match[1], slug: match[3] || null}; + return {type: 'linkChip', raw: match[0], kind, label: match[1], slug: match[3] || match[4] || null}; }, }, @@ -106,7 +107,7 @@ export function createLinkChip({suggestion}) { const PER_GROUP = 5; const SEARCH_DELAY = 200; // ms to wait for typing to pause before searching -// What @ can link to matching `term`: crops, members, and your own plantings. +// What @ can link to matching `term`: crops, members, and your own plantings and animals. // Each is {group, kind, label, slug?, detail?}. export async function fetchLinkItems(term, {signal} = {}) { const query = encodeURIComponent(term); @@ -128,6 +129,9 @@ export async function fetchLinkItems(term, {signal} = {}) { (others.data.plantings || []).forEach((planting) => { items.push({group: 'Yours', kind: 'planting', label: planting.name, slug: planting.slug, detail: 'Planting'}); }); + (others.data.animals || []).forEach((animal) => { + items.push({group: animal.group, kind: 'animal', label: animal.name, slug: String(animal.id), detail: animal.category}); + }); } return items; } diff --git a/app/javascript/menuIcons.json b/app/javascript/menuIcons.json index 49741ab9b1..b80a1c405b 100644 --- a/app/javascript/menuIcons.json +++ b/app/javascript/menuIcons.json @@ -1,4 +1,5 @@ { + "domesticated_animal": "", "garden": "", "planting": "", "harvest": "", diff --git a/app/javascript/site/job_notepad.js b/app/javascript/site/job_notepad.js index f1c6b1b7dd..2b4d79c073 100644 --- a/app/javascript/site/job_notepad.js +++ b/app/javascript/site/job_notepad.js @@ -450,7 +450,7 @@ document.addEventListener('DOMContentLoaded', function () { const found = mention(); if (found) { const rest = box.value.slice(box.selectionStart).replace(/^\s+/, ''); - const text = box.value.slice(0, found.start) + item.crop_name + ' '; + const text = box.value.slice(0, found.start) + (item.name || item.crop_name) + ' '; box.value = text + rest; box.setSelectionRange(text.length, text.length); } @@ -466,11 +466,13 @@ document.addEventListener('DOMContentLoaded', function () { option.id = list.id + '-' + i; option.setAttribute('role', 'option'); option.className = 'notepad-suggestion'; - const icon = document.createElement('img'); - icon.className = 'notepad-suggestion-icon'; - icon.src = item.icon_url; - icon.alt = ''; - option.appendChild(icon); + if (item.icon_url) { + const icon = document.createElement('img'); + icon.className = 'notepad-suggestion-icon'; + icon.src = item.icon_url; + icon.alt = ''; + option.appendChild(icon); + } [['kind', 'span', kinds[kindOf(item)]], ['', 'span', item.label], ['', 'small', item.detail]].forEach(function (part) { if (!part[2]) return; const el = document.createElement(part[1]); diff --git a/app/javascript/site/job_notepad.test.js b/app/javascript/site/job_notepad.test.js index f339f2c53a..b7ee0a419e 100644 --- a/app/javascript/site/job_notepad.test.js +++ b/app/javascript/site/job_notepad.test.js @@ -30,7 +30,7 @@ const page = () => `
+ data-kinds='{"planting":"Planting","seed":"Seeds","crop":"Crop","domesticatedanimal":"Animal"}' data-suggestions-url="/jobs/suggestions"> @@ -644,6 +644,30 @@ describe('@ suggestions', () => { expect(fetchMock).not.toHaveBeenCalled(); }); + describe('with an animal suggestion', () => { + beforeEach(async () => { + fetchMock.mockResolvedValue({ok: true, json: async () => [ + {jobbable_type: 'DomesticatedAnimal', jobbable_id: 7, name: 'Henrietta', label: 'Henrietta', detail: 'Chicken', icon_url: null}, + ]}); + await start(); + await type(addBox(), 'Feed @Hen'); + }); + + it('does not render a broken image without a photo', () => { + expect(options().querySelector('img')).toBeNull(); + }); + + it('replaces the mention with the animal name', () => { + press(addBox(), 'Enter'); + expect(addBox().value).toBe('Feed Henrietta '); + }); + + it('links the selected animal to the job', () => { + press(addBox(), 'Enter'); + expect(document.getElementById('notepad-jobbable-type').value).toBe('DomesticatedAnimal'); + }); + }); + it('asks for the crop name typed', async () => { await start(); await type(addBox(), 'prune the @tom'); diff --git a/app/models/ability.rb b/app/models/ability.rb index 09cf0e4f0d..022cf75246 100644 --- a/app/models/ability.rb +++ b/app/models/ability.rb @@ -132,6 +132,11 @@ def member_abilities(member) can :destroy, GardenCollaborator, garden: { owner_id: member.id } can :destroy, GardenCollaborator, member_id: member.id + if Feature.enabled?(:domesticated_animals, member) + can :create, DomesticatedAnimal + can %i(update destroy), DomesticatedAnimal, owner_id: member.id + end + can :create, Job can :update, Job, owner_id: member.id can :destroy, Job, owner_id: member.id diff --git a/app/models/animal_tag.rb b/app/models/animal_tag.rb new file mode 100644 index 0000000000..5cd1991a4a --- /dev/null +++ b/app/models/animal_tag.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +class AnimalTag < ApplicationRecord + belongs_to :domesticated_animal + belongs_to :taggable, polymorphic: true + + validates :domesticated_animal_id, uniqueness: { scope: %i(taggable_type taggable_id) } +end diff --git a/app/models/comment.rb b/app/models/comment.rb index e7624beda6..faae244a4c 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -1,6 +1,8 @@ # frozen_string_literal: true class Comment < ApplicationRecord + include AnimalTaggable + belongs_to :author, class_name: 'Member', inverse_of: :comments belongs_to :commentable, polymorphic: true, counter_cache: true # validates :body, presence: true diff --git a/app/models/concerns/animal_taggable.rb b/app/models/concerns/animal_taggable.rb new file mode 100644 index 0000000000..74f004a4b9 --- /dev/null +++ b/app/models/concerns/animal_taggable.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +# Animal mentions use IDs rather than names, which are not unique. Shared by +# posts and comments; the same markdown links work in other descriptions too. +module AnimalTaggable + extend ActiveSupport::Concern + + included do + has_many :animal_tags, as: :taggable, dependent: :delete_all + has_many :domesticated_animals, through: :animal_tags + after_save :update_animal_tags, if: :saved_change_to_body? + end + + private + + def update_animal_tags + ids = body.to_s.scan(Haml::Filters::GrowstuffMarkdown::ANIMAL_REGEX).pluck(1).uniq + self.domesticated_animals = DomesticatedAnimal.where(id: ids) + end +end diff --git a/app/models/concerns/jobbable.rb b/app/models/concerns/jobbable.rb index ba7f747e5e..f70ad29973 100644 --- a/app/models/concerns/jobbable.rb +++ b/app/models/concerns/jobbable.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -# Something a job can be about: a crop, a planting or some seeds. The job is +# Something a job can be about: a crop, a planting, seeds or an animal. The job is # kept when the thing goes, without the link. module Jobbable extend ActiveSupport::Concern diff --git a/app/models/domesticated_animal.rb b/app/models/domesticated_animal.rb new file mode 100644 index 0000000000..a8e8889e1a --- /dev/null +++ b/app/models/domesticated_animal.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +class DomesticatedAnimal < ApplicationRecord + include PhotoCapable + include Jobbable + + belongs_to :owner, class_name: 'Member', inverse_of: :domesticated_animals + has_many :animal_tags, dependent: :delete_all + has_many :posts, through: :animal_tags, source: :taggable, source_type: 'Post' + + default_scope { joins(:owner).merge(Member.kept) } + + enum :category, %w(dog cat chicken turkey guinea_pig).index_with(&:itself), validate: true + enum :biological_sex, %w(female male intersex unknown).index_with(&:itself), prefix: true, validate: { allow_nil: true } + + normalizes :biological_sex, with: ->(value) { value.presence } + validates :name, :species, presence: true + validates :name, :species, :description, length: { maximum: 255 } + validate :death_not_before_birth + + def to_s + name + end + + private + + def death_not_before_birth + return unless date_of_birth && date_of_death && date_of_death < date_of_birth + + errors.add(:date_of_death, :before_birth) + end +end diff --git a/app/models/feature.rb b/app/models/feature.rb index 661c8b767d..7b8a5aa2d7 100644 --- a/app/models/feature.rb +++ b/app/models/feature.rb @@ -2,7 +2,8 @@ # Features admins can enable globally or grant to individual members in Flipper. class Feature - NAMES = %i(job_ideas enable_planting_reminders enable_harvest_reminders planting_weather garden_stall planting_codes).freeze + NAMES = %i(job_ideas enable_planting_reminders enable_harvest_reminders planting_weather garden_stall planting_codes + domesticated_animals).freeze attr_reader :name diff --git a/app/models/job.rb b/app/models/job.rb index ef5ec6682f..bd7aec8e81 100644 --- a/app/models/job.rb +++ b/app/models/job.rb @@ -11,7 +11,7 @@ class Job < ApplicationRecord # The template step this job was made from, if it was. belongs_to :crop_job_step, optional: true - JOBBABLE_TYPES = %w(Crop Planting Seed).freeze + JOBBABLE_TYPES = %w(Crop Planting Seed DomesticatedAnimal).freeze # What each action can be about: plant a crop or the seeds of it, harvest a crop # or a planting of it. ACTION_JOBBABLES = { 'plant' => %w(Crop Seed), 'harvest' => %w(Crop Planting) }.freeze @@ -45,6 +45,7 @@ class Job < ApplicationRecord validates :jobbable_type, inclusion: { in: JOBBABLE_TYPES }, allow_nil: true validate :action_goes_with_jobbable, if: :action validate :jobbable_is_the_owners, if: -> { jobbable_id_changed? || jobbable_type_changed? } + validate :animal_feature_enabled, if: -> { jobbable_id_changed? || jobbable_type_changed? } before_validation :set_garden_from_planting before_save :stamp_finished_at, if: :finished_changed? @@ -92,6 +93,13 @@ def planting_name private + def animal_feature_enabled + return unless jobbable_type == 'DomesticatedAnimal' + return if Feature.enabled?(:domesticated_animals, owner) + + errors.add(:jobbable, :invalid) + end + def set_garden_from_planting self.garden ||= planting.garden if planting end @@ -104,7 +112,7 @@ def action_goes_with_jobbable errors.add(:action, :cannot_be_about_that) unless ACTION_JOBBABLES.fetch(action, []).include?(jobbable_type) end - # A job about something is about something that is there. Plantings and seeds are a member's own: a job can't + # A job about something is about something that is there. Plantings, seeds and animals are a member's own: a job can't # be about someone else's. Plantings in gardens the member collaborates on or owns are also allowed. def jobbable_is_the_owners return unless JOBBABLE_TYPES.include?(jobbable_type) diff --git a/app/models/member.rb b/app/models/member.rb index e3e4ea3ef2..2b90b73e5b 100644 --- a/app/models/member.rb +++ b/app/models/member.rb @@ -30,6 +30,7 @@ class Member < ApplicationRecord has_many :seeds, foreign_key: 'owner_id', dependent: :destroy, inverse_of: :owner has_many :harvests, foreign_key: 'owner_id', dependent: :destroy, inverse_of: :owner has_many :jobs, foreign_key: 'owner_id', dependent: :destroy, inverse_of: :owner + has_many :domesticated_animals, foreign_key: 'owner_id', dependent: :destroy, inverse_of: :owner has_and_belongs_to_many :roles has_many :notifications, foreign_key: 'recipient_id', inverse_of: :recipient has_many :sent_notifications, foreign_key: 'sender_id', inverse_of: :sender, class_name: "Notification" diff --git a/app/models/photo.rb b/app/models/photo.rb index 05cdab3a59..b0bfefbc2a 100644 --- a/app/models/photo.rb +++ b/app/models/photo.rb @@ -4,7 +4,7 @@ class Photo < ApplicationRecord include Likeable include Ownable - PHOTO_CAPABLE = %w(Garden Planting Harvest Seed Post Crop Job).freeze + PHOTO_CAPABLE = %w(Garden Planting Harvest Seed Post Crop Job DomesticatedAnimal).freeze # What Flickr says about a photo that may change: the picture, the licence and the date. # The title is ours, and stays. @@ -31,7 +31,7 @@ def crops # creates a relationship for each assignee type PHOTO_CAPABLE.each do |type| - has_many type.downcase.pluralize.to_s.to_sym, + has_many type.underscore.pluralize.to_sym, through: :photo_associations, source: :photographable, source_type: type diff --git a/app/models/post.rb b/app/models/post.rb index f46274bc10..681ec30949 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -3,6 +3,7 @@ class Post < ApplicationRecord extend FriendlyId include Likeable + include AnimalTaggable friendly_id :author_date_subject, use: %i(slugged finders) include PhotoCapable diff --git a/app/services/job_ideas/past_jobs.rb b/app/services/job_ideas/past_jobs.rb index afb5c592ae..38d346cdea 100644 --- a/app/services/job_ideas/past_jobs.rb +++ b/app/services/job_ideas/past_jobs.rb @@ -33,7 +33,7 @@ def done_jobs # The crop of every planting and seed a job is about, in one go. def preload_crops(jobs) - about = jobs.filter_map(&:jobbable).grep_v(Crop) + about = jobs.filter_map(&:jobbable).select { |item| item.is_a?(Planting) || item.is_a?(Seed) } ActiveRecord::Associations::Preloader.new(records: about, associations: :crop).call end diff --git a/app/views/domesticated_animals/_form.html.haml b/app/views/domesticated_animals/_form.html.haml new file mode 100644 index 0000000000..10f35ff5f6 --- /dev/null +++ b/app/views/domesticated_animals/_form.html.haml @@ -0,0 +1,16 @@ += bootstrap_form_for(@domesticated_animal) do |f| + = f.alert_message t('domesticated_animals.form_errors') + = f.text_field :name, required: true, maxlength: 255, label: t('domesticated_animals.fields.name') + = f.text_field :species, required: true, maxlength: 255, label: t('domesticated_animals.fields.species') + - categories = DomesticatedAnimal.categories.keys.map { |key| [t("domesticated_animals.categories.#{key}"), key] } + = f.select :category, categories, + { include_blank: true, label: t('domesticated_animals.fields.category') }, required: true + = f.text_area :description, maxlength: 255, label: t('domesticated_animals.fields.description') + = f.date_field :date_of_birth, label: t('domesticated_animals.fields.date_of_birth') + = f.date_field :date_of_death, label: t('domesticated_animals.fields.date_of_death') + - sexes = DomesticatedAnimal.biological_sexes.keys.map { |key| [t("domesticated_animals.sexes.#{key}"), key] } + = f.select :biological_sex, sexes, include_blank: true, label: t('domesticated_animals.fields.biological_sex') + .d-flex.justify-content-between.mt-3 + - cancel_path = @domesticated_animal.persisted? ? @domesticated_animal : current_member + = link_to t('domesticated_animals.cancel'), cancel_path, class: 'btn btn-secondary' + = f.submit t('domesticated_animals.save'), class: 'btn btn-primary' diff --git a/app/views/domesticated_animals/_profile.html.haml b/app/views/domesticated_animals/_profile.html.haml new file mode 100644 index 0000000000..8391a8bf8e --- /dev/null +++ b/app/views/domesticated_animals/_profile.html.haml @@ -0,0 +1,20 @@ +- animals = member.domesticated_animals.includes(:photos).order(:name, :id) +- can_add = current_member == member && can?(:create, DomesticatedAnimal) +- if animals.any? || can_add + %section.record-page.mb-4#domesticated-animals + .section-header + %h2= t('domesticated_animals.title') + - if can_add + = link_to t('domesticated_animals.add'), new_domesticated_animal_path, + class: 'btn btn-sm section-add' + .row + - animals.each do |animal| + .col-sm-6.col-lg-4.mb-3 + .card.h-100 + - if animal.default_photo + = link_to animal do + = image_tag animal.default_photo.thumbnail_url, alt: animal.name, class: 'card-img-top' + .card-body + %h3.h5= link_to animal.name, animal + %p.mb-0= t("domesticated_animals.categories.#{animal.category}") + %small.text-muted= animal.species diff --git a/app/views/domesticated_animals/edit.html.haml b/app/views/domesticated_animals/edit.html.haml new file mode 100644 index 0000000000..49263ff695 --- /dev/null +++ b/app/views/domesticated_animals/edit.html.haml @@ -0,0 +1,3 @@ +- content_for :title, t('domesticated_animals.edit') +%h1= t('domesticated_animals.edit') += render 'form' diff --git a/app/views/domesticated_animals/new.html.haml b/app/views/domesticated_animals/new.html.haml new file mode 100644 index 0000000000..42e59238db --- /dev/null +++ b/app/views/domesticated_animals/new.html.haml @@ -0,0 +1,3 @@ +- content_for :title, t('domesticated_animals.add') +%h1= t('domesticated_animals.add') += render 'form' diff --git a/app/views/domesticated_animals/show.html.haml b/app/views/domesticated_animals/show.html.haml new file mode 100644 index 0000000000..c108028c46 --- /dev/null +++ b/app/views/domesticated_animals/show.html.haml @@ -0,0 +1,45 @@ +- animal = @domesticated_animal +- content_for :title, animal.name +- content_for :scripts do + = javascript_include_tag 'react_islands', defer: true +- content_for :breadcrumbs do + %li.breadcrumb-item= link_to animal.owner, animal.owner + %li.breadcrumb-item.active= animal.name + +.record-page + .record-panel + .section-header + %h1= animal.name + - if can?(:update, animal) + = link_to t('domesticated_animals.edit'), edit_domesticated_animal_path(animal), + class: 'btn btn-sm section-add' + %dl + - %i(species category biological_sex date_of_birth date_of_death).each do |field| + - value = animal.public_send(field) + - next if value.blank? + + %dt= t("domesticated_animals.fields.#{field}") + %dd + - if field == :category + = t("domesticated_animals.categories.#{value}") + - elsif field == :biological_sex + = t("domesticated_animals.sexes.#{value}") + - elsif value.is_a?(Date) + = l(value) + - else + = value + - if animal.description.present? + %p= animal.description + %section#photos + .section-header + %h2= t('domesticated_animals.photos') + - if can?(:update, animal) + = link_to t('domesticated_animals.add_photo'), new_photo_path_for(animal), + class: 'btn btn-sm section-add', data: photo_dialog_data(animal) + = render 'photos/gallery', photos: animal.photos, item: animal + - if can?(:update, animal) + .d-flex.justify-content-between.mt-3 + = link_to t('domesticated_animals.add_job'), + new_job_path(jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id), class: 'btn btn-primary' + = button_to t('domesticated_animals.delete'), animal, method: :delete, + class: 'btn btn-outline-danger', data: { confirm: t('domesticated_animals.confirm_delete') } diff --git a/app/views/jobs/_card.html.haml b/app/views/jobs/_card.html.haml index b46d4725f3..b714e53356 100644 --- a/app/views/jobs/_card.html.haml +++ b/app/views/jobs/_card.html.haml @@ -1,4 +1,4 @@ -- cache job do +- cache [job, domesticated_animals_enabled?] do .card.job{class: job.active ? '' : 'card-finished'} - if member_signed_in? && current_member.id == job.owner_id .job-quick-actions= render 'jobs/actions', job: @@ -10,6 +10,9 @@ %div %small.text-justify{title: job.description}= job.description.to_s.truncate(150) %ul.list-unstyled.mb-0 + - if job.jobbable_type == 'DomesticatedAnimal' && job.jobbable && domesticated_animals_enabled? + %li + %small= link_to job.jobbable.name, job.jobbable - if job.garden %li %small= link_to job.garden_name, garden_path(job.garden) diff --git a/app/views/jobs/_form.html.haml b/app/views/jobs/_form.html.haml index e86d27b1e4..d24aed19cd 100644 --- a/app/views/jobs/_form.html.haml +++ b/app/views/jobs/_form.html.haml @@ -5,6 +5,10 @@ = planting_icon %strong=yield :title = bootstrap_form_for(@job) do |f| + - if @job.jobbable_type == 'DomesticatedAnimal' && domesticated_animals_enabled? + = f.hidden_field :jobbable_type + = f.hidden_field :jobbable_id + %p= link_to @job.jobbable.name, @job.jobbable if @job.jobbable .card-body - if @job.errors.any? #error_explanation diff --git a/app/views/jobs/_notepad.html.haml b/app/views/jobs/_notepad.html.haml index 5c45b86d9a..4d4799ccce 100644 --- a/app/views/jobs/_notepad.html.haml +++ b/app/views/jobs/_notepad.html.haml @@ -7,7 +7,7 @@ = content_tag(garden ? :h2 : :h1, garden ? t('jobs.pad.garden_title') : t('jobs.pad.title', owner: owner.login_name)) - if garden = link_to t('jobs.pad.all_jobs'), member_jobs_path(owner), class: 'notepad-all-jobs' - = form_with url: jobs_path, scope: :job, class: 'notepad-add', data: { suggestions_url: job_suggestions_path, kinds: { planting: t('jobs.pad.planting'), seed: t('jobs.pad.seeds'), crop: t('jobs.pad.crop') }.to_json } do |f| + = form_with url: jobs_path, scope: :job, class: 'notepad-add', data: { suggestions_url: job_suggestions_path, kinds: { planting: t('jobs.pad.planting'), seed: t('jobs.pad.seeds'), crop: t('jobs.pad.crop'), domesticatedanimal: t('domesticated_animals.singular') }.to_json } do |f| %span.notepad-add-plus{ 'aria-hidden': 'true' } + = f.text_field :name, required: true, autofocus: local_assigns.fetch(:autofocus, true), autocomplete: 'off', placeholder: t('jobs.pad.add'), 'aria-label': t('jobs.pad.add'), role: 'combobox', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'aria-controls': 'notepad-suggestions' diff --git a/app/views/jobs/_notepad_row.html.haml b/app/views/jobs/_notepad_row.html.haml index 6efe0cb1f9..334b322625 100644 --- a/app/views/jobs/_notepad_row.html.haml +++ b/app/views/jobs/_notepad_row.html.haml @@ -13,6 +13,11 @@ %span.kind= t('jobs.pad.garden') = job.garden.name - case job.jobbable + - when DomesticatedAnimal + - if domesticated_animals_enabled? + = link_to job.jobbable, class: 'notepad-chip' do + %span.kind= t('domesticated_animals.singular') + = job.jobbable.name - when Planting = link_to planting_path(job.jobbable), class: 'notepad-chip' do %span.kind= t('jobs.pad.planting') diff --git a/app/views/members/show.html.haml b/app/views/members/show.html.haml index 235ab3ae8d..e511cc032c 100644 --- a/app/views/members/show.html.haml +++ b/app/views/members/show.html.haml @@ -86,6 +86,8 @@ = render "contact", member: @member, flickr_auth: @flickr_auth, mastodon_auths: @mastodon_auths .col-md-10#content + - if domesticated_animals_enabled? + = render 'domesticated_animals/profile', member: @member = render 'stalls/card', member: @member .row %section.order-3.order-md-1.col-12= render "map", member: @member diff --git a/app/views/shared/_markdown_help.html.haml b/app/views/shared/_markdown_help.html.haml index 40076d1981..65515a3c95 100644 --- a/app/views/shared/_markdown_help.html.haml +++ b/app/views/shared/_markdown_help.html.haml @@ -5,3 +5,6 @@ = t('.crop_links') %br/ = t('.member_links') +- if domesticated_animals_enabled? + %br/ + = t('.animal_links') diff --git a/config/locales/en.yml b/config/locales/en.yml index 9442171f22..6c1fd5f9fc 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1,5 +1,37 @@ --- en: + domesticated_animals: + title: Animals + singular: Animal + add: Add an animal + edit: Edit animal + save: Save animal + cancel: Cancel + delete: Delete animal + confirm_delete: Delete this animal? Its jobs and posts will be kept without the link. + form_errors: Please check the animal's details. + photos: Photos + add_photo: Add a photo + add_job: Plan a job for this animal + fields: + name: Name + species: Species + category: Category + description: Description + date_of_birth: Date of birth + date_of_death: Date of death + biological_sex: Biological sex + categories: + dog: Dog + cat: Cat + chicken: Chicken + turkey: Turkey + guinea_pig: Guinea pig + sexes: + female: Female + male: Male + intersex: Intersex + unknown: Unknown likes: description_html: '%{member} liked %{item}' shared: @@ -10,6 +42,7 @@ en: examples: 'For instance, *italic*, **bold**, or a link [like this](http://to.some.site.com/).' crop_links: 'Quick crop links: [sweet potato](crop).' member_links: 'Quick member links: @Username or [Username](member).' + animal_links: 'Animal links: [name](animal:123), using the ID from the animal page address.' record_parent: growing_in_html: growing in %{garden} signin_signup: @@ -31,6 +64,7 @@ en: activerecord: errors: messages: + before_birth: cannot be before the date of birth bed_position_incomplete: must have both a column and a row, or neither bed_position_off_grid: would put this plant outside the bed calculate_crop_failed: failed to calculate crop @@ -228,6 +262,7 @@ en: features: member_not_found: Member not found. Enter an existing username. descriptions: + domesticated_animals: Animal profiles, photos, and links from jobs, posts and comments. enable_harvest_reminders: Sends the weekly harvest reminder emails to members who want them. enable_planting_reminders: Sends the weekly planting reminder emails to members who want them. garden_stall: A page where members offer spare seedlings and seeds to friends. Switch on once all the parts are deployed. @@ -248,6 +283,7 @@ en: switch_on: Switch on title: Features names: + domesticated_animals: Domesticated animals enable_harvest_reminders: Harvest reminders enable_planting_reminders: Planting reminders garden_stall: Garden stall @@ -3743,6 +3779,7 @@ en: delete_confirm: Delete this photo from Growstuff altogether? It is taken off everything it is attached to. It stays on its original hosting service. refresh: Refresh photo data from Flickr unlink: + domesticated_animal: "Remove from the animal: %{name}" crop: "Remove from the crop: %{name}" garden: "Remove from the garden: %{name}" harvest: "Remove from the harvest: %{name}" @@ -3827,6 +3864,9 @@ en: taken: Taken %{date} thing_by: A %{thing} by %{owner} shows: + domesticated_animal: + by: Animal of %{owner} + kind: Animal crop: about: Curious how to grow it? See when to plant, who else grows it near you, and what they harvest. go: Explore %{crop} diff --git a/config/routes.rb b/config/routes.rb index 1f7930ccd7..6d696a5b17 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -8,6 +8,7 @@ resources :garden_types resources :plant_parts + resources :domesticated_animals, except: :index devise_for :members, controllers: { confirmations: "confirmations", diff --git a/db/migrate/20261127000000_create_domesticated_animals.rb b/db/migrate/20261127000000_create_domesticated_animals.rb new file mode 100644 index 0000000000..010a4d54f5 --- /dev/null +++ b/db/migrate/20261127000000_create_domesticated_animals.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +class CreateDomesticatedAnimals < ActiveRecord::Migration[8.1] + def change + create_table :domesticated_animals do |t| + t.string :name, null: false + t.string :species, null: false + t.string :category, null: false + t.string :description + t.date :date_of_birth + t.date :date_of_death + t.string :biological_sex + t.references :owner, null: false, foreign_key: { to_table: :members } + t.timestamps + end + + create_table :animal_tags do |t| # rubocop:disable Rails/CreateTableWithTimestamps -- Join table, like crop_posts. + t.references :domesticated_animal, null: false, foreign_key: true + t.references :taggable, polymorphic: true, null: false + t.index %i(taggable_type taggable_id domesticated_animal_id), unique: true, name: 'index_animal_tags_unique' + end + end +end diff --git a/db/schema.rb b/db/schema.rb index 896ba930cf..58b98a6688 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2026_11_20_000000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_27_000000) do # These are extensions that must be enabled in order to support this database enable_extension "pg_catalog.plpgsql" enable_extension "pg_trgm" @@ -58,6 +58,15 @@ t.index ["normalised_name"], name: "index_alternate_names_on_normalised_name", opclass: :gin_trgm_ops, using: :gin end + create_table "animal_tags", force: :cascade do |t| + t.bigint "domesticated_animal_id", null: false + t.string "taggable_type", null: false + t.bigint "taggable_id", null: false + t.index ["domesticated_animal_id"], name: "index_animal_tags_on_domesticated_animal_id" + t.index ["taggable_type", "taggable_id", "domesticated_animal_id"], name: "index_animal_tags_unique", unique: true + t.index ["taggable_type", "taggable_id"], name: "index_animal_tags_on_taggable" + end + create_table "australian_food_classification_data", force: :cascade do |t| t.decimal "acetic_acid_g" t.decimal "added_sugars_g" @@ -673,6 +682,20 @@ t.index ["slug"], name: "index_crops_on_slug", unique: true end + create_table "domesticated_animals", force: :cascade do |t| + t.string "name", null: false + t.string "species", null: false + t.string "category", null: false + t.string "description" + t.date "date_of_birth" + t.date "date_of_death" + t.string "biological_sex" + t.bigint "owner_id", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["owner_id"], name: "index_domesticated_animals_on_owner_id" + end + create_table "ecocrop_data", force: :cascade do |t| t.integer "ecoportcode" t.string "scientificname" @@ -1418,6 +1441,7 @@ add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" + add_foreign_key "animal_tags", "domesticated_animals" add_foreign_key "blocks", "members", column: "blocked_id" add_foreign_key "blocks", "members", column: "blocker_id" add_foreign_key "claims", "members" @@ -1428,6 +1452,7 @@ add_foreign_key "crop_job_templates", "crops" add_foreign_key "crop_job_templates", "members", column: "creator_id" add_foreign_key "crops", "ecocrop_data", column: "ecocrop_data_id", on_delete: :nullify + add_foreign_key "domesticated_animals", "members", column: "owner_id" add_foreign_key "harvests", "plantings" add_foreign_key "job_idea_dismissals", "members" add_foreign_key "jobs", "crop_job_steps", on_delete: :nullify diff --git a/lib/haml/filters/growstuff_markdown.rb b/lib/haml/filters/growstuff_markdown.rb index ae8e1a3fb3..25950b9b43 100644 --- a/lib/haml/filters/growstuff_markdown.rb +++ b/lib/haml/filters/growstuff_markdown.rb @@ -7,6 +7,7 @@ class GrowstuffMarkdown MEMBER_REGEX = /(? 'application/json', 'ACCEPT' => 'application/json' } } def add_photo(label: nil) - query = { type: 'job', id: job.id, label: }.compact.to_query + query = { type: item.class.model_name.singular, id: item.id, label: }.compact.to_query post "/photos.json?#{query}", params: { photo: { source_id: '1234', source: 'flickr' } }.to_json, headers: json_headers end @@ -60,6 +61,46 @@ def add_photo(label: nil) end end + context 'with an animal', flipper: :domesticated_animals do + let(:item) { create(:domesticated_animal, owner: member) } + + it 'links the imported photo' do + add_photo + expect(item.photos.pluck(:title)).to eq ['Net on'] + end + + it 'unlinks the photo without deleting it' do + add_photo + photo = item.photos.first + delete photo_association_path(photo_id: photo.id, type: 'domesticated_animal', id: item.id) + expect(Photo.find_by(id: photo.id)).to eq photo + end + + it 'removes the photo association' do + add_photo + delete photo_association_path(photo_id: item.photos.first.id, type: 'domesticated_animal', id: item.id) + expect(item.photos.reload).to be_empty + end + + context 'when the animal belongs to someone else' do + let(:item) { create(:domesticated_animal) } + + it 'rejects the import' do + add_photo + expect(response).to have_http_status(:forbidden) + end + end + + context 'when the feature is disabled' do + before { Flipper.disable(:domesticated_animals) } + + it 'rejects the import' do + add_photo + expect(response).to have_http_status(:not_found) + end + end + end + context 'with a label that is not allowed' do before { add_photo(label: 'during') } diff --git a/spec/services/job_ideas/past_jobs_spec.rb b/spec/services/job_ideas/past_jobs_spec.rb index 8462bb2ecd..a2ce4e5116 100644 --- a/spec/services/job_ideas/past_jobs_spec.rb +++ b/spec/services/job_ideas/past_jobs_spec.rb @@ -25,6 +25,14 @@ expect(ideas.first.crop).to eq crop end + context 'with a job about an animal', flipper: :domesticated_animals do + let(:crop) { create(:domesticated_animal, owner: member) } + + it 'offers the job without looking up a crop' do + expect(ideas.first.crop).to be_nil + end + end + it 'dates a job by when it was crossed off, if known' do job.update!(due_date: nil) job.update!(finished: false) From 940184a93ba17d3eb748c2c86294d8c0c1e22c2a Mon Sep 17 00:00:00 2001 From: Daniel O'Connor Date: Fri, 27 Nov 2026 07:57:08 +0000 Subject: [PATCH 2/5] Goats are clearly chaotic good, so provide a way to capture that --- .../domesticated_animals_controller.rb | 14 +- app/javascript/application.js | 1 + app/javascript/components/AnimalDialog.jsx | 106 +++++++++++++++ .../components/AnimalDialog.test.jsx | 105 +++++++++++++++ app/javascript/print_label.test.js | 69 ++++++++++ app/javascript/react_islands.jsx | 3 +- app/javascript/site/domesticated_animals.js | 44 +++++++ .../site/domesticated_animals.test.js | 110 ++++++++++++++++ app/models/domesticated_animal.rb | 11 +- .../domesticated_animals/_form.html.haml | 35 ++++- .../domesticated_animals/_profile.html.haml | 6 +- app/views/domesticated_animals/new.html.haml | 4 +- app/views/domesticated_animals/show.html.haml | 19 ++- config/locales/en.yml | 37 +++++- ...0_add_alignment_to_domesticated_animals.rb | 7 + db/schema.rb | 3 +- spec/features/domesticated_animals_spec.rb | 124 ++++++++++++++++++ spec/features/posts/posting_a_post_spec.rb | 5 +- spec/models/domesticated_animal_spec.rb | 25 +++- .../domesticated_animals_controller_spec.rb | 93 +++++++++++++ 20 files changed, 797 insertions(+), 24 deletions(-) create mode 100644 app/javascript/components/AnimalDialog.jsx create mode 100644 app/javascript/components/AnimalDialog.test.jsx create mode 100644 app/javascript/print_label.test.js create mode 100644 app/javascript/site/domesticated_animals.js create mode 100644 app/javascript/site/domesticated_animals.test.js create mode 100644 db/migrate/20261127000100_add_alignment_to_domesticated_animals.rb create mode 100644 spec/features/domesticated_animals_spec.rb diff --git a/app/controllers/domesticated_animals_controller.rb b/app/controllers/domesticated_animals_controller.rb index 6b53dd1caf..cf8a12550e 100644 --- a/app/controllers/domesticated_animals_controller.rb +++ b/app/controllers/domesticated_animals_controller.rb @@ -11,11 +11,15 @@ class DomesticatedAnimalsController < ApplicationController responders :flash def show + @jobs = @domesticated_animal.jobs.accessible_by(current_ability) + .preload(:owner, :garden, :jobbable).order(:due_date, :id) 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 @@ -45,14 +49,20 @@ def destroy def render_errors(template) respond_to do |format| - format.html { render template, status: :unprocessable_content } + 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 + :name, :species, :category, :description, :date_of_birth, :date_of_death, :biological_sex, :alignment ) 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 ( +
+ {error &&

{errorLabel}

} +
{ + if (event.target.closest('[data-animal-dialog-cancel="true"]')) { + event.preventDefault(); + onClose(); + } + }} + dangerouslySetInnerHTML={{__html: formHtml}} + /> +
+ ); +} + +export default function AnimalDialog({url, label, title, loading_label: loadingLabel, error_label: errorLabel}) { + const [opened, setOpened] = useState(false); + const [html, setHtml] = useState(null); + + useEffect(() => { + if (!opened) return undefined; + const controller = new AbortController(); + async function load() { + try { + const response = await fetch(`${url}?dialog=true`, { + credentials: 'same-origin', headers: {Accept: 'text/html'}, signal: controller.signal, + }); + if (!response.ok || response.redirected) throw new Error('Could not load form'); + setHtml(await response.text()); + } catch { + if (!controller.signal.aborted) window.location.assign(url); + } + } + load(); + return () => controller.abort(); + }, [opened, url]); + + const close = () => { + setOpened(false); + setHtml(null); + }; + + return ( + <> + { + if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + event.preventDefault(); + setOpened(true); + }}>{label} + {opened && ( + + {html + ? window.location.assign(path)} /> + :
{loadingLabel}
} +
+ )} + + ); +} diff --git a/app/javascript/components/AnimalDialog.test.jsx b/app/javascript/components/AnimalDialog.test.jsx new file mode 100644 index 0000000000..dc0028400c --- /dev/null +++ b/app/javascript/components/AnimalDialog.test.jsx @@ -0,0 +1,105 @@ +import {render, screen, waitFor} from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import AnimalDialog from './AnimalDialog'; + +const formHtml = ` + + + + + + + + + Cancel + + `; + +function setup() { + render(); +} + +async function openForm() { + setup(); + await userEvent.click(screen.getByRole('link', {name: 'Add animal'})); + await screen.findByRole('textbox', {name: 'Name'}); +} + +describe('AnimalDialog', () => { + beforeEach(() => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok: true, text: async () => formHtml})); + }); + + afterEach(() => vi.unstubAllGlobals()); + + it('keeps a standalone link as a fallback', () => { + setup(); + expect(screen.getByRole('link', {name: 'Add animal'})).toHaveAttribute('href', '/domesticated_animals/new'); + }); + + it('opens the form in a dialog', async () => { + await openForm(); + expect(screen.getByRole('dialog', {name: 'Your animal'})).toBeInTheDocument(); + }); + + it('initializes the scientific name suggestions', async () => { + await openForm(); + await userEvent.click(screen.getByRole('radio', {name: 'Rabbit'})); + expect(screen.getByRole('textbox', {name: 'Species'})).toHaveValue('Oryctolagus cuniculus domesticus'); + }); + + it('closes when cancelled', async () => { + await openForm(); + await userEvent.click(screen.getByRole('link', {name: 'Cancel'})); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('closes with Escape', async () => { + await openForm(); + await userEvent.keyboard('{Escape}'); + expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); + }); + + it('restores focus to the trigger on close', async () => { + await openForm(); + await userEvent.keyboard('{Escape}'); + expect(screen.getByRole('link', {name: 'Add animal'})).toHaveFocus(); + }); + + it('shows server validation errors inside the dialog', async () => { + await openForm(); + fetch.mockResolvedValue({status: 422, text: async () => formHtml.replace('
Invalid details

{ + await openForm(); + await userEvent.type(screen.getByRole('textbox', {name: 'Name'}), 'Clover'); + fetch.mockRejectedValue(new Error('Offline')); + await userEvent.click(screen.getByRole('button', {name: 'Save animal'})); + await screen.findByRole('alert'); + expect(screen.getByRole('textbox', {name: 'Name'})).toHaveValue('Clover'); + }); + + it('navigates to the animal after saving', async () => { + const assign = vi.fn(); + vi.stubGlobal('location', {assign}); + await openForm(); + fetch.mockResolvedValue({redirected: true, url: '/domesticated_animals/1'}); + await userEvent.click(screen.getByRole('button', {name: 'Save animal'})); + await waitFor(() => expect(assign).toHaveBeenCalledWith('/domesticated_animals/1')); + }); + + it('falls back to the full page when the form cannot load', async () => { + const assign = vi.fn(); + vi.stubGlobal('location', {assign}); + fetch.mockRejectedValue(new Error('Offline')); + setup(); + await userEvent.click(screen.getByRole('link', {name: 'Add animal'})); + await waitFor(() => expect(assign).toHaveBeenCalledWith('/domesticated_animals/new')); + }); +}); diff --git a/app/javascript/print_label.test.js b/app/javascript/print_label.test.js new file mode 100644 index 0000000000..618f7fc58c --- /dev/null +++ b/app/javascript/print_label.test.js @@ -0,0 +1,69 @@ +import {fireEvent, waitFor} from '@testing-library/dom'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; +import {createLabel, createLabelImage} from './site/label_pdf'; +import './print_label'; + +vi.mock('./site/label_pdf', () => ({createLabel: vi.fn(), createLabelImage: vi.fn()})); + +describe('inline label preview', () => { + let form; + let preview; + let save; + + beforeEach(() => { + Object.defineProperty(document, 'fonts', {configurable: true, value: {ready: Promise.resolve()}}); + createLabelImage.mockReturnValue('data:image/png;base64,preview'); + save = vi.fn(); + createLabel.mockReturnValue({save}); + document.body.innerHTML = ` + + + + + +
`; + form = document.querySelector('form'); + preview = form.querySelector('img'); + document.dispatchEvent(new Event('DOMContentLoaded')); + }); + + afterEach(() => { + document.body.innerHTML = ''; + delete document.fonts; + vi.resetAllMocks(); + }); + + it('shows a PNG preview on page load', async () => { + await waitFor(() => expect(preview).toBeVisible()); + }); + + it('passes the planting code to the preview renderer', async () => { + await waitFor(() => expect(createLabelImage).toHaveBeenCalledWith(expect.objectContaining({shortCode: 'AB23'}))); + }); + + it('updates the preview when dimensions change', async () => { + form.elements.width.value = '60'; + fireEvent.change(form.elements.width); + await waitFor(() => expect(createLabelImage).toHaveBeenLastCalledWith(expect.objectContaining({width: 60}))); + }); + + it('hides a stale preview when dimensions are unreadable', async () => { + await waitFor(() => expect(preview).toBeVisible()); + createLabelImage.mockImplementation(() => { throw new RangeError(); }); + fireEvent.change(form.elements.width); + await waitFor(() => expect(preview).not.toBeVisible()); + }); + + it('explains when dimensions are unreadable', async () => { + createLabelImage.mockImplementation(() => { throw new RangeError(); }); + fireEvent.change(form.elements.width); + await waitFor(() => expect(form.querySelector('[role="alert"]')).toHaveTextContent(form.dataset.sizeError)); + }); + + it('keeps PDF downloads available', async () => { + fireEvent.submit(form); + await waitFor(() => expect(save).toHaveBeenCalledWith('label.pdf')); + }); +}); diff --git a/app/javascript/react_islands.jsx b/app/javascript/react_islands.jsx index 4bbcb9dfb6..8eefd710d7 100644 --- a/app/javascript/react_islands.jsx +++ b/app/javascript/react_islands.jsx @@ -5,6 +5,7 @@ // // To add a component: create it in ./components and register it below. import AlternateNames from './components/AlternateNames'; +import AnimalDialog from './components/AnimalDialog'; import ApiTokenCopy from './components/ApiTokenCopy'; import AuthDialog from './components/AuthDialog'; import CardPhotoDialog from './components/CardPhotoDialog'; @@ -39,7 +40,7 @@ import ScientificNames from './components/ScientificNames'; import SeedStack from './components/SeedStack'; import {mountIslands, registerIslands} from './islands'; -registerIslands({AlternateNames, ApiTokenCopy, AuthDialog, CardPhotoDialog, CropFilterPicker, EmailStep, FediConnect, FeedMore, FirstStepsPlanter, GardenCards, GardenLayout, GardenPicker, GardenPlanter, GrowingTable, HarvestChart, JobPicker, LocationPicker, NurseryChip, NurseryPlanter, PhotoDialog, PhotoPicker, PlantPicker, PlantingPicker, PlantingActions, PlantingOrigin, PlantingRating, PostEditor, RecordDialog, ScientificNames, SeasonSuggestions, SeedLibrary, SeedStack, UseMyLocation}); +registerIslands({AlternateNames, AnimalDialog, ApiTokenCopy, AuthDialog, CardPhotoDialog, CropFilterPicker, EmailStep, FediConnect, FeedMore, FirstStepsPlanter, GardenCards, GardenLayout, GardenPicker, GardenPlanter, GrowingTable, HarvestChart, JobPicker, LocationPicker, NurseryChip, NurseryPlanter, PhotoDialog, PhotoPicker, PlantPicker, PlantingPicker, PlantingActions, PlantingOrigin, PlantingRating, PostEditor, RecordDialog, ScientificNames, SeasonSuggestions, SeedLibrary, SeedStack, UseMyLocation}); if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => mountIslands()); diff --git a/app/javascript/site/domesticated_animals.js b/app/javascript/site/domesticated_animals.js new file mode 100644 index 0000000000..be3ec7a1a4 --- /dev/null +++ b/app/javascript/site/domesticated_animals.js @@ -0,0 +1,44 @@ +const speciesByCategory = { + dog: 'Canis lupus familiaris', + cat: 'Felis catus', + chicken: 'Gallus gallus domesticus', + turkey: 'Meleagris gallopavo', + duck: 'Anas platyrhynchos domesticus', + goose: 'Anser anser domesticus', + guinea_pig: 'Cavia porcellus', + sheep: 'Ovis aries', + horse: 'Equus caballus', + goat: 'Capra hircus', + pig: 'Sus scrofa domesticus', + rabbit: 'Oryctolagus cuniculus domesticus', + donkey: 'Equus asinus', + alpaca: 'Vicugna pacos', + llama: 'Lama glama', + quail: 'Coturnix japonica', + guinea_fowl: 'Numida meleagris', + pigeon: 'Columba livia domestica', + ferret: 'Mustela putorius furo', +}; + +export function initDomesticatedAnimals(root = document) { + const categories = root.querySelectorAll('input[name="domesticated_animal[category]"]'); + const species = root.querySelector('#domesticated_animal_species'); + if (!categories.length || !species) return; + + const selected = Array.from(categories).find((category) => category.checked); + let previousDefault = speciesByCategory[selected?.value] || ''; + categories.forEach((category) => { + category.addEventListener('change', () => { + if (!category.checked) return; + const nextDefault = speciesByCategory[category.value] || ''; + // Keep a member's own species name, including when editing an animal. + if (!species.value.trim() || species.value === previousDefault) { + species.value = nextDefault; + species.dispatchEvent(new Event('input', {bubbles: true})); + } + previousDefault = nextDefault; + }); + }); +} + +document.addEventListener('DOMContentLoaded', () => initDomesticatedAnimals()); diff --git a/app/javascript/site/domesticated_animals.test.js b/app/javascript/site/domesticated_animals.test.js new file mode 100644 index 0000000000..16e807616b --- /dev/null +++ b/app/javascript/site/domesticated_animals.test.js @@ -0,0 +1,110 @@ +import {beforeEach, describe, expect, it} from 'vitest'; +import {initDomesticatedAnimals} from './domesticated_animals'; + +describe('initDomesticatedAnimals', () => { + let species; + + const selectCategory = (value) => { + const category = document.querySelector(`input[value="${value}"]`); + category.checked = true; + category.dispatchEvent(new Event('change', {bubbles: true})); + }; + + beforeEach(() => { + document.body.innerHTML = ` + ${[ + 'dog', 'cat', 'chicken', 'turkey', 'duck', 'goose', 'guinea_pig', 'sheep', 'horse', 'goat', 'pig', + 'rabbit', 'donkey', 'alpaca', 'llama', 'quail', 'guinea_fowl', 'pigeon', 'ferret', 'other', + ].map((category) => ` + + `).join('')} + `; + species = document.getElementById('domesticated_animal_species'); + }); + + describe('when selecting a category', () => { + beforeEach(() => initDomesticatedAnimals()); + + it.each([ + ['dog', 'Canis lupus familiaris'], + ['cat', 'Felis catus'], + ['chicken', 'Gallus gallus domesticus'], + ['turkey', 'Meleagris gallopavo'], + ['duck', 'Anas platyrhynchos domesticus'], + ['goose', 'Anser anser domesticus'], + ['guinea_pig', 'Cavia porcellus'], + ['sheep', 'Ovis aries'], + ['horse', 'Equus caballus'], + ['goat', 'Capra hircus'], + ['pig', 'Sus scrofa domesticus'], + ['rabbit', 'Oryctolagus cuniculus domesticus'], + ['donkey', 'Equus asinus'], + ['alpaca', 'Vicugna pacos'], + ['llama', 'Lama glama'], + ['quail', 'Coturnix japonica'], + ['guinea_fowl', 'Numida meleagris'], + ['pigeon', 'Columba livia domestica'], + ['ferret', 'Mustela putorius furo'], + ['other', ''], + ])('prefills the scientific name for %s', (value, scientificName) => { + selectCategory(value); + expect(species.value).toBe(scientificName); + }); + + it('updates a previous suggestion', () => { + selectCategory('dog'); + selectCategory('cat'); + expect(species.value).toBe('Felis catus'); + }); + + it('clears the suggested species when choosing other', () => { + selectCategory('sheep'); + selectCategory('other'); + expect(species.value).toBe(''); + }); + + it('preserves a custom species when choosing other', () => { + species.value = 'Lama glama'; + selectCategory('other'); + expect(species.value).toBe('Lama glama'); + }); + + it('preserves a custom species', () => { + selectCategory('turkey'); + species.value = 'Meleagris ocellata'; + selectCategory('chicken'); + expect(species.value).toBe('Meleagris ocellata'); + }); + + it('fills a species that has been cleared', () => { + selectCategory('cat'); + species.value = ''; + selectCategory('dog'); + expect(species.value).toBe('Canis lupus familiaris'); + }); + }); + + describe('when editing an animal', () => { + beforeEach(() => { + document.querySelector('input[value="turkey"]').checked = true; + species.value = 'Meleagris ocellata'; + initDomesticatedAnimals(); + }); + + it('leaves the saved species unchanged on load', () => { + expect(species.value).toBe('Meleagris ocellata'); + }); + + it('preserves the saved custom species after changing category', () => { + selectCategory('chicken'); + expect(species.value).toBe('Meleagris ocellata'); + }); + }); + + describe('without an animal form', () => { + it('does not require the form fields', () => { + document.body.innerHTML = ''; + expect(() => initDomesticatedAnimals()).not.toThrow(); + }); + }); +}); diff --git a/app/models/domesticated_animal.rb b/app/models/domesticated_animal.rb index a8e8889e1a..bd396a2570 100644 --- a/app/models/domesticated_animal.rb +++ b/app/models/domesticated_animal.rb @@ -10,10 +10,19 @@ class DomesticatedAnimal < ApplicationRecord default_scope { joins(:owner).merge(Member.kept) } - enum :category, %w(dog cat chicken turkey guinea_pig).index_with(&:itself), validate: true + enum :category, %w( + dog cat chicken turkey duck goose guinea_pig sheep horse goat pig + rabbit donkey alpaca llama quail guinea_fowl pigeon ferret other + ).index_with(&:itself), validate: true enum :biological_sex, %w(female male intersex unknown).index_with(&:itself), prefix: true, validate: { allow_nil: true } + enum :alignment, %w( + lawful_good neutral_good chaotic_good + lawful_neutral true_neutral chaotic_neutral + lawful_evil neutral_evil chaotic_evil + ).index_with(&:itself), prefix: true, validate: { allow_nil: true } normalizes :biological_sex, with: ->(value) { value.presence } + normalizes :alignment, with: ->(value) { value.presence } validates :name, :species, presence: true validates :name, :species, :description, length: { maximum: 255 } validate :death_not_before_birth diff --git a/app/views/domesticated_animals/_form.html.haml b/app/views/domesticated_animals/_form.html.haml index 10f35ff5f6..2d9b711b12 100644 --- a/app/views/domesticated_animals/_form.html.haml +++ b/app/views/domesticated_animals/_form.html.haml @@ -1,16 +1,39 @@ = bootstrap_form_for(@domesticated_animal) do |f| + - if local_assigns[:dialog] + = hidden_field_tag :dialog, 'true' = f.alert_message t('domesticated_animals.form_errors') + %fieldset.mb-3 + %legend.form-label.fs-6= t('domesticated_animals.fields.category') + .d-flex.flex-wrap.gap-2 + - DomesticatedAnimal.categories.each_key do |category| + - id = "domesticated_animal_category_#{category}" + = radio_button_tag 'domesticated_animal[category]', category, @domesticated_animal.category == category, id: id, class: 'btn-check', required: true + - label = category == 'other' ? t('domesticated_animals.other_category_label') : t("domesticated_animals.categories.#{category}") + = label_tag id, label, class: 'btn btn-outline-primary' + - @domesticated_animal.errors.full_messages_for(:category).each do |message| + .invalid-feedback.d-block= message = f.text_field :name, required: true, maxlength: 255, label: t('domesticated_animals.fields.name') = f.text_field :species, required: true, maxlength: 255, label: t('domesticated_animals.fields.species') - - categories = DomesticatedAnimal.categories.keys.map { |key| [t("domesticated_animals.categories.#{key}"), key] } - = f.select :category, categories, - { include_blank: true, label: t('domesticated_animals.fields.category') }, required: true - = f.text_area :description, maxlength: 255, label: t('domesticated_animals.fields.description') + = f.text_area :description, maxlength: 255, label: t('domesticated_animals.fields.description'), placeholder: t('domesticated_animals.bio_placeholder') + %fieldset.mb-3.animal-alignment + %legend.form-label.fs-6= t('domesticated_animals.fields.alignment') + .row.row-cols-3.g-2.mb-2 + - DomesticatedAnimal.alignments.each_key do |alignment| + .col + - id = "domesticated_animal_alignment_#{alignment}" + = radio_button_tag 'domesticated_animal[alignment]', alignment, @domesticated_animal.alignment == alignment, id: id, class: 'btn-check' + = label_tag id, t("domesticated_animals.alignments.#{alignment}"), class: 'btn btn-outline-secondary w-100 h-100' + = radio_button_tag 'domesticated_animal[alignment]', '', @domesticated_animal.alignment.blank?, id: 'domesticated_animal_alignment_unrated', class: 'btn-check' + = label_tag 'domesticated_animal_alignment_unrated', t('domesticated_animals.alignment_unrated'), class: 'btn btn-outline-secondary btn-sm' + - @domesticated_animal.errors.full_messages_for(:alignment).each do |message| + .invalid-feedback.d-block= message = f.date_field :date_of_birth, label: t('domesticated_animals.fields.date_of_birth') - = f.date_field :date_of_death, label: t('domesticated_animals.fields.date_of_death') - sexes = DomesticatedAnimal.biological_sexes.keys.map { |key| [t("domesticated_animals.sexes.#{key}"), key] } = f.select :biological_sex, sexes, include_blank: true, label: t('domesticated_animals.fields.biological_sex') + %details.animal-advanced-options{ open: @domesticated_animal.date_of_death.present? || @domesticated_animal.errors[:date_of_death].any? } + %summary.mb-3= t('domesticated_animals.death_details') + = f.date_field :date_of_death, label: t('domesticated_animals.fields.date_of_death') .d-flex.justify-content-between.mt-3 - cancel_path = @domesticated_animal.persisted? ? @domesticated_animal : current_member - = link_to t('domesticated_animals.cancel'), cancel_path, class: 'btn btn-secondary' + = link_to t('domesticated_animals.cancel'), cancel_path, class: 'btn btn-secondary', data: { animal_dialog_cancel: local_assigns[:dialog] } = f.submit t('domesticated_animals.save'), class: 'btn btn-primary' diff --git a/app/views/domesticated_animals/_profile.html.haml b/app/views/domesticated_animals/_profile.html.haml index 8391a8bf8e..1313cb0c6b 100644 --- a/app/views/domesticated_animals/_profile.html.haml +++ b/app/views/domesticated_animals/_profile.html.haml @@ -5,8 +5,10 @@ .section-header %h2= t('domesticated_animals.title') - if can_add - = link_to t('domesticated_animals.add'), new_domesticated_animal_path, - class: 'btn btn-sm section-add' + - content_for :scripts do + = javascript_include_tag 'react_islands', defer: true + = react_component 'AnimalDialog', { url: new_domesticated_animal_path, label: t('domesticated_animals.add'), title: t('domesticated_animals.new_heading'), loading_label: t('domesticated_animals.loading'), error_label: t('domesticated_animals.save_error') } do + = link_to t('domesticated_animals.add'), new_domesticated_animal_path, class: 'btn btn-sm section-add' .row - animals.each do |animal| .col-sm-6.col-lg-4.mb-3 diff --git a/app/views/domesticated_animals/new.html.haml b/app/views/domesticated_animals/new.html.haml index 42e59238db..2578c88daf 100644 --- a/app/views/domesticated_animals/new.html.haml +++ b/app/views/domesticated_animals/new.html.haml @@ -1,3 +1,3 @@ -- content_for :title, t('domesticated_animals.add') -%h1= t('domesticated_animals.add') +- content_for :title, t('domesticated_animals.new_heading') +%h1= t('domesticated_animals.new_heading') = render 'form' diff --git a/app/views/domesticated_animals/show.html.haml b/app/views/domesticated_animals/show.html.haml index c108028c46..a20d8c2817 100644 --- a/app/views/domesticated_animals/show.html.haml +++ b/app/views/domesticated_animals/show.html.haml @@ -14,7 +14,7 @@ = link_to t('domesticated_animals.edit'), edit_domesticated_animal_path(animal), class: 'btn btn-sm section-add' %dl - - %i(species category biological_sex date_of_birth date_of_death).each do |field| + - %i(species category alignment biological_sex date_of_birth date_of_death).each do |field| - value = animal.public_send(field) - next if value.blank? @@ -22,6 +22,8 @@ %dd - if field == :category = t("domesticated_animals.categories.#{value}") + - elsif field == :alignment + = t("domesticated_animals.alignments.#{value}") - elsif field == :biological_sex = t("domesticated_animals.sexes.#{value}") - elsif value.is_a?(Date) @@ -37,9 +39,18 @@ = link_to t('domesticated_animals.add_photo'), new_photo_path_for(animal), class: 'btn btn-sm section-add', data: photo_dialog_data(animal) = render 'photos/gallery', photos: animal.photos, item: animal + %section#jobs + .section-header + %h2= t('domesticated_animals.jobs') + - if can?(:update, animal) && can?(:create, Job) + = link_to t('domesticated_animals.add_job'), + new_job_path(jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id), class: 'btn btn-sm section-add' + - if @jobs.any? + .index-cards + = render partial: 'jobs/card', collection: @jobs, as: :job + - else + %p.text-muted.mb-0= t('domesticated_animals.no_jobs') - if can?(:update, animal) - .d-flex.justify-content-between.mt-3 - = link_to t('domesticated_animals.add_job'), - new_job_path(jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id), class: 'btn btn-primary' + .d-flex.justify-content-end.mt-3 = button_to t('domesticated_animals.delete'), animal, method: :delete, class: 'btn btn-outline-danger', data: { confirm: t('domesticated_animals.confirm_delete') } diff --git a/config/locales/en.yml b/config/locales/en.yml index 6c1fd5f9fc..dce7102693 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -4,29 +4,64 @@ en: title: Animals singular: Animal add: Add an animal + new_heading: Add your loved or otherwise animal(s) edit: Edit animal save: Save animal cancel: Cancel delete: Delete animal confirm_delete: Delete this animal? Its jobs and posts will be kept without the link. form_errors: Please check the animal's details. + bio_placeholder: Tell us about them, what is their origin story? How do they patrol your garden? + death_details: Extras + other_category_label: Something even better than all of those + loading: Loading animal form… + save_error: Your animal could not be saved. Your details are still here. Please try again. + alignment_unrated: Not rated photos: Photos add_photo: Add a photo add_job: Plan a job for this animal + jobs: Jobs + no_jobs: No jobs planned for this animal yet. fields: name: Name species: Species category: Category - description: Description + description: Bio date_of_birth: Date of birth date_of_death: Date of death biological_sex: Biological sex + alignment: Alignment + alignments: + lawful_good: Lawful Good + neutral_good: Neutral Good + chaotic_good: Chaotic Good + lawful_neutral: Lawful Neutral + true_neutral: True Neutral + chaotic_neutral: Chaotic Neutral + lawful_evil: Lawful Evil + neutral_evil: Neutral Evil + chaotic_evil: Chaotic Evil categories: dog: Dog cat: Cat chicken: Chicken turkey: Turkey + duck: Duck + goose: Goose guinea_pig: Guinea pig + sheep: Sheep + horse: Horse + goat: Goat + pig: Pig + rabbit: Rabbit + donkey: Donkey + alpaca: Alpaca + llama: Llama + quail: Quail + guinea_fowl: Guinea fowl + pigeon: Pigeon + ferret: Ferret + other: Other sexes: female: Female male: Male diff --git a/db/migrate/20261127000100_add_alignment_to_domesticated_animals.rb b/db/migrate/20261127000100_add_alignment_to_domesticated_animals.rb new file mode 100644 index 0000000000..08478c4d83 --- /dev/null +++ b/db/migrate/20261127000100_add_alignment_to_domesticated_animals.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +class AddAlignmentToDomesticatedAnimals < ActiveRecord::Migration[8.1] + def change + add_column :domesticated_animals, :alignment, :string + end +end diff --git a/db/schema.rb b/db/schema.rb index 58b98a6688..7c4e8a5470 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2026_11_27_000000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_27_000100) do # These are extensions that must be enabled in order to support this database enable_extension "pg_catalog.plpgsql" enable_extension "pg_trgm" @@ -693,6 +693,7 @@ t.bigint "owner_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.string "alignment" t.index ["owner_id"], name: "index_domesticated_animals_on_owner_id" end diff --git a/spec/features/domesticated_animals_spec.rb b/spec/features/domesticated_animals_spec.rb new file mode 100644 index 0000000000..611fb239de --- /dev/null +++ b/spec/features/domesticated_animals_spec.rb @@ -0,0 +1,124 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe 'Animal form' do + include_context 'signed in member' + + before { Feature.find(:domesticated_animals).enable_member(member) } + + context 'when adding an animal from the member profile' do + before do + visit member_path(member) + within('#domesticated-animals') { click_link I18n.t('domesticated_animals.add') } + end + + it 'opens the form in a dialog' do + within('[role="dialog"]') do + expect(page).to have_field('domesticated_animal_name') + end + end + + it 'prefills a species in the dialog' do + within('[role="dialog"]') do + choose I18n.t('domesticated_animals.categories.rabbit'), allow_label_click: true + expect(page).to have_field('domesticated_animal_species', with: 'Oryctolagus cuniculus domesticus') + end + end + + it 'closes the dialog when cancelled' do + within('[role="dialog"]') { click_link I18n.t('domesticated_animals.cancel') } + expect(page).to have_no_css('[role="dialog"]') + end + + it 'creates the animal from the dialog' do + within('[role="dialog"]') do + choose I18n.t('domesticated_animals.categories.rabbit'), allow_label_click: true + fill_in 'domesticated_animal_name', with: 'Clover' + choose I18n.t('domesticated_animals.alignments.chaotic_good'), allow_label_click: true + click_button I18n.t('domesticated_animals.save') + end + expect(page).to have_css('.record-page h1', text: 'Clover') + end + + it 'keeps invalid details in the dialog for correction' do + within('[role="dialog"]') do + choose I18n.t('domesticated_animals.categories.rabbit'), allow_label_click: true + fill_in 'domesticated_animal_name', with: 'Clover' + fill_in 'domesticated_animal_date_of_birth', with: '2020-02-01' + find('.animal-advanced-options summary').click + fill_in 'domesticated_animal_date_of_death', with: '2020-01-01' + click_button I18n.t('domesticated_animals.save') + expect(page).to have_css('.invalid-feedback') + end + end + end + + context 'when adding an animal' do + before { visit new_domesticated_animal_path } + + it 'asks for the category first' do + within('#new_domesticated_animal') do + expect(first('select, input:not([type="hidden"])', visible: :all)[:name]).to eq 'domesticated_animal[category]' + end + end + + it 'prefills the species from the selected category' do + choose I18n.t('domesticated_animals.categories.chicken'), allow_label_click: true + expect(page).to have_field('domesticated_animal_species', with: 'Gallus gallus domesticus') + end + + it 'updates the suggested species when another category is chosen' do + choose I18n.t('domesticated_animals.categories.chicken'), allow_label_click: true + choose I18n.t('domesticated_animals.categories.cat'), allow_label_click: true + expect(page).to have_field('domesticated_animal_species', with: 'Felis catus') + end + + it 'allows another kind of animal without a suggested species' do + choose I18n.t('domesticated_animals.categories.horse'), allow_label_click: true + choose I18n.t('domesticated_animals.other_category_label'), allow_label_click: true + expect(page).to have_field('domesticated_animal_species', with: '') + end + + it 'offers a bio with a prompt' do + expect(page).to have_field(I18n.t('domesticated_animals.fields.description'), + placeholder: I18n.t('domesticated_animals.bio_placeholder')) + end + + it 'leaves the alignment unrated initially' do + expect(page).to have_checked_field('domesticated_animal_alignment_unrated', visible: :all) + end + + it 'hides the date of death initially' do + expect(page).to have_no_field('domesticated_animal_date_of_death') + end + + it 'reveals the date of death when expanded' do + find('.animal-advanced-options summary').click + expect(page).to have_field('domesticated_animal_date_of_death') + end + end + + context 'when editing an animal with a date of death' do + let(:animal) { create(:domesticated_animal, owner: member, date_of_death: Date.new(2020, 1, 1)) } + + it 'shows the saved date of death' do + visit edit_domesticated_animal_path(animal) + expect(page).to have_field('domesticated_animal_date_of_death', with: '2020-01-01') + end + + it 'selects the saved category' do + visit edit_domesticated_animal_path(animal) + expect(page).to have_checked_field('domesticated_animal_category_chicken', visible: :all) + end + end + + context 'when editing an animal with an alignment' do + let(:animal) { create(:domesticated_animal, owner: member, alignment: 'chaotic_neutral') } + + it 'selects the saved alignment' do + visit edit_domesticated_animal_path(animal) + expect(page).to have_checked_field('domesticated_animal_alignment_chaotic_neutral', visible: :all) + end + end +end diff --git a/spec/features/posts/posting_a_post_spec.rb b/spec/features/posts/posting_a_post_spec.rb index 34919443af..212ee2ef69 100644 --- a/spec/features/posts/posting_a_post_spec.rb +++ b/spec/features/posts/posting_a_post_spec.rb @@ -40,8 +40,11 @@ it "links the chosen crop" do find("[role=option]", text: "pumpkin").click + find_field('post[body]', type: :hidden, with: "I love [#{crop.name}](crop)", visible: false) click_button "Publish post" - expect(page).to have_link "pumpkin", href: crop_path(crop) + within('.post-content') do + expect(page).to have_link crop.name, href: crop_path(crop) + end end end diff --git a/spec/models/domesticated_animal_spec.rb b/spec/models/domesticated_animal_spec.rb index df5e6b3c38..263dccbd4d 100644 --- a/spec/models/domesticated_animal_spec.rb +++ b/spec/models/domesticated_animal_spec.rb @@ -21,9 +21,11 @@ expect(animal).not_to be_valid end - it 'accepts guinea pigs' do - animal.category = 'guinea_pig' - expect(animal).to be_valid + %w(guinea_pig sheep horse goat duck goose pig rabbit donkey alpaca llama quail guinea_fowl pigeon ferret other).each do |category| + it "accepts the #{category} category" do + animal.category = category + expect(animal).to be_valid + end end it 'allows an unspecified biological sex' do @@ -31,6 +33,23 @@ expect(animal).to be_valid end + described_class.alignments.each_key do |alignment| + it "accepts the #{alignment} alignment" do + animal.alignment = alignment + expect(animal).to be_valid + end + end + + it 'allows an unrated alignment' do + animal.alignment = '' + expect(animal).to be_valid + end + + it 'rejects an unsupported alignment' do + animal.alignment = 'chaos_demon' + expect(animal).not_to be_valid + end + it 'rejects an unsupported biological sex' do animal.biological_sex = 'invalid' expect(animal).not_to be_valid diff --git a/spec/requests/domesticated_animals_controller_spec.rb b/spec/requests/domesticated_animals_controller_spec.rb index da541da821..9e97fc804e 100644 --- a/spec/requests/domesticated_animals_controller_spec.rb +++ b/spec/requests/domesticated_animals_controller_spec.rb @@ -54,6 +54,16 @@ expect(response).to have_http_status(:ok) end + it 'provides the form without a page layout for the dialog' do + get new_domesticated_animal_path, params: { dialog: 'true' } + expect(Capybara.string(response.body)).to have_css('form#new_domesticated_animal input[name="dialog"][value="true"]', visible: :all) + end + + it 'keeps validation errors in the dialog form' do + post domesticated_animals_path, params: { dialog: 'true', domesticated_animal: attributes.merge(name: '') } + expect(Capybara.string(response.body)).to have_css('form#new_domesticated_animal .invalid-feedback') + end + it 'creates an animal owned by the signed-in member' do post domesticated_animals_path, params: { domesticated_animal: attributes.merge(owner_id: create(:member).id) } expect(member.domesticated_animals.pluck(:name)).to eq ['Henrietta'] @@ -64,6 +74,54 @@ expect(response).to have_http_status(:ok) end + it 'shows an empty jobs section without related jobs' do + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_css('#jobs p.text-muted') + end + + context 'with jobs linked to the animal' do + let(:job) { create(:job, owner: member, jobbable: animal, name: 'Feed Henrietta') } + + it 'shows the related job' do + job + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_css('#jobs .job', text: job.name) + end + + it 'includes completed jobs' do + job.update!(finished: true) + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_css('#jobs .card-finished', text: job.name) + end + + it 'excludes jobs for other animals' do + other_animal = create(:domesticated_animal, owner: member) + other_job = create(:job, owner: member, jobbable: other_animal, name: 'Walk Fido') + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_no_css('#jobs .job', text: other_job.name) + end + + it 'excludes unlinked jobs' do + other_job = create(:job, owner: member, name: 'Water the garden') + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_no_css('#jobs .job', text: other_job.name) + end + + it 'offers a job form linked to the animal' do + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_link( + href: new_job_path(jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id) + ) + end + + it 'orders dated jobs before undated jobs' do + job.update!(due_date: nil) + earlier_job = create(:job, owner: member, jobbable: animal, name: 'Check water', due_date: Date.new(2026, 1, 1)) + get domesticated_animal_path(animal) + expect(Capybara.string(response.body).all('#jobs .job h4').map(&:text)).to eq [earlier_job.name, job.name] + end + end + it 'shows the edit form' do get edit_domesticated_animal_path(animal) expect(response).to have_http_status(:ok) @@ -74,6 +132,28 @@ expect(animal.reload.name).to eq 'Henny' end + it 'saves an alignment when creating an animal' do + post domesticated_animals_path, params: { domesticated_animal: attributes.merge(alignment: 'chaotic_good') } + expect(member.domesticated_animals.last.alignment).to eq 'chaotic_good' + end + + it 'updates the alignment' do + patch domesticated_animal_path(animal), params: { domesticated_animal: { alignment: 'lawful_evil' } } + expect(animal.reload.alignment).to eq 'lawful_evil' + end + + it 'clears an alignment' do + animal.update!(alignment: 'chaotic_evil') + patch domesticated_animal_path(animal), params: { domesticated_animal: { alignment: '' } } + expect(animal.reload.alignment).to be_nil + end + + it 'shows the saved alignment' do + animal.update!(alignment: 'true_neutral') + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_css('dd', text: I18n.t('domesticated_animals.alignments.true_neutral')) + end + it 'renders validation errors' do post domesticated_animals_path, params: { domesticated_animal: attributes.merge(name: '') } expect(response).to have_http_status(:unprocessable_content) @@ -161,5 +241,18 @@ get domesticated_animal_path(animal) expect(response).to have_http_status(:ok) end + + it 'shows related jobs to visitors' do + job = create(:job, owner: member, jobbable: animal) + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_css('#jobs .job', text: job.name) + end + + it 'does not offer visitors the add job link' do + get domesticated_animal_path(animal) + expect(Capybara.string(response.body)).to have_no_link( + href: new_job_path(jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id) + ) + end end end From d4f0aeaaa36f2e32e1fc8c422f24481958dd20af Mon Sep 17 00:00:00 2001 From: Daniel O'Connor Date: Fri, 27 Nov 2026 22:32:02 +1030 Subject: [PATCH 3/5] Delete app/javascript/print_label.test.js --- app/javascript/print_label.test.js | 69 ------------------------------ 1 file changed, 69 deletions(-) delete mode 100644 app/javascript/print_label.test.js diff --git a/app/javascript/print_label.test.js b/app/javascript/print_label.test.js deleted file mode 100644 index 618f7fc58c..0000000000 --- a/app/javascript/print_label.test.js +++ /dev/null @@ -1,69 +0,0 @@ -import {fireEvent, waitFor} from '@testing-library/dom'; -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import {createLabel, createLabelImage} from './site/label_pdf'; -import './print_label'; - -vi.mock('./site/label_pdf', () => ({createLabel: vi.fn(), createLabelImage: vi.fn()})); - -describe('inline label preview', () => { - let form; - let preview; - let save; - - beforeEach(() => { - Object.defineProperty(document, 'fonts', {configurable: true, value: {ready: Promise.resolve()}}); - createLabelImage.mockReturnValue('data:image/png;base64,preview'); - save = vi.fn(); - createLabel.mockReturnValue({save}); - document.body.innerHTML = ` -
- - - - -
`; - form = document.querySelector('form'); - preview = form.querySelector('img'); - document.dispatchEvent(new Event('DOMContentLoaded')); - }); - - afterEach(() => { - document.body.innerHTML = ''; - delete document.fonts; - vi.resetAllMocks(); - }); - - it('shows a PNG preview on page load', async () => { - await waitFor(() => expect(preview).toBeVisible()); - }); - - it('passes the planting code to the preview renderer', async () => { - await waitFor(() => expect(createLabelImage).toHaveBeenCalledWith(expect.objectContaining({shortCode: 'AB23'}))); - }); - - it('updates the preview when dimensions change', async () => { - form.elements.width.value = '60'; - fireEvent.change(form.elements.width); - await waitFor(() => expect(createLabelImage).toHaveBeenLastCalledWith(expect.objectContaining({width: 60}))); - }); - - it('hides a stale preview when dimensions are unreadable', async () => { - await waitFor(() => expect(preview).toBeVisible()); - createLabelImage.mockImplementation(() => { throw new RangeError(); }); - fireEvent.change(form.elements.width); - await waitFor(() => expect(preview).not.toBeVisible()); - }); - - it('explains when dimensions are unreadable', async () => { - createLabelImage.mockImplementation(() => { throw new RangeError(); }); - fireEvent.change(form.elements.width); - await waitFor(() => expect(form.querySelector('[role="alert"]')).toHaveTextContent(form.dataset.sizeError)); - }); - - it('keeps PDF downloads available', async () => { - fireEvent.submit(form); - await waitFor(() => expect(save).toHaveBeenCalledWith('label.pdf')); - }); -}); From 9717603453e15cb098676b09c058439099ffcb4c Mon Sep 17 00:00:00 2001 From: Daniel O'Connor Date: Fri, 27 Nov 2026 08:21:02 +0000 Subject: [PATCH 4/5] Jobs on animals --- .../domesticated_animals_controller.rb | 3 +- app/controllers/jobs_controller.rb | 11 +++++- app/javascript/site/job_notepad.js | 10 +++-- app/javascript/site/job_notepad.test.js | 37 +++++++++++++++++++ app/services/jobs_notepad.rb | 11 ++++-- app/views/domesticated_animals/show.html.haml | 17 ++++----- app/views/jobs/_notepad.html.haml | 24 +++++++----- app/views/jobs/_notepad_groups.html.haml | 2 +- app/views/jobs/_notepad_row.html.haml | 2 +- config/locales/en.yml | 4 +- spec/features/domesticated_animals_spec.rb | 37 +++++++++++++++++++ .../domesticated_animals_controller_spec.rb | 26 ++++++------- spec/requests/jobs_controller_create_spec.rb | 23 ++++++++++++ spec/requests/jobs_controller_update_spec.rb | 23 ++++++++++++ spec/services/jobs_notepad_spec.rb | 23 +++++++++++- 15 files changed, 204 insertions(+), 49 deletions(-) diff --git a/app/controllers/domesticated_animals_controller.rb b/app/controllers/domesticated_animals_controller.rb index cf8a12550e..91ae463095 100644 --- a/app/controllers/domesticated_animals_controller.rb +++ b/app/controllers/domesticated_animals_controller.rb @@ -11,8 +11,7 @@ class DomesticatedAnimalsController < ApplicationController responders :flash def show - @jobs = @domesticated_animal.jobs.accessible_by(current_ability) - .preload(:owner, :garden, :jobbable).order(:due_date, :id) + @notepad = JobsNotepad.new(current_member, animal: @domesticated_animal) respond_with @domesticated_animal end diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb index 5b8c1f53b9..edeb22517f 100644 --- a/app/controllers/jobs_controller.rb +++ b/app/controllers/jobs_controller.rb @@ -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 diff --git a/app/javascript/site/job_notepad.js b/app/javascript/site/job_notepad.js index 2b4d79c073..49e5ee7ecb 100644 --- a/app/javascript/site/job_notepad.js +++ b/app/javascript/site/job_notepad.js @@ -57,6 +57,7 @@ document.addEventListener('DOMContentLoaded', function () { if (body) { kept.forEach(function (id) { body.append('keep[]', id); }); if (groups.dataset.gardenId) body.append('garden_id', groups.dataset.gardenId); + if (groups.dataset.animalId) body.append('animal_id', groups.dataset.animalId); } return fetch(url, { method: body ? 'POST' : 'GET', @@ -105,6 +106,7 @@ document.addEventListener('DOMContentLoaded', function () { kept.clear(); const url = new URL(hideDoneButton.dataset.url, window.location.origin); if (groups.dataset.gardenId) url.searchParams.set('garden_id', groups.dataset.gardenId); + if (groups.dataset.animalId) url.searchParams.set('animal_id', groups.dataset.animalId); send(url.toString(), null).catch(reload); }); @@ -279,11 +281,13 @@ document.addEventListener('DOMContentLoaded', function () { const link = document.getElementById('notepad-link'); const typeField = document.getElementById('notepad-jobbable-type'); const idField = document.getElementById('notepad-jobbable-id'); + const defaultType = typeField.value; + const defaultId = idField.value; let adding = false; const clearLink = function () { - typeField.value = ''; - idField.value = ''; + typeField.value = defaultType; + idField.value = defaultId; link.hidden = true; }; @@ -541,7 +545,7 @@ document.addEventListener('DOMContentLoaded', function () { }; // Linking a job being added: the link is shown in a chip, until it is added. - suggestions(input, document.getElementById('notepad-suggestions'), function (item) { + if (!groups.dataset.animalId) suggestions(input, document.getElementById('notepad-suggestions'), function (item) { typeField.value = item.jobbable_type; idField.value = item.jobbable_id; link.querySelector('.notepad-link-text').textContent = kinds[kindOf(item)] + ': ' + item.label; diff --git a/app/javascript/site/job_notepad.test.js b/app/javascript/site/job_notepad.test.js index b7ee0a419e..59186504ae 100644 --- a/app/javascript/site/job_notepad.test.js +++ b/app/javascript/site/job_notepad.test.js @@ -162,6 +162,43 @@ describe('a notepad on a garden\'s page', () => { }); }); +describe('a notepad on an animal page', () => { + beforeEach(() => { + document.getElementById('notepad-groups').dataset.animalId = '9'; + document.getElementById('notepad-jobbable-type').value = 'DomesticatedAnimal'; + document.getElementById('notepad-jobbable-id').value = '9'; + }); + + it('keeps mutations scoped to the animal', async () => { + fetchMock.mockResolvedValue(answer()); + await start(); + submit(document.querySelector('.notepad-tick')); + await flush(); + expect(fetchMock.mock.calls[0][1].body.get('animal_id')).toBe('9'); + }); + + it('retains the animal link for the next quick-added job', async () => { + fetchMock.mockResolvedValue(answer()); + await start(); + const form = document.querySelector('.notepad-add'); + form.querySelector('input[type="text"]').value = 'Feed Clover'; + submit(form); + await flush(); + form.querySelector('input[type="text"]').value = 'Check water'; + submit(form); + await flush(); + expect(fetchMock.mock.calls[1][1].body.get('job[jobbable_id]')).toBe('9'); + }); + + it('keeps the animal scope when hiding completed jobs', async () => { + fetchMock.mockResolvedValue(answer()); + await start(); + document.getElementById('notepad-hide-done').click(); + await flush(); + expect(fetchMock.mock.calls[0][0]).toContain('animal_id=9'); + }); +}); + describe('adding a job', () => { const type = (text) => { document.querySelector('.notepad-add input[type="text"]').value = text; diff --git a/app/services/jobs_notepad.rb b/app/services/jobs_notepad.rb index a91a36522c..fd248efa2e 100644 --- a/app/services/jobs_notepad.rb +++ b/app/services/jobs_notepad.rb @@ -1,12 +1,13 @@ # frozen_string_literal: true # A member's jobs, ready to show as a notepad: on their jobs page, or, with a -# garden, just their jobs for that garden, on the garden's page. With no member, -# a garden's jobs from everyone, for a visitor who is only looking. +# garden or animal, just the jobs for it. With no member, the scoped jobs are +# shown to a visitor who is only looking. class JobsNotepad - def initialize(member, garden: nil, pinned: []) + def initialize(member, garden: nil, animal: nil, pinned: []) @member = member @garden = garden + @animal = animal @pinned = pinned end @@ -29,7 +30,9 @@ def jobs end def scope - if @garden + if @animal + @animal.jobs + elsif @garden Job.for_garden(@garden) elsif @member Job.for_member(@member) diff --git a/app/views/domesticated_animals/show.html.haml b/app/views/domesticated_animals/show.html.haml index a20d8c2817..ad6c9967a9 100644 --- a/app/views/domesticated_animals/show.html.haml +++ b/app/views/domesticated_animals/show.html.haml @@ -40,16 +40,15 @@ class: 'btn btn-sm section-add', data: photo_dialog_data(animal) = render 'photos/gallery', photos: animal.photos, item: animal %section#jobs - .section-header - %h2= t('domesticated_animals.jobs') + .garden-notepad - if can?(:update, animal) && can?(:create, Job) - = link_to t('domesticated_animals.add_job'), - new_job_path(jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id), class: 'btn btn-sm section-add' - - if @jobs.any? - .index-cards - = render partial: 'jobs/card', collection: @jobs, as: :job - - else - %p.text-muted.mb-0= t('domesticated_animals.no_jobs') + = render 'jobs/notepad', owner: current_member, animal: animal, groups: @notepad.groups, autofocus: false + - else + .notepad + .notepad-title + %h2= t('domesticated_animals.jobs_title', animal: animal.name) + %span.badge.text-bg-light.garden-jobs-public{ title: t('jobs.pad.public_note') }= t('gardens.jobs_section.public') + = render 'jobs/notepad_groups', groups: @notepad.groups, in_animal: true, readonly: true - if can?(:update, animal) .d-flex.justify-content-end.mt-3 = button_to t('domesticated_animals.delete'), animal, method: :delete, diff --git a/app/views/jobs/_notepad.html.haml b/app/views/jobs/_notepad.html.haml index 4d4799ccce..65ea0b6e5c 100644 --- a/app/views/jobs/_notepad.html.haml +++ b/app/views/jobs/_notepad.html.haml @@ -1,11 +1,15 @@ -# A member's own jobs as a notepad: grouped by when, with what each is about. -# Crossed off jobs stay where they are, ticked. With a garden, it is the jobs for --# that garden, on the garden's page. +-# that garden, on the garden's page. An animal embeds the same notepad with +-# quick-added jobs linked to the animal instead. - garden = local_assigns[:garden] +- animal = local_assigns[:animal] +- embedded = garden || animal +- heading = animal ? t('domesticated_animals.jobs_title', animal: animal.name) : (garden ? t('jobs.pad.garden_title') : t('jobs.pad.title', owner: owner.login_name)) .notepad .notepad-title - = content_tag(garden ? :h2 : :h1, garden ? t('jobs.pad.garden_title') : t('jobs.pad.title', owner: owner.login_name)) - - if garden + = content_tag(embedded ? :h2 : :h1, heading) + - if embedded = link_to t('jobs.pad.all_jobs'), member_jobs_path(owner), class: 'notepad-all-jobs' = form_with url: jobs_path, scope: :job, class: 'notepad-add', data: { suggestions_url: job_suggestions_path, kinds: { planting: t('jobs.pad.planting'), seed: t('jobs.pad.seeds'), crop: t('jobs.pad.crop'), domesticatedanimal: t('domesticated_animals.singular') }.to_json } do |f| %span.notepad-add-plus{ 'aria-hidden': 'true' } + @@ -14,8 +18,8 @@ -# The script sends the job without reloading, so the button must not stay disabled. = f.submit t('jobs.pad.add_button'), class: 'btn btn-primary notepad-add-button', data: { disable_with: false, saving_label: t('jobs.pad.adding_button') } = f.hidden_field :garden_id, value: garden.id if garden - = f.hidden_field :jobbable_type, id: 'notepad-jobbable-type' - = f.hidden_field :jobbable_id, id: 'notepad-jobbable-id' + = f.hidden_field :jobbable_type, id: 'notepad-jobbable-type', value: (animal ? 'DomesticatedAnimal' : nil) + = f.hidden_field :jobbable_id, id: 'notepad-jobbable-id', value: animal&.id %ul.notepad-suggestions{ id: 'notepad-suggestions', role: 'listbox', 'aria-label': t('jobs.pad.link_hint'), hidden: true } .notepad-link{ id: 'notepad-link', hidden: true } %span.notepad-link-text @@ -24,13 +28,13 @@ %span.notepad-spinner{ 'aria-hidden': 'true' } %span.notepad-add-saving-text %p.notepad-add-failed.text-danger.mx-3{ id: 'notepad-add-failed', role: 'alert', hidden: true }= t('jobs.pad.add_failed') - %p.notepad-note= t('jobs.pad.public_note') + ' ' + t('jobs.pad.link_hint') - = render 'jobs/ideas', owner: owner unless garden || !local_assigns.fetch(:ideas_banner, true) + %p.notepad-note= t('jobs.pad.public_note') + ' ' + (animal ? t('domesticated_animals.jobs_note', animal: animal.name) : t('jobs.pad.link_hint')) + = render 'jobs/ideas', owner: owner unless embedded || !local_assigns.fetch(:ideas_banner, true) %button.btn.btn-sm.btn-outline-secondary.notepad-hide-done{ id: 'notepad-hide-done', type: 'button', hidden: true, data: { url: member_jobs_path(owner) } }= t('jobs.pad.hide_done') - #notepad-groups{ data: { celebrations: job_celebrations.to_json, garden_id: garden&.id } }= render 'jobs/notepad_groups', groups:, in_garden: garden.present? - -# The snail keeps the jobs pages company; on a garden's page the list is just the list. - - unless garden + #notepad-groups{ data: { celebrations: job_celebrations.to_json, garden_id: garden&.id, animal_id: animal&.id } }= render 'jobs/notepad_groups', groups:, in_garden: garden.present?, in_animal: animal.present? + -# The snail keeps the jobs pages company; an embedded list is just the list. + - unless embedded .notepad-snail .notepad-snail-track{ 'aria-hidden': 'true' } %span.notepad-snail-trail diff --git a/app/views/jobs/_notepad_groups.html.haml b/app/views/jobs/_notepad_groups.html.haml index 51e38635db..c70d3569c5 100644 --- a/app/views/jobs/_notepad_groups.html.haml +++ b/app/views/jobs/_notepad_groups.html.haml @@ -17,7 +17,7 @@ - if group.jobs.empty? %p.notepad-drop-hint= t('jobs.pad.drop_here') -# Later is rolled up until asked for: it is not for today's list. - - row_for = ->(job) { render 'jobs/notepad_row', job:, in_garden: local_assigns[:in_garden], readonly: } + - row_for = ->(job) { render 'jobs/notepad_row', job:, in_garden: local_assigns[:in_garden], in_animal: local_assigns[:in_animal], readonly: } - if group.key == :later && group.jobs.any? %details.notepad-older %summary= t('jobs.pad.show_later', count: group.jobs.size) diff --git a/app/views/jobs/_notepad_row.html.haml b/app/views/jobs/_notepad_row.html.haml index 334b322625..fcd7f1f566 100644 --- a/app/views/jobs/_notepad_row.html.haml +++ b/app/views/jobs/_notepad_row.html.haml @@ -14,7 +14,7 @@ = job.garden.name - case job.jobbable - when DomesticatedAnimal - - if domesticated_animals_enabled? + - if domesticated_animals_enabled? && !local_assigns[:in_animal] = link_to job.jobbable, class: 'notepad-chip' do %span.kind= t('domesticated_animals.singular') = job.jobbable.name diff --git a/config/locales/en.yml b/config/locales/en.yml index dce7102693..bbbdcb31da 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -20,8 +20,8 @@ en: photos: Photos add_photo: Add a photo add_job: Plan a job for this animal - jobs: Jobs - no_jobs: No jobs planned for this animal yet. + jobs_title: Jobs for %{animal} + jobs_note: Jobs added here are linked to %{animal}. fields: name: Name species: Species diff --git a/spec/features/domesticated_animals_spec.rb b/spec/features/domesticated_animals_spec.rb index 611fb239de..3ec51de83a 100644 --- a/spec/features/domesticated_animals_spec.rb +++ b/spec/features/domesticated_animals_spec.rb @@ -7,6 +7,43 @@ before { Feature.find(:domesticated_animals).enable_member(member) } + context 'when managing an animal\'s jobs' do + let(:animal) { create(:domesticated_animal, owner: member) } + + before do + create(:job, owner: member, jobbable: animal, name: 'Feed Clover', due_date: Time.zone.today) + create(:job, owner: member, name: 'Unrelated job') + visit domesticated_animal_path(animal) + end + + it 'uses the garden notepad layout' do + expect(page).to have_css('#jobs .garden-notepad .notepad .notepad-group-today', text: 'Feed Clover') + end + + it 'crosses off a job in place' do + click_button I18n.t('jobs.pad.cross_off', job: 'Feed Clover') + expect(page).to have_css('#jobs .notepad-job.done', text: 'Feed Clover') + end + + it 'keeps unrelated jobs out after changing a job' do + click_button I18n.t('jobs.pad.cross_off', job: 'Feed Clover') + find('#jobs .notepad-job.done', text: 'Feed Clover') + expect(page).to have_no_css('#jobs .notepad-name', text: 'Unrelated job') + end + + it 'links each quick-added job to the animal' do + within('#jobs') do + fill_in I18n.t('jobs.pad.add'), with: 'Check water' + click_button I18n.t('jobs.pad.add_button') + find('.notepad-name', text: 'Check water') + fill_in I18n.t('jobs.pad.add'), with: 'Clean shelter' + click_button I18n.t('jobs.pad.add_button') + find('.notepad-name', text: 'Clean shelter') + end + expect(animal.jobs.where(name: ['Check water', 'Clean shelter']).count).to eq 2 + end + end + context 'when adding an animal from the member profile' do before do visit member_path(member) diff --git a/spec/requests/domesticated_animals_controller_spec.rb b/spec/requests/domesticated_animals_controller_spec.rb index 9e97fc804e..6e552cfec2 100644 --- a/spec/requests/domesticated_animals_controller_spec.rb +++ b/spec/requests/domesticated_animals_controller_spec.rb @@ -76,7 +76,7 @@ it 'shows an empty jobs section without related jobs' do get domesticated_animal_path(animal) - expect(Capybara.string(response.body)).to have_css('#jobs p.text-muted') + expect(Capybara.string(response.body)).to have_css('#jobs .notepad .notepad-drop-hint') end context 'with jobs linked to the animal' do @@ -85,32 +85,32 @@ it 'shows the related job' do job get domesticated_animal_path(animal) - expect(Capybara.string(response.body)).to have_css('#jobs .job', text: job.name) + expect(Capybara.string(response.body)).to have_css('#jobs .notepad-job', text: job.name) end it 'includes completed jobs' do job.update!(finished: true) get domesticated_animal_path(animal) - expect(Capybara.string(response.body)).to have_css('#jobs .card-finished', text: job.name) + expect(Capybara.string(response.body)).to have_css('#jobs .notepad-job.done', text: job.name) end it 'excludes jobs for other animals' do other_animal = create(:domesticated_animal, owner: member) other_job = create(:job, owner: member, jobbable: other_animal, name: 'Walk Fido') get domesticated_animal_path(animal) - expect(Capybara.string(response.body)).to have_no_css('#jobs .job', text: other_job.name) + expect(Capybara.string(response.body)).to have_no_css('#jobs .notepad-job', text: other_job.name) end it 'excludes unlinked jobs' do other_job = create(:job, owner: member, name: 'Water the garden') get domesticated_animal_path(animal) - expect(Capybara.string(response.body)).to have_no_css('#jobs .job', text: other_job.name) + expect(Capybara.string(response.body)).to have_no_css('#jobs .notepad-job', text: other_job.name) end - it 'offers a job form linked to the animal' do + it 'prefills the shared notepad form with the animal' do get domesticated_animal_path(animal) - expect(Capybara.string(response.body)).to have_link( - href: new_job_path(jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id) + expect(Capybara.string(response.body)).to have_css( + "#jobs .notepad-add input[name='job[jobbable_id]'][value='#{animal.id}']", visible: :all ) end @@ -118,7 +118,7 @@ job.update!(due_date: nil) earlier_job = create(:job, owner: member, jobbable: animal, name: 'Check water', due_date: Date.new(2026, 1, 1)) get domesticated_animal_path(animal) - expect(Capybara.string(response.body).all('#jobs .job h4').map(&:text)).to eq [earlier_job.name, job.name] + expect(Capybara.string(response.body).all('#jobs .notepad-name').map(&:text)).to eq [earlier_job.name, job.name] end end @@ -245,14 +245,12 @@ it 'shows related jobs to visitors' do job = create(:job, owner: member, jobbable: animal) get domesticated_animal_path(animal) - expect(Capybara.string(response.body)).to have_css('#jobs .job', text: job.name) + expect(Capybara.string(response.body)).to have_css('#jobs .notepad-job', text: job.name) end - it 'does not offer visitors the add job link' do + it 'does not offer visitors the add job form' do get domesticated_animal_path(animal) - expect(Capybara.string(response.body)).to have_no_link( - href: new_job_path(jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id) - ) + expect(Capybara.string(response.body)).to have_no_css('#jobs .notepad-add') end end end diff --git a/spec/requests/jobs_controller_create_spec.rb b/spec/requests/jobs_controller_create_spec.rb index f922454bd6..0fee914d08 100644 --- a/spec/requests/jobs_controller_create_spec.rb +++ b/spec/requests/jobs_controller_create_spec.rb @@ -71,6 +71,29 @@ end end + context 'when adding from an animal\'s notepad', flipper: :domesticated_animals do + let(:animal) { create(:domesticated_animal, owner: member) } + + before do + create(:job, owner: member, name: 'Elsewhere') + post jobs_path, params: { + job: { name: 'Feed the hens', jobbable_type: 'DomesticatedAnimal', jobbable_id: animal.id }, animal_id: animal.id + }, headers: + end + + it 'links the new job to the animal' do + expect(member.jobs.find_by!(name: 'Feed the hens').jobbable).to eq animal + end + + it 'returns the animal job in the shared notepad rows' do + expect(Capybara.string(response.body)).to have_css('.notepad-name', text: 'Feed the hens') + end + + it 'leaves unrelated jobs out of the response' do + expect(Capybara.string(response.body)).to have_no_css('.notepad-name', text: 'Elsewhere') + end + end + context 'with the link left empty, as the notepad sends it' do before { post jobs_path, params: { job: { name: 'Sow the peas', jobbable_type: '', jobbable_id: '' } }, headers: } diff --git a/spec/requests/jobs_controller_update_spec.rb b/spec/requests/jobs_controller_update_spec.rb index 0f5183ac87..4129dc20e1 100644 --- a/spec/requests/jobs_controller_update_spec.rb +++ b/spec/requests/jobs_controller_update_spec.rb @@ -95,6 +95,29 @@ end end + context 'when changing a job on an animal\'s notepad', flipper: :domesticated_animals do + let(:animal) { create(:domesticated_animal, owner: member) } + let(:job) { create(:job, owner: member, jobbable: animal) } + + it 'keeps the response scoped to that animal' do + create(:job, owner: member, name: 'Elsewhere') + patch job_path(job), params: { job: { finished: '1' }, animal_id: animal.id }, headers: headers + expect(Capybara.string(response.body)).to have_no_css('.notepad-name', text: 'Elsewhere') + end + + it 'refreshes the animal list when hiding completed jobs' do + create(:job, owner: member, name: 'Elsewhere') + get member_jobs_path(member), params: { animal_id: animal.id }, headers: headers + expect(Capybara.string(response.body)).to have_no_css('.notepad-name', text: 'Elsewhere') + end + + it 'does not expose another member\'s animal notepad' do + other_animal = create(:domesticated_animal) + get member_jobs_path(member), params: { animal_id: other_animal.id }, headers: headers + expect(response).to have_http_status(:not_found) + end + end + context 'when renaming a job from the notepad' do before { patch job_path(job), params: { job: { name: 'Sow the beans' } }, headers: } diff --git a/spec/services/jobs_notepad_spec.rb b/spec/services/jobs_notepad_spec.rb index 73a58c5887..2f3b267038 100644 --- a/spec/services/jobs_notepad_spec.rb +++ b/spec/services/jobs_notepad_spec.rb @@ -3,10 +3,11 @@ require 'rails_helper' describe JobsNotepad do - subject(:notepad) { described_class.new(member, garden:, pinned:) } + subject(:notepad) { described_class.new(member, garden:, animal:, pinned:) } let(:member) { create(:member) } let(:garden) { nil } + let(:animal) { nil } let(:pinned) { [] } let(:berries) { create(:garden, owner: member) } let!(:in_berries) { create(:job, owner: member, garden: berries, name: 'Net the berries', due_date: Time.zone.today) } @@ -51,6 +52,26 @@ def names end end + context 'with an animal', flipper: :domesticated_animals do + let(:animal) { create(:domesticated_animal, owner: member) } + let(:animal_job) { create(:job, owner: member, jobbable: animal, name: 'Feed the hens') } + + it 'includes only jobs for the animal' do + animal_job + expect(names).to eq [animal_job.name] + end + + it 'includes completed jobs' do + animal_job.update!(finished: true) + expect(notepad.groups.find { |group| group.key == :done }.jobs).to eq [animal_job] + end + + it 'counts only completed jobs for the animal' do + elsewhere.update!(finished: true) + expect(notepad.done_this_week).to eq 0 + end + end + context 'when the member is a garden collaborator' do let(:community_garden) { create(:garden) } let!(:collab_job) { create(:job, garden: community_garden, name: 'Weed community plot', due_date: Time.zone.today) } From a7a8ea4fe71db6f5e1cd2d1f27e91c596ddbaa78 Mon Sep 17 00:00:00 2001 From: Daniel O'Connor Date: Thu, 3 Dec 2026 08:53:37 +0000 Subject: [PATCH 5/5] More styling --- .../stylesheets/_domesticated_animals.scss | 18 +++++ app/assets/stylesheets/application.scss | 1 + .../prompt_dismissals_controller.rb | 15 ++++ app/models/member.rb | 8 ++ .../domesticated_animals/_prompt.html.haml | 9 +++ app/views/domesticated_animals/show.html.haml | 44 +++++------ app/views/gardens/index.html.haml | 3 + app/views/members/_stats.html.haml | 5 ++ app/views/members/show.html.haml | 4 +- config/locales/en.yml | 8 ++ config/routes.rb | 1 + spec/features/domesticated_animals_spec.rb | 15 ++++ .../prompt_dismissals_controller_spec.rb | 79 +++++++++++++++++++ .../domesticated_animals_controller_spec.rb | 32 ++++++++ 14 files changed, 218 insertions(+), 24 deletions(-) create mode 100644 app/assets/stylesheets/_domesticated_animals.scss create mode 100644 app/controllers/domesticated_animals/prompt_dismissals_controller.rb create mode 100644 app/views/domesticated_animals/_prompt.html.haml create mode 100644 spec/requests/domesticated_animals/prompt_dismissals_controller_spec.rb 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/models/member.rb b/app/models/member.rb index 2b90b73e5b..8acd941350 100644 --- a/app/models/member.rb +++ b/app/models/member.rb @@ -162,6 +162,14 @@ def accept_nursery! update_column(:settings, settings.except('nursery_declined')) # rubocop:disable Rails/SkipsModelValidations end + def animals_prompt_dismissed? + settings['animals_prompt_dismissed'] == true + end + + def dismiss_animals_prompt! + update_column(:settings, settings.merge('animals_prompt_dismissed' => true)) # rubocop:disable Rails/SkipsModelValidations + end + AVAILABLE_LOCALES = %w[en de es fr ja zh].freeze def locale diff --git a/app/views/domesticated_animals/_prompt.html.haml b/app/views/domesticated_animals/_prompt.html.haml new file mode 100644 index 0000000000..45d319198c --- /dev/null +++ b/app/views/domesticated_animals/_prompt.html.haml @@ -0,0 +1,9 @@ +%section.gardens-section#animals-prompt + .gardens-section-header + %h2= t('domesticated_animals.prompt.title') + .gardens-section-body + %p= t('domesticated_animals.prompt.description') + .d-flex.justify-content-between.align-items-center.gap-3 + = button_to t('domesticated_animals.prompt.dismiss'), animal_prompt_dismissal_path, method: :post, class: 'btn btn-link' + = react_component 'AnimalDialog', { url: new_domesticated_animal_path, label: t('domesticated_animals.add'), title: t('domesticated_animals.new_heading'), loading_label: t('domesticated_animals.loading'), error_label: t('domesticated_animals.save_error') } do + = link_to t('domesticated_animals.add'), new_domesticated_animal_path, class: 'btn btn-primary' diff --git a/app/views/domesticated_animals/show.html.haml b/app/views/domesticated_animals/show.html.haml index ad6c9967a9..219314c375 100644 --- a/app/views/domesticated_animals/show.html.haml +++ b/app/views/domesticated_animals/show.html.haml @@ -6,7 +6,7 @@ %li.breadcrumb-item= link_to animal.owner, animal.owner %li.breadcrumb-item.active= animal.name -.record-page +.record-page.domesticated-animal-show .record-panel .section-header %h1= animal.name @@ -32,24 +32,24 @@ = value - if animal.description.present? %p= animal.description - %section#photos - .section-header - %h2= t('domesticated_animals.photos') - - if can?(:update, animal) - = link_to t('domesticated_animals.add_photo'), new_photo_path_for(animal), - class: 'btn btn-sm section-add', data: photo_dialog_data(animal) - = render 'photos/gallery', photos: animal.photos, item: animal - %section#jobs - .garden-notepad - - if can?(:update, animal) && can?(:create, Job) - = render 'jobs/notepad', owner: current_member, animal: animal, groups: @notepad.groups, autofocus: false - - else - .notepad - .notepad-title - %h2= t('domesticated_animals.jobs_title', animal: animal.name) - %span.badge.text-bg-light.garden-jobs-public{ title: t('jobs.pad.public_note') }= t('gardens.jobs_section.public') - = render 'jobs/notepad_groups', groups: @notepad.groups, in_animal: true, readonly: true - - if can?(:update, animal) - .d-flex.justify-content-end.mt-3 - = button_to t('domesticated_animals.delete'), animal, method: :delete, - class: 'btn btn-outline-danger', data: { confirm: t('domesticated_animals.confirm_delete') } + %section#photos + .section-header + %h2= t('domesticated_animals.photos') + - if can?(:update, animal) + = link_to t('domesticated_animals.add_photo'), new_photo_path_for(animal), + class: 'btn btn-sm section-add', data: photo_dialog_data(animal) + = render 'photos/gallery', photos: animal.photos, item: animal + %section#jobs + .garden-notepad + - if can?(:update, animal) && can?(:create, Job) + = render 'jobs/notepad', owner: current_member, animal: animal, groups: @notepad.groups, autofocus: false + - else + .notepad + .notepad-title + %h2= t('domesticated_animals.jobs_title', animal: animal.name) + %span.badge.text-bg-light.garden-jobs-public{ title: t('jobs.pad.public_note') }= t('gardens.jobs_section.public') + = render 'jobs/notepad_groups', groups: @notepad.groups, in_animal: true, readonly: true + - if can?(:update, animal) + .d-flex.justify-content-end.mt-3 + = button_to t('domesticated_animals.delete'), animal, method: :delete, + class: 'btn btn-outline-danger', data: { confirm: t('domesticated_animals.confirm_delete') } diff --git a/app/views/gardens/index.html.haml b/app/views/gardens/index.html.haml index 7aa59ca2e2..7a5e91c1b3 100644 --- a/app/views/gardens/index.html.haml +++ b/app/views/gardens/index.html.haml @@ -35,6 +35,9 @@ - if @nursery || (@own_gardens && !@owner.nursery_declined?) = render 'gardens/nursery_panel', owner: @owner, nursery: @nursery + - if @own_gardens && domesticated_animals_enabled? && !@owner.animals_prompt_dismissed? && @owner.domesticated_animals.empty? + = render 'domesticated_animals/prompt' + %section.gardens-section .gardens-section-header %h2 Gardens diff --git a/app/views/members/_stats.html.haml b/app/views/members/_stats.html.haml index 4b252de659..15973f34b2 100644 --- a/app/views/members/_stats.html.haml +++ b/app/views/members/_stats.html.haml @@ -25,6 +25,11 @@ - if member.jobs.present? %li.list-group-item = link_to localize_plural(member.jobs, Job), member_jobs_path(member) + - if domesticated_animals_enabled? + - animal_count = member.domesticated_animals.size + - if animal_count > 1 + %li.list-group-item + = link_to t('.animals', count: animal_count), member_path(member, anchor: 'domesticated-animals') - if member.followed.present? %li.list-group-item = link_to localize_plural(member.followed, Follow), member_follows_path(member) diff --git a/app/views/members/show.html.haml b/app/views/members/show.html.haml index e511cc032c..1ef2a5f27a 100644 --- a/app/views/members/show.html.haml +++ b/app/views/members/show.html.haml @@ -86,8 +86,6 @@ = render "contact", member: @member, flickr_auth: @flickr_auth, mastodon_auths: @mastodon_auths .col-md-10#content - - if domesticated_animals_enabled? - = render 'domesticated_animals/profile', member: @member = render 'stalls/card', member: @member .row %section.order-3.order-md-1.col-12= render "map", member: @member @@ -156,3 +154,5 @@ #{time_ago_in_words(event.event_at)} ago - else unknown date + - if domesticated_animals_enabled? + = render 'domesticated_animals/profile', member: @member diff --git a/config/locales/en.yml b/config/locales/en.yml index bbbdcb31da..b2f6fdd95b 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1,6 +1,11 @@ --- en: domesticated_animals: + prompt: + title: Add your pets and animals + description: Keep profiles and photos for your pets and animals, and plan their care with jobs. + dismiss: Dismiss + dismissed: We won't show the pets and animals prompt again. You can still add animals from your profile. title: Animals singular: Animal add: Add an animal @@ -2410,6 +2415,9 @@ en: signup: error: Failed to complete signup stats: + animals: + one: "%{count} animal" + other: "%{count} animals" followers: one: "%{count} follower" other: "%{count} followers" diff --git a/config/routes.rb b/config/routes.rb index 6d696a5b17..ea67370e5c 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -9,6 +9,7 @@ resources :garden_types resources :plant_parts resources :domesticated_animals, except: :index + resource :animal_prompt_dismissal, only: :create, controller: 'domesticated_animals/prompt_dismissals' devise_for :members, controllers: { confirmations: "confirmations", diff --git a/spec/features/domesticated_animals_spec.rb b/spec/features/domesticated_animals_spec.rb index 3ec51de83a..5f06d71103 100644 --- a/spec/features/domesticated_animals_spec.rb +++ b/spec/features/domesticated_animals_spec.rb @@ -7,6 +7,21 @@ before { Feature.find(:domesticated_animals).enable_member(member) } + context 'when prompted to add animals' do + before { visit member_gardens_path(member) } + + it 'opens the animal form in a dialog' do + within('#animals-prompt') { click_link I18n.t('domesticated_animals.add') } + expect(page).to have_css('[role="dialog"] #new_domesticated_animal') + end + + it 'keeps the prompt dismissed after revisiting' do + within('#animals-prompt') { click_button I18n.t('domesticated_animals.prompt.dismiss') } + visit member_gardens_path(member) + expect(page).to have_no_css('#animals-prompt') + end + end + context 'when managing an animal\'s jobs' do let(:animal) { create(:domesticated_animal, owner: member) } diff --git a/spec/requests/domesticated_animals/prompt_dismissals_controller_spec.rb b/spec/requests/domesticated_animals/prompt_dismissals_controller_spec.rb new file mode 100644 index 0000000000..f1b1888b0e --- /dev/null +++ b/spec/requests/domesticated_animals/prompt_dismissals_controller_spec.rb @@ -0,0 +1,79 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe DomesticatedAnimals::PromptDismissalsController do + let(:member) { create(:member) } + + context 'when the feature is enabled' do + before do + Feature.find(:domesticated_animals).enabled = true + sign_in member + end + + it 'offers to add animals on the member\'s gardens page' do + get member_gardens_path(member) + expect(Capybara.string(response.body)).to have_css("#animals-prompt a[href='#{new_domesticated_animal_path}']") + end + + it 'hides the prompt when the member has an animal' do + create(:domesticated_animal, owner: member) + get member_gardens_path(member) + expect(Capybara.string(response.body)).to have_no_css('#animals-prompt') + end + + it 'does not prompt on another member\'s gardens page' do + get member_gardens_path(create(:member)) + expect(Capybara.string(response.body)).to have_no_css('#animals-prompt') + end + + it 'does not prompt visitors' do + sign_out member + get member_gardens_path(member) + expect(Capybara.string(response.body)).to have_no_css('#animals-prompt') + end + + it 'remembers dismissal across visits' do + post animal_prompt_dismissal_path + get member_gardens_path(member) + expect(Capybara.string(response.body)).to have_no_css('#animals-prompt') + end + + it 'preserves other member settings when dismissing' do + member.update!(settings: member.settings.merge('nursery_declined' => true)) + post animal_prompt_dismissal_path + expect(member.reload).to be_nursery_declined + end + + it 'returns to the member\'s gardens after dismissal' do + post animal_prompt_dismissal_path + expect(response).to redirect_to(member_gardens_path(member)) + end + + it 'requires authentication to dismiss' do + sign_out member + post animal_prompt_dismissal_path + expect(response).to redirect_to(new_member_session_path) + end + + it 'still allows adding an animal after dismissal' do + post animal_prompt_dismissal_path + get new_domesticated_animal_path + expect(response).to have_http_status(:ok) + end + end + + context 'when the feature is disabled' do + before { sign_in member } + + it 'does not show the prompt' do + get member_gardens_path(member) + expect(Capybara.string(response.body)).to have_no_css('#animals-prompt') + end + + it 'does not allow dismissal' do + post animal_prompt_dismissal_path + expect(response).to have_http_status(:not_found) + end + end +end diff --git a/spec/requests/domesticated_animals_controller_spec.rb b/spec/requests/domesticated_animals_controller_spec.rb index 6e552cfec2..73c40144d4 100644 --- a/spec/requests/domesticated_animals_controller_spec.rb +++ b/spec/requests/domesticated_animals_controller_spec.rb @@ -25,6 +25,12 @@ expect(response.body).not_to include domesticated_animal_path(animal) end + it 'does not include animals in member stats' do + create_list(:domesticated_animal, 2, owner: member) + get member_path(member) + expect(Capybara.string(response.body)).to have_no_css('#stats-collapse a[href$="#domesticated-animals"]') + end + it 'does not offer animals in job suggestions' do animal get job_suggestions_path, params: { q: 'Henri' } @@ -74,6 +80,32 @@ expect(response).to have_http_status(:ok) end + it 'shows animals below activity on the member profile' do + animal + create(:job, owner: member) + get member_path(member) + expect(Capybara.string(response.body)).to have_css('#content .row:has(#activity) + #domesticated-animals') + end + + context 'with animal stats' do + it 'links to the animals section for two animals' do + create_list(:domesticated_animal, 2, owner: member) + get member_path(member) + expect(Capybara.string(response.body)).to have_css('#stats-collapse a[href$="#domesticated-animals"]') + end + + it 'omits the animal entry for one animal' do + animal + get member_path(member) + expect(Capybara.string(response.body)).to have_no_css('#stats-collapse a[href$="#domesticated-animals"]') + end + + it 'omits the animal entry without animals' do + get member_path(member) + expect(Capybara.string(response.body)).to have_no_css('#stats-collapse a[href$="#domesticated-animals"]') + end + end + it 'shows an empty jobs section without related jobs' do get domesticated_animal_path(animal) expect(Capybara.string(response.body)).to have_css('#jobs .notepad .notepad-drop-hint')