Skip to main content

Reporting Service

internal/api/v1/instasites/services/reporting.service.js powers /instasites/reporting/* endpoints. It aggregates site status trends, industry performance, and CSV upload history used in dashboard analytics widgets.

๐Ÿ“– Overviewโ€‹

Responsibilities:

  • Daily status funnel metrics (viewed, built, purchased, failed) for a date range.
  • Industry breakdowns keyed by template categories.
  • Paginated CSV import log retrieval for back-office audit trails.

๐Ÿ—„๏ธ Collections Usedโ€‹

instasitesโ€‹

  • Operations: Read
  • Model: shared/models/instasite.js
  • Usage: Source of lifecycle metrics (status, viewed flag, created timestamp) for both status and industry reports.

queueโ€‹

  • Operations: Read
  • Model: shared/models/instasite-queue.js
  • Usage: Stores type: instasite-csv jobs; getLogs exposes these records and supports pagination.

instasites.templatesโ€‹

  • Operations: Read
  • Model: shared/models/instasite-template.js
  • Usage: Joined in getIndustries to determine the category associated with each site.

instasites.templates.categoriesโ€‹

  • Operations: Read
  • Model: shared/models/instasite-template-category.js
  • Usage: Supplies industry names when consolidating template lookups.

๐Ÿง  Function Referenceโ€‹

getStatus({ account_id, startDate, endDate })โ€‹

Purpose: Returns daily InstaSite funnel metrics for a single account, plus aggregate totals.

Inputs:

  • account_id โ€” Account whose InstaSites should be analyzed.
  • startDate โ€” ISO or date string; default validations ensure presence before service call.
  • endDate โ€” Optional; defaults to one month ahead when omitted.

Business Logic Flow:

  1. Normalize startDate and endDate boundaries with moment, capturing both day start/end.
  2. Aggregate instasites via $match on account_id and created range; deserialize to iterate in-memory.
  3. Iterate each day between start/end (inclusive):
    • Build a daily object keyed by formatted date.
    • Tally viewed, built, purchased, and failed based on InstaSite status flags.
    • Track running totals for the entire range.
    • Handle timezone edge cases by merging overflows into the last bucket.
  4. Run a second aggregation (totalCountsQuery) to compute overall counts regardless of date window:
    • Separate facets for total_built, total_viewed, total_purchased, total_failed.
    • Convert missing counts to zero via $ifNull.
    • Note: total_built in the return payload sums NOT_PUBLISHED_YET + UNPUBLISHED + PUBLISHED statuses.
  5. Return { data, total_by_date, total }.

Key Rules:

  • total.total_built is redefined to include published sites in addition to the unfinished total from aggregation.
  • The returned data array is sorted chronologically by construction of the iteration loop.
  • Invalid dates raise validation errors before reaching the service.

getIndustries({ parent_account, startDate, endDate })โ€‹

Purpose: Produces an industry summary showing how each template category performs during a time window.

Inputs:

  • parent_account โ€” Account whose sites should be analyzed (often agency-level).
  • startDate, endDate โ€” Date range boundaries (inclusive) applied to site created timestamps.

Business Logic Flow:

  1. Run an aggregation on instasites to filter by parent_account and date window.
  2. $lookup template documents to fetch category_id, then $lookup categories for display titles.
  3. Iterate the result set client-side:
    • Build a unique set of category titles.
    • For each category, count sites in each status bucket (built, purchased, viewed, failed).
  4. Return array of { industry, built, purchased, viewed, failed } objects.

Key Rules:

  • A site marked PUBLISHED increments both built and purchased counters.
  • Unpublished states (UNPUBLISHED, NOT_PUBLISHED_YET) increment built only.
  • Missing category titles surface as undefined; controllers typically filter these out before rendering.

getLogs({ account_id, skip, limit })โ€‹

Purpose: Retrieves paginated CSV import jobs for auditing.

Inputs:

  • account_id โ€” Filters queue documents to a single account.
  • skip, limit โ€” Numeric pagination controls (validated prior to invocation).

Business Logic Flow:

  1. Build query { account_id, type: 'instasite-csv' }.
  2. Execute Promise.all to fetch both countDocuments and the latest documents (sort: {_id: -1}) within provided bounds.
  3. Return [totalCount, docs], matching the controller expectation.

Key Rules:

  • Errors propagate; controllers handle rejected promises and convert to API responses.
  • Consumers should convert the tuple into { total, data } before returning to clients for clarity.

โš™๏ธ Configurationโ€‹

  • Relies on the same date parsing format enforced by the validation layer (reporting.validation.js).
  • No additional environment variables beyond Mongo and the shared timezone assumptions.

๐Ÿงช Testing Touchpointsโ€‹

  • internal/api/v1/instasites/tests/reporting.test.js covers status and industry aggregation scenarios.
  • Tests seed fixture data to validate date iteration, facet totals, and CSV log pagination.
๐Ÿ’ฌ

Documentation Assistant

Ask me anything about the docs

Hi! I'm your documentation assistant. Ask me anything about the docs!

I can help you with:
- Code examples
- Configuration details
- Troubleshooting
- Best practices

Try asking: How do I configure the API?
09:31 AM