Skip to content

Feat/multi farm polygon management 2#39

Open
Shade555 wants to merge 10 commits into
jpdevhub:mainfrom
Shade555:feat/multi-farm-polygon-management
Open

Feat/multi farm polygon management 2#39
Shade555 wants to merge 10 commits into
jpdevhub:mainfrom
Shade555:feat/multi-farm-polygon-management

Conversation

@Shade555
Copy link
Copy Markdown
Contributor

@Shade555 Shade555 commented Jun 6, 2026

Title:

feat: multi-farm polygon management

Description:

Summary

Allows a single farmer to draw and manage multiple distinct named field polygons (e.g. "Wheat Field", "Rice Paddy") per farm, backed by a dedicated database table.

Related Issue

Closes #23

Changes

Database

  • Added farm_fields table (id, farm_id, name, area_acres, area_hectares generated, polygon JSONB, center_latitude, center_longitude, created_at, updated_at)
  • RLS policies scoped to farm owner for SELECT, INSERT, UPDATE, DELETE
  • Index on farm_id for fast field lookups, partial index on centre coordinates
  • Trigger trg_sync_farm_total_area auto-updates farms.total_area on any field insert/update/delete — no application-level bookkeeping needed
  • Migration script migrates any existing JSONB fields from farms.location.fields into the new table
  • Migration: backend/supabase/migrations/20260607000000_farm_fields_table.sql

Backend (backend/main.py)

  • Rewrote GET /api/farms/{id}/fields to query farm_fields table directly
  • Rewrote POST /api/farms/{id}/fields to insert into farm_fields table
  • Rewrote DELETE /api/farms/{id}/fields/{field_id} to delete from farm_fields table
  • Removed manual JSONB array manipulation and manual total_area recalculation (now handled by DB trigger)
  • Added FieldResponse Pydantic model for typed field responses
  • Removed area_hectares from FieldCreate (now a generated column in DB)
  • Fixed pre-existing double-index bug (owned.data[0][0]owned.data[0]) in old field endpoints
  • Fixed pre-existing res.data.get() bug on list type in get_fields
  • Added -> dict return type annotations and user: dict parameter type on all three field endpoints

Frontend

  • PolygonMapper (frontend/src/components/map/PolygonMapper.tsx):

    • Added required "Field Name" text input above the map with inline validation
    • onPolygonComplete callback now includes fieldName in the payload
    • Component auto-resets name and polygon after each confirmed field so multiple fields can be drawn without a page reload
    • Updated UI copy to correctly say "4 corners" matching the usePolygonArea hook threshold
    • Removed unused showInstructions prop and locationLoading state
  • Dashboard Field Manager tab (frontend/src/components/Dashboard.tsx):

    • Added fields: Field[] state loaded from GET /api/farms/{id}/fields
    • Fields refresh automatically when selected farm changes and after add/delete
    • Replaced handleSavePolygon (which called updateFarm) with handleAddField (calls addFarmField) and handleDeleteField (calls deleteFarmField)
    • Pending field confirm panel shows field name and area before saving
    • "Mapped Fields" list shows all saved fields with coloured dot, name, area, and per-field Remove button with individual loading state
    • Removed stale farm.location.fields JSONB reads — all field data now comes from the API
    • Farm cards show field count for the currently selected farm
    • Removed the wrapper border around PolygonMapper
  • FarmMap (frontend/src/components/FarmMap.tsx):

    • Fetches fields from GET /api/farms/{id}/fields (new table) instead of reading farm.location.fields
    • Each named field polygon renders in a distinct colour from the shared FIELD_COLORS palette
    • Clicking a field polygon opens a popup with field name, area, and parent farm name
    • Legacy farms.location.polygon still renders for farms with no named fields yet (backwards compatible)
    • Parallel field loading for all farms when showAllFarms is true
  • frontend/src/utils/mapUtils.ts (new file):

    • Extracted FIELD_COLORS palette into a shared utility so Dashboard and FarmMap use the same colours

Testing

  • Tested locally (describe steps)

    1. Run npm run dev from the project root
    2. Log in → go to Field Manager tab
    3. Select a farm from the dropdown
    4. Enter "Wheat Field" in the Field Name input, drop 4 pins on the map, click Add field →, then Save Field — field appears in the Mapped Fields list
    5. Repeat with "Rice Paddy" — second field appears with a different colour dot
    6. Click Remove on one field — it disappears and total area updates
    7. Navigate to My Farms tab — farm card shows correct field count
    8. Verify via GET /api/farms/{id}/fields in FastAPI docs (http://localhost:8000/docs) that fields are stored in the farm_fields table
    9. Verify farms.total_area in Supabase Studio (http://127.0.0.1:54323) matches the sum of field areas

Checklist

  • Code follows the project's TypeScript / Python style conventions
  • No secrets or .env values are committed
  • CI passes

Shade555 and others added 10 commits June 6, 2026 01:38
- Added a required 'Field Name' text input above the map
- Validation prevents confirming a polygon without a name
- onPolygonComplete callback now includes fieldName in the payload
- Map instructions updated to reflect the new flow
- Component resets name and polygon after each confirmed field
  so multiple fields can be drawn back-to-back without a page reload
- Added Field interface to Farm type covering id, name, area, polygon coords
- Replaced polygonData state with pendingField (includes fieldName)
- handleSavePolygon replaced by handleAddField (calls addFarmField API)
  and handleDeleteField (calls deleteFarmField API)
- Map tab renamed 'Field Manager' with an updated subtitle
- Pending field confirm panel shows field name, area, discard/save buttons
- Saved fields list renders below the mapper with coloured dot per field,
  name, area, and a Remove button with loading state per field
- Farm cards in Farms tab now show field count when fields exist
- FIELD_COLORS palette constant added for consistent colour cycling
- Removed any cast in error handlers; using err instanceof Error pattern
- Each named field gets a distinct colour from the FIELD_COLORS palette
- Field popups show field name, area in acres/ha, and parent farm name
- Legacy farm.location.polygon still renders for backwards compatibility
  (only shown when a farm has no named fields yet)
- Farm marker position derived from first field centre, then legacy polygon
  centroid, then explicit lat/lng — graceful fallback chain
- Removed unused showAllFields prop; all fields always shown when present
- Error handling uses err instanceof Error instead of any cast
TypeScript:
- Extract FIELD_COLORS into frontend/src/utils/mapUtils.ts so Dashboard
  and FarmMap share a single source of truth (no duplication)
- Remove unused showInstructions prop from PolygonMapper
- Remove unused locationLoading state from PolygonMapper
- Import FIELD_COLORS from mapUtils in Dashboard and FarmMap

Python:
- Add explicit return type annotation (-> dict) to get_fields,
  add_field, and delete_field endpoints
- Add user: dict type annotation on the Depends(verify_token) parameter
  in all three field endpoints
- Reformat long chained Supabase calls onto multiple lines (PEP 8)
- Add current_loc: dict and current_fields: list local type annotations
The hook uses isComplete: points.length >= 4 (by design — a rectangle
needs 4 corners). Updated all UI copy that said '3+' to say '4', and
fixed the 'Drop X more pins' counter which was subtracting from 3
instead of 4.
@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 6, 2026

@Shade555 is attempting to deploy a commit to the karan3431's projects Team on Vercel.

A member of the Team first needs to authorize it.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jun 6, 2026

🎉 Thanks for your contribution, @Shade555!

Please make sure CI passes and the checklist in the PR template is complete. A maintainer will review this soon.

— The AgroNavis team

@Shade555 Shade555 changed the title Feat/multi farm polygon management Feat/multi farm polygon management 2 Jun 6, 2026
@Shade555 Shade555 mentioned this pull request Jun 6, 2026
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Full-Stack] Multi-Farm Management

1 participant