Skip to content
forms-raw_singleitemedit-icon
navigation
modification_btn
docs
messages
flatprojectmap.handlebars
Plug-in - Work Orders
modificationbutton
docs_htmltables.handlebars

Plug-in - Work Orders

docs_html.handlebars
documentation.handlebars

1. Overview

1.1 Plugin Name

Osprey – an asset work order allocation, scheduling and management module.

1.2 Purpose

Osprey provides an Asset Work Order Registry and Work Order Dashboard for the Shiftbulk ecosystem:

  • A CRUD interface for defining “work orders” (e.g. Inspect fire water ring main, Calibrate blocked chute probe, Service deluge system, E-room housekeeping check).
  • Tight linkage to the Atlas asset hierarchy (Site → Area → Equipment / Asset).
  • Scheduling for recurring work orders (periodic tasks with next-due dates) and one-off work orders.
  • Status tracking (open, in progress, completed, overdue, cancelled) with dashboard summaries by location, asset and frequency.
  • A dashboard view showing overall work order load and health, with drill-down from high level (site/area) to asset-specific work orders.

Osprey integrates into the existing Shiftbulk app:

  • Express + Handlebars
  • Tailwind CSS (via parent layout)
  • MongoDB + Mongoose
  • Existing layout: views/osprey/main.handlebars (or main layout via 'main')

1.3 Mount Point

  • Plugin root router: plugins/osprey/index.js
  • Mount path in main app:
    const osprey = require('./plugins/osprey');
                        app.use('/osprey', osprey);

2. Goals & Non-Goals

2.1 Goals

  1. Provide a central registry of asset work orders with:
    • Title / short description
    • Full description / instructions
    • Status and priority
    • Linkage to Atlas assets (site, area, equipment/asset)
    • Scheduling information for periodic work (frequency, next due date, last completed)
  2. Provide a work order dashboard with:
    • Global counts by status (open, in progress, completed, overdue, cancelled).
    • Roll-ups by site and area, with drill-down to individual assets and work orders.
    • Simple indicators for overdue and upcoming work.
  3. Provide full CRUD:
    • List
    • Create
    • Edit
    • View detail
    • Soft delete / archive
  4. Use Tailwind CSS and Shiftbulk main layout:
    • No Bootstrap classes in Osprey templates.
  5. Define everything clearly so an LLM can generate a complete plugin code tree and provide it as a downloadable zip for the user.

2.2 Non-Goals

  • No complex resource planning or capacity balancing (simple assignment and status only).
  • No advanced permissions model (this is a secondary requirement).
  • No real-time / websocket updates (plain HTTP is sufficient).
  • No automated background job scheduler in v1 (recurrence fields are stored; date updates can be triggered on completion or via manual refresh routes).
  • No deep cross-plugin joins beyond basic Atlas references (IDs and names pulled from Atlas are sufficient).

4. Data Model

4.1 Mongoose Model: WorkOrder

File: plugins/osprey/models/WorkOrder.js

Collection naming: All collections must be prefixed with osprey_.

Collection name: osprey_workorders (default Mongoose naming).

Fields

  • _id – ObjectId
  • title – String, required, max length ~200 (e.g. “Inspect fire water ring main isolation valves”).
  • description – String, optional, long text (detailed task instructions, PPE, tools, acceptance criteria).
  • Status & Priority:
    • status – String, enum: 'open' | 'in_progress' | 'completed' | 'overdue' | 'cancelled', default 'open'.
    • priority – String, enum: 'low' | 'medium' | 'high' | 'critical', default 'medium'.
  • Scheduling & Recurrence:
    • isRecurring – Boolean, default false.
    • frequency – String, enum: 'once' | 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'yearly' | 'custom', default 'once'.
    • customIntervalDays – Number, optional (used when frequency === 'custom').
    • startDate – Date, optional (when the work order becomes active).
    • dueDate – Date, optional (current/next due date).
    • lastCompletedDate – Date, optional.
    • nextDueDate – Date, optional (computed when work is completed, based on frequency).
  • Atlas Asset Linkage: (using Atlas collections as reference for assets)
    • siteId – ObjectId, ref 'AtlasSite' (or the appropriate Atlas model), nullable.
    • areaId – ObjectId, ref 'AtlasArea', nullable.
    • equipmentId – ObjectId, ref 'AtlasEquipment', nullable.
    • Optional denormalized fields for quick display (kept in sync by controller logic):
      • siteName – String
      • areaName – String
      • equipmentName – String
  • Assignment & Context:
    • assignee – String or ObjectId (for v1, can be a simple String such as username or contractor name).
    • createdBy – String or ObjectId, optional.
    • tags – [String], optional (e.g. “fire-protection”, “mechanical”, “inspection”).
    • notes – String, optional (free-form comments).
  • isActive – Boolean, default true (soft delete & archive flag).
  • createdAt / updatedAt – Date (via timestamps: true).

4.2 Work Order Aggregation Model (In Memory)

  • No separate DB model for aggregated dashboard metrics.
  • Aggregation is computed on the fly in the controller:
    • By status for high-level dashboard counts.
    • By siteId and areaId for location-based drill-down.
    • Optionally by equipmentId and/or frequency for deeper analysis.
  • Helper function to derive aggregated status counts and simple “health” indicator:
    • “Health” can be derived from ratio of overdue/open items to total items.
    • For v1, a simple derived health flag is sufficient (e.g. 'good', 'warning', 'critical').

5. Navigation & Routes

5.1 Router File

File: plugins/osprey/index.js

Exports an Express router.

5.2 Middleware

  • bodyParser.urlencoded({ extended: true })
  • bodyParser.json()
  • cookieParser and CSRF can be applied at the router level, consistent with other plugins (optional but recommended).
  • Set res.locals.basePath = req.baseUrl || '/osprey' for URL generation in views.

5.3 Route List

Dashboard & Browsing

  • GET /osprey → Osprey Dashboard – global status summary and site/area roll-up.
  • GET /osprey/site/:siteId → Site-level detail view (aggregated work orders for a given site).
  • GET /osprey/site/:siteId/area/:areaId → Area-level detail view.
  • GET /osprey/equipment/:equipmentId → Asset-level detail view (list of work orders for a specific asset).

Work Orders CRUD

  • GET /osprey/workorders → List view of all work orders with filters.
  • GET /osprey/workorders/new → New work order form.
  • POST /osprey/workorders → Create work order.
  • GET /osprey/workorders/:id → Work order detail page.
  • GET /osprey/workorders/:id/edit → Edit work order form.
  • POST /osprey/workorders/:id or POST /osprey/workorders/:id?_method=PUT → Update work order.
  • POST /osprey/workorders/:id/delete or POST /osprey/workorders/:id?_method=DELETE → Soft delete (set isActive = false).

Status & Completion Actions

  • POST /osprey/workorders/:id/complete → Mark work order as completed, set lastCompletedDate and compute nextDueDate if recurring.
  • POST /osprey/workorders/:id/reopen → Reopen a completed or cancelled work order (set status back to 'open').

Optional Export Routes

  • GET /osprey/export/json → Return JSON of all work orders (Content-Disposition: attachment).
  • GET /osprey/export/csv → Return CSV of all work orders.
  • Export routes are optional, not mandatory for v1.

6. Controllers

File: plugins/osprey/controllers/ospreyController.js

You may split into dashboardController and workordersController, but a single controller file is acceptable for v1.

6.1 Helper: summarizeWorkOrders(workOrders)

Input: Array of WorkOrder documents or simplified objects with .status.

Output:

{
                      counts: {
                        open: Number,
                        in_progress: Number,
                        completed: Number,
                        overdue: Number,
                        cancelled: Number
                      },
                      total: Number,
                      health: 'good' | 'warning' | 'critical'
                    }

Logic

  • Initialise counts for each status to zero.
  • Iterate through workOrders and increment counts based on status.
  • Set total as the sum of all counts.
  • Determine health with simple rules, e.g.:
    • If overdue / total >= 0.3 → 'critical'
    • Else if overdue / total > 0 → 'warning'
    • Else → 'good'

6.2 Helper: computeNextDueDate(workOrder)

Input: A WorkOrder document with frequency and optional customIntervalDays.

Output: A Date (or null) representing the next due date.

Logic

  • Use lastCompletedDate (if available) as the base; otherwise startDate or dueDate.
  • Based on frequency:
    • 'once' → no further dates (return null).
    • 'daily' → base date + 1 day.
    • 'weekly' → base date + 7 days.
    • 'monthly' → base date + 1 month.
    • 'quarterly' → base date + 3 months.
    • 'yearly' → base date + 12 months.
    • 'custom' → base date + customIntervalDays days.
  • Return the computed Date; controller updates nextDueDate accordingly.

6.3 Controller Methods

dashboard(req, res, next)

  • Route: GET /osprey
  • Query active work orders only ({ isActive: true }).
  • Compute global summary using summarizeWorkOrders.
  • Group work orders by site (using siteId / siteName):
    • Use Array.prototype.reduce or a Mongoose aggregate pipeline.
    • For each site, compute a site-level summary.
  • Map status/health to Tailwind classes (example):
    • health = 'critical' → bg-red-500 text-white
    • health = 'warning' → bg-amber-400 text-black
    • health = 'good' → bg-green-500 text-white
  • Render osprey/dashboard with:
    {
                          title: 'Osprey Work Order Dashboard',
                          summary: { counts, total, health, cssClass },
                          sites: [
                            {
                              siteId,
                              siteName,
                              summary: { counts, total, health, cssClass }
                            },
                            ...
                          ]
                        }

siteDetail(req, res, next)

  • Route: GET /osprey/site/:siteId
  • Filter work orders by isActive: true and the given siteId.
  • Group by areaId (and areaName) and compute each group’s summary.
  • Compute overall summary for this site.
  • Render osprey/site.

areaDetail(req, res, next)

  • Route: GET /osprey/site/:siteId/area/:areaId
  • Filter by siteId and areaId.
  • Group by equipmentId and compute summaries, or list work orders directly.
  • Render osprey/area.

equipmentDetail(req, res, next)

  • Route: GET /osprey/equipment/:equipmentId
  • Filter by equipmentId.
  • Show list of individual work orders for that asset.
  • Render osprey/equipment.

listWorkOrders(req, res, next)

  • Route: GET /osprey/workorders
  • Support optional query filters:
    • siteId, areaId, equipmentId
    • status, priority, frequency
    • isRecurring
    • search (text search on title/description).
  • Return list and counts; display a simple table.
  • Render osprey/workorders/index.

newWorkOrderForm(req, res)

  • Route: GET /osprey/workorders/new
  • Optionally pre-populate asset fields if query parameters are provided (?equipmentId=... etc.).
  • Render osprey/workorders/new with an empty work order object.
  • Default status is 'open', frequency is 'once'.

createWorkOrder(req, res, next)

  • Route: POST /osprey/workorders
  • Validate required fields: title, and at least one asset linkage (e.g. siteId or equipmentId).
  • Normalize empty strings for optional fields (e.g. areaId, equipmentId, tags).
  • Parse tags from comma-separated string if provided.
  • Set status, priority, frequency from form (with sane defaults/fallbacks).
  • Call WorkOrder.create.
  • On success: redirect to /osprey/workorders or /osprey/workorders/:id.
  • On validation error: re-render new with errors and entered data.

showWorkOrder(req, res, next)

  • Route: GET /osprey/workorders/:id
  • Fetch work order by id; check isActive if appropriate.
  • Compute derived fields (e.g. overdue flag if dueDate < now).
  • Map status and priority to CSS badge classes.
  • Render osprey/workorders/show.

editWorkOrderForm(req, res, next)

  • Route: GET /osprey/workorders/:id/edit
  • Fetch the work order and pre-populate form fields.
  • Render osprey/workorders/edit.

updateWorkOrder(req, res, next)

  • Route: POST /osprey/workorders/:id (or PUT with method override)
  • Fetch work order by id.
  • Update editable fields:
    • title, description
    • siteId, areaId, equipmentId (+ names if denormalized)
    • status, priority
    • isRecurring, frequency, customIntervalDays
    • startDate, dueDate, nextDueDate (if manually adjusted)
    • assignee, tags, notes
  • Save and redirect to the show or list page.
  • On validation error: re-render edit.

deleteWorkOrder(req, res, next)

  • Route: POST /osprey/workorders/:id/delete
  • Soft delete: set workOrder.isActive = false and workOrder.save().
  • Redirect to the list page and optionally show a flash message.

completeWorkOrder(req, res, next)

  • Route: POST /osprey/workorders/:id/complete
  • Fetch work order by id.
  • Set status = 'completed' and lastCompletedDate = new Date().
  • If isRecurring is true, compute nextDueDate via computeNextDueDate and update dueDate/nextDueDate accordingly. Also optionally set status = 'open' again for the next cycle.
  • Save and redirect back to the work order detail or list.

7. Views & Tailwind Layout

All views are located under: plugins/osprey/views/osprey/...

  • Use Tailwind CSS classes only.
  • Extend Shiftbulk main layout:
    {{#extends 'main'}}
                          {{#block 'content'}}
                            ...
                          {{/block}}
                        {{/extends}}

7.1 Dashboard View

File: plugins/osprey/views/osprey/dashboard.handlebars

Sections:

  1. Header: Title “Osprey Work Order Dashboard” and a short subtitle.
  2. Global Summary Card: Status counts and health indicator pill.
  3. Site / Area Grid: For each site:
    • Site name
    • Summary badges (open, overdue, completed)
    • Health indicator badge.
    • Link to site detail view.
  4. Quick Actions:
    • “View All Work Orders” → /osprey/workorders
    • “New Work Order” → /osprey/workorders/new (if permitted)

7.2 Site View

File: plugins/osprey/views/osprey/site.handlebars

  • Breadcrumb: Osprey > {{siteName}}
  • Summary card for this site (counts & health).
  • Table or grid grouping by areaName with status counts.
  • Links to /osprey/site/{{siteId}}/area/{{areaId}}.

7.3 Area View

File: plugins/osprey/views/osprey/area.handlebars

  • Breadcrumb: Osprey > {{siteName}} > {{areaName}}
  • Summary for this area.
  • Table listing equipment and/or work orders with status badges and due dates.
  • Links to /osprey/equipment/{{equipmentId}}.

7.4 Equipment View

File: plugins/osprey/views/osprey/equipment.handlebars

  • Breadcrumb: Osprey > {{siteName}} > {{areaName}} > {{equipmentName}}
  • Summary card plus list of work orders (table or cards) for this asset.
  • Links from each work order to its detail page.

7.5 Work Orders List View

File: plugins/osprey/views/osprey/workorders/index.handlebars

  • Filters (compact filter bar):
    • Selects or text inputs for Site, Area, Equipment (could integrate with Atlas search).
    • Status select (open, in progress, overdue, completed, cancelled).
    • Priority select.
    • Frequency select (once, daily, weekly, etc.).
    • Search text input (title/description).
  • Table columns:
    • Title
    • Site
    • Area
    • Equipment / Asset
    • Status badge
    • Priority badge
    • Due date / Overdue indicator
    • Assignee
    • Actions (view / edit / delete / complete)

7.6 Work Orders New / Edit Views

Files:

  • plugins/osprey/views/osprey/workorders/new.handlebars
  • plugins/osprey/views/osprey/workorders/edit.handlebars

Form fields:

  • Text input: title
  • Textarea: description
  • Selectors / inputs linked to Atlas:
    • Site (select or autocomplete)
    • Area (cascading)
    • Equipment / Asset (cascading)
  • Status select (Open, In Progress, Completed, Overdue, Cancelled)
  • Priority select (Low, Medium, High, Critical)
  • Recurrence fields:
    • Checkbox: isRecurring
    • Frequency select (Once, Daily, Weekly, Monthly, Quarterly, Yearly, Custom)
    • Numeric input: customIntervalDays (shown if custom selected)
  • Date inputs: startDate, dueDate
  • Assignee (text or select, depending on available data)
  • Tags (comma-separated string)
  • Notes (optional)

Use Tailwind form styles similar to the falcon/finding_edit template.

7.7 Work Order Show View

File: plugins/osprey/views/osprey/workorders/show.handlebars

  • Display work order details in a panel:
    • Title + status & priority badges
    • Asset hierarchy: Site / Area / Equipment
    • Recurrence details (frequency, next due date, last completed)
    • Due date and overdue indicator
    • Description
    • Assignee
    • Tags
    • Notes
  • Buttons:
    • “Edit”
    • “Mark as Completed” (if applicable)
    • “Back to list”

8. Integration Points

8.1 Views Root

In the main app’s app.set('views', [...]), append:

path.join(__dirname, 'plugins/osprey/views')

8.2 Partials

If Osprey defines partials (e.g. status or priority badge components):

  • Directory: plugins/osprey/views/osprey/partials
  • Add to partialsDir array in main app:
    {
                          dir: path.join(__dirname, 'plugins', 'osprey', 'views', 'osprey', 'partials'),
                          namespace: 'osprey'
                        }
  • Optionally call the app’s helper to register the directory as a namespace.

8.3 Atlas Integration

  • Use Atlas models (AtlasSite, AtlasArea, AtlasEquipment) as references in the WorkOrder model.
  • Controllers may query Atlas to populate dropdowns for site/area/equipment selection.
  • Denormalized names (siteName, etc.) help render tables without extra joins.

8.4 Tailwind

  • Osprey views rely on Tailwind being included in the main layout.
  • No additional CSS or JS is strictly required in v1 (optional lightweight JS for dependent dropdowns).

9. Validation & Error Handling

9.1 Server-Side Validation

  • title must be non-empty.
  • status must be one of the allowed values.
  • priority must be one of the allowed values.
  • At least one asset link (e.g. siteId or equipmentId) must be provided.
  • If isRecurring and frequency === 'custom', then customIntervalDays must be a positive integer.

9.2 On Validation Failure

  • Re-render the same form with error messages (simple <div> text is sufficient).
  • Preserve the user’s entered values where possible.

9.3 404 Handling

  • If a work order is not found, use the main app’s 404 handler or redirect to /osprey/workorders.

10. LLM Implementation Instructions (Meta)

10.1 Overall

  • Use CommonJS (require, module.exports).
  • Add "use strict"; at the top of each JS file.
  • Do not output diffs; output complete file contents.
  • Structure all code under plugins/osprey.

10.2 File Structure

plugins/
                      osprey/
                        index.js                          // Express router
                        models/
                          WorkOrder.js                    // Mongoose model
                        controllers/
                          ospreyController.js             // All controller logic
                        views/
                          osprey/
                            dashboard.handlebars
                            site.handlebars
                            area.handlebars
                            equipment.handlebars
                            workorders/
                              index.handlebars
                              new.handlebars
                              edit.handlebars
                              show.handlebars
                            partials/                     // optional, e.g. status/priority badges
                              status_badge.handlebars
                              priority_badge.handlebars
                    

10.3 index.js Requirements

  • Create an Express router.
  • Apply bodyParser middleware.
  • Set res.locals.basePath for all requests.
  • Wire up controller methods for all routes described in Section 5.
  • Export the router.

10.4 Controller Requirements

  • Implement all methods listed in Section 6.
  • Use the WorkOrder model for DB operations.
  • Centralize aggregation, status summarization, and schedule logic in helper function(s).
  • Compute CSS class strings in the controller and pass them to views (e.g. item.statusClass, item.priorityClass, site.healthClass).

10.5 Model Requirements

  • Implement the schema exactly as described in Section 4.
  • Use timestamps: true.
  • Export Mongoose model as:
    module.exports = mongoose.model('WorkOrder', WorkOrderSchema);

10.6 View Requirements

  • All views must:
    • Extend the 'main' layout.
    • Use Tailwind classes only (no Bootstrap).
    • Follow visual patterns from falcon/finding_edit (spacing, card containers, headings, etc.).

10.7 Packaging as Downloadable Files

  • Bundle everything under plugins/osprey into a zip archive (e.g. osprey-plugin.zip).
  • Provide a link or reference for the user to download the zip (depending on execution environment).
  • Preserve directory structure exactly inside the archive.
modal1
modal2
modal3
docs_javascript
new_issue_button.handlebars
shortcut_edit