# Rollschool feedback surveys

## Current model and rollout

The module is controlled by `SURVEYS_ENABLED`, initially disabled and managed in
**Zarządzanie stroną → ustawienia systemu**. It uses MINI3 MVC, Bootstrap 5.3.8,
the existing editable text service, notification queue and RollPoints ledger.
There are no new dependencies, configuration secrets or server file operations.

There is one general family questionnaire and independent personalized campaigns.
The former separate standard definitions supply three object question sets:
**groups, locations and instructors**. A fourth **O Rollschool** set collects
one general opinion per family completion, without a rated object. Category/level
remains an audience filter, not a rating section. The old definitions' rewards, enabled/public flags
and individual target flags do not control the general questionnaire.

Migration `20261020120000_add_general_survey.sql`:

- preserves all existing section questions and their identifiers;
- adds one `survey` definition with `code = kind = general`, initially disabled,
  public, with base reward 0 and invitation reward NULL;
- adds `survey_answer.id_survey_target` (unsigned integer, default 0);
- replaces answer uniqueness with
  `(id_survey_response, id_survey_question, id_survey_target)`;
- removes only the obsolete target placeholder/separator from the general email
  template, preserving the other customized body text and opt-out instruction.

The migration is additive and retry-safe. It does not drop tables, columns or
records, rewrite applied migrations, reset administrator configuration on replay,
or migrate/archive real responses. No participant rollout has occurred.
The historical category definition remains stored but has no participant/admin
rating entry point. Existing personalized answers use target 0 and retain their
one-answer-per-question constraint.

Follow the standard full-backup migration runner. After code and migration are
available, configure the general survey in **Ankiety → Ankieta ogólna** before
activating it. Module activation and a deployment require explicit authorization.
Old per-object participant links redirect to the general form; their invitations
never grant access to the new definition. Old admin configuration/audience links
redirect to the corresponding general screen. A code rollback must keep the
module disabled until the old code/schema compatibility has been reviewed;
never undo schema or erase answers automatically.

Migration `20261020160000_add_rollschool_survey_section.sql` adds only the
`standard_rollschool` definition (`kind = rollschool`), with no schema changes,
new tables, question seeds or changes to existing settings. It is replay-safe.
The section questions are entered through the administrator panel. Its own
activation/reward columns are unused; the general definition controls access/RP.
Answers use the existing target 0 and question identity, once per completion.

## Six tables

| Table | Current responsibility |
| --- | --- |
| `survey` | General definition, four section definitions and personalized campaigns. |
| `survey_question` | Stable text, type, required flag, position and visibility. |
| `survey_target` | An object linked to its section definition; created/reused at submission. |
| `survey_response` | One complete questionnaire, technical main-account association, submission time and one RP award. |
| `survey_answer` | Typed answer to a question for a rated target; target 0 for Rollschool questions and personalized campaigns. |
| `survey_recipient` | A single invitation attempt to the whole questionnaire, its response cycle, batch and mail queue reference. |

Section targets are not public availability controls. Form GETs and audience
previews create no target rows. Repeated invitations create separate recipient
rows, preserving delivery/conversion cohorts without extra tables.

## Family eligibility and form

`SurveyEligibility` supplies confirmed attendance within the last 30 days for
an active main account and its active children. Group meetings must belong to a
visible/active season. Attended courses must be completed and not cancelled;
individual lessons must be completed. Meeting-level location and actual
instructor are used, including instructor substitutions. A course/individual
lesson contributes location and instructor, never an invented group/category.
Future meetings, absences and old-season groups do not qualify.

`SurveyGeneral` builds **Grupy → Lokalizacje → Instruktorzy → O Rollschool**. Each distinct object
appears once across the family, regardless of children or repeated meetings.
Object sections without eligible objects or visible questions are omitted.
Group headings show the category, location, weekday, start time, group number
and the instructor currently assigned to the group (`event.id_instructor`).
The same label is used in survey administration and results, including historical
responses; it is not a snapshot of a meeting or its substitute instructor.
Groups without an assigned instructor omit that part. No data migration is needed.
To verify, open a family survey and compare the group heading with its assigned
instructor; administration choices should show the instructor only once.
Rollschool questions appear once, without an object heading/count or target row;
the section is omitted when it has no visible questions. Recent confirmed family
attendance is still required, including when only Rollschool questions are configured.
Object questions repeat once for each object within their section. The form uses one address,
`ankiety/wypelnij/<general-definition-id>/`, without an object identifier.

The mobile form uses Bootstrap tabs that wrap at narrow widths, with an active
section indicator. It provides **← Poprzednia sekcja / Następna sekcja →** at the end
of each applicable section and one final **Wyślij ankietę**. Switching sections
focuses and scrolls to the start of the selected step, without manually returning
to the top.
Earlier answers remain in the same form when changing steps. Required questions
are validated before next and again across all steps on final submit. Without
JavaScript all sections remain visible and native validation still applies.
Ratings 1–5 retain colors, a single mobile row and scale explanation; optional
booleans offer **Nie mam zdania**. No answers or consents are preselected.
A final completeness marker detects truncated POST data. At least one answer is
needed overall; unanswered optional questions are omitted, not stored as zeros.

## Access and invitation lifecycle

The general definition has one enabled flag, one public-access switch and two RP
rates. Disabling it blocks every form and new audience approval, including
invited accounts. Public means eligible logged-in main accounts may complete it
90 days after their latest general completion. It is not an anonymous public form.

An active invitation is an account-level recipient row for the latest general
response cycle (the latest response ID, or 0 before any response). It lasts exactly
seven calendar days from audience approval, with the end exclusive. It grants
one full completion even within the organic 90-day cooldown, regardless of how
the account opens the form. The next completed response changes the cycle and
consumes that invitation. An active unused invitation excludes further selection.
After completion or expiry the account can be explicitly selected again.

On expiry, public access falls back to the normal 90-day rule and base rate.
Private access requires a new invitation. Eligibility is rechecked when opening
and submitting the general form; an invitation does not invent recent attendance.
Personalized assignment instead persists until that campaign ends, even if its
original qualifying attendance later falls outside the selection window.

**Oceń nas** shows at most one general questionnaire, plus available personalized
campaigns. A public questionnaire in cooldown can show its next eligible date.
The **Moje zajęcia grupowe** shortcut includes active unused general invitations
and available personalized campaigns. It links to the whole questionnaire, not a
single object. Selecting a child never changes the respondent or family limit.

## Editing questions

One configuration form saves the global settings and all four question sets in
one transaction. Adding a question in the browser does not submit that form or
reset title, description, access or reward fields. Save confirmation uses the
shared flash modal; validation retains safe input.

Adding a question does not replace the questionnaire, reset answers or reset
cooldowns. A new question starts gathering answers only from that point. Hiding
one removes it from forms and all displayed reports/comments, while preserving
its answers. Correcting text keeps the same question ID/results. A changed
meaning should be represented by hiding the old question and adding another.
Changing the type of a question that already has answers is rejected.

The complete question ID set is validated to reject truncated/stale editors.
Root/section locks serialize edits against general submissions. A loaded form
whose visible questions, family object set, invitation or reward changed must
be reviewed again before submission; safe previous answers remain available.

## Audience selection and email

General administration has **Konfiguracja · Zaproś · Odbiorcy · Wyniki**.
Administration and the shared instructor results use a compact layout based on
Bootstrap spacing utilities. Recipient counters occupy two text rows; overview
totals are inline. Result questions, result sections and comments use simple
separators instead of individual cards. Answer distributions wrap horizontally,
while monthly trends remain expandable. Filter fields use desktop columns and
stack on narrow screens. Cards retained for campaign choices, configuration,
question editing and invitation forms have reduced padding and explicit margins.
This presentation change preserves all filters, figures, privacy thresholds,
question controls and form submission protections; participant questionnaires
retain their existing layout.
`ankiety_admin/uruchom/` retains audience selection under **Zaproś**;
`ankiety_admin/odbiorcy/` lists approved general invitations. Existing personalized
audience URLs with an explicit survey identifier retain their selection form.
The history has one row per invitation attempt, including historical attempts,
with account name/email, selection time, seven-day deadline, completion status
and completion time. It does not expose answers, response identifiers or links
to an individual's answers, and is restricted to administrators by the existing
controller guard. It does not inspect mail transport logs or show queue/delivery
statuses. For survey operations, queueing invitation email counts as sending it.
An envelope icon marks attempts with a non-null `id_comm_queue`, regardless of
the queue record's current status or existence. It does not query `comm_queue`.
Existing accounts link to `zarzadzanie/pokaz_uzytkownika/<id_user>/`; deleted
accounts retain invitation history without a broken profile link.

The summary always covers all general invitations, independent of list filters,
pagination and filter validation errors. It counts invitation attempts in total,
currently pending attempts, expired unanswered attempts, and distinct matched
completions overall and in the last 7/30 days. Public completions without a valid
invitation are excluded. Completion windows use submission time, from the current
Warsaw time minus 7/30 calendar days (inclusive) through the current time
(inclusive). Pending and expired use the same deadline rule as the list. All
metrics share the list's invitation-to-response matching query, including renewal
and cycle handling. No migration, configuration change or mail-log access is needed.

Completion metadata is derived from the first response after the invitation's
`cycle_key`, submitted at or after selection and strictly before its seven-day
deadline. Responses after expiry do not complete an expired invitation; renewed
invitations remain separate. Otherwise the status is pending before the deadline
and expired at or after it. This status describes the invitation lifecycle;
current module availability, account eligibility or survey configuration may
independently block access. Historical data is not rewritten and no migration
or environment configuration change is required.

History supports literal substring search by account name/email, status and an
inclusive selection-date range in the application's timezone. Invalid dates or
reversed ranges show validation errors. Results use 50-row pages ordered by
selection time and invitation ID descending; pagination preserves all filters.
Verify a current unanswered invitation, a completion within its validity window,
an expired attempt followed by a new invitation/completion, date boundaries,
literal wildcard search, empty results, pagination, global counters across
filters, completion periods, profile links and mail indicators. The regression scenario
is `tests/survey_recipients_test.php` using the isolated survey fixture database.

Audience filters select accounts only; they never narrow the subsequent family
questionnaire. Instructor, location, category, group and explicit participant
filters are supported. Multiple values of a filter are alternatives; different
filters must match the same meeting. An explicitly selected parent can qualify
through their children. Children are mapped to the main account before deduplication.
Categories and enrollment filters concern groups. Enrollment is **Obecnie zapisani
stale / Bez aktualnego zapisu stałego / Wszyscy**. General attendance always uses
the last 30 days; personalized campaigns retain selectable attendance dates.

Selection modes are random total, random per explicitly selected active group,
or all qualified accounts. The per-group algorithm randomizes group order,
allocates each family at most once globally and may underfill a group's quota
when accounts overlap or the pool is small. The preview shows the exact selected
account list, qualified/selected/mail counts and per-group counts where relevant.
A preview lasts 15 minutes, is stored server-side and requires explicit approval.
Approval reuses the selected set without drawing again. Account/cycle, consent,
email, questionnaire and source-group eligibility changes invalidate it atomically.
Repeated approval is idempotent. No per-instructor/location/group campaign is
created or activated by this operation.

`user.survey_invitations` is independent of marketing and defaults to off. Switches
in registration (below marketing), account settings and **Oceń nas** use the same
preference. Lack of consent never blocks in-system invitation access. Only
consenting accounts with confirmed email addresses contribute planned mail.
No reminders are sent. Each invitation attempt can queue at most one message.
A renewed attempt cancels previous unsent messages and creates a fresh recipient
row rather than overwriting the old invitation date/queue reference.

`mail_survey_standard` (general) and `mail_survey_custom` are editable templates.
Participants see titles, rewards and deadlines, without technical classification.
Both explain how to stop invitation email and link to
`konto/ocen_nas/#survey-invitations`. Immediately before SMTP, `CommQueue` rechecks
the module flag, current consent/address, questionnaire availability and invitation
expiry/consumption. Old per-object messages are rejected. Non-survey mail is
unaffected. The module never invokes a separate mail transport.

## Atomic completion and RP

The account and general definition are locked before checking the current cycle.
Submission rechecks eligibility, invitation, visible questions, required answers
and the displayed reward fingerprint. All context answers, the one completion,
the used invitation cycle and the RP credit are committed in one transaction.
The main-account lock serializes requests for different forms/keys; the unique
request key supports idempotent retry. The ledger source is `survey`, with that
opaque key and generic description **Nagroda za wypełnienie ankiety**.

There is one award for the entire form, regardless of children, sections or
objects. During an active invitation, `invited_reward_points` replaces the base
rate; NULL falls back to base, explicit 0 earns none. Otherwise `reward_points`
applies only if organic access is allowed. Existing RollPoints membership is
checked at submission. No membership means no points and no retroactive credit
after joining. Ratings and mail consent do not affect the award. Nonmembers see
a prompt to join before submitting when the available rate is positive.

## Personalized campaign archive

Migration `20261020170000_add_survey_archive.sql` adds the approved
`survey.is_archived` boolean, NOT NULL/default 0, without new tables or removal.
The guarded migration is retry-safe and leaves all existing campaigns on the
main list. New definitions and copies default to not archived.

Only personalized campaigns can be archived/restored. Both transitions lock the
definition in a transaction, preserve its active flag, start/end dates, closure,
questions, responses, invitations and RP, and are idempotent. The administrator
list excludes archived campaigns; **Archiwum** contains only archived personalized
campaigns. Results and copying remain available. Archived drafts cannot be
edited until restored; copying creates a separate disabled, unarchived draft.

Archiving blocks form access, new submissions, audience previews/confirmation,
account/class shortcuts and queued invitation delivery through the existing
availability guard. It does not erase or reset anything. Restore removes only
the archive flag: a still-active open campaign within its original dates becomes
available to its assigned accounts again; completed accounts cannot answer twice.
Closed or expired campaigns stay unavailable, and restore never extends dates.
A queue item already discarded while archived is not recreated by restore.

Archive/restore requests use the existing administrator-level controller, POST,
CSRF, shared confirmation modal and one-time success modal. No public FAQ update
is needed for this administrator-only organization feature. On the main list,
new-campaign creation sits below the list navigation, and the general invitation
button belongs to the general questionnaire card. The list explains the ongoing
90-day general survey, separate seven-day invitation rate and panel/email
notifications. Personalized campaigns are described as occasion-specific
one-off research with retained results but no trends; ongoing satisfaction
tracking belongs to the historical general questionnaire.

Verify with `survey_archive_test.php`, the custom/general regression suites and
`survey_interface_test.php`. Check the list/archive navigation, confirmation,
restore, retained reports, availability and queued mail on an isolated database.
Only the additive migration is required by deployment; no extra file or config
operations are needed. Old code ignores the archive flag, so keep the survey
module off during a rollback until archive availability behavior is reviewed.

## Reports and confidentiality

**Przegląd Rollschool** distinguishes completed forms, distinct responding
accounts, rated objects and object assessment sets (distinct response/target
pairs with at least one visible answered question). It never combines different
questions into one average. Group, location and instructor summaries are
separate. Rollschool has its own response-set count and direct details view,
with distributions, comments and the same periods/trends, without object comparison.
These results are administrator-only and never enter instructor panels. Comment
filters include Rollschool without requiring an object. Section reports constrain
both the question definition and answer context, so target 0 cannot mix campaigns.
One instructor/location assessment is not multiplied by related groups.

Area lists support object-name search, a comparison question and period. By
default all active questions appear in definition order, each with its full text
above a separate table. Selecting one question limits the report to that table.
Rows sort by the displayed result descending, with alphabetical object names
breaking ties. Open questions, which have no numeric result, sort alphabetically.
Sorting applies before pagination. Each table paginates independently at 50
objects and retains the shared filters.
Tables show answer count, distinct account count, average rating or percentage yes,
and the recent-30-day change versus the preceding 30 days. Open questions show
counts rather than an invented numeric metric. Object details include all visible
questions, distributions, comments, recent/previous/earlier comparisons and a
12-month trend. **Komentarze** filters by area, object and period. Lists paginate
at 50 objects/comments. Optional missing answers never enter denominators.

Administrators see anonymous individual answers scoped to one object (or one
personalized campaign). They never receive the linked family questionnaire.
Delivery reports belong to the whole questionnaire: invited distinct accounts,
invitation attempts, actually sent messages and converted attempts. Conversion
matches the first response in that cycle within the invitation's seven-day
window. Cohorts are selected by invitation approval date; organic completions
are counted separately by response date. No queue-monitoring metrics appear.

Instructors may see only their own instructor object and currently led active
seasonal groups; personalized campaigns and location results remain admin-only.
A minimum of three **distinct main accounts** is enforced separately for each
object, question and reporting period, including comments and both compared
periods. Repeated early completions by one family do not satisfy that minimum.
No individual answer packets are supplied to instructors.

Report DTOs contain no author/child identity, response/invitation/ledger IDs,
request keys, exact individual submission time, or cross-context family links.
Comments are ordered by content rather than submission time. Free text may itself
identify someone; participants are asked not to enter personal data. Feedback is
internal only: no publication consent, pseudonym or public review publication.
The privacy policy and concise participant FAQ describe the current flow.

Disabling the module preserves data and the ability to revoke email consent.
The prior manually approved publication-column cleanup remains independent;
no destructive cleanup is included in the new automatic migration.

## Verification

Use `scripts/prepare-rollpoints-tests.php` with a new `RP_TEST_DATABASE` matching
`codex_rollpoints_*`. It clones ordinary schema without customer records, includes
the general migration and builds test ledger tables. Never point these tests at
an application database. Queue fixtures use `.invalid` addresses and never SMTP.

Core suites: `survey_rollschool_test.php`, `survey_general_test.php`, `survey_launch_test.php`,
`survey_public_access_test.php`, `survey_invitation_reward_test.php`,
`survey_results_test.php`, `survey_editor_test.php`, `survey_test.php`
(personalized regression), and `survey_general_migration_test.php`. Fixtures roll
back. `survey_concurrency_test.php` requires a fresh disposable isolated schema;
it commits synthetic fixtures and starts independent PDO/PHP workers to verify
same-key replay and different-key single invitation consumption.

Keep interface, shortcut, registration, historical access/default-copy/template
and metadata-cleanup regressions. Check PHP/JS syntax and browser behavior at
phone/desktop widths: required-step validation, back navigation retaining input,
final modal/single award, shared settings with dynamic questions, exact audience
preview, overview/list/object/comment reports and instructor restrictions.

Participant/admin instructions: [ankiety-instrukcja.md](ankiety-instrukcja.md).
