This document provides instructions and technical guidelines for AI agents working in the Map-OS repository.
Map-OS is an open-source Service Order and Business Management system built in PHP using the CodeIgniter 3 framework.
- Language: PHP >= 8.5
- Framework: CodeIgniter 3 (
application/) - Database: MySQL / MariaDB (managed via CodeIgniter Query Builder and Migrations in
application/database/migrations/) - Dependency Manager: Composer (vendor directory configured at
application/vendor) - Front-end Build: Tailwind CSS v4 and the JS libraries (Alpine.js, Tom Select, flatpickr, IMask, SweetAlert2, Chart.js 4, FullCalendar 6) via npm (
package.json, Node >= 22). Only needed to change views, CSS or JS libraries; installing Map-OS never requires Node.
application/controllers/: Request handlers and business logic entry points.application/models/: Data access layer and database operations.application/views/: Frontend view templates (Tailwind, v5 components). Print views (imprimir*.php) useassets/dist/imprimir.cssand PDF reports (relatorios/imprimir/) useassets/dist/pdf.css, both built with Tailwind (see Front-end Build).application/libraries/: Custom libraries, REST controllers, and payment gateway integrations.application/config/: Configuration files (config.php,database.php,routes.php, etc.).application/database/migrations/: Database schema migration files.docker/: Docker Compose configuration for local development.
- Code Formatting:
- Always format PHP code using project standards:
composer format(which invokesapplication/vendor/bin/php-cs-fixer fix).
- Always format PHP code using project standards:
- Security & Input/Output Handling:
- Always validate user input.
- Always escape output in views with
e()(application/helpers/escape_helper.php):<?= e($cliente->nome) ?>. Trusted HTML goes throughprintSafeHtml()(HTMLPurifier), never raw. - CI runs
php scripts/check-escape.php, which fails on any new unescaped<?= $x ?>/echo $xinapplication/views/. Existing occurrences are counted per file inescape-baseline.json; never raise those counts to make CI pass — escape the output instead. - Never use raw SQL string concatenation; use CodeIgniter Query Builder or query bindings (
?or$this->db->where()) to prevent SQL injection. - Never expose sensitive data (e.g., password hashes) in public models or API responses.
- Every login entry point goes through
Limite_login(application/libraries/Limite_login.php): checkbloqueado()before verifying the password, callregistrarFalha()on a wrong e-mail or password andregistrarSucesso()on success, and answer with the same generic message for an unknown e-mail and a wrong password.
- Database Changes:
- Schema modifications must be implemented via migrations (
application/database/migrations/), never by editingbanco.sqldirectly.
- Schema modifications must be implemented via migrations (
- Commit Messages:
- Follow Conventional Commits:
feat,fix,docs,refactor,chore, etc.
- Follow Conventional Commits:
- Tests:
- Run
composer test(PHPUnit,tests/Unit) andcomposer analyse(PHPStan) before opening a PR. Tests must execute the behavior; a test that only reads the source code does not catch runtime errors. Security changes need a test for the denied case (no permission, another customer's record, invalid value).
- Run
- Files, API and docs:
- Service-order attachments and files from the Arquivos screen live in
STORAGE_PATH(outsideassets/) and are served by controllers that check permissions; never link them by a public URL (docs/armazenamento-de-arquivos.md). - The API only exists with
API_ENABLED=true(everyapi/v1route answers 404 otherwise); authentication is described indocs/api-autenticacao.md. - A change that alters what an upgrading admin has to do (new
.envvariable, migration, route) updatesdocs/migracao-4x-para-5.md.
- Service-order attachments and files from the Arquivos screen live in
DESIGN.mdis the source of truth for the v5 UI — colors, typography, components, states, dark mode, and responsive behavior. Read it before touching any view, component, or CSS, and reference its token and component names ({colors.primary},button-primary,pill-status, ...).- When existing code diverges from
DESIGN.md, the document wins. The foundation is being aligned in epic #2911 (done: tokens #2912, accent picker removed in #2913, replaced by the color themes of DESIGN.md (Color Themes), local fonts #2914, Lucide icons #2915, components #2916, sidebar/topbar #2917, logins #2918, sticker illustrations #2919); don't build new screens on the parts it replaces. - Non-negotiables:
- One action color at a time: orange
#F37338is the default and the brand; the user may pick a color theme (DESIGN.md, Color Themes, values checked bynode scripts/contraste-temas.mjs). The label is always the theme's{colors.on-primary}(ink on orange, never white; white only where the theme table says so), and status never uses the action hex. One filledbutton-primaryper screen; secondary actions usebutton-outline/button-ghost. - Orange means "act here" only. States use the semantic status palette (success, warning, danger, info, progress, neutral) as a
pill-statuswith its word; red is only for errors and destructive actions (button-dangerinsidemodal-confirm). - A thin orange indicator (active sidebar item, tab, pagination) always has a second cue: weight 600 text and the
{colors.primary-tint}background. - Data (table cells, values, typed input text) is weight 400; labels and names are 500 (
{typography.label-md}). - Form controls use the
{colors.hairline-input}border and implement the focused, error, and disabled states from the spec. - Dark mode always switches the whole screen (Panel Dark Mode tokens), never a single band. The dark sidebar of a color theme in light mode is part of the theme; in dark mode the sidebar is dark too.
- Only design tokens — no fixed colors, sizes, or fonts outside
assets/src/tokens.css(theme values included, never hard-coded in views or components). Icons are Lucide; fonts (Rubik, Space Grotesk) are served locally.
- One action color at a time: orange
- Changing the design system is a PR that edits
DESIGN.mdfirst — with recalculated WCAG contrast ratios — and then the code.
- Source CSS lives in
assets/src/(app.cssfor new screens,layout.cssfor the admin shell, sharedtokens.css); the compiled output inassets/dist/is committed. - After changing any view or CSS, run
npm ci && npm run buildand commit theassets/distchanges. CI rebuilds and fails if the committed output is stale. - Tailwind scans
application/views/**/*.php: write full class names in PHP, never build them by string concatenation. - JS libraries are copied by
npm run build:vendor(scripts/build-vendor.mjs, part ofnpm run build) intoassets/vendor/<lib>/, which is committed and fully generated: never edit it by hand. To add or update a library, pin it withnpm install --save-exactand list its files inscripts/build-vendor.mjs. jQuery, Bootstrap, the Matrix theme and Font Awesome are gone from the whole project, including the print views, the PDF reports and the installer (#2960); do not add them back or libraries that depend on jQuery. - Never commit
node_modules/. - Three more Tailwind builds, all part of
npm run build:cssand committed:assets/dist/imprimir.css(A4 and receipt print views opened in the browser:os/imprimir*,vendas/imprimir*,garantias/imprimir*,conecte/imprimir*; document classesdoc-*andcupom-*inassets/src/imprimir.css),assets/dist/pdf.cssandinstall/assets/css/instalador.css. mPDF reads only CSS 2.1 plus a little CSS 3 (no variables,@layer, flex, grid, logical properties), soassets/src/pdf.cssis flattened byscripts/build-pdf-css.mjs: inrelatorios/imprimir/use only table, border, color, typography, float and spacing utilities (therel-*classes) and check the result with a real PDF. The installer (install/) is standalone, with its own CSS and plain JS (noassets/dist, no jQuery). - New views use only the design tokens from
assets/src/tokens.css(bg-surface,bg-surface-subtle,text-text,text-muted,border-border,border-input,bg-primary+text-on-primary,text-danger-inkonbg-danger-soft, ...; the file header lists them). Tailwind's default palette is disabled, so fixed colors such asbg-whitedon't exist. Theme settings areapp_tema_modo(claro/escuro/sistema) andapp_tema_cor(padrao/azul/verde/violeta/grafite,TEMA_CORES), each overridable per user (usuarios.tema_modo,usuarios.tema_cor); the layout prints them withtemaAtributosHtml()(tema_helper.php:data-tema-modo,data-tema), and the client area stays on the brand colors.tests/js/temas-tokens.test.mjsfails iftokens.cssdrifts fromscripts/contraste-temas.mjs. There is no free accent color picker (#2913): the only color choice is one of the fixed themes in DESIGN.md (Color Themes), each with its own checked palette; the default is the orange brand. - No inline
<script>code in views. Page JS lives in ES modules underassets/js/modules/<folder>/<name>.js(no bundler); the view attaches it with<?= js_module('folder/name') ?>on an element and passes data viadata-*attributes or<?= page_data('id', $data) ?>(application/helpers/js_helper.php).assets/js/app.jsloads the modules. AJAX goes throughget()/post()inassets/js/lib/http.js(CSRF token,X-Requested-With, 403 handling). php scripts/check-inline-script.php(run in CI through PHPUnit) fails on new inline<script>blocks; legacy ones are counted ininline-script-baseline.json. Never raise those counts. JS utilities are tested withnpm run test:js.- New views build UI from the component library instead of hand-written markup:
<?= component('button', ['label' => 'Salvar', 'type' => 'submit']) ?>(partials inapplication/views/components/, props and validation inapplication/helpers/componente_helper.php). Components escape every value; slots (body,footer,actions,message, table cells) only accept HTML as anHtmlSeguro(output ofcomponent()orhtml_purificado()), never as a string. Never build anHtmlSeguroby hand from user data. Extra attributes go in theattrsprop;on*handlers are rejected. The catalog is at/index.php/componentesindevelopmentonly. - The component library follows the
DESIGN.mdspecs:button(variants primary, outline, ghost, danger, inverted, ghost-on-dark, link — one primary per screen; inverted/ghost-on-dark only on dark entry surfaces),input/select/textarea/checkbox/radio/switch(with help, error and disabled states),pill-statusfor every OS/sale/charge state (success, warning, danger, info, progress, neutral — neverbadge, which is only for counters),alert,toast,modal,modal-confirm(destructive confirmation withbutton-danger),data-table,kpi-card,tabs,pagination,card,empty-stateandbreadcrumb. - Icons are Lucide, from an SVG sprite with only the names in
assets/src/icones.json:<?= icon('wrench', ['class' => 'size-4']) ?>in views (application/helpers/icone_helper.php; components take the name in theiconprop) andcriarIcone('wrench', 'size-4')fromassets/js/lib/icone.jsin JS. A new icon goes intoicones.jsonfollowed bynpm run build:vendor;IconeTestfails on names outside the list. Boxicons and Font Awesome are gone. - New listings follow the pattern of
Clientes::gerenciar()+views/clientes/clientes.php(#2852): filters in the query string read withlistagemFiltros()(allow-list) and counted with the same filters;component('pagination', $this->paginacao($baseUrl, $total, $offset, null, $filtros))keeps them in the links; distinct empty states for "nothing yet" and "no match"; row actions as ghost icon buttons gated by$this->permite('xPerm')(UI only — routes are protected bypermissions_map.php); deletion through one sharedmodal-confirmfilled bydata-valor-*on the row button. - New forms follow
Clientes::formulario()+views/clientes/formulario.php(#2851): plain POST with CSRF;<form novalidate <?= js_module('formulario/padrao') ?>>validates with the HTML constraints and shows errors in the field (assets/js/lib/formulario.js), appliesdata-mascaraand puts the submit button in a loading state; the server always revalidates with$this->validarFormulario('grupo')(pt-br messages, errors per field passed to each component'serror), re-renders with the posted values or redirects with a success flash (toast). The edited id comes from the URL, never from the POST, and the saved data comes from a function that only reads the form fields. Paginate withcomponent('pagination', $this->paginacao($baseUrl, $total, $offset))(MY_Controller::paginacao(), same URL offset asCI_Pagination). No panel screen usesCI_Pagination::create_links()anymore (application/config/pagination.phponly remains for the app API); do not add markup back toMY_Controller. - Screen parts that change without a reload follow the OS screen (#2842:
Os::visualizar(),views/os/partes/,assets/js/modules/os/tela.js): each part is a partial view used on first render insidedata-os-parte="<part>"; forms withdata-os-acaoare posted throughpost()(lib/http.js); the endpoint answers JSON{result, message, erros?, html?}with the re-rendered parts and per-field errors (403 no permission or closed record, 404 item of another record, 422 field errors). The record id comes from the POST but is checked in the database (exists, editable) and every item must belong to it; totals, discounts and stock are always computed server-side. - Admin screens render through
MY_Controller::layout()(views inapplication/views/tema/, data fromapplication/helpers/layout_helper.php). The menu comes fromlayoutMenu(), split into sidebar sections by each top-level item'sgrupo(Operação, Financeiro, Sistema), and each item is shown only ifpermissions_map.phpallows its target route. A screen's primary action (its singlebutton-primary) goes in the topbar as button props, with an icon (phones show it icon-only):$this->data['topbar_acao'] = ['label' => 'Nova OS', 'icon' => 'plus', 'href' => site_url('os/adicionar')]. - Entry surfaces (the panel and client-area logins) are always dark, whatever the panel color mode: they include
application/views/entrada/inicio.phpandfim.php(dark canvas with the starfield image, top nav with the secondary action asbutton-ghost-on-dark, lime squiggle footer) and put the form card in.superficie-entrada, a token scope intokens.cssthat applies the dark palette to the card while keeping form fields light. - Sticker illustrations live in
assets/src/stickers/(readable source) and are optimized bynpm run build:stickers(svgo, part ofnpm run build) intoassets/img/stickers/, which is committed. Only on entry surfaces and dark highlights, never inside cards or on operational screens; never orange; used as<img alt="" aria-hidden="true">hidden on small phones.StickerTestchecks size (< 4 KB), palette and usage. Every panel screen renders throughlayout()withassets/dist/app.cssandassets/dist/layout.css(there is no legacy mode anymore). Shell markup goes inside a.v5-shellwrapper, whose Tailwind utilities and reset (assets/dist/layout.css) are scoped there and!important; the screen content goes in.v5-conteudo, outside.v5-shell, and usesapp.css; never put screen content inside.v5-shell.
- Secrets: Never log, print, or commit
.envfiles, credentials, API keys, or database dumps. - Vulnerabilities: Security issues must be handled following
SECURITY.md(report privately tocontato@mapos.com.br).