mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-27 14:23:05 +00:00
Compare commits
8 commits
59a6480df8
...
f1bc634385
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1bc634385 | ||
|
|
8608aeb317 | ||
|
|
fa1bf52ccd | ||
|
|
90a9d0039a | ||
|
|
5a3fec1e78 | ||
|
|
432d5a10e2 | ||
|
|
35eb2ed432 | ||
|
|
ad2b165e5e |
41 changed files with 7598 additions and 250 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -84,6 +84,8 @@ next-env.d.ts
|
|||
/data/falas-web/
|
||||
# C231 — Flickr photo-archive cache + receipts (pnpm flickr:import)
|
||||
/data/flickr/
|
||||
# C230-followup — Instagram content import receipts (pnpm content:instagram:import)
|
||||
/data/content-instagram/
|
||||
# C229 — speech semantic index reports (pnpm acervo:index)
|
||||
/data/acervo-index/
|
||||
# C232 — photo-archive cataloguing receipts (pnpm archive:catalog)
|
||||
|
|
|
|||
10
Dockerfile
10
Dockerfile
|
|
@ -19,6 +19,11 @@ FROM base AS migrator
|
|||
WORKDIR /app
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
# C230-followup — the maintenance image is also the runtime of the operational
|
||||
# CLIs, and the Central content import job (`content:instagram:import`) extracts
|
||||
# audio with ffmpeg; the runbook executes it in this service. The deps/builder
|
||||
# stages still never pay for it.
|
||||
RUN apk add --no-cache ffmpeg
|
||||
# Bake the package manager INTO the image: `pnpm migrate` runs at CONTAINER
|
||||
# START, so without a corepack cache the runtime downloads pnpm from
|
||||
# registry.npmjs.org — the maintenance container's outbound is not guaranteed
|
||||
|
|
@ -75,8 +80,9 @@ FROM base AS runner
|
|||
WORKDIR /app
|
||||
|
||||
# C167 — `ffmpeg` cuts the exact [início,fim] excerpt of an acervo speech
|
||||
# (speechCutJob). Only the runner stage pays for it: the deps/builder/migrator
|
||||
# stages never run it. `FFMPEG_PATH` can still override the binary.
|
||||
# (speechCutJob). Only the runner and migrator stages pay for it (the migrator
|
||||
# is the maintenance CLI runtime, see above): deps/builder never run it.
|
||||
# `FFMPEG_PATH` can still override the binary.
|
||||
RUN apk add --no-cache ffmpeg
|
||||
|
||||
ENV NODE_ENV=production
|
||||
|
|
|
|||
1
docs/changelog/2026-09-29-c230-instagram-import.md
Normal file
1
docs/changelog/2026-09-29-c230-instagram-import.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**C230-followup — importação em lote do Instagram para a Central de Conteúdos (CLI) (2026-09-29):** a "Importar do perfil" da tela (C230) é sob demanda e de janela fixa (12 mídias, tudo Rascunho); a comunicação precisava de uma varredura maior, já publicada, sem scraping e pelo caminho oficial. O repo ganha o CLI `pnpm content:instagram:import`: lê o feed do perfil próprio pela Graph API (credencial do global `Social Feed`, fail-closed), filtra a janela por dias (`--days`, default 60), deduplica pela identidade do post (qualquer grafia de URL já catalogada — o predicado compartilhado com a colagem C220 e o importador C230), e com `--apply` cria cada novidade no shape do link e processa **inline** pelo pipeline C220 (download do arquivo do próprio perfil, transcrição e catalogação); com `--publish`, publica ao fim do lote o que terminou `pronto`, do mais antigo para o mais novo (o listing público ordena por `-publishedAt`, então o post mais recente lidera) — `falhou` fica rascunho e é nomeado no recibo, e uma falha de publicação é contada. O dry-run é o padrão (lê feed + banco, não baixa nem escreve) e os recibos JSON datados ficam em `data/content-instagram/`. Guardas no padrão C155/C195/C231: `--apply` exige `TEQO_ENV` casando o nome exato do banco (`teqo_1313`/`teqo_staging`), `CONTENT_INSTAGRAM_IMPORT_CONFIRM=1` fora do dev local, as quatro `S3_*` (a mídia vai ao bucket privado; sem elas o job gravaria em disco efêmero) e recusa `ALLOW_REMOTE_DB`; a credencial nunca entra em log/recibo. Dois donos ganharam um seam de sistema (sem twinning): `contentPieceExistsForPostIdentity` e `createContentPieceFromProfilePost` aceitam `actor: null` (bypass admin intencional, `createdBy` sem carimbo) e a criação devolve `{ outcome, contentPieceId }` — a ação da tela segue devolvendo só `{ outcome }`. O estágio `migrator` do Dockerfile passa a instalar `ffmpeg` (é o runtime dos CLIs de manutenção e o job extrai o áudio), com o comentário do C167 atualizado. Como o CLI escreve direto no banco (fora de request, o `revalidateTag` do hook é no-op nesse processo), o `--publish` revalida a Central pública ao final pela rota oficial (`tag=contentPieces`, best-effort, nomeado no recibo) — a tag entrou na allowlist do `/api/revalidate` como a do álbum no C233. Testes: unit do planejador (janela, dedupe nas duas direções, classificação peça-link, resumo com custo de ASR, recibo), das guardas do CLI em subprocesso (flag/TEQO_ENV/banco/S3/`--publish` sem `--apply`/argumento desconhecido), da allowlist nova e int do modo sistema (cria sem ator, sem gêmea, devolve o id). Runbook novo em `docs/ops/teqo-1313-deploy.md` (dry-run → canário → lote em tmux; staging antes quando possível) com a dependência de rede: o serviço de manutenção precisa da `teqo-ipv6` para o CDN do Instagram (post-mortem `2026-09-25`). Sem migration, sem UI, sem Consent.
|
||||
1
docs/changelog/2026-09-29-c231-exif.md
Normal file
1
docs/changelog/2026-09-29-c231-exif.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**EXIF do acervo do Flickr (2026-09-29):** o aceite do C231 pedia EXIF "quando houver" e a API do Flickr responde `getExif` com `raw`/`clean` embrulhados em `{ _content: "…" }` (herança XML) — o mapper só aceitava string e descartou todo mundo: as 6.492 fotos foram ingeridas com `exif: []`. `archivePhotoExifEntries` (`src/lib/archivePhoto.ts`) agora desembrulha os dois shapes (o helper `contentScalar` também substituiu o desembrulho ad-hoc do `description`, que já aceitava `_content`), e o CLI ganhou o modo `--refresh-metadata` — o backfill antes deferido: re-busca o EXIF das linhas existentes via API (pacing ~1 req/s), atualiza só o que mudou (`updateArchivePhotoExif`, write-only no campo `exif`, bypass de access documentado do CLI) e grava recibo com atualizadas/inalteradas/falhas nomeadas. Guardas: `--refresh-metadata` é mutuamente exclusivo com `--apply`/`--verify`, exige `FLICKR_IMPORT_CONFIRM=1` e o `TEQO_ENV` casando o banco exato fora de teste — mas **não** exige S3 (não sobe mídia). O geotag segue vazio porque a conta de fato não tem geo (`flickr.photos.search&has_geo=1` → total 0), não por bug. A operação de backfill em produção roda pelo runbook (`docs/ops/teqo-1313-deploy.md`, §C231) e o `--verify` passa a mostrar a cobertura de EXIF.
|
||||
1
docs/changelog/2026-09-29-c235.md
Normal file
1
docs/changelog/2026-09-29-c235.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**C235 — Central de Conteúdos: importar qualquer janela de publicações do perfil (2026-09-29):** a importação do perfil oficial (`@depjorgesolla`) deixa de ter só a janela fixa de 12 mídias recentes (C230) e passa a aceitar **qualquer período** — "Recentes" continua o default e o clique único, e "Período" (desde; até opcional, por data de publicação, com atalhos de 30 dias/6 meses/este ano) é gesto explícito que mostra o tamanho honesto antes de criar (**novas · já estavam · total na janela**) e confirma ("Importar N publicações"), com aviso âmbar de "Janela grande" acima de 50 novidades. O recibo continua honesto (**novas / já estavam / falharam com motivo**, peça-link com o porquê) e ganha o aviso de corte quando a via oficial não alcança o início da janela ("o Instagram entrega as 10K mídias mais recentes"; reexecutar continua sem duplicar). Mecânica sem teto artificial: o planner puro de janela/dedupe que vivia no CLI (`scripts/lib/instagramContentPlan.mjs`) passou ao dono em `src/lib/contentPieceProfileWindow.ts` (CLI re-exporta os nomes antigos, pins intocados) e a varredura usa o cursor do feed com **early-stop por data** — o teto defensivo de páginas do `loadInstagramFeed` agora deriva de `maxResults` (piso 20 intacto para board/sync/lookup; a janela de 10K sobe a 200 páginas) e o corte é denunciado por cobertura (`truncated`), nunca em silêncio. Limites civis da Bahia: as datas do formulário viram o início do dia `since` e o fim exclusivo do dia `until` (novos `formatCivilDateLabel`/`subtractBahiaCivilMonths` em `campaignTime.ts`); o request vira união (`{}`/`recent` default | `period` com `since`/`until`), com validação pura (data real, ordem, não-futuro) no schema e no cliente, e o lookup de identidade (`sourceUrl in` nas 3 grafias do post) roda em chunks de 2.000 URLs. Nada de novo em schema/Consent/collection (sem migration); o token segue só no servidor, fail-closed de credencial nas duas pontas e tudo entra como Rascunho. Testes: unit novo do módulo puro (janela com/sem bounds, bounds civis, validação, cobertura, label), pin novo do teto de páginas derivado e do CLI por re-export; int com `loadFeed` fake (período com `shouldStopAt` no limite, fora-da-janela fora, dedupe por variante de kind, `truncated` true/false, recente default 12, período impossível antes do feed, envelope da rota com `{}`/período/inválido). Verificação: `pnpm gate:fast` (451 arquivos, 4984 unit verdes), `pnpm test:int` (109 arquivos, 1068 verdes), lint/typecheck. **Design gate: artefato DEGRADED** (`docs/plans/central-conteudos-importar-janela-ui-design.html`, cenas 01–08 portadas classe-a-classe); a crítica de paridade do `designer` no tier primário (triggers b/c) não pôde rodar nesta sessão por quota (`usage limit reached`) e o humano deu **sign-off explícito** do artefato e do port (2026-09-29), registrado no PR com `Design tier: DEGRADED`.
|
||||
|
|
@ -1363,13 +1363,36 @@ docker compose --profile maintenance run --rm \
|
|||
```
|
||||
|
||||
Os recibos JSON ficam em `data/flickr/reports/` do container — monte um volume
|
||||
(`-v /srv/flickr-reports:/app/data/flickr`) para preservá-los. Guardas: fora de
|
||||
(`-v $HOME/flickr-reports:/app/data/flickr`) para preservá-los. Guardas: fora de
|
||||
teste o `TEQO_ENV=staging|production` é obrigatório com o **nome exato** do
|
||||
banco (`teqo_staging`/`teqo_1313`); `ALLOW_REMOTE_DB` é recusado; sem as 4
|
||||
`S3_*` o `--apply` recusa (o container gravaria em disco efêmero); e
|
||||
`FLICKR_IMPORT_CONFIRM=1` é exigido em alvo não-local. A chave da API nunca
|
||||
entra em recibo/log.
|
||||
|
||||
### Backfill de EXIF (`--refresh-metadata`)
|
||||
|
||||
Fotos ingeridas antes da correção do mapper gravaram `exif: []` (a API devolve
|
||||
`raw`/`clean` como `{ _content }`). O modo re-busca o EXIF das linhas
|
||||
existentes, atualiza só o que mudou e escreve apenas no banco — exige
|
||||
`FLICKR_API_KEY` e as guardas de escrita, mas **não** exige S3:
|
||||
|
||||
```bash
|
||||
# no homeserver (canary e depois o lote completo):
|
||||
docker compose --profile maintenance run --rm \
|
||||
-v $HOME/flickr-reports:/app/data/flickr \
|
||||
-e TEQO_ENV=production -e FLICKR_IMPORT_CONFIRM=1 \
|
||||
teqo-1313-migrate pnpm flickr:import --refresh-metadata --limit 5
|
||||
docker compose --profile maintenance run --rm \
|
||||
-v $HOME/flickr-reports:/app/data/flickr \
|
||||
-e TEQO_ENV=production -e FLICKR_IMPORT_CONFIRM=1 \
|
||||
teqo-1313-migrate pnpm flickr:import --refresh-metadata
|
||||
```
|
||||
|
||||
O recibo (`flickr-*-refresh.json`) conta atualizadas/inalteradas/falhas com
|
||||
motivo; o `--verify` mostra a cobertura (`EXIF: N`). O modo é idempotente:
|
||||
reexecutar converge e linhas inalteradas não são reescritas.
|
||||
|
||||
Rollback: a migration `add_archive_photo` é aditiva. O rollback funcional é
|
||||
apagar as linhas do `archivePhoto` no admin (o objeto correspondente no bucket
|
||||
pode ser removido à parte); reexecutar a ingestão recria as mesmas chaves de
|
||||
|
|
@ -1488,6 +1511,71 @@ levam vetor nem bytes de imagem). O engine carrega os mesmos modelos do
|
|||
navegador de `node_modules`; a cópia same-origin para o browser é artefato de
|
||||
build (`scripts/copy-face-vision-assets.mjs`).
|
||||
|
||||
## C230-followup — importação do Instagram para a Central de Conteúdos
|
||||
|
||||
O comando `pnpm content:instagram:import` traz as mídias recentes do perfil
|
||||
oficial `@depjorgesolla` para a Central pelo caminho oficial (Graph API da
|
||||
própria conta; a credencial é a do global `Social Feed`): cada novidade vira
|
||||
uma peça no pipeline C220 (download do arquivo do próprio perfil, transcrição e
|
||||
catalogação) e, com `--publish`, é publicada ao fim do lote o que terminou
|
||||
`pronto` — falha fica rascunho e é nomeada no recibo. Reexecutar converge
|
||||
("novas / já estavam / falharam com motivo") e nunca duplica: a identidade é o
|
||||
post, não a grafia da URL. Nada de scraping, terceiro ou stories; a mídia de
|
||||
terceiro nunca é baixada (o match é dentro do feed da própria conta).
|
||||
|
||||
O dry-run é o padrão e não escreve (lê o feed e o banco):
|
||||
|
||||
```bash
|
||||
# no homeserver:
|
||||
ssh homeserver
|
||||
cd ~/stack
|
||||
# 1) plano (dry-run; mostra janela, candidatos e peça-link previstos):
|
||||
docker compose --profile maintenance run --rm \
|
||||
-v /srv/content-instagram:/app/data/content-instagram \
|
||||
teqo-1313-migrate pnpm content:instagram:import --days 60
|
||||
# 2) canário no alvo (exige TEQO_ENV + confirmação; as 4 S3_* são obrigatórias):
|
||||
docker compose --profile maintenance run --rm \
|
||||
-e TEQO_ENV=production -e CONTENT_INSTAGRAM_IMPORT_CONFIRM=1 \
|
||||
-v /srv/content-instagram:/app/data/content-instagram \
|
||||
teqo-1313-migrate pnpm content:instagram:import --apply --publish --limit 2
|
||||
# 3) lote completo — rode em tmux: o processamento baixa, transcreve e cataloga
|
||||
# cada peça em sequência (docker compose run sem -d segura a sessão SSH):
|
||||
docker compose --profile maintenance run --rm \
|
||||
-e TEQO_ENV=production -e CONTENT_INSTAGRAM_IMPORT_CONFIRM=1 \
|
||||
-v /srv/content-instagram:/app/data/content-instagram \
|
||||
teqo-1313-migrate pnpm content:instagram:import --apply --publish --days 60
|
||||
```
|
||||
|
||||
Os recibos JSON ficam em `data/content-instagram/` do container — monte o
|
||||
volume acima para preservá-los. Com `--publish`, o CLI revalida a Central
|
||||
pública ao final pela rota oficial de revalidação
|
||||
(`POST {NEXT_PUBLIC_SITE_URL}/api/revalidate?tag=contentPieces`, com
|
||||
`REVALIDATE_SECRET` do env do stack — a tag entrou na allowlist do endpoint,
|
||||
como o álbum do C233); se a revalidação falhar, o
|
||||
recibo nomeia o motivo e o fallback manual no homeserver é
|
||||
`curl -X POST http://localhost:1313/api/revalidate?tag=contentPieces -H "x-revalidate-secret: $REVALIDATE_SECRET"`
|
||||
(no staging, `:1314`). Guardas: fora de teste o
|
||||
`TEQO_ENV=staging|production` é obrigatório com o **nome exato** do banco
|
||||
(`teqo_staging`/`teqo_1313`); `ALLOW_REMOTE_DB` é recusado; sem as 4 `S3_*` o
|
||||
`--apply` recusa (o job gravaria em disco efêmero); e
|
||||
`CONTENT_INSTAGRAM_IMPORT_CONFIRM=1` é exigido em alvo não-local. Sem
|
||||
credencial no global o comando falha fechado com a mensagem de produto; o token
|
||||
nunca entra em recibo/log.
|
||||
|
||||
**Rede:** o job baixa o arquivo do CDN do Instagram e a rota IPv4 do container
|
||||
é instável (post-mortem `2026-09-25-instagram-cdn-ipv4-instavel.md`) — o
|
||||
serviço de manutenção usado precisa estar anexado à rede `teqo-ipv6` do stack
|
||||
(a mesma do container de produção). Sem ela, parte dos vídeos vira peça-link
|
||||
por `indisponivel` (honesto, mas não é o desejado).
|
||||
|
||||
**Reprocessar uma falha:** um `falhou` fica rascunho e a reimportação **pula**
|
||||
o que já existe — o retry é o botão "Reprocessar" da ficha (C211), não uma
|
||||
segunda rodada do CLI. `--limit` deixa a cauda no lote: rode de novo (o CLI
|
||||
pula o que já entrou).
|
||||
|
||||
Rollback: nada de schema. O kill switch é despublicar/apagar as peças no admin
|
||||
(a Central pública atualiza na hora pelo tag `contentPieces`).
|
||||
|
||||
## Referências
|
||||
|
||||
- `scripts/deploy-homeserver.sh` — o script (fonte da verdade do fluxo; parametrizado por `TEQO_ENV`)
|
||||
|
|
|
|||
2746
docs/plans/central-conteudos-acoes-em-lote-ui-design.html
Normal file
2746
docs/plans/central-conteudos-acoes-em-lote-ui-design.html
Normal file
File diff suppressed because it is too large
Load diff
116
docs/plans/central-conteudos-acoes-em-lote.md
Normal file
116
docs/plans/central-conteudos-acoes-em-lote.md
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
# C236 — Central de Conteúdos — publicar, despublicar e apagar em lote
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-09-29
|
||||
Issue: #1388
|
||||
Priority: P2
|
||||
Impeccable: B — encaixe na lista existente da Central de Conteúdos (`/campanha/comunicacao/conteudos`): seleção múltipla + barra de ações
|
||||
Design UI: docs/plans/central-conteudos-acoes-em-lote-ui-design.html
|
||||
Appetite: ~1–1,5 dia eng; um outcome verificável — o mesmo veredito editorial aplicado a várias peças num gesto
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
A Central de Conteúdos resolveu o garimpo: a peça entra, é catalogada e publicada/despublicada por um gesto — mas o kill switch mora só na ficha, e apagar é uma confirmação por linha. O uso real chega em blocos: um evento despeja dezenas de peças, uma importação traz uma leva de posts, e a assessoria precisa dar o **mesmo veredito** a várias delas ("essas cinco vão para a pública", "essas três não servem"). Hoje são N decisões iguais custando N navegações.
|
||||
|
||||
O pedido humano é direto: "selecionar vários para publicar/despublicar/apagar". O C222 (`docs/plans/central-conteudos-apagar-peca.md`) declarou "sem lote" como anti-goal — mas o próprio Fora de escopo dizia "lote é item próprio se o uso pedir". **Este item é esse item próprio: a reabertura do anti-goal é de propósito**, do mesmo modo que o C222 reabriu o "sem delete" do C211. O lote não é semântica nova: é o gesto unitário existente repetido sobre a seleção, com recibo honesto.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** assessoria de comunicação (`communicator`; `coordinator`/`candidate` também), na mesa ou no celular, logo depois de uma leva de peças entrar — quando decidir caso a caso atrapalha a triagem.
|
||||
- **Job principal:** aplicar o mesmo veredito — publicar, despublicar ou apagar — a várias peças da tela num gesto, sem abrir ficha por ficha.
|
||||
- **Fluxo desejado:** abre a lista → marca as peças da página (checkbox na tabela, card no celular) → a barra aparece com `N selecionadas` → `Publicar`/`Despublicar` agem na hora com recibo; `Apagar` pede confirmação (avisando os links públicos quando houver publicadas na seleção) → a lista atualiza e diz o que aconteceu.
|
||||
- **Anti-goals de produto:** não vira planilha (sem edição de campos em lote); não é lote global (cross-page/"todos os filtrados"); não é pipeline (sem job assíncrono/progresso); não mexe na semântica do gesto unitário; não cria rota pública nenhuma.
|
||||
|
||||
### Esboço de fluxo (B)
|
||||
|
||||
```text
|
||||
[/campanha/comunicacao/conteudos] → marcar peças da página (checkbox na tabela, card no celular)
|
||||
→ barra "N selecionadas" · Publicar | Despublicar | Apagar
|
||||
→ Publicar/Despublicar: age na hora, lista atualiza, recibo "N peças publicadas/despublicadas"
|
||||
→ Apagar: confirmação (avisa links públicos das publicadas) → recibo "N peças apagadas"
|
||||
[outcome: o mesmo veredito em várias peças num gesto, com recibo honesto e sem ficha por ficha]
|
||||
```
|
||||
|
||||
### Design UI (B)
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-acoes-em-lote-ui-design.html` — cenas na tabela (~1280) e no card list (~390), barra de seleção, confirmação em massa e recibos; a forma do affordance é do design.
|
||||
- Design tier: DEGRADED (opencode-go/deepseek-v4.1-flash; frontier `openai/gpt-5.6-sol` sem quota) — sign-off humano obrigatório no PR.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- Selecionar várias peças **da página visível** (as 25 do filtro/página atual), com a seleção visível e contada na barra; "selecionar todas" = todas as da página; a seleção morre ao trocar de página ou filtro.
|
||||
- A barra de ações só existe com seleção ativa e oferece `Publicar`, `Despublicar` e `Apagar`; as ações por linha/ficha continuam exatamente como estão (o lote não cria publicar/despublicar por linha).
|
||||
- `Publicar` e `Despublicar` em lote agem sem confirmação (são reversíveis) e dão recibo; `Apagar` em lote sempre confirma — o diálogo avisa que, havendo publicadas, seus links públicos deixam de funcionar, e sempre que a ação não pode ser desfeita.
|
||||
- Nunca sucesso silencioso parcial: o recibo diz quantas peças foram afetadas e quantas falharam; a falha de uma peça não reverte as demais (é o mesmo gesto unitário, repetido) e a lista reflete o desfecho.
|
||||
- O lote respeita a elegibilidade do gesto unitário, sem regra nova: peça `processando` ou `falhou` publica/despublica/apaga como no unitário (apagar `processando` continua sendo a saída para job travado).
|
||||
- Existe no celular (card list) e no desktop (tabela) — a assessoria usa os dois.
|
||||
- **Quem pode:** a mesma audiência da vertical (`communicator`, `coordinator`, `candidate`); `advisor`/`leader` negados (fail-closed). Nada de papel novo.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não — é o mesmo gesto de estado do item, repetido; nenhum painel, contador de vaidade ou telemetria.
|
||||
- **Decisões desbloqueadas:** a assessoria decide o destino editorial de várias peças de uma vez (o que vai à pública, o que sai, o que morre); nenhuma leitura agregada nova.
|
||||
- **Forma:** _adiada ao plano de implementação_ — restrição de produto: sem métrica de exclusão/ação em lote, sem dashboard, sem auditoria exposta.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- **Barra de seleção:** contador `N selecionadas`; ações `Publicar` · `Despublicar` · `Apagar`.
|
||||
- **Confirmação de apagar em massa:** título `Apagar N peças selecionadas?` (singular reusa o C222: `Apagar esta peça?`); botões `Cancelar` / `Apagar`.
|
||||
- **Corpo (há publicadas na seleção):** `Os links públicos das peças publicadas da seleção deixam de funcionar para quem já recebeu. Esta ação não pode ser desfeita.`
|
||||
- **Corpo (nenhuma publicada):** `Esta ação não pode ser desfeita.`
|
||||
- **Recibos:** `3 peças publicadas` · `3 peças despublicadas` · `3 peças apagadas`; falha parcial: `2 de 3 peças apagadas. 1 falhou.`
|
||||
- **Estados:** processamento `processando` | `pronto` | `falhou`; publicação `rascunho` | `publicado` — o lote vale em todos, como no unitário.
|
||||
- **Rota interna:** `/campanha/comunicacao/conteudos` (lista). Nenhuma rota pública nova.
|
||||
- **Nota de comportamento (herdada do unitário):** publicar peça sem arquivo nem link a deixa `publicado` mas fora da Central pública (é o `contentPieceIsPublic` de sempre); apagar publicada quebra o link `/conteudos/<slug>` já distribuído — daí o aviso.
|
||||
- **Acesso:** `communicator`, `coordinator`, `candidate`; `advisor`/`leader` negados (fail-closed).
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** página `src/app/(campaign)/campanha/(app)/comunicacao/conteudos/page.tsx`; `src/components/campaign/content/ContentPieceTable.tsx` e `ContentPieceCardList.tsx` (a lista é renderizada 2×: card no mobile, tabela no desktop); actions `src/app/(campaign)/campanha/actions/contentPieces.ts` (`setContentPiecePublishedForActor`, `deleteContentPieceForActor`, hoje uma peça cada) e as rotas `.../conteudos/[id]/publicacao/route.ts` / `.../[id]/apagar/route.ts`; `src/components/campaign/shared/CampaignDeleteDialog.tsx`.
|
||||
- **Precedente a olhar:** `src/components/campaign/tour/TourComposerForm.tsx` (checkbox + contador `N selecionadas`, único precedente real de seleção no `/campanha`); FD2 (`docs/plans/field-desk-ux-pos-critique.md` §Fase 1) desenhou checkbox por linha + barra com contador para a fila de prioridade e nunca implementou — referência de desenho, não de código; `CampaignTable` **não tem API de seleção** — o "como" fica para o plano de implementação.
|
||||
- **Risco de acoplamento:** a lista tem dois corpos (card/tabela) exibidos por breakpoint — a seleção precisa existir nos dois; toda escrita via Local API já busta a tag `contentPieces` por hook (`afterChange`/`afterDelete`) e o lote herda se escrever pelo Local API; o job de processamento tolera a row sumida; `ContentEvent` de circulação nunca é limpo; não tocar nas rotas públicas (S27).
|
||||
|
||||
## Dependências
|
||||
|
||||
- Nenhuma dura — C211 (Central interna) e C222 (apagar uma peça) entregues; S27 é o contrato público a respeitar.
|
||||
- Suave: C213 (contadores de circulação) segue intocado — o lote não limpa nem recalcula eventos.
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Cross-page / "todos os resultados do filtro" — a seleção não sobrevive à navegação de página/filtro.
|
||||
- Publicar/despublicar por linha na lista (o lote não muda a ação rotineira por linha).
|
||||
- Lixeira/desfazer/restauração; agendamento; edição de campos em lote; seleção em outras listas (a fila FD2 segue item próprio).
|
||||
- Progresso/job assíncrono, fila/retomada/cancelamento — o lote é uma ação curta de mesa.
|
||||
- Mudar a semântica do gesto unitário: publicação (slug canônico, `publishedAt` e arquivo preservados) e exclusão (mídia privada exclusiva sai best-effort; `ContentEvent` nunca é limpo).
|
||||
- Central pública (S27): nada muda além do efeito que publicar/despublicar/apagar já têm.
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que seleciona, seleciona todos os filtrados / entre páginas."** Se alguém "só completar": seleção persistente, dedupe, contagem global, confirmação sobre um conjunto que ninguém vê. **Corte neste item:** só a página visível; a seleção morre ao navegar.
|
||||
- **"Já que apaga muito, faz um job com progresso."** Se alguém "só completar": fila, retomada, cancelamento, tela de acompanhamento. **Corte neste item:** ação curta com recibo honesto; falha parcial nomeada.
|
||||
- **"Já que publica em lote, agenda por data."** Se alguém "só completar": agendamento e calendário editorial. **Corte neste item:** publicar é agora.
|
||||
- **"Já que tem barra, edita campos em lote."** Vira spreadsheet mode. **Corte neste item:** só os três verbos.
|
||||
- **"Já que publicar não confirma, apagar também não."** **Corte neste item:** o reversível age; o irreversível confirma.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Escopo da seleção?** **Opções:** A) peças da página visível (as 25 do filtro atual); "selecionar todas" = a página | B) cross-page/"todos os resultados do filtro". **Recomendação:** A — B é rabbit hole (seleção invisível, dedupe, confirmação sobre conjunto que ninguém vê). _(assumido — validar no gate)_
|
||||
- **Confirmação vale para qual ação?** **Opções:** A) só `Apagar` confirma (com aviso de links públicos), `Publicar`/`Despublicar` agem direto com recibo | B) todas confirmam | C) nenhuma confirma. **Recomendação:** A — publicar/despublicar são o kill switch reversível; apagar é a família irreversível do C222. _(assumido — validar no gate)_
|
||||
- **Falha parcial: tudo-ou-nada ou honesta?** **Opções:** A) cada peça é o mesmo gesto unitário — falha de uma não reverte as outras, e o recibo nomeia (`2 de 3 peças apagadas. 1 falhou.`) | B) lote transacional (uma falha cancela tudo). **Recomendação:** A — espelha o "falha de um não derruba os outros" do C211 e evita esconder o que já aconteceu. _(assumido — validar no gate)_
|
||||
- **Elegibilidade no lote?** **Opções:** A) a mesma do unitário, sem filtro novo (inclusive `processando`/`falhou`) | B) bloquear estados no lote. **Recomendação:** A — o lote é o gesto unitário repetido; regra nova criaria duas verdades. _(assumido — validar no gate)_
|
||||
- **Onde mora o affordance da barra?** **Opções:** A) barra só quando há seleção, sem poluir a varredura rotineira | B) checkbox sempre visível com barra fixa. **Recomendação:** A — o "como" (posição, fixa vs. inline) é do design; o produto fixa só que a rotina não ganha ruído. _(assumido — validar no gate)_
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue: #1388
|
||||
- Design UI (gate): `docs/plans/central-conteudos-acoes-em-lote-ui-design.html`
|
||||
- Anti-goal reaberto: `docs/plans/central-conteudos-apagar-peca.md` (C222, "sem lote"; Fora de escopo: "lote é item próprio se o uso pedir") · `docs/plans/central-conteudos-ingestao.md` (C211)
|
||||
- Precedentes: `docs/plans/field-desk-ux-pos-critique.md` (FD2 §Fase 1) · `src/components/campaign/tour/TourComposerForm.tsx`
|
||||
- Arquivos-pista: `src/app/(campaign)/campanha/(app)/comunicacao/conteudos/page.tsx` · `src/components/campaign/content/ContentPieceTable.tsx` · `ContentPieceCardList.tsx` · `src/app/(campaign)/campanha/actions/contentPieces.ts` · `.../conteudos/[id]/publicacao/route.ts` e `.../[id]/apagar/route.ts` · `src/components/campaign/shared/CampaignDeleteDialog.tsx` · `CampaignTable.tsx` · `src/lib/campaignRoles.ts`
|
||||
- Testes a tocar: `tests/int/contentPiece.int.spec.ts` · `tests/unit/contentPieceDeleteDialog.unit.spec.tsx` · `tests/e2e/campaignSpeechAcervo.e2e.spec.ts`
|
||||
- `AGENTS.md` — vertical Comunicação, fail-closed, mídia privada/S3, contrato de cache
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
5/5 — (1) fatia = um outcome verificável (o mesmo veredito em várias peças num gesto, com a lista e a pública refletindo); (2) appetite ~1–1,5 dia declarado e o escopo cabe (seleção da página visível; cross-page, job e agendamento cortados); (3) persona, job e aceite em linguagem de usuário, com reabertura do anti-goal e literais fixados, sem jargão de stack; (4) direção no codebase é hipótese com precedentes nomeados, sem contrato; (5) zero decisão dura de engenharia (forma da barra, mecanismo do lote e transporte ficam para o plano de implementação; aqui só se fixa produto).
|
||||
180
docs/plans/central-conteudos-importar-janela-impl.md
Normal file
180
docs/plans/central-conteudos-importar-janela-impl.md
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
# Impl: C235 — Central de Conteúdos — importar qualquer janela de publicações do perfil
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-09-29
|
||||
Issue: #1386
|
||||
Intenção: docs/plans/central-conteudos-importar-janela.md
|
||||
Appetite restante: herdado (~1–2 dias eng) — sem corte novo: a fatia reusa o cliente do feed, o pipeline C220, o dedupe por identidade e o diálogo C230; backfill total, cursor persistido, agendador e triagem prévia seguem fora (intenção).
|
||||
|
||||
> Modo `--auto` (work-issue): plano nasce aprovado pelo agente. Design UI do gate: `docs/plans/central-conteudos-importar-janela-ui-design.html` — **DEGRADED** (`:7`, `:261-266`, tier fallback; cenas 01–08 cobrem o fluxo).
|
||||
>
|
||||
> **Registro de execução (2026-09-29):** o dispatch do `designer` primário no trigger (b) foi tentado no início da execução e **falhou por quota** (`usage limit reached`); o port foi feito contra o artefato DEGRADED como referência (precedente S16/S18/S34/S40: artefato degradado + crítica de fechamento no tier primário), sem improvisar estrutura visual — todos os estados do fluxo (janela, prévia, progresso, recibo, vazio, falha, corte, mobile) estão nas cenas 01–08. A certificação de fechamento (trigger c) e o sign-off humano continuam obrigatórios: **sem tier primário não há PR** — o fluxo `--auto` para antes do `pnpm push`, comenta a Issue e flipa para `blocked` (D6).
|
||||
>
|
||||
> **Sign-off humano (2026-09-29):** o humano aprovou explicitamente o artefato DEGRADED e o port nesta sessão; a entrega segue para PR **Ready** com `Design tier: DEGRADED (<slug>)` e o registro do sign-off no body, conforme o caminho de `work-issue` com humano presente para `DEGRADED`.
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** com a credencial configurada, o operador escolhe a janela da importação do perfil oficial — **recentes** (default, como hoje) ou **período** (desde; até opcional) — vê o tamanho antes de criar em janelas de período (novas · já estavam · total), confirma, e lê o recibo honesto **novas / já estavam / falharam com motivo**; a execução cobre a janela pela via oficial sem teto artificial e, quando a API/limite corta, o recibo diz; dedupe por identidade do post segue soberano (reexecução e janelas sobrepostas não duplicam); tudo entra como Rascunho, nada é publicado.
|
||||
- **O que NÃO negociar:**
|
||||
- Só o perfil próprio (`@depjorgesolla`) pela API oficial (`loadInstagramFeed`, `src/utilities/socialFeed/instagramFeed.ts:253`); sem scraping, terceiro ou stories; `instagramFeed.ts` não importa `@payload-config` (gate de ciclos madge).
|
||||
- Dedupe por identidade do post — `contentPiecePostIdentityUrls` (`src/lib/contentPiece.ts:487`) e `contentPieceExistsForPostIdentity` (`src/utilities/content/contentPieceLink.ts:93`) — sem segundo resolvedor, segunda fila ou segunda identidade.
|
||||
- Fail-closed de credencial nas duas pontas ("Instagram ainda não configurado."); token nunca em log/URL/wire; erro de feed vira mensagem de produto.
|
||||
- Tudo Rascunho; nenhuma publicação automática; `curatedFields` preservado; board/feed da home intocados.
|
||||
- Gate de comunicação `canReadCommunicationCatalog`; `user` + `overrideAccess:false` em todo caminho de request.
|
||||
- Sem migration/collection/Consent novo (nenhum campo/global muda; `push:false` intacto); sem escrita multi-collection nova.
|
||||
- Design **DEGRADED** não autoriza markup: certificação/estouro do designer primário antes da fase 2; sign-off humano antes do push (D6).
|
||||
- **O que reavaliar (hipóteses da intenção, resolvidas no código):**
|
||||
- "`since`/`until` da edge resolvem a janela" — **rejeitada**: documentado mas não provado no host `graph.instagram.com` e sem teste offline; o caminho provado no repo é cursor + `shouldStopAt` (C220/C230/CLI) — D1.
|
||||
- "o teto de 20 páginas do feed comporta a janela" — **não**: `INSTAGRAM_MAX_MEDIA_PAGES = 20` (`instagramFeed.ts:156`) = 1000 posts; cortaria janelas antigas. Vira parâmetro opcional (default intacto) e o importer usa o próprio limite da edge — D1.
|
||||
- "a lógica pura de janela não existe" — **existe** em `scripts/lib/instagramContentPlan.mjs:120` (`planInstagramContentWindow`), e o CLI já faz early-stop por data (`scripts/import-instagram-content.mjs:201-204`); o plano move o dono e o CLI delega — D2.
|
||||
- "o request de listagem é `z.object({})`" (`src/lib/schemas/contentPiece.ts:89`) — vira união com default `recent` para não quebrar o envelope pinado C230 — D3.
|
||||
- "o diálogo C230 cria direto após a busca" (`ImportContentPieceProfileDialog.tsx:107-169`) — período ganha prévia/confirmação; recentes mantém clique único — D4.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
P["Central de Conteúdos<br/>page.tsx intocada"] --> D["Dialog<br/>recentes (default) · período"]
|
||||
D -->|"recentes · clique único"| A["POST .../conteudos/importar<br/>{} ou {mode:'recent'}"]
|
||||
D -->|"período · prévia"| B["POST .../conteudos/importar<br/>{mode:'period', since, until?}"]
|
||||
A --> F["contentPieceProfileImport<br/>global fail-closed · loadInstagramFeed"]
|
||||
B --> G["scan por cursor + shouldStopAt<br/>teto de páginas derivado do maxResults (10K) · timeout 120s"]
|
||||
F --> H["planner puro (src/lib)<br/>janela · dedupe por identidade"]
|
||||
G --> H
|
||||
H --> R["found · existingCount · candidates · truncated"]
|
||||
R -->|"período"| K["confirmação: novas · já estavam · total<br/>aviso 'Janela grande' > 50"]
|
||||
K -->|"Importar N publicações"| L["loop 1 POST por candidato<br/>.../importar/criar (C230 intacto)"]
|
||||
R -->|"recentes"| L
|
||||
L --> REC["recibo honesto<br/>+ aviso de corte quando truncated"]
|
||||
```
|
||||
|
||||
**Opções consideradas (geral):** A) janela por cursor walk + `shouldStopAt` com teto parametrizado no cliente do feed, planner puro movido para `src/lib` (sem twinning) e fluxo de diálogo com prévia/confirmação; B) `since`/`until` nativos da Graph API; C) segunda implementação de janela/dedupe dentro do importador com fila/estado próprio.
|
||||
**Recomendação:** **A** — um dono por mecanismo (feed, planner, identidade, pipeline), zero schema novo, testável offline com `fetchImpl`/`loadFeed` injetados e cabe no appetite.
|
||||
**Rejeitadas:** **B** — não testável offline, comportamento real desconhecido no host e contraria o caminho provado; **C** — twinning do dedupe/janela e fila fora de escopo (C212 §Q4).
|
||||
|
||||
### D1 — Mecânica da varredura: cursor + early-stop, teto parametrizado e corte denunciado por cobertura
|
||||
|
||||
**Opções:** A) manter o cursor walk do feed com `shouldStopAt` por timestamp (o mesmo que C220 e o CLI provam), derivar o teto defensivo de páginas do próprio `maxResults` (piso 20 intacto; a janela de 10K sobe o teto para 200 páginas), denunciando corte por **cobertura** (`truncated` quando o feed não é vazio e nenhum post retornado é mais antigo que o `since` pedido); B) `since`/`until` nativos da edge `/{ig-user-id}/media`; C) híbrido (manda `since`/`until` e também pagina com cursor).
|
||||
**Recomendação:** **A** — é o único caminho exercitado e testável sem rede (`fetchImpl` fake pino o walk em `tests/unit/instagramFeed.unit.spec.ts:342-396`); o early-stop para no primeiro post mais antigo que `since` (a página inteira ainda entra, o planner descarta o excedente) e a cobertura cobre os três cortes possíveis — teto do cliente, fim de paginação da API (limite de 10K) e fatia de `maxResults`. `truncated` é inferido no importer (`posts.length > 0 && !covered`), sem novo estado no feed. O early-stop só é composto para período; recentes segue sem ele.
|
||||
**Rejeitadas:** **B** — sem teste offline, o comportamento real de `limit`+cursor no host graph.instagram.com é pergunta aberta (`docs/plans/central-conteudos-varredura-instagram.md:151`) e o cliente do feed é dono do cursor; **C** — dois mecanismos para o mesmo corte = drift e nenhum ganho.
|
||||
|
||||
### D2 — Dono do planner puro: mover para `src/lib`, CLI delega (sem twinning)
|
||||
|
||||
**Opções:** A) mover `planInstagramContentWindow` (`scripts/lib/instagramContentPlan.mjs:120`) e `instagramContentFeedIdentityUrls` (`:92`) para `src/lib/contentPieceProfileWindow.ts` (puro, client-safe), o mjs re-exportar com os nomes antigos e o importador C230 passar a usar o mesmo planner para recentes e período (bounds nulos = sem filtro de data); B) o servidor importar o `.mjs` de `scripts/`; C) reimplementar o filtro dentro de `contentPieceProfileImport.ts`.
|
||||
**Recomendação:** **A** — depth check: a política de janela/dedupe já existe e tem dono; mover para `src/lib` deixa o CLI como shell (parse/report ficam) e o servidor reusa a mesma contagem honesta (`found` = candidatos + já existentes + duplicatas do feed; `outsideWindow`/`malformed` ficam no plano, não no wire). Mantém o shape de retorno do plano idêntico para os pins do CLI (`tests/unit/instagramContentPlan.unit.spec.ts:88-144`); no modo recentes o planner roda sem bounds e a semântica dos pins C230 (`found`/`existingCount`/`candidates`) permanece.
|
||||
**Rejeitadas:** **B** — app/Server Action importando `scripts/**` é superfície errada (build/knip/`server-only`); **C** — vira segunda identidade de dedupe/janela no mesmo módulo (o defeito que o C230 resolveu).
|
||||
|
||||
### D3 — Contrato do request/rota e datas civis
|
||||
|
||||
**Opções:** A) `contentPieceProfileImportRequestSchema` (`src/lib/schemas/contentPiece.ts:89`) vira união: `{}`/`{mode:'recent'}` (default) | `{mode:'period', since:'YYYY-MM-DD', until?:'YYYY-MM-DD'}` com refine puro (forma, data real, `until ≥ since`, `since ≤ hoje` BRT); o range civil vira instantes com `parseBahiaDateTimeInput` (`src/lib/campaignTime.ts:83`) — início do dia `T00:00`, fim do dia `T23:59` + 59,999 s, `until` ausente = agora; a action re-parseia (precedente C230) e o diálogo valida antes com o mesmo helper para copy/desabilitar; B) `mode` obrigatório; C) `since`/`until` como instantes ISO no wire.
|
||||
**Recomendação:** **A** — o default do produto continua um body vazio (o pin do envelope C230 em `tests/int/contentPiece.int.spec.ts:1852-1905` segue verde), `<input type="date">` fala `YYYY-MM-DD` e o operador pensa em dia civil da Bahia, não em instante. Sem nova safe message: período inválido cai no genérico (o diálogo impede antes; o servidor é defesa em profundidade). `criar/route.ts` e `contentPieceLinkRequestSchema` intocados.
|
||||
**Rejeitadas:** **B** — quebra o pin `{}` e o default sem ganho; **C** — instante no wire empurra conversão de fuso para o cliente e ignora o input nativo.
|
||||
|
||||
### D4 — Fluxo do diálogo: recentes clique único; período prévia + confirmação
|
||||
|
||||
**Opções:** A) recentes mantém o clique único de hoje (lista e cria no mesmo gesto, janela 12); período ganha prévia com contagens ("novas a criar · já estavam · total na janela"), aviso âmbar "Janela grande" quando `candidates > CONTENT_PIECE_PROFILE_IMPORT_LARGE_WINDOW_THRESHOLD` (50 = uma página do feed), botões "Importar N publicações"/"Trocar"/"Voltar", e os estados da cena 06 (vazio, falha com "Tentar de novo", corte no recibo); B) período cria direto; C) prévia para tudo, inclusive recentes.
|
||||
**Recomendação:** **A** — o recorte por período é gesto explícito e o design fixa o tamanho antes de criar (cenas 02/03); a operação diária não muda; `truncated` aparece no recibo (cena 06d) e um período sem candidatos nem vira botão "Importar 0" (receita cena 05 adaptada com "Nenhuma novidade na janela"). O limiar de "janela grande" vive como constante no módulo puro (client-safe), revisável por gatilho.
|
||||
**Rejeitadas:** **B** — despejo acidental de rascunhos que o produto quer evitar; **C** — fricção nova no fluxo diário.
|
||||
|
||||
### D5 — Tempo limite e feedback da busca
|
||||
|
||||
**Opções:** A) recentes mantém 30 s (`CONTENT_PIECE_PROFILE_IMPORT_FEED_TIMEOUT_MS`, `contentPieceProfileImport.ts:43`); período ganha orçamento maior (120 s) para o walk de muitas páginas; spinner sem progresso de páginas; B) timeout único alto para os dois modos; C) progresso por página/streaming.
|
||||
**Recomendação:** **A** — `AbortSignal.timeout` já cobre todas as chamadas do walk e o período pode custar dezenas de fetches; estourou, cai na mensagem honesta de retry existente e nada foi criado (a criação só começa depois da prévia). A UI não conhece o total de páginas — progresso de busca seria inventado; o "pode demorar" do design é o feedback.
|
||||
**Rejeitadas:** **B** — uma API pendurada seguraria o recente por 2 min sem motivo; **C** — progresso inventado (não há total antes de varrer).
|
||||
|
||||
### D6 — Design gate: DEGRADED ⇒ certificação antes do markup e sign-off antes do push
|
||||
|
||||
**Opções:** A) tratar o artefato como gate duro: o designer primário certifica/estende as cenas **antes** de qualquer markup da fase 2; a crítica final certificada + sign-off humano ficam registrados no PR (`Design tier:`), e o DEGRADED sozinho **não** vai ao push; B) seguir o DEGRADED como aprovado; C) redesenhar do zero.
|
||||
**Recomendação:** **A** — a doutrina do repo só permite port classe-a-classe sob artefato certificado; DEGRADED é explicitamente "design NÃO certificado; requer sign-off humano" (`design html:261-266`). **Execução:** o designer primário estava indisponível (quota) no trigger (b); o port seguiu o artefato como referência (precedente S16/S18/S34/S40) e a certificação fica no fechamento (trigger c) — se o tier primário não certificar, o fluxo para antes do push (sem PR; Issue `blocked`). Estados não desenhados que a execução encontrar → designer estende antes do markup.
|
||||
**Rejeitadas:** **B** — viola a disciplina de design; **C** — as cenas 01–08 já cobrem o fluxo; estender é mais barato.
|
||||
|
||||
### D7 — Testes: unit do puro + int com deps injetadas; e2e fica fora
|
||||
|
||||
**Opções:** A) unit do módulo puro (janela com/sem bounds, cobertura/`truncated`, bounds civis, validação, limiar) e pin novo do teto derivado de `maxResults` no feed; int do `contentPieceProfileImport` com `loadFeed` fake (recent/period, `shouldStopAt` no limite, `truncated`, dedupe por identidade, fail-closed, erro honesto) e envelope da rota; e2e sem spec nova; B) e2e novo com stub do Instagram; C) só int.
|
||||
**Recomendação:** **A** — mesma razão do C230: a fronteira é coberta com dep injetada, sem credencial real e sem estado compartilhado do `social-feed-settings` entre projetos; pins C230/C220/CLI seguem verdes e o diff acorda `campaignSpeechAcervo` pelo manifesto (`src/lib/schemas/contentPiece.ts` é risk prefix mapeado, `:575-577`; `src/components/campaign/content` e `src/utilities/content`, `:552-558`; o arquivo novo casa o prefixo `src/lib/contentPiece`, `:574`).
|
||||
**Rejeitadas:** **B** — flake e custo sem cobrir o que o int cobre; **C** — a política de janela (a parte mais fácil de errar) ficaria sem pin barato.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`src/lib/contentPieceProfileWindow.ts`** (novo, puro, client-safe; não importa `utilities/`): dono do recorte. Move `planContentPieceProfileWindow` (de `instagramContentPlan.mjs:120`; `from`/`to` opcionais/null = sem filtro) e `contentPieceProfileFeedIdentityUrls` (`:92`); tipos `ContentPieceProfileWindowInput` (`{mode:'recent'} | {mode:'period'; since; until?}`); `contentPieceProfilePeriodError({since, until, today})` (forma `YYYY-MM-DD`, data real por round-trip `formatBahiaCivilDate`, ordem, `since` não-futuro); `contentPieceProfilePeriodBounds({window, now})` → `{fromIso, toIso}` compondo `parseBahiaDateTimeInput` (`campaignTime.ts:83`); `contentPieceProfileWindowCovered({posts, fromMs})`; `contentPieceProfileWindowLabel` (compõe `formatCivilDateLabel`, `campaignTime.ts`, para "01/08/2026 → hoje"); `CONTENT_PIECE_PROFILE_IMPORT_LARGE_WINDOW_THRESHOLD = 50`.
|
||||
- **`src/lib/campaignTime.ts`**: ganha `formatCivilDateLabel` (`aaaa-mm-dd` → `dd/mm/aaaa`) e `subtractBahiaCivilMonths` (clamp de fim de mês) — donos puros dos atalhos de janela do diálogo.
|
||||
- **`scripts/lib/instagramContentPlan.mjs`**: passa a importar e re-exportar o planner/identidades com os nomes antigos (`planInstagramContentWindow`, `instagramContentFeedIdentityUrls`) — CLI (`import-instagram-content.mjs:55/236`), unit (`instagramContentPlan.unit.spec.ts`) e guards (`instagramContentImportCli.unit.spec.ts`) intocados. Args/report/summary ficam.
|
||||
- **`src/utilities/socialFeed/instagramFeed.ts`**: o teto defensivo de páginas passa a **derivar de `maxResults`** (`max(INSTAGRAM_MAX_MEDIA_PAGES, ceil(maxResults / INSTAGRAM_MAX_RESULTS_CAP))`) — janela de 12 e o lookup/board ficam idênticos (piso 20); só a janela de 10K do período amplia o walk. `loadInstagramFeed` não aprende `since`/`until`.
|
||||
- **`src/utilities/content/contentPieceProfileImport.ts`**: `listContentPieceProfileImportCandidates({payload, actor, window = {mode:'recent'}, loadFeed?, fetchImpl?, now?})`; recentes = hoje (`maxResults: CONTENT_PIECE_PROFILE_IMPORT_INSTAGRAM_WINDOW = 12`, timeout 30 s); período = `maxResults: CONTENT_PIECE_PROFILE_IMPORT_SCAN_LIMIT = 10_000`, `shouldStopAt` por `timestamp < fromMs`, timeout `CONTENT_PIECE_PROFILE_IMPORT_PERIOD_FEED_TIMEOUT_MS = 120_000`; lookup de identidade em chunks de 2.000 URLs via `contentPieceProfileFeedIdentityUrls`; retorno ganha `truncated` (inferido por `contentPieceProfileWindowStartReached`). `createContentPieceFromProfilePost` (`:205`) e o fail-closed (`:110-146`) intocados.
|
||||
- **`src/lib/schemas/contentPiece.ts`**: `contentPieceProfileImportRequestSchema` vira união com default recente + refine de período via `contentPieceProfilePeriodError`; safe messages existentes bastam.
|
||||
- **`src/app/(campaign)/campanha/actions/contentPieces.ts`**: `listContentPieceProfileImportCandidatesForActor(input = {})` re-parseia e repassa `window`; gate fresco intocado (`:388-395`).
|
||||
- **`.../conteudos/importar/route.ts`**: handler passa o body parseado à action; envelope/safe messages inalterados. **`.../importar/criar/route.ts`** intocada.
|
||||
- **`.../conteudos/types.ts`**: `ContentPieceProfileImportCandidatesResponse` ganha `truncated: boolean` (aditivo).
|
||||
- **`src/components/campaign/content/ImportContentPieceProfileDialog.tsx`**: seletor de janela (radiogroup cena 01/02: "Recentes · Padrão" default; "Período" com Desde/Até nativos + chips "Últimos 30 dias"/"Últimos 6 meses"/"Este ano", via `subtractBahiaCivilDays`/`formatBahiaCivilDate`), prévia+confirmação (cena 03), progresso real (cena 04, barra com `aria-valuenow`), recibo com a linha da janela + aviso de corte (cenas 05/06d), vazio (06a) e falha com "Tentar de novo" (06b); mantém loop sequencial, bloqueio de fechar em running e `router.refresh()`.
|
||||
- **`page.tsx`** (lista): intocada — toolbar/banner/empty da C230 já cobrem o fail-closed (cena 06c).
|
||||
- **`docs/changelog/2026-09-29-c235.md`** (novo).
|
||||
|
||||
**Migration: sem migration** — nenhuma collection/global/field muda; `push:false` intacto; sem `generate:types` (tipos novos são de aplicação).
|
||||
|
||||
**Access / Consent:** sem Consent (sem PII nova) e sem chave hardcoded; gate fresco `canReadCommunicationCatalog` nas actions (como as irmãs); leitura do global via Local API sem `user` (bypass admin já documentado em `contentPieceProfileImport.ts:119-121`) só para o boolean/credencial, e o listing com `user: actor` + `overrideAccess:false` (`:83-84`). Sem escrita multi-collection nova: a fase A só lê; a fase B é o `payload.create` único já transacional do C230.
|
||||
|
||||
**UI:** Impeccable **C** (encaixe no diálogo existente). Shells/componentes reusados: `Dialog/Alert/Badge/Button/Spinner`, `postCampaignJson`, `buildContentPieceListHref` (`contentPieceListUrl.ts:89-90`). **Trigger de design:** DEGRADED → certificação/estouro do designer primário antes do markup (D6); estados não desenhados param a execução.
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
N/A — operação/curadoria, não analytics: o tamanho da janela e o recibo são contagem operacional (novas/já estavam/falhas) e detalhe textual (motivo da peça-link), sem agregado, taxa, série, engajamento ou alcance. A intenção fixou "sem números do Instagram nesta tela" (métricas de post são C213, fora).
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer / schema+server — quota ~50%:** módulo puro (`contentPieceProfileWindow.ts`) + re-export do CLI; teto de páginas derivado de `maxResults` no feed; `contentPieceProfileImport` com janela/truncated; schema/route/action/types. **Tracer bullet cedo:** int com `loadFeed` fake — período devolve `found`/`existingCount`/`candidates` deduplicados por identidade e `truncated` correto com o `shouldStopAt` pinado no limite; recentes segue com `receivedMaxResults === 12` e os pins C230 verdes; CLI spec verde pelo re-export. Só então a UI.
|
||||
2. **UI — quota ~30%:** port das cenas 01–08 no diálogo, **após certificação do designer** (D6). Prova: build/typecheck e revisão no browser; sem tocar `page.tsx`.
|
||||
3. **Gates — quota ~20%:** `pnpm gate:fast`; `pnpm test:int`; e2e selecionado/curado (o diff acorda `campaignSpeechAcervo` pelo risk mapping; nenhuma spec e2e nova); crítica final do designer certificada + sign-off humano (DEGRADED) com `Design tier:` no PR; `pnpm push` via GitHub.
|
||||
|
||||
### Testes previstos
|
||||
|
||||
- **`tests/unit/contentPieceProfileWindow.unit.spec.ts` (novo):** planner com bounds (dentro/fora, `outsideWindow`, duplicata de feed, identidade já catalogada em outra grafia), bounds nulos (modo recentes) e ordenação newest-first; `contentPieceProfilePeriodError` (formato, data impossível 2026-02-30, `until < since`, `since` futuro, válido); `contentPieceProfilePeriodBounds` (início/fim do dia civil BRT, `until` ausente = agora); `contentPieceProfileWindowCovered` (post mais antigo que `fromMs` = coberto; só mais novos = corte; vazio); limiar e label.
|
||||
- **`tests/unit/instagramFeed.unit.spec.ts` (estender sem quebrar pins):** uma janela mais profunda (`maxResults: 1_100`) anda 22 páginas; default segue 20 (pins de clamp/one-page/walk/early-stop/refresh intactos).
|
||||
- **`tests/int/contentPiece.int.spec.ts` — novo describe C235 (deps injetadas, sem rede):** período com `loadFeed` fake — `receivedMaxResults === SCAN_LIMIT` e `shouldStopAt(postAntigo) === true`/`shouldStopAt(postNaJanela) === false`; posts fora da janela não entram; dedupe por variante de kind (`/p/` no banco × `/reel/` no feed); `truncated: true` quando o feed não alcança o `since`, `false` quando alcança; período sem credencial → fail-closed sem chamar `loadFeed`; feed lançando → mensagem honesta; envelope da rota com `{}` (recente) e com body de período; período inválido → 400 sem escrita.
|
||||
- **Pins que seguem intocados:** C230 (`:1653-1929`, janela 12 em `:1696`), C220 (`:1214-1230`), `instagramContentPlan.unit.spec.ts` e `instagramContentImportCli.unit.spec.ts` via re-export.
|
||||
- **e2e — não entra.** Mesma razão do C230: sem credencial real e o global é estado compartilhado; o int cobre a fronteira. **Gatilho:** regressão do envelope HTTP que o int não pegar → e2e HTTP curto com o stub (`tests/e2e/instagram-stub.mjs`), semeando/restaurando o global em `finally`.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- **Backfill total/"importa as 10K de uma vez"** — a janela é escolhida; o corte é dito e reexecutar continua sem duplicar; varredura automática é C212 §Q4.
|
||||
- **Cursor persistido/retomada/painel de varredura** — nada de estado próprio; o recibo é a verdade.
|
||||
- **`since`/`until` nativos da edge** — fora (D1); não ensinar isso ao `loadInstagramFeed`.
|
||||
- **Segunda identidade/fila/resolvedor; agendador/webhook; auto-publicar; triagem peça a peça; analytics/stories** — permanentes (intenção/C211/C213).
|
||||
- **Progresso de busca por página, scroll infinito de seleção, edição em massa** — fora.
|
||||
- **Tocar board/feed da home, snapshot/cache/kill switch/lock do `SocialFeedSettings`, outras rotas da Central** — o diff é zero fora do listado.
|
||||
- **Mexer no `instagramFeed.ts` além do teto de páginas derivado** — sem `since`/`until`, sem novo retorno.
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Janela antiga = muitas páginas → rate limit/timeout:** o walk respeita `AbortSignal` de 120 s; estourou, mensagem honesta e nada criado (criação só após a prévia); reexecutar converge. Se virar rotina, o item é a varredura com cursor (C212 §Q4).
|
||||
- **`truncated` por cobertura tem falso positivo quando o perfil inteiro está dentro da janela** (conta nasceu depois do `since`): o aviso é conservador ("importamos o que foi possível neste recorte") e nunca esconde corte; gatilho: se incomodar, o feed devolve o motivo do fim do walk (`stopReason`) e o flag refina.
|
||||
- **Página do feed com menos de 50 itens:** o teto de páginas pode cortar antes dos 10K, mas a cobertura denuncia `truncated` — honesto.
|
||||
- **Mover o planner quebra o CLI/pins:** re-export com os nomes antigos; `pnpm gate:fast` (knip/cycles/unit) pega qualquer órfão.
|
||||
- **Datas impossíveis normalizadas pelo parse** (`2026-02-30` → março): validação por round-trip em `contentPieceProfilePeriodError` no schema e no cliente.
|
||||
- **Divergência prévia × criação (corrida):** o probe da fase B responde `existing` e o recibo fecha nas categorias; candidato criado por outro ator conta em "já estavam".
|
||||
- **Design DEGRADED:** gate duro — sem certificação não há markup; sem sign-off humano não há push.
|
||||
- **`page.tsx`/board/feed:** intocados por construção; `loadInstagramFeed` só ganha o teto derivado.
|
||||
|
||||
## Triage do /simplify (2026-09-29)
|
||||
|
||||
Dois revisores (estrutural + qualidade) rodaram sobre o diff; os fixes baratos já estão na entrega (preprocess do schema restrito a `{}` — fim do downgrade silencioso de `{since,until}` sem `mode`; teto de páginas derivado de `maxResults` em vez de arg público; `contentPieceProfileWindowStartReached` no lugar de "covered"; tipo do post reusando `ContentPieceProfilePost`; pins de `formatCivilDateLabel`/`subtractBahiaCivilMonths`; spec do CLI reduzido a pin de re-export; `role="alert"` redundante e `setSearching(false)` no-op removidos; radios com roving tabindex/setas; labels de data sem `aria-label` divergente; `Number.isFinite` redundante no early-stop).
|
||||
|
||||
- **Já resolvido (não reabrir):** os fixes acima; o `maxMediaPages` público removido e os pins atualizados.
|
||||
- **Adiado com gatilho:**
|
||||
- **Fatia do diálogo em steps locais** (`ImportContentPiecePreviewDialog` tem a cadeia de fases em JSX): gatilho — a certificação de design mexer na estrutura do diálogo ou um passo novo entrar; hoje a estrutura é o port fiel do artefato.
|
||||
- **`loadConfiguredInstagramFeed`** acumula fail-closed + validação/bounds + composição + persistência: a parte pura já tem dono (`contentPieceProfileWindow.ts`); gatilho — 2º consumidor do mapeamento janela→`maxResults`/timeout/early-stop.
|
||||
- **`truncated` conservador** (S5): gatilho — o feed devolver `stopReason` (ver Riscos).
|
||||
- **e2e do diálogo** (S6): gatilho — regressão do envelope HTTP que o int não pegar (ver Testes).
|
||||
- **Explicitamente fora:** `formatCivilDateLabel` privado do `activityAllDay.ts` (recebe instante ISO, semântica distinta — não é duplicata); tipos de wire importados de `app/(campaign)/.../types` em client components (padrão do repo, precedente C230).
|
||||
- **Registro adiado:** não há Issue nova neste fechamento — o fluxo para antes do PR (design DEGRADED); o gatilho da fatia do diálogo fica aqui e o débito pode virar `C235-FOLLOWUP-DRY` (`depends: 1386`) quando o fechamento landar.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: recentes default preservado; período com desde/até opcional cobre a janela pedida pela via oficial; prévia com tamanho antes de criar em período; recibo honesto (novas/já estavam/falharam + motivo) e aviso de corte quando a via oficial não alcança; dedupe por identidade (sobreposição/reexecução/link manual sem gêmeas); nada publicado; fail-closed de credencial; só perfil próprio/API oficial; token nunca em log.
|
||||
- [ ] Invariantes AGENTS/engineering-standards: gate fresco `canReadCommunicationCatalog`; `user` + `overrideAccess:false` (bypass admin só o já documentado do global); **sem migration/collection/Consent novo**; sem escrita multi-collection nova; `lib/` não importa `utilities/` e o módulo novo é puro/client-safe; `instagramFeed.ts` não importa `@payload-config`; um dono por mecanismo (planner movido, sem segundo dedupe/fila/identidade); board/feed da home e pipeline C220 intocados.
|
||||
- [ ] Testes de domínio previstos (unit/int) verdes e pins C230/C220/CLI verdes; nenhuma spec e2e nova; manifest sem edição e seleção não-zero.
|
||||
- [ ] UI apenas após certificação do designer; crítica final + sign-off humano (DEGRADED) com `Design tier:` no PR antes do push.
|
||||
- [ ] `pnpm gate:fast` verde; `pnpm test:int` verde; e2e selecionado/curado verde; `pnpm push` via GitHub.
|
||||
|
||||
## Self-score
|
||||
|
||||
**Self-score decision-quality: 4/5.** (1) Decisões caras com Opções/Recomendação/Rejeitadas explícitas (mecânica da varredura, dono do planner, contrato/datas, fluxo do diálogo, timeout, gate de design, testes); (2) cabe no appetite — move a pura, adiciona um arg opcional ao feed e porta cenas no diálogo existente, sem schema/infra; (3) rabbit holes nomeados (backfill, cursor, `since/until`, segunda fila, agendador, analytics, progresso inventado); (4) depth check: planner e identidade movidos para o dono em `src/lib`, CLI delega, dedupe segue num predicado único e o cliente do feed só parametriza o teto; (5) aceite de produto intacto. Não 5/5 por três incertezas assumidas: (a) o falso positivo conservador de `truncated` na cobertura; (b) o limiar de "Janela grande" (50) inferido do design/mock; (c) o design **DEGRADED**, cuja certificação é pré-condição da fase 2 e não está sob controle da execução.
|
||||
1512
docs/plans/central-conteudos-importar-janela-ui-design.html
Normal file
1512
docs/plans/central-conteudos-importar-janela-ui-design.html
Normal file
File diff suppressed because it is too large
Load diff
112
docs/plans/central-conteudos-importar-janela.md
Normal file
112
docs/plans/central-conteudos-importar-janela.md
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
# C235 — Central de Conteúdos — importar qualquer janela de publicações do perfil
|
||||
|
||||
Status: rascunho
|
||||
Atualizado em: 2026-09-29
|
||||
Issue: #1386
|
||||
Priority: P2
|
||||
Impeccable: C — encaixe na tela/diálogo existente
|
||||
Design UI: docs/plans/central-conteudos-importar-janela-ui-design.html
|
||||
Appetite: ~1–2 dias eng; um outcome verificável
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
A importação do perfil (@depjorgesolla) na Central de Conteúdos trouxe o gesto que faltava (C230), mas com janela fixa: só as publicações mais recentes. O dono pediu o contrário — "importar qualquer janela de publicações" — porque a campanha tem acervo para trás: posts que ficaram fora, períodos em que a importação não rodou, semanas de evento. Hoje o único jeito de trazer esse passado é colar link a link. O caminho oficial já pagina, o dedupe por identidade do post já impede gêmeas e a reexecução já é inofensiva; falta deixar o operador escolher o recorte. A operação diária não muda: "recentes" continua o default; a novidade é a janela.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** assessoria de comunicação (`communicator`; `coordinator`/`candidate` também) na mesa, agora em mutirão de acervo — fechar a lacuna de um período —, não no ritmo do dia a dia.
|
||||
- **Job principal:** trazer para a Central as publicações de um período escolhido do perfil oficial, sem colar link a link e sem duplicar o que já está.
|
||||
- **Fluxo desejado:** abre a Central → "Importar do perfil" → escolhe a janela (default: recentes; ou um período desde [até]) → vê o tamanho antes de criar (novas · já estavam) → confirma → acompanha o progresso → lê o recibo honesto (novas / já estavam / falharam com motivo) → revisa na lista.
|
||||
- **Anti-goals de produto:** não vira triagem peça a peça antes de importar; não vira sincronizador agendado; não publica nada; não cria segunda identidade nem segunda fila; não busca além do que a via oficial entrega.
|
||||
|
||||
### Esboço de fluxo (C)
|
||||
|
||||
```text
|
||||
[Central de Conteúdos] → "Importar do perfil"
|
||||
→ escolhe a janela: recentes (default) ou período desde [até opcional]
|
||||
→ a busca varre o perfil próprio pela API oficial até cobrir a janela
|
||||
→ o operador vê o tamanho (novas · já estavam) e confirma — obrigatório em janelas maiores
|
||||
→ cada novidade vira Rascunho no pipeline existente, deduplicada pela identidade do post
|
||||
→ fim: recibo honesto "novas · já estavam · falharam com motivo"
|
||||
→ se a API/limite cortar, o recibo diz; reexecutar a mesma janela continua sem duplicar
|
||||
[outcome: o acervo de qualquer período do perfil entra na Central como Rascunho, sem duplicar e sem publicar nada]
|
||||
```
|
||||
|
||||
### Design UI (C)
|
||||
|
||||
- Design UI (gate): `docs/plans/central-conteudos-importar-janela-ui-design.html`
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- O operador escolhe a janela da importação; "recentes" segue o default e o recorte é gesto explícito.
|
||||
- Janela maior pede confirmação com o tamanho (novas · já estavam) antes de criar; o recibo honesto "novas / já estavam / falharam com motivo" continua.
|
||||
- A execução cobre a janela pedida pela via oficial, sem teto artificial; se a API/limite cortar (10K mais recentes, rate limit), o que foi feito é dito e reexecutar continua sem duplicar.
|
||||
- Dedupe por identidade do post segue soberano: janelas sobrepostas, reexecuções e o que entrou por link não geram gêmeas.
|
||||
- Guardrails: tudo Rascunho; sem credencial a ação fica indisponível (fail-closed, "Instagram ainda não configurado."); só perfil próprio pela API oficial — sem scraping, terceiro ou stories; token nunca em log; nada publicado automaticamente; board/feed da home intocados.
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não — é operação/curadoria, não analytics: sem agregado, KPI ou superfície nova. O tamanho da janela e o recibo são recibo operacional, não métrica.
|
||||
- **Decisões desbloqueadas:** N/A — a decisão é editorial ("quero o acervo de tal período"), não numérica. **Forma:** N/A — sem números de alcance/engajamento do Instagram nesta tela.
|
||||
|
||||
## Dados da decisão (literais)
|
||||
|
||||
- **Default preservado:** "recentes" (a janela atual da ação) continua o comportamento padrão; o recorte por período é escolha explícita do operador.
|
||||
- **Janela:** período com **data inicial** (e **data final opcional**), contado pela **data de publicação** do post.
|
||||
- **Curadoria:** todo post importado entra como **Rascunho**; **nenhuma publicação automática**.
|
||||
- **Dedupe:** identidade do **post** (shortcode; variantes de URL), não a grafia do link; reexecutar e sobrepor janelas não duplica.
|
||||
- **Fail-closed:** sem credencial, ação indisponível — **"Instagram ainda não configurado."**
|
||||
- **Fonte:** só o **perfil próprio** (`@depjorgesolla`) pela **API oficial** — sem scraping, sem terceiro, sem stories.
|
||||
- **Limites honestos:** só as **10K mídias mais recentes** da edge oficial; quando a API cortar, o recibo é honesto.
|
||||
- **Recibo mantido:** **novas criadas / já estavam / falharam com motivo** (falha nunca em silêncio).
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** `src/utilities/socialFeed/instagramFeed.ts` (cliente Graph API — paginação por cursor, `maxResults`, early-stop; hoje sem `since`/`until`); `src/utilities/content/contentPieceProfileImport.ts` (dono da janela fixa `CONTENT_PIECE_PROFILE_IMPORT_INSTAGRAM_WINDOW` e da listagem/dedupe); `src/components/campaign/content/ImportContentPieceProfileDialog.tsx` (fases intro/running/done); actions `src/app/(campaign)/campanha/actions/contentPieces.ts` (`listContentPieceProfileImportCandidatesForActor`, `createContentPieceFromProfilePostForActor`, gate `canReadCommunicationCatalog`); request hoje vazio em `src/lib/schemas/contentPiece.ts`.
|
||||
- **Precedente a olhar:** C230 (plano e impl D4 — janela 12, backfill cortado como rabbit hole), C220 (`contentPieceLink.ts` usa `maxResults: 500` + early-stop; job por peça), C212 §Q1/Q3/Q4 (10K, cursor como caminho de backfill, webhook como item irmão), C211 (tudo Rascunho).
|
||||
- **Risco de acoplamento:** o dedupe tem dono único (`contentPiecePostIdentityUrls` / `contentPieceExistsForPostIdentity`) — não abrir segundo probe; `instagramFeed.ts` não pode importar `@payload-config` (gate de ciclos); não guardar estado/cursor da varredura no `SocialFeedSettings` (hook de save com lock transacional) nem reusar o caminho do board; nada de segunda fila/identidade; o job por peça e o N+1 de ~1 chamada de feed por post seguem aceitos.
|
||||
|
||||
## Dependências
|
||||
|
||||
- **Duras:** nenhuma.
|
||||
- **Soft:** C230 (#1362, entregue — dono do gesto, do dedupe e do recibo) · C220/C211 (entregues) · credencial do Instagram configurada em produção (sem ela a janela não paga).
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Triagem/seleção peça a peça antes de importar — a triagem é depois, na lista.
|
||||
- Agendador/webhook/reconciliação automática — item irmão futuro (C212 §Q4).
|
||||
- Retomada por cursor/estado próprio da varredura; segunda identidade ou fila; auto-publicação; analytics/engajamento do Instagram (C213); scraping/terceiro/stories; redesenho da tela da Central; outras redes (YouTube segue no link C220).
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que escolhe janela, seleciona antes."** Se alguém "só completar": checklist de mídias, preview peça a peça, edição em massa. **Corte neste item:** importa a janela como Rascunho; revisar/excluir é na lista, depois.
|
||||
- **"Já que varre, sincroniza sozinho."** Se alguém "só completar": webhook, cron diário, painel de última varredura. **Corte:** sob demanda; o automático é o item irmão (C212 §Q4).
|
||||
- **"Já que pagina, guarda cursor e retoma."** Se alguém "só completar": estado de varredura, retomada exata, contador de páginas. **Corte:** o recibo é honesto e reexecutar a mesma janela continua sem duplicar.
|
||||
- **"Importa o perfil inteiro de uma vez."** Se alguém "só completar": backfill total das 10K, progresso persistente, retomada entre sessões. **Corte:** a janela é escolhida; o limite da edge (10K, sem stories) é dito.
|
||||
- **"Importou, publica."** Se alguém "só completar": auto-publicar por período. **Corte:** tudo Rascunho; publicar é ato humano.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **O default muda?** **Opções:** A) recentes continua o default, período é opção explícita | B) sempre pedir a janela | C) default passa a ser período. **Recomendação:** A — a operação diária não muda; recorte é mutirão. _(assumido — validar com produto)_
|
||||
- **Qual o modelo da janela?** **Opções:** A) período (desde; até opcional) | B) "últimas N" | C) ambos. **Recomendação:** A — é a linguagem do humano ("qualquer janela"), cobre lacunas por data, e sobreposição é inofensiva por dedupe; N pode virar preset de design sobre o período. B/C registradas como alternativas.
|
||||
- **Confirma antes de criar?** **Opções:** A) sempre | B) só janelas maiores que a de hoje | C) nunca. **Recomendação:** B — o recente pequeno mantém o clique único de hoje; janela larga mostra o tamanho (novas · já estavam) e pede confirmação, evitando despejo acidental de rascunhos. _(assumido)_
|
||||
- **Tem teto de janela?** **Opções:** A) sem teto artificial — pagina até cobrir e o recibo diz se cortou | B) teto fixo de quantidade | C) teto = limite da edge (10K). **Recomendação:** A — teto de produto só fabrica frustração; o corte real (10K, rate limit) já é limite honesto e a reexecução continua sem duplicar. A mecânica de páginas/lote é implementação.
|
||||
- **Recorte por quê?** **Opções:** A) data de publicação do post (timestamp) | B) posição no feed. **Recomendação:** A — é o vocabulário do operador ("de tal dia a tal dia") e o timestamp já vem no feed; posição não é estável fora do topo.
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue [#1386](https://github.com/fsolla/teqo/issues/1386)
|
||||
- Design UI (gate): `docs/plans/central-conteudos-importar-janela-ui-design.html`
|
||||
- Planos irmãos: `central-conteudos-importar-perfil.md` (C230) e `-impl.md` · `central-conteudos-link-instagram.md` (C220) · `central-conteudos-varredura-instagram.md` (C212 §Q1/Q3/Q4) · `central-conteudos-ingestao.md` (C211)
|
||||
- Arquivos-pista: `src/utilities/content/contentPieceProfileImport.ts` · `src/utilities/socialFeed/instagramFeed.ts` · `src/components/campaign/content/ImportContentPieceProfileDialog.tsx` · `src/app/(campaign)/campanha/actions/contentPieces.ts` · `src/lib/schemas/contentPiece.ts` · `src/app/(campaign)/campanha/(app)/comunicacao/conteudos/page.tsx` · `AGENTS.md` (sem scraping/terceiro; token nunca em log)
|
||||
|
||||
## Self-score (shaping)
|
||||
|
||||
1. Fatia = um outcome verificável? **Sim** — o acervo de qualquer período escolhido entra na Central como Rascunho, sem duplicar e sem publicar nada.
|
||||
2. Appetite declarado e a intenção cabe? **Sim** (~1–2 dias; triagem prévia, agendador, retomada de cursor e analytics cortados).
|
||||
3. Persona + job + aceite claros sem jargão de stack? **Sim**.
|
||||
4. Direção no codebase é hipótese? **Sim** — áreas/pistas com os caminhos citados, sem schema/signature.
|
||||
5. Zero decisões duras de engenharia no plano? **Sim** — cursor, lote, page cap, estado e persistência ficam na implementação.
|
||||
|
||||
**Score: 5/5.**
|
||||
|
|
@ -35,6 +35,7 @@
|
|||
"media:recover": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/recover-media.mjs",
|
||||
"reels:ingest": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/reels-ingest.mjs",
|
||||
"flickr:import": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/ingest-flickr-archive.mjs",
|
||||
"content:instagram:import": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/import-instagram-content.mjs",
|
||||
"archive:catalog": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/catalog-archive-photos.mjs",
|
||||
"faces:enroll": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/enroll-face-subject.mjs",
|
||||
"faces:index": "cross-env NODE_OPTIONS=\"--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs\" node scripts/index-archive-faces.mjs",
|
||||
|
|
|
|||
437
scripts/import-instagram-content.mjs
Normal file
437
scripts/import-instagram-content.mjs
Normal file
|
|
@ -0,0 +1,437 @@
|
|||
/**
|
||||
* C230-followup — imports the official Instagram profile's recent media into
|
||||
* the Central de Conteúdos through the C220 pipeline: the feed comes from the
|
||||
* official Graph API of the OWN account (no scraping, no third-party media),
|
||||
* each novelty is created in the link shape and processed inline (download of
|
||||
* the profile's own file, transcription and automatic cataloguing). With
|
||||
* `--publish`, every piece the pipeline finished (`pronto`) goes public at the
|
||||
* end of the batch; a `falhou` piece stays a draft and is named in the receipt.
|
||||
* Re-running converges ("novas / já estavam / falharam com motivo") and never
|
||||
* duplicates — the identity is the post, not the URL spelling.
|
||||
*
|
||||
* Modes:
|
||||
* pnpm content:instagram:import plan/dry-run (default):
|
||||
* reads the feed and the DB,
|
||||
* writes nothing
|
||||
* pnpm content:instagram:import --apply processes the window; needs
|
||||
* CONTENT_INSTAGRAM_IMPORT_CONFIRM=1
|
||||
* on a non-local target and the
|
||||
* complete S3_* set
|
||||
* pnpm content:instagram:import --apply --publish
|
||||
* also publishes what is `pronto`
|
||||
*
|
||||
* Options: --days <n> (default 60), --limit <n> (canary), --out <dir> (receipts,
|
||||
* default `data/content-instagram`), --help.
|
||||
*
|
||||
* Guards: --apply refuses a non-local/production target without the intent flag
|
||||
* (C155) and demands the declared TEQO_ENV matching the exact database name
|
||||
* (C195/C231); a remote target also demands the complete S3_* set, because the
|
||||
* job uploads the extracted media to the private bucket (without S3 the file
|
||||
* would land on the container's ephemeral disk). The Instagram credential lives
|
||||
* in the `social-feed-settings` global and never enters a log; without it the
|
||||
* run fails closed with the product message.
|
||||
*
|
||||
* Runbook: on the homeserver, inside the compose maintenance service with the
|
||||
* stack env file — see docs/ops/teqo-1313-deploy.md.
|
||||
*/
|
||||
import { mkdir, writeFile } from 'node:fs/promises'
|
||||
import { dirname, join } from 'node:path'
|
||||
|
||||
import { getPayload } from 'payload'
|
||||
|
||||
import {
|
||||
assertEnvironmentDatabaseTarget,
|
||||
assertWriteConfirm,
|
||||
databaseTarget,
|
||||
dieWithLabel,
|
||||
loadCliEnv,
|
||||
mirroredMediaRequired,
|
||||
} from './lib/cli.mjs'
|
||||
import {
|
||||
formatInstagramContentReport,
|
||||
instagramContentFeedIdentityUrls,
|
||||
instagramContentReportStamp,
|
||||
parseInstagramContentCliArgs,
|
||||
planInstagramContentWindow,
|
||||
shouldPublishImportedPiece,
|
||||
summarizeInstagramContentResults,
|
||||
} from './lib/instagramContentPlan.mjs'
|
||||
|
||||
loadCliEnv()
|
||||
|
||||
const die = dieWithLabel('content:instagram:import')
|
||||
|
||||
const WRITE_CONFIRM_FLAG = 'CONTENT_INSTAGRAM_IMPORT_CONFIRM'
|
||||
/** A hung Graph API must not hold the run forever. */
|
||||
const FEED_TIMEOUT_MS = 60_000
|
||||
/**
|
||||
* Feed window of one run: one page serves 50, and the date early-stop ends the
|
||||
* walk at the page that carries the first post older than `--days`, so the cap
|
||||
* is only a defensive ceiling (6 pages), never the real window.
|
||||
*/
|
||||
const FEED_MAX_RESULTS = 300
|
||||
|
||||
const HELP = `Uso: pnpm content:instagram:import [opções]
|
||||
|
||||
Importa as mídias recentes do perfil oficial (@depjorgesolla) para a Central de
|
||||
Conteúdos pelo caminho oficial (Graph API da própria conta), processando cada
|
||||
novidade pelo pipeline da peça (download do arquivo próprio, transcrição e
|
||||
catalogação). Sem --apply, é um plano read-only (não baixa, não escreve).
|
||||
|
||||
Opções:
|
||||
--apply processa o lote (exige ${WRITE_CONFIRM_FLAG}=1 em alvo
|
||||
não-local e as 4 S3_*; o job grava a mídia no bucket privado)
|
||||
--publish publica o que terminar "pronto" (exige --apply); falhas ficam
|
||||
como rascunho e são nomeadas no recibo
|
||||
--days <n> janela em dias (default 60; 1..365)
|
||||
--limit <n> canário: processa no máximo n candidatos (o resto fica no lote)
|
||||
--out <dir> recibos JSON (default data/content-instagram)
|
||||
--help esta ajuda
|
||||
|
||||
Flags: TEQO_ENV=staging|production (obrigatória no --apply fora de teste; o nome
|
||||
do banco tem de casar) e ${WRITE_CONFIRM_FLAG}=1 para a escrita.
|
||||
`
|
||||
|
||||
/**
|
||||
* The CLI writes straight to the DB, so the collection hook's `revalidateTag`
|
||||
* is a no-op in this process (the seed loader stubs `next/cache`): the public
|
||||
* Central is busted over HTTP, best-effort — a failure never fails the run and
|
||||
* is named in the receipt. Uses the same tag the hook busts.
|
||||
*/
|
||||
const revalidatePublicCentral = async () => {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_SITE_URL?.trim().replace(/\/+$/, '')
|
||||
const secret = process.env.REVALIDATE_SECRET?.trim()
|
||||
if (!baseUrl || !secret) {
|
||||
return { attempted: true, ok: false, reason: 'NEXT_PUBLIC_SITE_URL/REVALIDATE_SECRET ausentes' }
|
||||
}
|
||||
try {
|
||||
const { REVALIDATE_CONTENT_PIECES_TAG } = await import('../src/utilities/revalidateRequest.ts')
|
||||
const response = await fetch(
|
||||
`${baseUrl}/api/revalidate?tag=${encodeURIComponent(REVALIDATE_CONTENT_PIECES_TAG)}`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'x-revalidate-secret': secret },
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
},
|
||||
)
|
||||
return response.ok
|
||||
? { attempted: true, ok: true, reason: null }
|
||||
: { attempted: true, ok: false, reason: `HTTP ${response.status}` }
|
||||
} catch (error) {
|
||||
return {
|
||||
attempted: true,
|
||||
ok: false,
|
||||
reason: error instanceof Error && error.message !== '' ? error.message : 'falha de rede',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const writeReport = async (options, report, suffix = '') => {
|
||||
const stamp = instagramContentReportStamp(report.runAt)
|
||||
const reportPath = join(options.out, `${stamp}${suffix}.json`)
|
||||
await mkdir(dirname(reportPath), { recursive: true })
|
||||
await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`, 'utf8')
|
||||
return reportPath
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let options
|
||||
try {
|
||||
options = parseInstagramContentCliArgs()
|
||||
} catch (error) {
|
||||
die(error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
if (options.help) {
|
||||
console.log(HELP)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (!process.env.DATABASE_URL) die('DATABASE_URL não definida; recusando continuar.')
|
||||
const mode = options.apply ? 'apply' : 'plan'
|
||||
|
||||
if (mode === 'apply') {
|
||||
assertWriteConfirm({
|
||||
label: 'content:instagram:import',
|
||||
flag: WRITE_CONFIRM_FLAG,
|
||||
command: 'pnpm content:instagram:import --apply',
|
||||
})
|
||||
const target = assertEnvironmentDatabaseTarget()
|
||||
const { resolveS3StorageEnv } = await import('../src/utilities/mediaStorage.ts')
|
||||
const storage = resolveS3StorageEnv(process.env)
|
||||
if (mirroredMediaRequired({ s3Enabled: storage.enabled })) {
|
||||
die(
|
||||
`escrita em produção/remoto (${target.environment}) exige mídia espelhada: configure S3_BUCKET, S3_ENDPOINT, S3_ACCESS_KEY_ID e S3_SECRET_ACCESS_KEY; sem elas a mídia iria para o disco efêmero do container.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(
|
||||
`[content:instagram:import] alvo: ${databaseTarget()} | modo: ${mode} | janela: ${options.days} dias`,
|
||||
)
|
||||
|
||||
const config = (await import('../src/payload.config.ts')).default
|
||||
const { createContentPieceFromProfilePost } =
|
||||
await import('../src/utilities/content/contentPieceProfileImport.ts')
|
||||
const { runContentPieceJob } = await import('../src/utilities/content/contentPieceJob.ts')
|
||||
const { isInstagramFeedConfigured, loadInstagramFeed, persistInstagramAccessToken } =
|
||||
await import('../src/utilities/socialFeed/instagramFeed.ts')
|
||||
const { DEEPINFRA_TRANSCRIBE_COST_PER_MINUTE_USD } =
|
||||
await import('../src/utilities/ai/deepInfraTranscribe.ts')
|
||||
const payload = await getPayload({ config })
|
||||
|
||||
// Intentional admin bypass: the global is admin-only and its credential is
|
||||
// read solely to call the official API; the token never leaves this process.
|
||||
const settings = await payload.findGlobal({ slug: 'social-feed-settings', depth: 0 })
|
||||
if (!isInstagramFeedConfigured(settings)) {
|
||||
die(
|
||||
'Instagram ainda não configurado (token/ID ausentes ou feed desligado no global Social Feed) — a importação só roda pelo caminho oficial.',
|
||||
)
|
||||
}
|
||||
|
||||
const to = new Date()
|
||||
const from = new Date(to.getTime() - options.days * 86_400_000)
|
||||
let feed
|
||||
try {
|
||||
feed = await loadInstagramFeed({
|
||||
accessToken: settings.instagramAccessToken,
|
||||
userId: settings.instagramUserId,
|
||||
maxResults: FEED_MAX_RESULTS,
|
||||
// The feed is newest-first: the first page carrying a post older than the
|
||||
// window ends the walk, so the typical run costs one page per 50 medias.
|
||||
shouldStopAt: (post) => {
|
||||
const timestamp = Date.parse(post.timestamp)
|
||||
return Number.isFinite(timestamp) && timestamp < from.getTime()
|
||||
},
|
||||
signal: AbortSignal.timeout(FEED_TIMEOUT_MS),
|
||||
})
|
||||
} catch {
|
||||
die(
|
||||
'não foi possível ler o feed oficial do Instagram agora (API ou credencial) — tente novamente.',
|
||||
)
|
||||
}
|
||||
if (feed.refreshedAccessToken) {
|
||||
await persistInstagramAccessToken(payload, feed.refreshedAccessToken).catch(() => undefined)
|
||||
}
|
||||
|
||||
// One `sourceUrl in` lookup covers every spelling of every feed post.
|
||||
const identityUrls = instagramContentFeedIdentityUrls(feed.posts)
|
||||
let existingSourceUrls = []
|
||||
if (identityUrls.length > 0) {
|
||||
const existing = await payload.find({
|
||||
collection: 'contentPiece',
|
||||
where: { sourceUrl: { in: identityUrls } },
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: { sourceUrl: true },
|
||||
// Intentional admin bypass: the ops import must see every catalogue row,
|
||||
// including drafts no actor could read.
|
||||
overrideAccess: true,
|
||||
})
|
||||
existingSourceUrls = existing.docs
|
||||
.map((doc) => doc.sourceUrl)
|
||||
.filter((sourceUrl) => typeof sourceUrl === 'string' && sourceUrl !== '')
|
||||
}
|
||||
|
||||
const plan = planInstagramContentWindow({
|
||||
posts: feed.posts,
|
||||
existingSourceUrls,
|
||||
from: from.toISOString(),
|
||||
to: to.toISOString(),
|
||||
})
|
||||
|
||||
if (mode === 'plan') {
|
||||
const report = {
|
||||
runAt: new Date().toISOString(),
|
||||
mode,
|
||||
target: databaseTarget(),
|
||||
window: { days: options.days, from: from.toISOString(), to: to.toISOString() },
|
||||
feed: { username: feed.username, count: feed.posts.length },
|
||||
plan,
|
||||
}
|
||||
const reportPath = await writeReport(options, report)
|
||||
for (const line of formatInstagramContentReport({
|
||||
target: report.target,
|
||||
mode,
|
||||
window: report.window,
|
||||
feedCount: report.feed.count,
|
||||
plan,
|
||||
})) {
|
||||
console.log(line)
|
||||
}
|
||||
console.log(
|
||||
`\n[content:instagram:import] plano sem escrita — para importar: --apply [--publish]`,
|
||||
)
|
||||
console.log(`[content:instagram:import] recibo JSON: ${reportPath}`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const selected =
|
||||
options.limit === null ? plan.candidates : plan.candidates.slice(0, options.limit)
|
||||
const results = []
|
||||
const created = []
|
||||
const startedAt = Date.now()
|
||||
|
||||
for (const [index, candidate] of selected.entries()) {
|
||||
const prefix = `[${index + 1}/${selected.length}] ${candidate.shortcode}`
|
||||
try {
|
||||
const { outcome, contentPieceId } = await createContentPieceFromProfilePost({
|
||||
payload,
|
||||
actor: null,
|
||||
url: candidate.url,
|
||||
// The CLI owns the processing: the job runs inline, not after a response.
|
||||
startJob: () => {},
|
||||
})
|
||||
|
||||
if (outcome === 'existing' || contentPieceId === null) {
|
||||
results.push({
|
||||
...candidate,
|
||||
contentPieceId: null,
|
||||
outcome: 'existing',
|
||||
processingStatus: null,
|
||||
linkFailureReason: null,
|
||||
durationSeconds: null,
|
||||
error: null,
|
||||
published: false,
|
||||
})
|
||||
console.log(`${prefix} — já estava na Central`)
|
||||
continue
|
||||
}
|
||||
|
||||
await runContentPieceJob(payload, contentPieceId)
|
||||
const row = await payload.findByID({
|
||||
collection: 'contentPiece',
|
||||
id: contentPieceId,
|
||||
depth: 0,
|
||||
select: {
|
||||
processingStatus: true,
|
||||
linkFailureReason: true,
|
||||
durationSeconds: true,
|
||||
error: true,
|
||||
},
|
||||
// Intentional admin bypass: the pipeline owns the row it just wrote.
|
||||
overrideAccess: true,
|
||||
})
|
||||
const failed = row.processingStatus === 'falhou'
|
||||
results.push({
|
||||
...candidate,
|
||||
contentPieceId,
|
||||
outcome: 'created',
|
||||
processingStatus: row.processingStatus,
|
||||
linkFailureReason: row.linkFailureReason ?? null,
|
||||
durationSeconds: row.durationSeconds ?? null,
|
||||
error: failed ? (row.error ?? 'falha no processamento') : null,
|
||||
published: false,
|
||||
})
|
||||
if (!failed) created.push({ contentPieceId, processingStatus: row.processingStatus })
|
||||
console.log(
|
||||
`${prefix} — ${row.processingStatus}${row.linkFailureReason ? ` (peça-link: ${row.linkFailureReason})` : ''}`,
|
||||
)
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error && error.message !== '' ? error.message : 'falha inesperada'
|
||||
results.push({
|
||||
...candidate,
|
||||
contentPieceId: null,
|
||||
outcome: 'failed',
|
||||
processingStatus: 'falhou',
|
||||
linkFailureReason: null,
|
||||
durationSeconds: null,
|
||||
error: message,
|
||||
published: false,
|
||||
})
|
||||
console.log(`${prefix} — falhou: ${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
let publishFailures = 0
|
||||
if (options.publish) {
|
||||
// Oldest first so the newest post carries the latest `publishedAt` — the
|
||||
// public listing sorts by `-publishedAt`, so the newest leads the Central.
|
||||
for (const entry of [...created].reverse()) {
|
||||
if (!shouldPublishImportedPiece({ ...entry, publish: true })) continue
|
||||
try {
|
||||
await payload.update({
|
||||
collection: 'contentPiece',
|
||||
id: entry.contentPieceId,
|
||||
data: { status: 'publicado' },
|
||||
depth: 0,
|
||||
// Intentional admin bypass: the ops run publishes what it imported.
|
||||
overrideAccess: true,
|
||||
})
|
||||
const result = results.find((item) => item.contentPieceId === entry.contentPieceId)
|
||||
if (result) result.published = true
|
||||
} catch (error) {
|
||||
publishFailures += 1
|
||||
const result = results.find((item) => item.contentPieceId === entry.contentPieceId)
|
||||
if (result) {
|
||||
result.error = `publicação: ${
|
||||
error instanceof Error && error.message !== '' ? error.message : 'falha inesperada'
|
||||
}`
|
||||
}
|
||||
}
|
||||
}
|
||||
if (publishFailures > 0) {
|
||||
console.log(`[content:instagram:import] ${publishFailures} falha(s) ao publicar`)
|
||||
}
|
||||
}
|
||||
|
||||
let revalidation = { attempted: false, ok: false, reason: null }
|
||||
if (results.some((result) => result.published === true)) {
|
||||
revalidation = await revalidatePublicCentral()
|
||||
console.log(
|
||||
`[content:instagram:import] Central pública: ${
|
||||
revalidation.ok ? 'revalidada' : `revalidação falhou (${revalidation.reason})`
|
||||
}`,
|
||||
)
|
||||
}
|
||||
|
||||
const summary = summarizeInstagramContentResults(results, {
|
||||
costPerMinuteUsd: DEEPINFRA_TRANSCRIBE_COST_PER_MINUTE_USD,
|
||||
})
|
||||
const failures = results
|
||||
.filter((result) => result.error !== null)
|
||||
.map((result) => ({ shortcode: result.shortcode, error: result.error }))
|
||||
const candidatesRemaining = plan.candidates.length - selected.length
|
||||
const runAt = new Date().toISOString()
|
||||
const report = {
|
||||
runAt,
|
||||
mode,
|
||||
target: databaseTarget(),
|
||||
window: { days: options.days, from: from.toISOString(), to: to.toISOString() },
|
||||
feed: { username: feed.username, count: feed.posts.length },
|
||||
plan,
|
||||
selected: selected.map((candidate) => candidate.shortcode),
|
||||
results,
|
||||
summary: { ...summary, durationMs: Date.now() - startedAt },
|
||||
failures,
|
||||
candidatesRemaining,
|
||||
publishFailures,
|
||||
revalidation,
|
||||
}
|
||||
const reportPath = await writeReport(options, report, '-apply')
|
||||
for (const line of formatInstagramContentReport({
|
||||
target: report.target,
|
||||
mode,
|
||||
window: report.window,
|
||||
feedCount: report.feed.count,
|
||||
plan,
|
||||
summary,
|
||||
failures,
|
||||
candidatesRemaining,
|
||||
reportPath,
|
||||
})) {
|
||||
console.log(line)
|
||||
}
|
||||
console.log(`\n[content:instagram:import] recibo JSON: ${reportPath}`)
|
||||
|
||||
// Only a systemic failure (nothing entered the Central) is an error exit.
|
||||
if (results.length > 0 && summary.created === 0 && summary.existing === 0) {
|
||||
die('nenhuma peça entrou na Central — falhas listadas no recibo.')
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
die(error instanceof Error && error.message !== '' ? error.message : 'falha inesperada.')
|
||||
})
|
||||
|
|
@ -14,17 +14,24 @@
|
|||
* dev and the complete S3_* envs
|
||||
* pnpm flickr:import --verify read-only inventory of the stored
|
||||
* archive (no Flickr, no bucket)
|
||||
* pnpm flickr:import --refresh-metadata
|
||||
* re-fetches the EXIF of the rows already
|
||||
* in the archive and updates only what
|
||||
* changed (backfill; DB-only write,
|
||||
* needs FLICKR_API_KEY but no S3)
|
||||
*
|
||||
* Options: --limit <n> (canary), --page <n> (listing start page), --out <dir>
|
||||
* (receipts, default `data/flickr`), --help. `--limit` caps the photos
|
||||
* processed; the album walk still covers every album so a canary never loses
|
||||
* memberships.
|
||||
* memberships. In the refresh mode `--limit` caps the rows visited.
|
||||
*
|
||||
* Guards: --apply refuses a non-local/production target without the intent
|
||||
* flag (C155) and demands the declared TEQO_ENV matching the exact database
|
||||
* name (C195/C231); a remote target also demands the complete S3_* set. The
|
||||
* API key lives in FLICKR_API_KEY (env only, never the repo) and the account
|
||||
* NSID in FLICKR_USER_ID.
|
||||
* Guards: --apply and --refresh-metadata refuse a non-local/production target
|
||||
* without the intent flag (C155) and demand the declared TEQO_ENV matching the
|
||||
* exact database name (C195/C231); --apply on a remote target also demands the
|
||||
* complete S3_* set (the original never lands on ephemeral disk) while the
|
||||
* metadata-only refresh writes just the database. The API key lives in
|
||||
* FLICKR_API_KEY (env only, never the repo) and the account NSID in
|
||||
* FLICKR_USER_ID.
|
||||
*
|
||||
* Runbook: on the homeserver, inside the compose maintenance service with the
|
||||
* stack env file — see docs/ops/teqo-1313-deploy.md.
|
||||
|
|
@ -36,6 +43,7 @@ import { dirname, join } from 'node:path'
|
|||
import { getPayload } from 'payload'
|
||||
|
||||
import {
|
||||
archivePhotoExifEntries,
|
||||
archivePhotoImportFromFlickr,
|
||||
archivePhotoStorageFilename,
|
||||
} from '../src/lib/archivePhoto.ts'
|
||||
|
|
@ -57,11 +65,13 @@ import {
|
|||
collectArchiveListing,
|
||||
formatArchiveBytes,
|
||||
formatArchiveInventory,
|
||||
formatArchiveRefresh,
|
||||
formatArchiveReport,
|
||||
parseArchiveCliArgs,
|
||||
planArchiveEntries,
|
||||
summarizeArchiveInventory,
|
||||
summarizeArchivePlan,
|
||||
summarizeArchiveRefresh,
|
||||
summarizeArchiveResults,
|
||||
} from './lib/flickrPlan.mjs'
|
||||
|
||||
|
|
@ -90,21 +100,24 @@ Modos (mutuamente exclusivos; o default é o plano):
|
|||
(sem flag) plano/dry-run — lista, mapeia e reporta; sem download nem escrita
|
||||
--apply baixa os originais e cria as linhas/objetos no alvo
|
||||
--verify inventário read-only do que já está no acervo (sem Flickr)
|
||||
--refresh-metadata re-busca o EXIF das linhas existentes e atualiza o que mudou
|
||||
(backfill; escreve só no banco, exige FLICKR_API_KEY)
|
||||
|
||||
Opções:
|
||||
--limit <n> processa no máximo n fotos (a varredura de álbuns continua completa)
|
||||
--page <n> começa a listagem na página n (retomada)
|
||||
--limit <n> processa no máximo n fotos; no refresh, no máximo n linhas
|
||||
--page <n> começa a listagem na página n (retomada; não vale no refresh)
|
||||
--out <dir> diretório dos recibos (default ${ARCHIVE_PHOTO_DEFAULT_OUT_DIR})
|
||||
--help esta ajuda
|
||||
|
||||
Ambiente:
|
||||
FLICKR_API_KEY chave da API do Flickr (nunca no repo)
|
||||
FLICKR_USER_ID NSID da conta (ex.: 12345678@N00)
|
||||
FLICKR_USER_ID NSID da conta (ex.: 12345678@N00; não exigido no --refresh-metadata)
|
||||
DATABASE_URL alvo (obrigatório em todos os modos)
|
||||
|
||||
--apply em alvo não-local/produção exige ${WRITE_CONFIRM_FLAG}=1, TEQO_ENV=${envLines}
|
||||
casando o banco exato e as quatro envs S3_* (o original nunca vai para disco
|
||||
efêmero). O dry-run e o --verify são read-only.
|
||||
--apply e --refresh-metadata em alvo não-local/produção exigem ${WRITE_CONFIRM_FLAG}=1
|
||||
e TEQO_ENV=${envLines} casando o banco exato; o --apply exige também as quatro
|
||||
envs S3_* (o original nunca vai para disco efêmero). O dry-run e o --verify são
|
||||
read-only.
|
||||
`
|
||||
|
||||
class StageError extends Error {
|
||||
|
|
@ -238,39 +251,49 @@ async function main() {
|
|||
}
|
||||
|
||||
if (!process.env.DATABASE_URL) die('DATABASE_URL não definida; recusando continuar.')
|
||||
const mode = options.apply ? 'apply' : options.verify ? 'verify' : 'plan'
|
||||
const mode = options.apply
|
||||
? 'apply'
|
||||
: options.verify
|
||||
? 'verify'
|
||||
: options.refreshMetadata
|
||||
? 'refresh-metadata'
|
||||
: 'plan'
|
||||
const runAt = new Date().toISOString()
|
||||
console.log(`[flickr:import] alvo: ${databaseTarget()} | modo: ${mode}`)
|
||||
|
||||
if (mode === 'apply') {
|
||||
if (mode === 'apply' || mode === 'refresh-metadata') {
|
||||
assertWriteConfirm({
|
||||
label: 'flickr:import',
|
||||
flag: WRITE_CONFIRM_FLAG,
|
||||
command: 'pnpm flickr:import --apply',
|
||||
command: `pnpm flickr:import --${mode === 'apply' ? 'apply' : 'refresh-metadata'}`,
|
||||
})
|
||||
const target = assertEnvironmentDatabaseTarget()
|
||||
const { resolveS3StorageEnv } = await import('../src/utilities/mediaStorage.ts')
|
||||
const storage = resolveS3StorageEnv(process.env)
|
||||
if (mirroredMediaRequired({ s3Enabled: storage.enabled })) {
|
||||
die(
|
||||
`escrita em produção/remoto (${target.environment}) exige mídia espelhada: configure S3_BUCKET, S3_ENDPOINT, S3_ACCESS_KEY_ID e S3_SECRET_ACCESS_KEY; sem elas o original iria para disco local efêmero.`,
|
||||
)
|
||||
if (mode === 'apply') {
|
||||
const { resolveS3StorageEnv } = await import('../src/utilities/mediaStorage.ts')
|
||||
const storage = resolveS3StorageEnv(process.env)
|
||||
if (mirroredMediaRequired({ s3Enabled: storage.enabled })) {
|
||||
die(
|
||||
`escrita em produção/remoto (${target.environment}) exige mídia espelhada: configure S3_BUCKET, S3_ENDPOINT, S3_ACCESS_KEY_ID e S3_SECRET_ACCESS_KEY; sem elas o original iria para disco local efêmero.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mode !== 'verify') {
|
||||
if (!process.env.FLICKR_API_KEY?.trim()) {
|
||||
die('FLICKR_API_KEY ausente — configure a chave da API do Flickr (veja .env.example).')
|
||||
}
|
||||
if (!process.env.FLICKR_USER_ID?.trim()) {
|
||||
die('FLICKR_USER_ID ausente — informe o NSID da conta (ex.: 12345678@N00).')
|
||||
}
|
||||
if (mode !== 'verify' && !process.env.FLICKR_API_KEY?.trim()) {
|
||||
die('FLICKR_API_KEY ausente — configure a chave da API do Flickr (veja .env.example).')
|
||||
}
|
||||
if ((mode === 'plan' || mode === 'apply') && !process.env.FLICKR_USER_ID?.trim()) {
|
||||
die('FLICKR_USER_ID ausente — informe o NSID da conta (ex.: 12345678@N00).')
|
||||
}
|
||||
|
||||
const config = (await import('../src/payload.config.ts')).default
|
||||
const { downloadUrlToFile } = await import('../src/utilities/media/downloadToFile.ts')
|
||||
const { findArchivePhotoByFlickrId, ingestArchivePhoto, listArchivePhotos } =
|
||||
await import('../src/utilities/flickr/archivePhotoIngest.ts')
|
||||
const {
|
||||
findArchivePhotoByFlickrId,
|
||||
ingestArchivePhoto,
|
||||
listArchivePhotos,
|
||||
updateArchivePhotoExif,
|
||||
} = await import('../src/utilities/flickr/archivePhotoIngest.ts')
|
||||
const payload = await getPayload({ config })
|
||||
const startedAt = Date.now()
|
||||
|
||||
|
|
@ -295,6 +318,57 @@ async function main() {
|
|||
process.exit(0)
|
||||
}
|
||||
|
||||
if (mode === 'refresh-metadata') {
|
||||
const client = createFlickrClient({ apiKey: process.env.FLICKR_API_KEY })
|
||||
const rows = await listArchivePhotos(payload)
|
||||
const selected = options.limit === null ? rows : rows.slice(0, options.limit)
|
||||
console.log(
|
||||
`[flickr:import] refresh de metadados (EXIF) de ${selected.length} linha(s) do acervo...`,
|
||||
)
|
||||
const results = []
|
||||
for (const row of selected) {
|
||||
const flickrId = String(row.flickrId)
|
||||
try {
|
||||
const rawExif = await withStage('metadata', () => client.getExif(flickrId))
|
||||
const exif = archivePhotoExifEntries(rawExif)
|
||||
const current = Array.isArray(row.exif) ? row.exif : []
|
||||
if (JSON.stringify(current) === JSON.stringify(exif)) {
|
||||
results.push({ flickrId, status: 'unchanged', entries: exif.length })
|
||||
continue
|
||||
}
|
||||
const updated = await updateArchivePhotoExif(payload, { id: row.id, flickrId, exif })
|
||||
if (updated.status === 'failed') {
|
||||
results.push({ flickrId, status: 'failed', error: updated.error })
|
||||
console.log(`[flickr:import] falha refresh ${flickrId}: ${updated.error}`)
|
||||
continue
|
||||
}
|
||||
results.push({ flickrId, status: 'updated', entries: exif.length })
|
||||
console.log(`[flickr:import] atualizada ${flickrId} (${exif.length} entrada(s) EXIF)`)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
results.push({ flickrId, status: 'failed', error: message })
|
||||
console.log(`[flickr:import] falha metadata ${flickrId}: ${message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const summary = summarizeArchiveRefresh(results)
|
||||
const report = {
|
||||
runAt,
|
||||
mode,
|
||||
target: databaseTarget(),
|
||||
total: selected.length,
|
||||
summary,
|
||||
durationMs: Date.now() - startedAt,
|
||||
}
|
||||
const reportPath = await writeReport(options, report, '-refresh')
|
||||
for (const line of formatArchiveRefresh(report)) console.log(line)
|
||||
console.log(`\n[flickr:import] recibo JSON: ${reportPath}`)
|
||||
if (summary.updated + summary.unchanged === 0 && results.length > 0) {
|
||||
die('nenhuma linha foi refrescada — falhas listadas no recibo.')
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const userId = process.env.FLICKR_USER_ID.trim()
|
||||
const client = createFlickrClient({ apiKey: process.env.FLICKR_API_KEY })
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ const VIDEO_MEDIA = 'video'
|
|||
const BYTES_PER_MIB = 1024 * 1024
|
||||
|
||||
const USAGE =
|
||||
'uso: `pnpm flickr:import [--apply|--verify] [--limit <n>] [--page <n>] [--out <dir>]`'
|
||||
'uso: `pnpm flickr:import [--apply|--verify|--refresh-metadata] [--limit <n>] [--page <n>] [--out <dir>]`'
|
||||
|
||||
export const ARCHIVE_PHOTO_DEFAULT_OUT_DIR = 'data/flickr'
|
||||
|
||||
|
|
@ -43,12 +43,13 @@ export const archivePhotoReportStamp = (runAt) => runAt.replace(/[:.]/g, '-')
|
|||
* errors carry the usage line.
|
||||
*
|
||||
* @param {string[]} [argv]
|
||||
* @returns {{ apply: boolean, verify: boolean, limit: number | null, page: number, out: string, help: boolean }}
|
||||
* @returns {{ apply: boolean, verify: boolean, refreshMetadata: boolean, limit: number | null, page: number, out: string, help: boolean }}
|
||||
*/
|
||||
export const parseArchiveCliArgs = (argv = process.argv.slice(2)) => {
|
||||
const options = {
|
||||
apply: false,
|
||||
verify: false,
|
||||
refreshMetadata: false,
|
||||
limit: null,
|
||||
page: 1,
|
||||
out: ARCHIVE_PHOTO_DEFAULT_OUT_DIR,
|
||||
|
|
@ -67,6 +68,7 @@ export const parseArchiveCliArgs = (argv = process.argv.slice(2)) => {
|
|||
if (arg === '--help' || arg === '-h') options.help = true
|
||||
else if (arg === '--apply') options.apply = true
|
||||
else if (arg === '--verify') options.verify = true
|
||||
else if (arg === '--refresh-metadata') options.refreshMetadata = true
|
||||
else if (arg === '--limit') options.limit = Number(value())
|
||||
else if (arg === '--page') options.page = Number(value())
|
||||
else if (arg === '--out') options.out = value()
|
||||
|
|
@ -74,8 +76,9 @@ export const parseArchiveCliArgs = (argv = process.argv.slice(2)) => {
|
|||
}
|
||||
|
||||
if (options.help) return options
|
||||
if (options.apply && options.verify) {
|
||||
throw new Error(`--apply e --verify são mutuamente exclusivos — ${USAGE}.`)
|
||||
const modes = [options.apply, options.verify, options.refreshMetadata].filter(Boolean).length
|
||||
if (modes > 1) {
|
||||
throw new Error(`--apply, --verify e --refresh-metadata são mutuamente exclusivos — ${USAGE}.`)
|
||||
}
|
||||
if (options.limit !== null && (!Number.isInteger(options.limit) || options.limit < 1)) {
|
||||
throw new Error('--limit deve ser >= 1.')
|
||||
|
|
@ -83,6 +86,11 @@ export const parseArchiveCliArgs = (argv = process.argv.slice(2)) => {
|
|||
if (!Number.isInteger(options.page) || options.page < 1) {
|
||||
throw new Error('--page deve ser >= 1.')
|
||||
}
|
||||
if (options.refreshMetadata && options.page !== 1) {
|
||||
throw new Error(
|
||||
`--page não se aplica a --refresh-metadata (a varredura é das linhas do acervo) — ${USAGE}.`,
|
||||
)
|
||||
}
|
||||
if (options.out.split(/[\\/]/).includes('..')) {
|
||||
throw new Error('--out não pode escapar do diretório do repo (sem "..").')
|
||||
}
|
||||
|
|
@ -274,6 +282,22 @@ export const summarizeArchiveResults = (results) => ({
|
|||
})),
|
||||
})
|
||||
|
||||
/**
|
||||
* The `--refresh-metadata` results: rows updated/unchanged, the EXIF entries
|
||||
* written and the named failures — no row is silently dropped.
|
||||
*
|
||||
* @param {Array<{ status: string, flickrId: string, entries?: number | null, error?: string | null }>} results
|
||||
*/
|
||||
export const summarizeArchiveRefresh = (results) => ({
|
||||
updated: results.filter((result) => result.status === 'updated').length,
|
||||
unchanged: results.filter((result) => result.status === 'unchanged').length,
|
||||
failed: results.filter((result) => result.status === 'failed').length,
|
||||
entries: results.reduce((total, result) => total + (Number(result.entries) || 0), 0),
|
||||
failures: results
|
||||
.filter((result) => result.status === 'failed')
|
||||
.map((result) => ({ flickrId: result.flickrId, error: result.error ?? null })),
|
||||
})
|
||||
|
||||
/**
|
||||
* The `--verify` inventory over the stored rows (read-only, no Flickr, no
|
||||
* bucket): counts, bytes, per-album coverage, metadata gaps and rows without
|
||||
|
|
@ -388,3 +412,19 @@ export const formatArchiveInventory = (inventory) => {
|
|||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
/** `--refresh-metadata` human lines (rows touched + named failures). */
|
||||
export const formatArchiveRefresh = (report) => {
|
||||
const label = REPORT_LABEL
|
||||
const lines = [
|
||||
`${label} refresh (metadados): atualizadas: ${report.summary.updated} · inalteradas: ${report.summary.unchanged} · falhas: ${report.summary.failed} · entradas EXIF: ${report.summary.entries}`,
|
||||
`${label} tempo: ${(report.durationMs / 1000).toFixed(1)}s`,
|
||||
]
|
||||
if (report.summary.failures.length > 0) {
|
||||
lines.push(`${label} falhas:`)
|
||||
for (const failure of report.summary.failures) {
|
||||
lines.push(` - ${failure.flickrId}: ${failure.error ?? 'erro'}`)
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
|
|
|||
180
scripts/lib/instagramContentPlan.mjs
Normal file
180
scripts/lib/instagramContentPlan.mjs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
/**
|
||||
* C230-followup — pure planning/reporting of the Instagram content import CLI
|
||||
* (`import-instagram-content.mjs`): filter the official feed to the declared
|
||||
* recency window, classify each post into an import candidate, dedupe by the
|
||||
* post identity (what the Central already carries, in any URL spelling) and
|
||||
* aggregate the honest run report. No I/O and no `server-only`: the unit specs
|
||||
* read this module and the CLI is the impure shell.
|
||||
*/
|
||||
|
||||
import {
|
||||
contentPieceProfileFeedIdentityUrls,
|
||||
planContentPieceProfileWindow,
|
||||
} from '../../src/lib/contentPieceProfileWindow.ts'
|
||||
|
||||
// C235 — the window filter and the identity dedupe moved to their single owner
|
||||
// in `src/lib` (the server importer reads the same policy); the names below are
|
||||
// the CLI contract this module has always exported.
|
||||
export const planInstagramContentWindow = planContentPieceProfileWindow
|
||||
export const instagramContentFeedIdentityUrls = contentPieceProfileFeedIdentityUrls
|
||||
|
||||
/** Default recency window of one import run (the request's 60 days). */
|
||||
const INSTAGRAM_CONTENT_DEFAULT_DAYS = 60
|
||||
|
||||
/** Defensive ceiling: a window longer than a year is a typo, not an intent. */
|
||||
const INSTAGRAM_CONTENT_MAX_DAYS = 365
|
||||
|
||||
const INSTAGRAM_CONTENT_DEFAULT_OUT_DIR = 'data/content-instagram'
|
||||
|
||||
const INSTAGRAM_CONTENT_USAGE =
|
||||
'pnpm content:instagram:import [--apply] [--publish] [--days 60] [--limit n] [--out data/content-instagram]'
|
||||
|
||||
/** Report file stamp: the run's ISO instant with `:`/`.` swapped, like C215. */
|
||||
export const instagramContentReportStamp = (runAt) => runAt.replace(/[:.]/g, '-')
|
||||
|
||||
/**
|
||||
* Parses the CLI arguments. `--publish` only exists with `--apply` (there is
|
||||
* nothing to publish in the plan mode) and `--out` cannot escape the repo.
|
||||
*
|
||||
* @param {string[]} [argv]
|
||||
*/
|
||||
export const parseInstagramContentCliArgs = (argv = process.argv.slice(2)) => {
|
||||
const options = {
|
||||
apply: false,
|
||||
publish: false,
|
||||
days: INSTAGRAM_CONTENT_DEFAULT_DAYS,
|
||||
limit: null,
|
||||
out: INSTAGRAM_CONTENT_DEFAULT_OUT_DIR,
|
||||
help: false,
|
||||
}
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index]
|
||||
const value = () => {
|
||||
const next = argv[++index]
|
||||
if (next === undefined || next.startsWith('--')) {
|
||||
throw new Error(`faltou valor para ${arg} — ${INSTAGRAM_CONTENT_USAGE}.`)
|
||||
}
|
||||
return next
|
||||
}
|
||||
if (arg === '--help' || arg === '-h') options.help = true
|
||||
else if (arg === '--apply') options.apply = true
|
||||
else if (arg === '--publish') options.publish = true
|
||||
else if (arg === '--days') options.days = Number(value())
|
||||
else if (arg === '--limit') options.limit = Number(value())
|
||||
else if (arg === '--out') options.out = value()
|
||||
else throw new Error(`argumento desconhecido: ${arg} — ${INSTAGRAM_CONTENT_USAGE}.`)
|
||||
}
|
||||
|
||||
if (options.help) return options
|
||||
if (options.publish && !options.apply) {
|
||||
throw new Error(`--publish exige --apply — ${INSTAGRAM_CONTENT_USAGE}.`)
|
||||
}
|
||||
if (
|
||||
!Number.isInteger(options.days) ||
|
||||
options.days < 1 ||
|
||||
options.days > INSTAGRAM_CONTENT_MAX_DAYS
|
||||
) {
|
||||
throw new Error(`--days deve ser um inteiro entre 1 e ${INSTAGRAM_CONTENT_MAX_DAYS}.`)
|
||||
}
|
||||
if (options.limit !== null && (!Number.isInteger(options.limit) || options.limit < 1)) {
|
||||
throw new Error('--limit deve ser >= 1.')
|
||||
}
|
||||
if (options.out.split(/[\\/]/).includes('..')) {
|
||||
throw new Error('--out não pode escapar do diretório do repo (sem "..").')
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
/**
|
||||
* The publish rule of the import: only a piece the pipeline finished (`pronto`)
|
||||
* goes public, and only when the run asked for it. A `falhou` piece stays a
|
||||
* draft and the receipt names it.
|
||||
*/
|
||||
export const shouldPublishImportedPiece = ({ processingStatus, publish }) =>
|
||||
publish === true && processingStatus === 'pronto'
|
||||
|
||||
/**
|
||||
* Aggregates the per-candidate results of an `--apply` run. `asrCostUsd` uses
|
||||
* the provider's per-audio-minute price passed by the shell (the app-side
|
||||
* owner of the constant), never a guessed duration.
|
||||
*
|
||||
* @param {Array<{ outcome: string, processingStatus?: string | null, linkFailureReason?: string | null, published?: boolean, durationSeconds?: number | null, error?: string | null }>} results
|
||||
* @param {{ costPerMinuteUsd?: number }} [options]
|
||||
*/
|
||||
export const summarizeInstagramContentResults = (results, { costPerMinuteUsd = 0 } = {}) => {
|
||||
const count = (predicate) => results.filter(predicate).length
|
||||
const asrSeconds = results.reduce(
|
||||
(total, result) => total + (Number(result.durationSeconds) || 0),
|
||||
0,
|
||||
)
|
||||
|
||||
return {
|
||||
attempted: results.length,
|
||||
created: count((result) => result.outcome === 'created'),
|
||||
existing: count((result) => result.outcome === 'existing'),
|
||||
ready: count((result) => result.processingStatus === 'pronto'),
|
||||
failed: count((result) => result.processingStatus === 'falhou'),
|
||||
published: count((result) => result.published === true),
|
||||
linkOnly: count(
|
||||
(result) => typeof result.linkFailureReason === 'string' && result.linkFailureReason !== '',
|
||||
),
|
||||
asrSeconds: Math.round(asrSeconds),
|
||||
asrCostUsd: Number(((asrSeconds / 60) * costPerMinuteUsd).toFixed(4)),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The receipt lines the operator reads (and the JSON mirrors). Only facts the
|
||||
* run actually observed: a failure is named with its shortcode and reason.
|
||||
*
|
||||
* @param {{
|
||||
* target: string,
|
||||
* mode: 'plan' | 'apply',
|
||||
* window: { days: number, from: string, to: string },
|
||||
* feedCount: number,
|
||||
* plan: ReturnType<typeof planInstagramContentWindow>,
|
||||
* summary?: ReturnType<typeof summarizeInstagramContentResults>,
|
||||
* failures?: Array<{ shortcode: string, error: string }>,
|
||||
* candidatesRemaining?: number,
|
||||
* reportPath?: string | null,
|
||||
* }} report
|
||||
*/
|
||||
export const formatInstagramContentReport = (report) => {
|
||||
const lines = []
|
||||
const plannedLinkOnly = report.plan.candidates.filter(
|
||||
(candidate) => candidate.linkOnlyReason !== null,
|
||||
).length
|
||||
|
||||
lines.push(`[content:instagram:import] alvo: ${report.target} | modo: ${report.mode}`)
|
||||
lines.push(`janela: ${report.window.days} dias (${report.window.from} → ${report.window.to})`)
|
||||
lines.push(
|
||||
`feed: ${report.feedCount} mídias · na janela: ${report.plan.found} · já na Central: ${report.plan.existingCount} · fora da janela: ${report.plan.outsideWindow} · sem identidade: ${report.plan.malformed}`,
|
||||
)
|
||||
lines.push(
|
||||
`candidatos: ${report.plan.candidates.length} (peça-link previstos: ${plannedLinkOnly})`,
|
||||
)
|
||||
|
||||
if (report.summary) {
|
||||
lines.push(
|
||||
`novas: ${report.summary.created} · já estavam: ${report.summary.existing} · prontas: ${report.summary.ready} · falharam: ${report.summary.failed} · publicadas: ${report.summary.published} · peça-link: ${report.summary.linkOnly}`,
|
||||
)
|
||||
lines.push(`ASR: ${report.summary.asrSeconds}s (~US$ ${report.summary.asrCostUsd})`)
|
||||
for (const failure of report.failures ?? []) {
|
||||
lines.push(` - falha ${failure.shortcode}: ${failure.error}`)
|
||||
}
|
||||
for (const candidate of report.plan.candidates.filter(
|
||||
(entry) => entry.linkOnlyReason !== null,
|
||||
)) {
|
||||
lines.push(` - peça-link ${candidate.shortcode}: ${candidate.linkOnlyReason}`)
|
||||
}
|
||||
}
|
||||
|
||||
if ((report.candidatesRemaining ?? 0) > 0) {
|
||||
lines.push(
|
||||
`restam ${report.candidatesRemaining} candidatos no lote — rode de novo para terminar.`,
|
||||
)
|
||||
}
|
||||
if (report.reportPath) lines.push(`recibo: ${report.reportPath}`)
|
||||
return lines
|
||||
}
|
||||
|
|
@ -86,6 +86,7 @@ export const SCRIPTS_SPEC_PINNED = [
|
|||
'scripts/lib/graficosInstagramRender.mjs',
|
||||
'scripts/lib/imageFill.mjs',
|
||||
'scripts/lib/imageResize.mjs',
|
||||
'scripts/lib/instagramContentPlan.mjs',
|
||||
'scripts/lib/issues-panel.mjs',
|
||||
'scripts/lib/markdown-ansi.mjs',
|
||||
'scripts/lib/mediaBinaries.mjs',
|
||||
|
|
|
|||
|
|
@ -23,8 +23,8 @@ export const POST = campaignJsonMutationRoute(
|
|||
safeMessages: CONTENT_PIECE_PROFILE_IMPORT_SAFE_MESSAGES,
|
||||
genericMessage: CONTENT_PIECE_GENERIC_ERROR_MESSAGE,
|
||||
},
|
||||
async () => {
|
||||
const listing = await listContentPieceProfileImportCandidatesForActor()
|
||||
async (body) => {
|
||||
const listing = await listContentPieceProfileImportCandidatesForActor(body)
|
||||
return NextResponse.json<ContentPieceProfileImportCandidatesResponse>({
|
||||
status: 'success',
|
||||
...listing,
|
||||
|
|
|
|||
|
|
@ -10,13 +10,15 @@ export type ContentPieceLinkResponse =
|
|||
| { status: 'success'; piece: ContentPieceViewModel }
|
||||
| { status: 'error'; message: string }
|
||||
|
||||
/** Wire contract of `POST .../conteudos/importar` (C230) — profile listing. */
|
||||
/** Wire contract of `POST .../conteudos/importar` (C230/C235) — profile listing. */
|
||||
export type ContentPieceProfileImportCandidatesResponse =
|
||||
| {
|
||||
status: 'success'
|
||||
found: number
|
||||
existingCount: number
|
||||
candidates: ContentPieceProfileCandidate[]
|
||||
/** The official API did not reach the requested window start (C235). */
|
||||
truncated: boolean
|
||||
}
|
||||
| { status: 'error'; message: string }
|
||||
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ import {
|
|||
CONTENT_PIECE_RETRY_NOT_FAILED_MESSAGE,
|
||||
contentPieceDeleteRequestSchema,
|
||||
contentPieceLinkRequestSchema,
|
||||
contentPieceProfileImportRequestSchema,
|
||||
contentPiecePublicationRequestSchema,
|
||||
contentPieceRetryRequestSchema,
|
||||
contentPieceStatusRequestSchema,
|
||||
|
|
@ -385,14 +386,16 @@ export const addContentPieceByLinkForActor = async (input: {
|
|||
* Central by the identity of the post, never by the URL spelling. The listing
|
||||
* persists nothing; the confirmation creates the pieces one by one.
|
||||
*/
|
||||
export const listContentPieceProfileImportCandidatesForActor =
|
||||
async (): Promise<ContentPieceProfileImportListing> => {
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
export const listContentPieceProfileImportCandidatesForActor = async (
|
||||
input: unknown = {},
|
||||
): Promise<ContentPieceProfileImportListing> => {
|
||||
const window = contentPieceProfileImportRequestSchema.parse(input)
|
||||
const { payload, actor } = await getCampaignActionContext()
|
||||
|
||||
if (!canReadCommunicationCatalog(actor.role)) throw new Error(CONTENT_PIECE_FORBIDDEN_MESSAGE)
|
||||
if (!canReadCommunicationCatalog(actor.role)) throw new Error(CONTENT_PIECE_FORBIDDEN_MESSAGE)
|
||||
|
||||
return listContentPieceProfileImportCandidates({ payload, actor })
|
||||
}
|
||||
return listContentPieceProfileImportCandidates({ payload, actor, window })
|
||||
}
|
||||
|
||||
/**
|
||||
* C230 — creates ONE draft from ONE listed media through the C220 pipeline
|
||||
|
|
@ -407,7 +410,7 @@ export const createContentPieceFromProfilePostForActor = async (input: {
|
|||
|
||||
if (!canReadCommunicationCatalog(actor.role)) throw new Error(CONTENT_PIECE_FORBIDDEN_MESSAGE)
|
||||
|
||||
const outcome = await createContentPieceFromProfilePost({ payload, actor, url: parsed.url })
|
||||
const { outcome } = await createContentPieceFromProfilePost({ payload, actor, url: parsed.url })
|
||||
return { outcome }
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,17 @@
|
|||
'use client'
|
||||
|
||||
import { CheckIcon, CircleAlertIcon, InstagramIcon } from 'lucide-react'
|
||||
import {
|
||||
CalendarDaysIcon,
|
||||
CalendarXIcon,
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
InstagramIcon,
|
||||
SearchIcon,
|
||||
TriangleAlertIcon,
|
||||
} from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/navigation'
|
||||
import { useState } from 'react'
|
||||
import { useRef, useState, type KeyboardEvent } from 'react'
|
||||
|
||||
import type {
|
||||
ContentPieceProfileImportCandidatesResponse,
|
||||
|
|
@ -21,13 +29,27 @@ import {
|
|||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Progress } from '@/components/ui/Progress'
|
||||
import { Spinner } from '@/components/ui/Spinner'
|
||||
import { postCampaignJson } from '@/lib/campaignJsonRequest'
|
||||
import {
|
||||
CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_CREATE_HREF,
|
||||
CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_HREF,
|
||||
} from '@/lib/campaignPaths'
|
||||
import {
|
||||
formatBahiaCivilDate,
|
||||
formatCivilDateLabel,
|
||||
subtractBahiaCivilDays,
|
||||
subtractBahiaCivilMonths,
|
||||
} from '@/lib/campaignTime'
|
||||
import type { ContentPieceProfileLinkOnlyReason } from '@/lib/contentPiece'
|
||||
import {
|
||||
CONTENT_PIECE_PROFILE_IMPORT_LARGE_WINDOW_THRESHOLD,
|
||||
contentPieceProfilePeriodError,
|
||||
contentPieceProfileWindowLabel,
|
||||
type ContentPieceProfileWindow,
|
||||
} from '@/lib/contentPieceProfileWindow'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { buildContentPieceListHref } from '@/utilities/content/contentPieceListUrl'
|
||||
|
||||
|
|
@ -35,7 +57,9 @@ const GENERIC_ERROR_MESSAGE = 'Não foi possível concluir a importação. Tente
|
|||
|
||||
const PROFILE_HANDLE = '@depjorgesolla'
|
||||
|
||||
type ImportPhase = 'intro' | 'running' | 'done'
|
||||
type ImportPhase = 'window' | 'confirm' | 'running' | 'done' | 'empty' | 'error'
|
||||
|
||||
type WindowMode = 'recent' | 'period'
|
||||
|
||||
type ImportResult = {
|
||||
created: number
|
||||
|
|
@ -45,8 +69,14 @@ type ImportResult = {
|
|||
linkOnly: ContentPieceProfileLinkOnlyReason[]
|
||||
/** First non-generic failure message of the loop, shown in the receipt. */
|
||||
failureMessage: string | null
|
||||
/** The official API did not reach the window start (design scene 06d). */
|
||||
truncated: boolean
|
||||
/** "Período · 01/08/2026 → hoje" in period mode; null for the recency slice. */
|
||||
windowLabel: string | null
|
||||
}
|
||||
|
||||
type ImportListing = Extract<ContentPieceProfileImportCandidatesResponse, { status: 'success' }>
|
||||
|
||||
const IMPORT_STATUS: Record<
|
||||
ContentPieceProfileLinkOnlyReason,
|
||||
{ title: string; description: string }
|
||||
|
|
@ -72,13 +102,17 @@ const countByReason = (
|
|||
return [...counts]
|
||||
}
|
||||
|
||||
const plural = (count: number, singular: string, pluralForm: string): string =>
|
||||
count === 1 ? singular : pluralForm
|
||||
|
||||
/**
|
||||
* C230 — "Importar do perfil" (approved design scenes 2–4): the assessoria
|
||||
* brings the recent publications of the official profile into the Central.
|
||||
* The dialog drives the two phases for real — the listing (Graph API, own
|
||||
* profile only, dedupe by post identity) and one creation per novelty through
|
||||
* the C220 pipeline — so "Importando X de N…" is progress, never decoration.
|
||||
* Nothing is published: every novelty lands as Rascunho for curation.
|
||||
* C230/C235 — "Importar do perfil": the assessoria brings the publications of
|
||||
* the official profile into the Central. The dialog drives the two phases for
|
||||
* real — the listing (Graph API, own profile only, dedupe by post identity)
|
||||
* and one creation per novelty through the C220 pipeline. C235 adds the window
|
||||
* choice: Recents stays the default single-click gesture; a period is an
|
||||
* explicit gesture that shows the honest size (new · already there · total)
|
||||
* before creating. Nothing is published: every novelty lands as Rascunho.
|
||||
*/
|
||||
export const ImportContentPieceProfileDialog = ({
|
||||
configured,
|
||||
|
|
@ -90,55 +124,72 @@ export const ImportContentPieceProfileDialog = ({
|
|||
}) => {
|
||||
const router = useRouter()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [phase, setPhase] = useState<ImportPhase>('intro')
|
||||
const [listing, setListing] = useState(false)
|
||||
const [phase, setPhase] = useState<ImportPhase>('window')
|
||||
const [mode, setMode] = useState<WindowMode>('recent')
|
||||
const [since, setSince] = useState('')
|
||||
const [until, setUntil] = useState('')
|
||||
const [windowError, setWindowError] = useState<string | null>(null)
|
||||
const [searching, setSearching] = useState(false)
|
||||
const [listing, setListing] = useState<ImportListing | null>(null)
|
||||
const [progress, setProgress] = useState({ done: 0, total: 0 })
|
||||
const [result, setResult] = useState<ImportResult | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const recentRadioRef = useRef<HTMLButtonElement>(null)
|
||||
const periodRadioRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
const today = formatBahiaCivilDate(new Date())
|
||||
|
||||
const selectWindowMode = (next: WindowMode) => {
|
||||
setMode(next)
|
||||
setWindowError(null)
|
||||
}
|
||||
|
||||
// WAI-ARIA radiogroup: arrows move the selection and the focus (roving
|
||||
// tabindex), so the two window options behave like one control.
|
||||
const handleWindowChoiceKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (!['ArrowDown', 'ArrowRight', 'ArrowUp', 'ArrowLeft'].includes(event.key)) return
|
||||
event.preventDefault()
|
||||
const next = mode === 'recent' ? 'period' : 'recent'
|
||||
selectWindowMode(next)
|
||||
;(next === 'recent' ? recentRadioRef : periodRadioRef).current?.focus()
|
||||
}
|
||||
|
||||
const reset = () => {
|
||||
setPhase('intro')
|
||||
setListing(false)
|
||||
setPhase('window')
|
||||
setMode('recent')
|
||||
setSince('')
|
||||
setUntil('')
|
||||
setWindowError(null)
|
||||
setSearching(false)
|
||||
setListing(null)
|
||||
setProgress({ done: 0, total: 0 })
|
||||
setResult(null)
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const runImport = async () => {
|
||||
const periodWindow = (): ContentPieceProfileWindow => ({
|
||||
mode: 'period',
|
||||
since,
|
||||
until: until || undefined,
|
||||
})
|
||||
|
||||
const requestWindow = (): ContentPieceProfileWindow =>
|
||||
mode === 'recent' ? { mode: 'recent' } : periodWindow()
|
||||
|
||||
const requestLabel = (request: ContentPieceProfileWindow): string | null =>
|
||||
request.mode === 'period' ? `Período · ${contentPieceProfileWindowLabel(request)}` : null
|
||||
|
||||
const runCreationLoop = async (window: ContentPieceProfileWindow, listed: ImportListing) => {
|
||||
setPhase('running')
|
||||
setListing(true)
|
||||
setProgress({ done: 0, total: 0 })
|
||||
setResult(null)
|
||||
setError(null)
|
||||
|
||||
let candidates: ContentPieceProfileImportCandidatesResponse & { status: 'success' }
|
||||
try {
|
||||
const { ok, payload } = await postCampaignJson<ContentPieceProfileImportCandidatesResponse>(
|
||||
CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_HREF,
|
||||
{},
|
||||
)
|
||||
if (!ok || payload.status !== 'success') {
|
||||
setError(payload.status === 'error' ? payload.message : GENERIC_ERROR_MESSAGE)
|
||||
setPhase('intro')
|
||||
return
|
||||
}
|
||||
candidates = payload
|
||||
} catch {
|
||||
setError(GENERIC_ERROR_MESSAGE)
|
||||
setPhase('intro')
|
||||
return
|
||||
}
|
||||
|
||||
setListing(false)
|
||||
setProgress({ done: 0, total: candidates.candidates.length })
|
||||
setProgress({ done: 0, total: listed.candidates.length })
|
||||
|
||||
let created = 0
|
||||
let existing = candidates.existingCount
|
||||
let existing = listed.existingCount
|
||||
let failed = 0
|
||||
let failureMessage: string | null = null
|
||||
const linkOnly: ContentPieceProfileLinkOnlyReason[] = []
|
||||
|
||||
for (const [index, candidate] of candidates.candidates.entries()) {
|
||||
for (const [index, candidate] of listed.candidates.entries()) {
|
||||
try {
|
||||
const { ok, payload } = await postCampaignJson<ContentPieceProfileImportCreateResponse>(
|
||||
CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_CREATE_HREF,
|
||||
|
|
@ -160,15 +211,311 @@ export const ImportContentPieceProfileDialog = ({
|
|||
} catch {
|
||||
failed += 1
|
||||
}
|
||||
setProgress({ done: index + 1, total: candidates.candidates.length })
|
||||
setProgress({ done: index + 1, total: listed.candidates.length })
|
||||
}
|
||||
|
||||
setResult({ created, existing, failed, linkOnly, failureMessage })
|
||||
setResult({
|
||||
created,
|
||||
existing,
|
||||
failed,
|
||||
linkOnly,
|
||||
failureMessage,
|
||||
truncated: listed.truncated,
|
||||
windowLabel: requestLabel(window),
|
||||
})
|
||||
setPhase('done')
|
||||
router.refresh()
|
||||
}
|
||||
|
||||
const runSearch = async () => {
|
||||
const request = requestWindow()
|
||||
if (request.mode === 'period') {
|
||||
const message = contentPieceProfilePeriodError({
|
||||
since: request.since,
|
||||
until: request.until ?? null,
|
||||
today,
|
||||
})
|
||||
if (message) {
|
||||
setWindowError(message)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
setWindowError(null)
|
||||
setError(null)
|
||||
setListing(null)
|
||||
setPhase('running')
|
||||
setSearching(true)
|
||||
setProgress({ done: 0, total: 0 })
|
||||
|
||||
let found: ImportListing
|
||||
try {
|
||||
const { ok, payload } = await postCampaignJson<ContentPieceProfileImportCandidatesResponse>(
|
||||
CAMPAIGN_CONTENT_PIECE_PROFILE_IMPORT_HREF,
|
||||
request,
|
||||
)
|
||||
if (!ok || payload.status !== 'success') {
|
||||
setError(payload.status === 'error' ? payload.message : GENERIC_ERROR_MESSAGE)
|
||||
setPhase('error')
|
||||
return
|
||||
}
|
||||
found = payload
|
||||
} catch {
|
||||
setError(GENERIC_ERROR_MESSAGE)
|
||||
setPhase('error')
|
||||
return
|
||||
}
|
||||
|
||||
setListing(found)
|
||||
setSearching(false)
|
||||
|
||||
if (request.mode === 'recent') {
|
||||
await runCreationLoop(request, found)
|
||||
return
|
||||
}
|
||||
if (found.found === 0) {
|
||||
setPhase('empty')
|
||||
return
|
||||
}
|
||||
if (found.candidates.length === 0) {
|
||||
setResult({
|
||||
created: 0,
|
||||
existing: found.existingCount,
|
||||
failed: 0,
|
||||
linkOnly: [],
|
||||
failureMessage: null,
|
||||
truncated: found.truncated,
|
||||
windowLabel: requestLabel(request),
|
||||
})
|
||||
setPhase('done')
|
||||
return
|
||||
}
|
||||
setPhase('confirm')
|
||||
}
|
||||
|
||||
const linkOnlyRows = result ? countByReason(result.linkOnly) : []
|
||||
const progressPercent =
|
||||
progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0
|
||||
const largeWindow =
|
||||
listing !== null &&
|
||||
listing.candidates.length > CONTENT_PIECE_PROFILE_IMPORT_LARGE_WINDOW_THRESHOLD
|
||||
|
||||
const windowStep = (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<div className="mb-4 grid size-10 place-items-center rounded-full bg-red-50 text-primary">
|
||||
<InstagramIcon className="size-5" aria-hidden="true" />
|
||||
</div>
|
||||
<DialogTitle className="border-b-0 pb-0">Importar do perfil</DialogTitle>
|
||||
<DialogDescription>
|
||||
Escolha quais publicações de <b className="text-foreground">{PROFILE_HANDLE}</b> procurar.
|
||||
Só as que ainda não estão na Central entram, sempre como rascunho.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="mt-5">
|
||||
<p className="text-sm font-semibold">Qual janela de publicações?</p>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||||
O recorte usa a data de publicação do post.
|
||||
</p>
|
||||
|
||||
<div
|
||||
className="mt-3 space-y-2"
|
||||
role="radiogroup"
|
||||
aria-label="Janela de publicações"
|
||||
onKeyDown={handleWindowChoiceKeyDown}
|
||||
>
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<button
|
||||
ref={recentRadioRef}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={mode === 'recent'}
|
||||
tabIndex={mode === 'recent' ? 0 : -1}
|
||||
onClick={() => selectWindowMode('recent')}
|
||||
className={cn(
|
||||
'flex w-full items-start gap-3 p-3.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
||||
mode === 'recent' ? 'bg-stone-50' : 'bg-white hover:bg-stone-50',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'mt-0.5 size-4 shrink-0 rounded-full border-2',
|
||||
mode === 'recent'
|
||||
? 'border-primary bg-primary ring-2 ring-white ring-inset'
|
||||
: 'border-stone-300',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="min-w-0">
|
||||
<span className="flex flex-wrap items-center gap-2">
|
||||
<b className="text-sm">Recentes</b>
|
||||
<Badge variant="secondary">Padrão</Badge>
|
||||
</span>
|
||||
<span className="mt-0.5 block text-xs leading-5 text-muted-foreground">
|
||||
As publicações mais novas do perfil. É o comportamento de sempre.
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="overflow-hidden rounded-lg border">
|
||||
<button
|
||||
ref={periodRadioRef}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={mode === 'period'}
|
||||
tabIndex={mode === 'period' ? 0 : -1}
|
||||
onClick={() => selectWindowMode('period')}
|
||||
className={cn(
|
||||
'flex w-full items-start gap-3 p-3.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
||||
mode === 'period' ? 'bg-stone-50' : 'bg-white hover:bg-stone-50',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'mt-0.5 size-4 shrink-0 rounded-full border-2',
|
||||
mode === 'period'
|
||||
? 'border-primary bg-primary ring-2 ring-white ring-inset'
|
||||
: 'border-stone-300',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="min-w-0">
|
||||
<span className="flex items-center gap-2">
|
||||
<b className="text-sm">Período</b>
|
||||
</span>
|
||||
<span className="mt-0.5 block text-xs leading-5 text-muted-foreground">
|
||||
Escolha desde uma data; a data final é opcional.
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{mode === 'period' ? (
|
||||
<div className="border-t bg-white px-3.5 py-3">
|
||||
<div className="grid grid-cols-2 gap-3 max-sm:grid-cols-1">
|
||||
<label className="block">
|
||||
<span className="text-xs font-medium text-muted-foreground">Desde</span>
|
||||
<Input
|
||||
type="date"
|
||||
className="mt-1 min-h-11"
|
||||
value={since}
|
||||
max={today}
|
||||
onChange={(event) => {
|
||||
setSince(event.target.value)
|
||||
setWindowError(null)
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
Até (opcional)
|
||||
</span>
|
||||
<Input
|
||||
type="date"
|
||||
className="mt-1 min-h-11"
|
||||
value={until}
|
||||
max={today}
|
||||
placeholder="dd/mm/aaaa"
|
||||
onChange={(event) => {
|
||||
setUntil(event.target.value)
|
||||
setWindowError(null)
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
className="min-h-8 rounded-full border px-2.5 text-xs font-medium hover:bg-stone-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => {
|
||||
setSince(subtractBahiaCivilDays(today, 30))
|
||||
setUntil('')
|
||||
setWindowError(null)
|
||||
}}
|
||||
>
|
||||
Últimos 30 dias
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="min-h-8 rounded-full border px-2.5 text-xs font-medium hover:bg-stone-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => {
|
||||
setSince(subtractBahiaCivilMonths(today, 6))
|
||||
setUntil('')
|
||||
setWindowError(null)
|
||||
}}
|
||||
>
|
||||
Últimos 6 meses
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="min-h-8 rounded-full border px-2.5 text-xs font-medium hover:bg-stone-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring max-sm:hidden"
|
||||
onClick={() => {
|
||||
setSince(`${today.slice(0, 4)}-01-01`)
|
||||
setUntil('')
|
||||
setWindowError(null)
|
||||
}}
|
||||
>
|
||||
Este ano
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
Deixe “Até” em branco para buscar até hoje.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{windowError ? (
|
||||
<p className="mt-2 text-xs font-medium text-red-700" role="alert">
|
||||
{windowError}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="mt-4 space-y-2 rounded-lg border bg-stone-50 p-3.5 text-xs leading-5 text-muted-foreground">
|
||||
<p className="flex gap-2">
|
||||
<CheckIcon className="mt-0.5 size-3.5 shrink-0 text-primary" aria-hidden="true" />
|
||||
<span>
|
||||
<b className="text-foreground">Somente novidades</b> — o que já está é reconhecido, sem
|
||||
cópias.
|
||||
</span>
|
||||
</p>
|
||||
<p className="flex gap-2">
|
||||
<CheckIcon className="mt-0.5 size-3.5 shrink-0 text-primary" aria-hidden="true" />
|
||||
<span>
|
||||
<b className="text-foreground">Tudo entra como Rascunho</b> — nada é publicado
|
||||
automaticamente.
|
||||
</span>
|
||||
</p>
|
||||
<p className="flex gap-2">
|
||||
<CheckIcon className="mt-0.5 size-3.5 shrink-0 text-primary" aria-hidden="true" />
|
||||
<span>
|
||||
<b className="text-foreground">Só o perfil oficial, pela API oficial</b> — sem scraping.
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="max-sm:flex-col-reverse">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11 max-sm:w-full"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
reset()
|
||||
}}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="button" className="min-h-11 max-sm:w-full" onClick={() => void runSearch()}>
|
||||
<SearchIcon data-icon="inline-start" aria-hidden="true" />
|
||||
Buscar publicações
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
)
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
|
|
@ -209,12 +556,29 @@ export const ImportContentPieceProfileDialog = ({
|
|||
<DialogTitle className="border-b-0 pb-0">Importação concluída</DialogTitle>
|
||||
<DialogDescription>
|
||||
{result.created === 0 && result.failed === 0
|
||||
? 'Nenhuma novidade na janela recente — a Central já estava em dia.'
|
||||
? `Nenhuma novidade na ${
|
||||
result.windowLabel ? 'janela escolhida' : 'janela recente'
|
||||
} — a Central já estava em dia.`
|
||||
: 'As novidades já estão na Central como rascunho. Nada foi publicado.'}
|
||||
</DialogDescription>
|
||||
{result.windowLabel ? (
|
||||
<p className="text-xs text-muted-foreground">{result.windowLabel}</p>
|
||||
) : null}
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{result.truncated ? (
|
||||
<div className="mt-4 flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 p-3.5 text-xs leading-5 text-amber-900">
|
||||
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||
<div>
|
||||
<b className="text-sm">A janela pedida é maior do que a via oficial alcança.</b> O
|
||||
Instagram entrega as <b>10K mídias mais recentes</b>; importamos o que foi
|
||||
possível neste recorte. Reexecutar a mesma janela continua de onde parou, sem
|
||||
duplicar.
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-4 grid grid-cols-3 gap-2">
|
||||
<div className="rounded-lg border border-green-200 bg-green-50 p-3">
|
||||
<b className="block text-xl tabular-nums text-green-800">{result.created}</b>
|
||||
<span className="text-xs font-medium text-green-800">novas criadas</span>
|
||||
|
|
@ -232,7 +596,7 @@ export const ImportContentPieceProfileDialog = ({
|
|||
</div>
|
||||
|
||||
{linkOnlyRows.length > 0 || result.failed > 0 ? (
|
||||
<div className="overflow-hidden rounded-lg border text-xs">
|
||||
<div className="mt-4 overflow-hidden rounded-lg border text-xs">
|
||||
{linkOnlyRows.map(([reason, count], index) => {
|
||||
const status = IMPORT_STATUS[reason]
|
||||
return (
|
||||
|
|
@ -277,11 +641,11 @@ export const ImportContentPieceProfileDialog = ({
|
|||
</div>
|
||||
) : null}
|
||||
|
||||
<DialogFooter>
|
||||
<DialogFooter className="max-sm:flex-col-reverse">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11"
|
||||
className="min-h-11 max-sm:w-full"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
reset()
|
||||
|
|
@ -289,7 +653,7 @@ export const ImportContentPieceProfileDialog = ({
|
|||
>
|
||||
Fechar
|
||||
</Button>
|
||||
<Button asChild className="min-h-11">
|
||||
<Button asChild className="min-h-11 max-sm:w-full">
|
||||
<Link
|
||||
href={buildContentPieceListHref({ page: 1, statuses: ['rascunho'] }, 1)}
|
||||
onClick={() => {
|
||||
|
|
@ -302,6 +666,180 @@ export const ImportContentPieceProfileDialog = ({
|
|||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
) : phase === 'confirm' && listing ? (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<div className="mb-4 grid size-10 place-items-center rounded-full bg-red-50 text-primary">
|
||||
<InstagramIcon className="size-5" aria-hidden="true" />
|
||||
</div>
|
||||
<DialogTitle className="border-b-0 pb-0">Importar do perfil</DialogTitle>
|
||||
<DialogDescription>
|
||||
A janela escolhida tem <b className="text-foreground">{listing.found}</b>{' '}
|
||||
{plural(listing.found, 'publicação', 'publicações')}. Confira o tamanho antes de
|
||||
criar os rascunhos.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="mt-5 space-y-3">
|
||||
<div className="flex items-center gap-2 rounded-lg border bg-stone-50 px-3.5 py-2.5 text-xs">
|
||||
<CalendarDaysIcon
|
||||
className="size-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="font-medium">Período</span>
|
||||
<span className="text-muted-foreground">
|
||||
{contentPieceProfileWindowLabel(periodWindow())}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="ml-auto text-xs font-medium text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => setPhase('window')}
|
||||
>
|
||||
Trocar
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div className="rounded-lg border border-green-200 bg-green-50 p-3">
|
||||
<b className="block text-xl tabular-nums text-green-800">
|
||||
{listing.candidates.length}
|
||||
</b>
|
||||
<span className="text-xs font-medium text-green-800">novas a criar</span>
|
||||
</div>
|
||||
<div className="rounded-lg border bg-stone-50 p-3">
|
||||
<b className="block text-xl tabular-nums">{listing.existingCount}</b>
|
||||
<span className="text-xs font-medium text-muted-foreground">já estavam</span>
|
||||
</div>
|
||||
<div className="rounded-lg border p-3">
|
||||
<b className="block text-xl tabular-nums">{listing.found}</b>
|
||||
<span className="text-xs font-medium text-muted-foreground">total na janela</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{largeWindow ? (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 p-3.5 text-xs leading-5 text-amber-900">
|
||||
<TriangleAlertIcon className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
|
||||
<div>
|
||||
<b className="text-sm">Janela grande.</b> {listing.candidates.length} rascunhos
|
||||
serão criados de uma vez. Nada é publicado — tudo entra como rascunho para
|
||||
revisão na lista.
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<p className="rounded-lg bg-muted/70 p-3 text-xs leading-5 text-muted-foreground">
|
||||
Reexecutar a mesma janela não duplica: o que já está é reconhecido pela identidade
|
||||
do post. Pode demorar um pouco em janelas grandes.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="max-sm:flex-col-reverse">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11 max-sm:w-full"
|
||||
onClick={() => setPhase('window')}
|
||||
>
|
||||
Voltar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="min-h-11 max-sm:w-full"
|
||||
onClick={() => void runCreationLoop(periodWindow(), listing)}
|
||||
>
|
||||
Importar {listing.candidates.length}{' '}
|
||||
{plural(listing.candidates.length, 'publicação', 'publicações')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
) : phase === 'empty' ? (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<div className="mb-4 grid size-10 place-items-center rounded-full border bg-stone-50 text-stone-600">
|
||||
<CalendarXIcon className="size-5" aria-hidden="true" />
|
||||
</div>
|
||||
<DialogTitle className="border-b-0 pb-0">
|
||||
Nenhuma publicação neste período
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Nada de <b className="text-foreground">{PROFILE_HANDLE}</b> foi publicado entre{' '}
|
||||
<b className="text-foreground">{formatCivilDateLabel(since)}</b> e{' '}
|
||||
<b className="text-foreground">{until ? formatCivilDateLabel(until) : 'hoje'}</b>.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<p className="mt-4 rounded-lg border bg-stone-50 p-3.5 text-xs leading-5 text-muted-foreground">
|
||||
O recorte está vazio. Confira as datas ou importe as publicações recentes do perfil.
|
||||
</p>
|
||||
<DialogFooter className="max-sm:flex-col-reverse">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11 max-sm:w-full"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
reset()
|
||||
}}
|
||||
>
|
||||
Fechar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="min-h-11 max-sm:w-full"
|
||||
onClick={() => setPhase('window')}
|
||||
>
|
||||
Escolher outra janela
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
) : phase === 'error' ? (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<div className="mb-4 grid size-10 place-items-center rounded-full bg-red-50 text-primary">
|
||||
<InstagramIcon className="size-5" aria-hidden="true" />
|
||||
</div>
|
||||
<DialogTitle className="border-b-0 pb-0">Importar do perfil</DialogTitle>
|
||||
<DialogDescription>
|
||||
{mode === 'period' ? (
|
||||
<>
|
||||
A janela de{' '}
|
||||
<b className="text-foreground">
|
||||
{contentPieceProfileWindowLabel(periodWindow())}
|
||||
</b>{' '}
|
||||
não pôde ser buscada agora.
|
||||
</>
|
||||
) : (
|
||||
<>As publicações recentes não puderam ser buscadas agora.</>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Alert variant="destructive" className="mt-4 py-2">
|
||||
<CircleAlertIcon aria-hidden="true" />
|
||||
<AlertDescription className="text-xs">
|
||||
<b>Não foi possível buscar as publicações.</b>{' '}
|
||||
{error ?? 'A API oficial não respondeu.'} Nada foi criado.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<DialogFooter className="max-sm:flex-col-reverse">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11 max-sm:w-full"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
reset()
|
||||
}}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
className="min-h-11 max-sm:w-full"
|
||||
onClick={() => void runSearch()}
|
||||
>
|
||||
Tentar de novo
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
) : phase === 'running' ? (
|
||||
<>
|
||||
<DialogHeader>
|
||||
|
|
@ -319,10 +857,10 @@ export const ImportContentPieceProfileDialog = ({
|
|||
<div
|
||||
className={cn(
|
||||
'mt-0.5 grid size-6 shrink-0 place-items-center rounded-full',
|
||||
listing ? 'bg-stone-100 text-stone-500' : 'bg-green-100 text-green-700',
|
||||
searching ? 'bg-stone-100 text-stone-500' : 'bg-green-100 text-green-700',
|
||||
)}
|
||||
>
|
||||
{listing ? (
|
||||
{searching ? (
|
||||
<Spinner className="size-3.5" />
|
||||
) : (
|
||||
<CheckIcon className="size-3.5" aria-hidden="true" />
|
||||
|
|
@ -330,29 +868,42 @@ export const ImportContentPieceProfileDialog = ({
|
|||
</div>
|
||||
<div>
|
||||
<b className="text-sm">
|
||||
{listing
|
||||
? 'Buscando as publicações recentes…'
|
||||
: 'Publicações recentes encontradas'}
|
||||
{searching
|
||||
? mode === 'period'
|
||||
? 'Buscando as publicações do período…'
|
||||
: 'Buscando as publicações recentes…'
|
||||
: mode === 'period' && listing
|
||||
? `Janela encontrada · ${listing.found} avaliadas`
|
||||
: 'Publicações recentes encontradas'}
|
||||
</b>
|
||||
<p className="mt-1 text-xs leading-5 text-muted-foreground">
|
||||
{listing
|
||||
{searching
|
||||
? `Consultando ${PROFILE_HANDLE} pela API oficial.`
|
||||
: `A busca foi feita em ${PROFILE_HANDLE} pela API oficial.`}
|
||||
: mode === 'period' && listing
|
||||
? `${listing.candidates.length} novas · ${listing.existingCount} já estavam. A busca foi feita em ${PROFILE_HANDLE} pela API oficial.`
|
||||
: `A busca foi feita em ${PROFILE_HANDLE} pela API oficial.`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!listing && progress.total > 0 ? (
|
||||
{!searching && progress.total > 0 ? (
|
||||
<>
|
||||
<div className="my-3 ml-3 h-5 border-l border-dashed" />
|
||||
<div className="flex items-start gap-3">
|
||||
<Spinner className="mt-0.5 shrink-0" />
|
||||
<div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<b className="text-sm">
|
||||
Importando {Math.min(progress.done + 1, progress.total)} de {progress.total}
|
||||
…
|
||||
</b>
|
||||
<p className="mt-1 text-xs leading-5 text-muted-foreground">
|
||||
{mode === 'period' ? (
|
||||
<Progress
|
||||
className="mt-2 h-2"
|
||||
value={progressPercent}
|
||||
aria-label="Progresso da importação"
|
||||
/>
|
||||
) : null}
|
||||
<p className="mt-2 text-xs leading-5 text-muted-foreground">
|
||||
Criando apenas as novidades como rascunho e reconhecendo o que já estava na
|
||||
Central.
|
||||
</p>
|
||||
|
|
@ -363,8 +914,18 @@ export const ImportContentPieceProfileDialog = ({
|
|||
</div>
|
||||
|
||||
<p className="rounded-lg bg-muted/70 p-3 text-xs leading-5 text-muted-foreground">
|
||||
Algumas mídias podem levar mais tempo para serem preparadas. O resultado final separa
|
||||
novas, já existentes e falhas — nenhuma falha fica escondida.
|
||||
{mode === 'period' ? (
|
||||
<>
|
||||
<b className="text-foreground">Pode demorar</b> — a janela é grande e cada mídia é
|
||||
preparada uma a uma. O resultado final separa novas, já existentes e falhas;
|
||||
nenhuma falha fica escondida.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Algumas mídias podem levar mais tempo para serem preparadas. O resultado final
|
||||
separa novas, já existentes e falhas — nenhuma falha fica escondida.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
|
||||
<DialogFooter>
|
||||
|
|
@ -375,72 +936,7 @@ export const ImportContentPieceProfileDialog = ({
|
|||
</DialogFooter>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<DialogHeader>
|
||||
<div className="mb-4 grid size-10 place-items-center rounded-full bg-red-50 text-primary">
|
||||
<InstagramIcon className="size-5" aria-hidden="true" />
|
||||
</div>
|
||||
<DialogTitle className="border-b-0 pb-0">Importar do perfil</DialogTitle>
|
||||
<DialogDescription>
|
||||
Vamos procurar as publicações recentes de{' '}
|
||||
<b className="text-foreground">{PROFILE_HANDLE}</b> que ainda não estão na Central.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="space-y-3">
|
||||
<div className="flex gap-3 rounded-lg border p-3.5">
|
||||
<CheckIcon className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden="true" />
|
||||
<div>
|
||||
<b className="text-sm">Somente novidades da janela recente</b>
|
||||
<p className="mt-0.5 text-xs leading-5 text-muted-foreground">
|
||||
Publicações que já estão na Central serão reconhecidas e não criam cópias.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-3 rounded-lg border p-3.5">
|
||||
<CheckIcon className="mt-0.5 size-4 shrink-0 text-primary" aria-hidden="true" />
|
||||
<div>
|
||||
<b className="text-sm">Tudo entra como Rascunho</b>
|
||||
<p className="mt-0.5 text-xs leading-5 text-muted-foreground">
|
||||
Nada é publicado automaticamente. A assessoria revisa e decide o que publicar.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border bg-stone-50 p-4 text-xs leading-5 text-muted-foreground">
|
||||
<b className="text-foreground">Sem scraping.</b>
|
||||
<br />
|
||||
Só o perfil oficial {PROFILE_HANDLE}, pela API oficial. Carrossel ou mídia sem
|
||||
arquivo extraível continua como peça-link, com o motivo visível.
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<Alert variant="destructive" className="py-2" role="alert">
|
||||
<CircleAlertIcon aria-hidden="true" />
|
||||
<AlertDescription className="text-xs">{error}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="min-h-11"
|
||||
onClick={() => {
|
||||
setOpen(false)
|
||||
reset()
|
||||
}}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button type="button" className="min-h-11" onClick={() => void runImport()}>
|
||||
Buscar publicações
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</>
|
||||
windowStep
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
|
|
|||
|
|
@ -175,6 +175,19 @@ export const archivePhotoGeoFrom = (
|
|||
return { latitude: lat, longitude: lon }
|
||||
}
|
||||
|
||||
/**
|
||||
* The `clean`/`raw` leaves of the JSON API answer arrive wrapped as
|
||||
* `{ _content: "…" }` (Flickr's XML heritage); plain strings appear in older
|
||||
* shapes and fixtures. Both are accepted, everything else drops.
|
||||
*/
|
||||
const contentScalar = (value: unknown): string | null => {
|
||||
if (typeof value === 'string') return trimmed(value)
|
||||
if (value !== null && typeof value === 'object') {
|
||||
return trimmed((value as Record<string, unknown>)._content)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes `flickr.photos.getExif` (when it answered) into the stored json:
|
||||
* one entry per tag, empty values dropped, deterministic order.
|
||||
|
|
@ -187,7 +200,7 @@ export const archivePhotoExifEntries = (value: unknown): ArchivePhotoExifEntry[]
|
|||
const entry = raw as Record<string, unknown>
|
||||
const tag = trimmed(entry.tag) ?? trimmed(entry.tagspace)
|
||||
const label = trimmed(entry.label) ?? tag
|
||||
const value = trimmed(entry.clean) ?? trimmed(entry.raw)
|
||||
const value = contentScalar(entry.clean) ?? contentScalar(entry.raw)
|
||||
if (tag === null || label === null || value === null) continue
|
||||
entries.push({ tag, label, value })
|
||||
}
|
||||
|
|
@ -250,10 +263,7 @@ export const archivePhotoImportFromFlickr = ({
|
|||
const originalUrl = original ?? fallback
|
||||
if (originalUrl === null) return { ok: false, reason: 'original' }
|
||||
|
||||
const description =
|
||||
item.description !== null && typeof item.description === 'object'
|
||||
? trimmed((item.description as Record<string, unknown>)._content)
|
||||
: trimmed(item.description)
|
||||
const description = contentScalar(item.description)
|
||||
|
||||
const license = licenseOrNull(item.license)
|
||||
|
||||
|
|
|
|||
|
|
@ -181,6 +181,19 @@ export const subtractBahiaCivilDays = (civilDate: string, days: number): string
|
|||
return `${anchor.getUTCFullYear()}-${pad(anchor.getUTCMonth() + 1)}-${pad(anchor.getUTCDate())}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Subtract whole civil months from a Bahia civil date anchor (`aaaa-mm-dd`),
|
||||
* clamping the day to the target month (31/08 − 6 = 28/02) — the C235
|
||||
* "last N months" shortcuts never invent a date that does not exist.
|
||||
*/
|
||||
export const subtractBahiaCivilMonths = (civilDate: string, months: number): string => {
|
||||
const [year, month, day] = civilDate.split('-').map(Number)
|
||||
const target = new Date(Date.UTC(year, month - 1 - months, 1))
|
||||
const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0))
|
||||
target.setUTCDate(Math.min(day, lastDay.getUTCDate()))
|
||||
return `${target.getUTCFullYear()}-${pad(target.getUTCMonth() + 1)}-${pad(target.getUTCDate())}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Latest of two ISO timestamps, ignoring nulls. String comparison is only
|
||||
* sound because every writer here produces fixed-width UTC — Payload's own
|
||||
|
|
@ -230,6 +243,16 @@ export const formatBahiaCivilDateTimeLabel = (civil: string): string => {
|
|||
return `${day}/${month}/${year} às ${hour}:${minute}`
|
||||
}
|
||||
|
||||
/**
|
||||
* pt-BR label of a Bahia civil date anchor (`aaaa-mm-dd` → `dd/mm/aaaa`) —
|
||||
* the C235 window inputs speak date-only, same string arithmetic as the
|
||||
* datetime label below.
|
||||
*/
|
||||
export const formatCivilDateLabel = (civil: string): string => {
|
||||
const [year = '', month = '', day = ''] = civil.split('-')
|
||||
return `${day}/${month}/${year}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Date-only pt-BR label of a civil datetime input value (`dd/mm/aaaa`) —
|
||||
* the C104 all-day mode of the date+time picker, same string arithmetic.
|
||||
|
|
|
|||
235
src/lib/contentPieceProfileWindow.ts
Normal file
235
src/lib/contentPieceProfileWindow.ts
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
import {
|
||||
formatBahiaCivilDate,
|
||||
formatCivilDateLabel,
|
||||
parseBahiaDateTimeInput,
|
||||
} from '@/lib/campaignTime'
|
||||
import {
|
||||
contentPiecePostIdentityUrls,
|
||||
contentPieceProfileCandidateFromPost,
|
||||
parseContentPieceLink,
|
||||
type ContentPieceProfileLinkOnlyReason,
|
||||
type ContentPieceProfilePost,
|
||||
} from '@/lib/contentPiece'
|
||||
|
||||
/**
|
||||
* C235 — the publication window of the profile import: the pure owner of the
|
||||
* recency filter (each post timestamp against the civil Bahia dates the
|
||||
* operator typed), the identity dedupe (the feed against the Central in any
|
||||
* URL spelling and against itself) and the honest coverage check that tells
|
||||
* when the official API did not reach the requested start. No I/O and no
|
||||
* `server-only`: the server importer and the ops CLI both read this, and the
|
||||
* unit specs pin the policy without Payload.
|
||||
*/
|
||||
|
||||
/** The window the operator chose: the default recency slice or a civil period. */
|
||||
export type ContentPieceProfileWindow =
|
||||
| { mode: 'recent' }
|
||||
| { mode: 'period'; since: string; until?: string | null }
|
||||
|
||||
/** The feed post the window filter needs: the shared metadata + its timestamp. */
|
||||
export type ContentPieceProfileWindowPost = ContentPieceProfilePost & { timestamp: string }
|
||||
|
||||
type ContentPieceProfileWindowCandidate = {
|
||||
url: string
|
||||
shortcode: string
|
||||
linkOnlyReason: ContentPieceProfileLinkOnlyReason | null
|
||||
timestamp: string
|
||||
mediaType: string
|
||||
}
|
||||
|
||||
export type ContentPieceProfileWindowPlan = {
|
||||
/** The bounds actually applied; null means unbounded on that side. */
|
||||
window: { from: string | null; to: string | null }
|
||||
/** Parseable posts inside the window: candidates + already catalogued + feed twins. */
|
||||
found: number
|
||||
existingCount: number
|
||||
existingShortcodes: string[]
|
||||
feedDuplicates: number
|
||||
malformed: number
|
||||
outsideWindow: number
|
||||
/** The novelties, in feed order (newest first). */
|
||||
candidates: ContentPieceProfileWindowCandidate[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Above this many novelties the confirmation warns that a large batch of
|
||||
* drafts will be created at once (design scene 03). One feed page is the unit
|
||||
* the operator already sees in the recency import.
|
||||
*/
|
||||
export const CONTENT_PIECE_PROFILE_IMPORT_LARGE_WINDOW_THRESHOLD = 50
|
||||
|
||||
type CivilDateCheck = { since: string; until?: string | null }
|
||||
|
||||
/** Exact civil-round-trip: a syntactically valid but impossible date fails. */
|
||||
const isRealCivilDate = (value: string): boolean => {
|
||||
const instantIso = parseBahiaDateTimeInput(`${value}T00:00`)
|
||||
return instantIso !== null && formatBahiaCivilDate(new Date(instantIso)) === value
|
||||
}
|
||||
|
||||
/**
|
||||
* The domain message of an invalid period window, or null when it is valid.
|
||||
* `today` is a civil Bahia date so the future check is stable and testable.
|
||||
*/
|
||||
export const contentPieceProfilePeriodError = ({
|
||||
since,
|
||||
until,
|
||||
today,
|
||||
}: CivilDateCheck & { today: string }): string | null => {
|
||||
if (!isRealCivilDate(since)) return 'Informe uma data inicial válida.'
|
||||
if (until && !isRealCivilDate(until)) return 'Informe uma data final válida.'
|
||||
if (until && until < since) return 'A data final não pode ser anterior à data inicial.'
|
||||
if (since > today) return 'A data inicial não pode estar no futuro.'
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The instants of the chosen period: the start of the `since` civil day and
|
||||
* the exclusive end of the `until` civil day (Bahia is UTC-3 all year round,
|
||||
* so the next civil midnight is a fixed 24h later). An absent `until` is
|
||||
* open-ended — the feed runs to today.
|
||||
*/
|
||||
export const contentPieceProfilePeriodBounds = ({
|
||||
since,
|
||||
until,
|
||||
}: CivilDateCheck): { fromIso: string; toIso: string | null } => {
|
||||
const fromIso = isRealCivilDate(since) ? parseBahiaDateTimeInput(`${since}T00:00`) : null
|
||||
if (!fromIso) throw new Error('Informe uma data inicial válida.')
|
||||
|
||||
if (!until) return { fromIso, toIso: null }
|
||||
|
||||
const untilStart = isRealCivilDate(until) ? parseBahiaDateTimeInput(`${until}T00:00`) : null
|
||||
if (!untilStart) throw new Error('Informe uma data final válida.')
|
||||
return { fromIso, toIso: new Date(Date.parse(untilStart) + 86_400_000).toISOString() }
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the walk went past the start of the window (the feed is
|
||||
* newest-first, so a post older than `fromIso` proves the window start was
|
||||
* reached). A null bound means unbounded — always reached. The check is
|
||||
* conservative on purpose: a profile whose whole history sits inside the
|
||||
* window is reported as not reached, which only makes the receipt more
|
||||
* cautious, never less honest.
|
||||
*/
|
||||
export const contentPieceProfileWindowStartReached = ({
|
||||
posts,
|
||||
fromIso,
|
||||
}: {
|
||||
posts: readonly ContentPieceProfileWindowPost[]
|
||||
fromIso: string | null
|
||||
}): boolean => {
|
||||
if (fromIso === null) return true
|
||||
const fromMs = Date.parse(fromIso)
|
||||
return posts.some((post) => Date.parse(post.timestamp) < fromMs)
|
||||
}
|
||||
|
||||
/** The pt-BR label of the chosen window ("01/08/2026 → hoje"). */
|
||||
export const contentPieceProfileWindowLabel = (window: ContentPieceProfileWindow): string => {
|
||||
if (window.mode === 'recent') return 'Recentes'
|
||||
const from = formatCivilDateLabel(window.since)
|
||||
return `${from} → ${window.until ? formatCivilDateLabel(window.until) : 'hoje'}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The identity URLs of every parseable post of the feed — what the dedupe
|
||||
* query asks the Central for in `sourceUrl in` lookups. A permalink the
|
||||
* catalogue cannot parse contributes nothing (it never becomes a candidate).
|
||||
*/
|
||||
export const contentPieceProfileFeedIdentityUrls = (
|
||||
posts: readonly ContentPieceProfileWindowPost[],
|
||||
): string[] => {
|
||||
const urls = new Set<string>()
|
||||
for (const post of posts) {
|
||||
const candidate = contentPieceProfileCandidateFromPost(post)
|
||||
if (!candidate) continue
|
||||
const link = parseContentPieceLink(candidate.url)
|
||||
if (!link) continue
|
||||
for (const url of contentPiecePostIdentityUrls(link)) urls.add(url)
|
||||
}
|
||||
return [...urls]
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the feed to the chosen window and splits it into novelties, pieces
|
||||
* the Central already had and posts that cannot be imported (outside the
|
||||
* window, unparseable permalink or a repeated identity inside the feed).
|
||||
* Candidates keep the feed order (newest first). The bounds are optional:
|
||||
* without them the whole feed is the window (the recency import).
|
||||
*
|
||||
* `found` counts the parseable posts inside the window: candidates + already
|
||||
* catalogued + repeated identities.
|
||||
*/
|
||||
export const planContentPieceProfileWindow = ({
|
||||
posts,
|
||||
existingSourceUrls = [],
|
||||
from = null,
|
||||
to = null,
|
||||
}: {
|
||||
posts: readonly ContentPieceProfileWindowPost[]
|
||||
existingSourceUrls?: readonly string[]
|
||||
from?: string | null
|
||||
to?: string | null
|
||||
}): ContentPieceProfileWindowPlan => {
|
||||
const fromMs = from === null ? null : Date.parse(from)
|
||||
const toMs = to === null ? null : Date.parse(to)
|
||||
if ((fromMs !== null && !Number.isFinite(fromMs)) || (toMs !== null && !Number.isFinite(toMs))) {
|
||||
throw new Error('janela inválida: from/to precisam ser instantes ISO ou null.')
|
||||
}
|
||||
|
||||
const existing = new Set(existingSourceUrls)
|
||||
const seen = new Set<string>()
|
||||
const candidates: ContentPieceProfileWindowCandidate[] = []
|
||||
const existingShortcodes: string[] = []
|
||||
let outsideWindow = 0
|
||||
let malformed = 0
|
||||
let feedDuplicates = 0
|
||||
|
||||
for (const post of posts) {
|
||||
const timestamp = Date.parse(post.timestamp)
|
||||
if (!Number.isFinite(timestamp)) {
|
||||
// An item without a usable timestamp cannot be placed in any window.
|
||||
malformed += 1
|
||||
continue
|
||||
}
|
||||
if ((fromMs !== null && timestamp < fromMs) || (toMs !== null && timestamp > toMs)) {
|
||||
outsideWindow += 1
|
||||
continue
|
||||
}
|
||||
|
||||
const candidate = contentPieceProfileCandidateFromPost(post)
|
||||
const link = candidate ? parseContentPieceLink(candidate.url) : null
|
||||
if (!candidate || !link) {
|
||||
malformed += 1
|
||||
continue
|
||||
}
|
||||
|
||||
const identityUrls = contentPiecePostIdentityUrls(link)
|
||||
const shortcode = link.origin === 'instagram' ? link.shortcode : link.videoId
|
||||
if (identityUrls.some((url) => existing.has(url))) {
|
||||
existingShortcodes.push(shortcode)
|
||||
continue
|
||||
}
|
||||
if (identityUrls.some((url) => seen.has(url))) {
|
||||
feedDuplicates += 1
|
||||
continue
|
||||
}
|
||||
identityUrls.forEach((url) => seen.add(url))
|
||||
candidates.push({
|
||||
url: candidate.url,
|
||||
shortcode,
|
||||
linkOnlyReason: candidate.linkOnlyReason,
|
||||
timestamp: post.timestamp,
|
||||
mediaType: post.mediaType,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
window: { from, to },
|
||||
found: candidates.length + existingShortcodes.length + feedDuplicates,
|
||||
existingCount: existingShortcodes.length,
|
||||
existingShortcodes,
|
||||
feedDuplicates,
|
||||
malformed,
|
||||
outsideWindow,
|
||||
candidates,
|
||||
}
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import { z } from 'zod'
|
||||
|
||||
import { formatBahiaCivilDate } from '@/lib/campaignTime'
|
||||
import {
|
||||
CONTENT_PIECE_DESCRIPTION_MAX_LENGTH,
|
||||
CONTENT_PIECE_INSTITUTION_MAX_LENGTH,
|
||||
|
|
@ -10,6 +11,7 @@ import {
|
|||
CONTENT_PIECE_TITLE_MAX_LENGTH,
|
||||
CONTENT_PIECE_TYPES,
|
||||
} from '@/lib/contentPiece'
|
||||
import { contentPieceProfilePeriodError } from '@/lib/contentPieceProfileWindow'
|
||||
import { trimmedNullableText } from '@/lib/schemas/primitives'
|
||||
import { TRANSCRIPT_TEXT_MAX_LENGTH } from '@/lib/speechSearch'
|
||||
|
||||
|
|
@ -82,11 +84,36 @@ export const contentPieceLinkRequestSchema = z.object({
|
|||
})
|
||||
|
||||
/**
|
||||
* C230 — list the novelties of the official profile: the request carries no
|
||||
* input (the window is the server's decision), so the schema only keeps the
|
||||
* envelope honest.
|
||||
* C235 — the window of the profile import: the default recency slice (`{}` or
|
||||
* `recent`, the C230 contract) or an explicit civil period (`since` required,
|
||||
* `until` optional). The period is validated against the Bahia civil day —
|
||||
* real date, order, not in the future — so the wire never carries an
|
||||
* impossible window.
|
||||
*/
|
||||
export const contentPieceProfileImportRequestSchema = z.object({})
|
||||
const contentPieceProfileImportWindowSchema = z.discriminatedUnion('mode', [
|
||||
z.object({ mode: z.literal('recent') }),
|
||||
z.object({
|
||||
mode: z.literal('period'),
|
||||
since: z.string().trim(),
|
||||
until: z.string().trim().nullish(),
|
||||
}),
|
||||
])
|
||||
|
||||
export const contentPieceProfileImportRequestSchema = z.preprocess(
|
||||
(value) =>
|
||||
value && typeof value === 'object' && Object.keys(value).length === 0
|
||||
? { mode: 'recent' }
|
||||
: value,
|
||||
contentPieceProfileImportWindowSchema.superRefine((window, context) => {
|
||||
if (window.mode !== 'period') return
|
||||
const message = contentPieceProfilePeriodError({
|
||||
since: window.since,
|
||||
until: window.until ?? null,
|
||||
today: formatBahiaCivilDate(new Date()),
|
||||
})
|
||||
if (message) context.addIssue({ code: 'custom', message })
|
||||
}),
|
||||
)
|
||||
|
||||
/** The editable catalogue of one piece (the ficha form). */
|
||||
export const contentPieceUpdateRequestSchema = z.object({
|
||||
|
|
|
|||
|
|
@ -84,8 +84,11 @@ const matchesInstagramShortcode =
|
|||
/**
|
||||
* C230 — the one identity probe of the vertical: a post is already catalogued
|
||||
* when ANY canonical spelling of its shortcode is a `sourceUrl`. The paste
|
||||
* path (C220) and the profile importer (C230) share it, so pasting `/p/ABC/`
|
||||
* answers "já está na Central" for a piece that entered as `/reel/ABC/`.
|
||||
* path (C220), the profile importer (C230) and the ops import CLI share it, so
|
||||
* pasting `/p/ABC/` answers "já está na Central" for a piece that entered as
|
||||
* `/reel/ABC/`. `actor: null` is the ops/system mode: the probe runs with the
|
||||
* intentional admin bypass (the pipeline owns those rows), never for a request
|
||||
* path.
|
||||
*/
|
||||
export const contentPieceExistsForPostIdentity = async ({
|
||||
payload,
|
||||
|
|
@ -93,7 +96,7 @@ export const contentPieceExistsForPostIdentity = async ({
|
|||
link,
|
||||
}: {
|
||||
payload: Payload
|
||||
actor: CampaignUser
|
||||
actor: CampaignUser | null
|
||||
link: ContentPieceLink
|
||||
}): Promise<boolean> => {
|
||||
const found = await payload.find({
|
||||
|
|
@ -102,8 +105,9 @@ export const contentPieceExistsForPostIdentity = async ({
|
|||
depth: 0,
|
||||
limit: 1,
|
||||
pagination: false,
|
||||
user: actor,
|
||||
overrideAccess: false,
|
||||
// Intentional admin bypass only for the ops/system mode (`actor: null`);
|
||||
// every request path passes the acting campaign user.
|
||||
...(actor ? { user: actor, overrideAccess: false } : { overrideAccess: true }),
|
||||
})
|
||||
return found.docs.length > 0
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,14 +2,20 @@ import 'server-only'
|
|||
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { formatBahiaCivilDate } from '@/lib/campaignTime'
|
||||
import {
|
||||
contentPieceLinkTitle,
|
||||
contentPiecePostIdentityUrls,
|
||||
contentPieceProfileCandidateFromPost,
|
||||
parseContentPieceLink,
|
||||
type ContentPieceLink,
|
||||
type ContentPieceProfileCandidate,
|
||||
} from '@/lib/contentPiece'
|
||||
import {
|
||||
contentPieceProfileFeedIdentityUrls,
|
||||
contentPieceProfilePeriodBounds,
|
||||
contentPieceProfilePeriodError,
|
||||
contentPieceProfileWindowStartReached,
|
||||
planContentPieceProfileWindow,
|
||||
type ContentPieceProfileWindow,
|
||||
} from '@/lib/contentPieceProfileWindow'
|
||||
import {
|
||||
CONTENT_PIECE_LINK_INVALID_MESSAGE,
|
||||
CONTENT_PIECE_PROFILE_IMPORT_FEED_ERROR_MESSAGE,
|
||||
|
|
@ -39,9 +45,26 @@ import {
|
|||
/** The recency window of one import (12 media ≈ the profile's last days). */
|
||||
export const CONTENT_PIECE_PROFILE_IMPORT_INSTAGRAM_WINDOW = 12
|
||||
|
||||
/**
|
||||
* C235 — the scan ceiling of one period import: the official edge itself only
|
||||
* answers the 10K most recently created media, so this is the real limit of
|
||||
* the walk, not a product cap.
|
||||
*/
|
||||
export const CONTENT_PIECE_PROFILE_IMPORT_SCAN_LIMIT = 10_000
|
||||
|
||||
/** A hung Graph API must not hold the confirm dialog until the job reaper. */
|
||||
const CONTENT_PIECE_PROFILE_IMPORT_FEED_TIMEOUT_MS = 30_000
|
||||
|
||||
/** A period walk can cost many pages; the honest ceiling is still the edge. */
|
||||
const CONTENT_PIECE_PROFILE_IMPORT_PERIOD_FEED_TIMEOUT_MS = 120_000
|
||||
|
||||
/**
|
||||
* The catalogue identity lookup asks `sourceUrl in (...)`; a 10K-media window
|
||||
* spells up to 30K URLs, so the probe runs in bounded chunks instead of one
|
||||
* oversized statement.
|
||||
*/
|
||||
const CONTENT_PIECE_PROFILE_IMPORT_IDENTITY_LOOKUP_CHUNK = 2_000
|
||||
|
||||
type FeedLoader = typeof loadInstagramFeed
|
||||
type FetchLike = (input: string, requestInit?: RequestInit) => Promise<Response>
|
||||
|
||||
|
|
@ -52,10 +75,22 @@ export type ContentPieceProfileImportListing = {
|
|||
existingCount: number
|
||||
/** The novelties, in feed order (newest first). */
|
||||
candidates: ContentPieceProfileCandidate[]
|
||||
/**
|
||||
* True when the official API did not reach the start of the requested window
|
||||
* (edge limit, page ceiling or end of pagination): the receipt says the
|
||||
* window was not fully covered. Always false for the recency window.
|
||||
*/
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export type ContentPieceProfileImportOutcome = 'created' | 'existing'
|
||||
|
||||
export type ContentPieceProfileImportCreation = {
|
||||
outcome: ContentPieceProfileImportOutcome
|
||||
/** The created row; null when the identity already existed (no new piece). */
|
||||
contentPieceId: number | null
|
||||
}
|
||||
|
||||
const cataloguedSourceUrls = async ({
|
||||
payload,
|
||||
actor,
|
||||
|
|
@ -65,24 +100,31 @@ const cataloguedSourceUrls = async ({
|
|||
actor: CampaignUser
|
||||
identityUrls: readonly string[]
|
||||
}): Promise<Set<string>> => {
|
||||
if (identityUrls.length === 0) return new Set()
|
||||
const unique = [...new Set(identityUrls)]
|
||||
const catalogued = new Set<string>()
|
||||
|
||||
const found = await payload.find({
|
||||
collection: 'contentPiece',
|
||||
where: { sourceUrl: { in: [...new Set(identityUrls)] } },
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: { sourceUrl: true },
|
||||
user: actor,
|
||||
overrideAccess: false,
|
||||
})
|
||||
for (
|
||||
let index = 0;
|
||||
index < unique.length;
|
||||
index += CONTENT_PIECE_PROFILE_IMPORT_IDENTITY_LOOKUP_CHUNK
|
||||
) {
|
||||
const chunk = unique.slice(index, index + CONTENT_PIECE_PROFILE_IMPORT_IDENTITY_LOOKUP_CHUNK)
|
||||
const found = await payload.find({
|
||||
collection: 'contentPiece',
|
||||
where: { sourceUrl: { in: chunk } },
|
||||
depth: 0,
|
||||
limit: 0,
|
||||
pagination: false,
|
||||
select: { sourceUrl: true },
|
||||
user: actor,
|
||||
overrideAccess: false,
|
||||
})
|
||||
for (const doc of found.docs) {
|
||||
if (typeof doc.sourceUrl === 'string' && doc.sourceUrl) catalogued.add(doc.sourceUrl)
|
||||
}
|
||||
}
|
||||
|
||||
return new Set(
|
||||
found.docs
|
||||
.map((doc) => doc.sourceUrl)
|
||||
.filter((sourceUrl): sourceUrl is string => Boolean(sourceUrl)),
|
||||
)
|
||||
return catalogued
|
||||
}
|
||||
|
||||
/** True when the official credential is armed — what arms the import button. */
|
||||
|
|
@ -100,16 +142,28 @@ export const readContentPieceProfileImportAvailability = async (
|
|||
* unconfigured credential never reaches the API, and a feed failure becomes
|
||||
* the honest product message instead of a raw transport error. A refreshed
|
||||
* token is persisted best-effort, exactly like the link path.
|
||||
*
|
||||
* C235 — the recency window keeps the C230 one-page read; a period window
|
||||
* scans cursor pages with a date early-stop (the feed is newest-first, so the
|
||||
* first post older than the requested start ends the walk) up to the edge's
|
||||
* own 10K-media limit, and denounces the bounds actually applied.
|
||||
*/
|
||||
const loadConfiguredInstagramFeed = async ({
|
||||
payload,
|
||||
loadFeed,
|
||||
fetchImpl,
|
||||
window,
|
||||
now,
|
||||
}: {
|
||||
payload: Payload
|
||||
loadFeed: FeedLoader
|
||||
fetchImpl: FetchLike
|
||||
}): Promise<Awaited<ReturnType<FeedLoader>>> => {
|
||||
window: ContentPieceProfileWindow
|
||||
now: Date
|
||||
}): Promise<{
|
||||
feed: Awaited<ReturnType<FeedLoader>>
|
||||
bounds: { fromIso: string; toIso: string | null } | null
|
||||
}> => {
|
||||
// Intentional admin bypass: the global's read access is admin-only, and the
|
||||
// listing is already behind the communication gate; the token stays inside
|
||||
// this call and never reaches the wire or a log.
|
||||
|
|
@ -118,14 +172,35 @@ const loadConfiguredInstagramFeed = async ({
|
|||
throw new Error(CONTENT_PIECE_PROFILE_IMPORT_UNAVAILABLE_MESSAGE)
|
||||
}
|
||||
|
||||
if (window.mode === 'period') {
|
||||
const error = contentPieceProfilePeriodError({
|
||||
since: window.since,
|
||||
until: window.until ?? null,
|
||||
today: formatBahiaCivilDate(now),
|
||||
})
|
||||
if (error) throw new Error(error)
|
||||
}
|
||||
const bounds =
|
||||
window.mode === 'period'
|
||||
? contentPieceProfilePeriodBounds({ since: window.since, until: window.until ?? null })
|
||||
: null
|
||||
const fromMs = bounds ? Date.parse(bounds.fromIso) : null
|
||||
|
||||
let feed: Awaited<ReturnType<FeedLoader>>
|
||||
try {
|
||||
feed = await loadFeed({
|
||||
accessToken: settings.instagramAccessToken as string,
|
||||
userId: settings.instagramUserId as string,
|
||||
maxResults: CONTENT_PIECE_PROFILE_IMPORT_INSTAGRAM_WINDOW,
|
||||
maxResults: bounds
|
||||
? CONTENT_PIECE_PROFILE_IMPORT_SCAN_LIMIT
|
||||
: CONTENT_PIECE_PROFILE_IMPORT_INSTAGRAM_WINDOW,
|
||||
...(fromMs !== null ? { shouldStopAt: (post) => Date.parse(post.timestamp) < fromMs } : {}),
|
||||
fetchImpl,
|
||||
signal: AbortSignal.timeout(CONTENT_PIECE_PROFILE_IMPORT_FEED_TIMEOUT_MS),
|
||||
signal: AbortSignal.timeout(
|
||||
bounds
|
||||
? CONTENT_PIECE_PROFILE_IMPORT_PERIOD_FEED_TIMEOUT_MS
|
||||
: CONTENT_PIECE_PROFILE_IMPORT_FEED_TIMEOUT_MS,
|
||||
),
|
||||
})
|
||||
} catch {
|
||||
// Token expired, API down: the operator reads the retry copy, never a
|
||||
|
|
@ -136,52 +211,64 @@ const loadConfiguredInstagramFeed = async ({
|
|||
if (feed.refreshedAccessToken) {
|
||||
await persistInstagramAccessToken(payload, feed.refreshedAccessToken).catch(() => undefined)
|
||||
}
|
||||
return feed
|
||||
return { feed, bounds }
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the window's novelties, already deduplicated by post identity: `found`
|
||||
* is what the API answered with (parseable), `existingCount` what the Central
|
||||
* already had and `candidates` what the confirmation will create, newest
|
||||
* first.
|
||||
* is what the API answered with inside the window (parseable), `existingCount`
|
||||
* what the Central already had, `candidates` what the confirmation will
|
||||
* create, newest first, and `truncated` when the official API did not reach
|
||||
* the requested start.
|
||||
*
|
||||
* The recency mode is the C230 behavior untouched (12 media, one page); the
|
||||
* period mode is the C235 window — the planner is the same owner for both.
|
||||
*/
|
||||
export const listContentPieceProfileImportCandidates = async ({
|
||||
payload,
|
||||
actor,
|
||||
window = { mode: 'recent' },
|
||||
loadFeed = loadInstagramFeed,
|
||||
fetchImpl = fetch,
|
||||
now = new Date(),
|
||||
}: {
|
||||
payload: Payload
|
||||
actor: CampaignUser
|
||||
window?: ContentPieceProfileWindow
|
||||
loadFeed?: FeedLoader
|
||||
fetchImpl?: FetchLike
|
||||
now?: Date
|
||||
}): Promise<ContentPieceProfileImportListing> => {
|
||||
const feed = await loadConfiguredInstagramFeed({ payload, loadFeed, fetchImpl })
|
||||
|
||||
const parsed: { link: ContentPieceLink; candidate: ContentPieceProfileCandidate }[] = []
|
||||
for (const post of feed.posts) {
|
||||
const candidate = contentPieceProfileCandidateFromPost(post)
|
||||
if (!candidate) continue
|
||||
const link = parseContentPieceLink(candidate.url)
|
||||
if (!link) continue
|
||||
parsed.push({ link, candidate })
|
||||
}
|
||||
const { feed, bounds } = await loadConfiguredInstagramFeed({
|
||||
payload,
|
||||
loadFeed,
|
||||
fetchImpl,
|
||||
window,
|
||||
now,
|
||||
})
|
||||
|
||||
const catalogued = await cataloguedSourceUrls({
|
||||
payload,
|
||||
actor,
|
||||
identityUrls: parsed.flatMap(({ link }) => contentPiecePostIdentityUrls(link)),
|
||||
identityUrls: contentPieceProfileFeedIdentityUrls(feed.posts),
|
||||
})
|
||||
const plan = planContentPieceProfileWindow({
|
||||
posts: feed.posts,
|
||||
existingSourceUrls: [...catalogued],
|
||||
from: bounds?.fromIso ?? null,
|
||||
to: bounds?.toIso ?? null,
|
||||
})
|
||||
const candidates = parsed
|
||||
.filter(({ link }) =>
|
||||
contentPiecePostIdentityUrls(link).every((identityUrl) => !catalogued.has(identityUrl)),
|
||||
)
|
||||
.map(({ candidate }) => candidate)
|
||||
|
||||
return {
|
||||
found: parsed.length,
|
||||
existingCount: parsed.length - candidates.length,
|
||||
candidates,
|
||||
found: plan.found,
|
||||
existingCount: plan.existingCount,
|
||||
candidates: plan.candidates.map(({ url, linkOnlyReason }) => ({ url, linkOnlyReason })),
|
||||
truncated:
|
||||
feed.posts.length > 0 &&
|
||||
!contentPieceProfileWindowStartReached({
|
||||
posts: feed.posts,
|
||||
fromIso: bounds?.fromIso ?? null,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -191,6 +278,10 @@ export const listContentPieceProfileImportCandidates = async ({
|
|||
* peça-link reason), transcribes and catalogues — the importer never
|
||||
* downloads anything itself. `existing` covers the race with another actor
|
||||
* (the identity probe lost) and the unique index is the last barrier.
|
||||
*
|
||||
* `actor: null` is the ops/system mode used by the content import CLI: the
|
||||
* same shape and probe, with the intentional admin bypass of the pipeline
|
||||
* (the caller runs the job inline instead of scheduling it after a response).
|
||||
*/
|
||||
export const createContentPieceFromProfilePost = async ({
|
||||
payload,
|
||||
|
|
@ -199,16 +290,18 @@ export const createContentPieceFromProfilePost = async ({
|
|||
startJob = startContentPieceJobInBackground,
|
||||
}: {
|
||||
payload: Payload
|
||||
actor: CampaignUser
|
||||
actor: CampaignUser | null
|
||||
url: string
|
||||
startJob?: (contentPieceId: number) => void
|
||||
}): Promise<ContentPieceProfileImportOutcome> => {
|
||||
}): Promise<ContentPieceProfileImportCreation> => {
|
||||
const link = parseContentPieceLink(url)
|
||||
if (!link || link.origin !== 'instagram') {
|
||||
throw new Error(CONTENT_PIECE_LINK_INVALID_MESSAGE)
|
||||
}
|
||||
|
||||
if (await contentPieceExistsForPostIdentity({ payload, actor, link })) return 'existing'
|
||||
if (await contentPieceExistsForPostIdentity({ payload, actor, link })) {
|
||||
return { outcome: 'existing', contentPieceId: null }
|
||||
}
|
||||
|
||||
try {
|
||||
const piece = await payload.create({
|
||||
|
|
@ -223,15 +316,18 @@ export const createContentPieceFromProfilePost = async ({
|
|||
step: 'extraindo',
|
||||
},
|
||||
depth: 0,
|
||||
user: actor,
|
||||
overrideAccess: false,
|
||||
// Intentional admin bypass only for the ops/system mode (`actor: null`);
|
||||
// every request path passes the acting campaign user.
|
||||
...(actor ? { user: actor, overrideAccess: false } : { overrideAccess: true }),
|
||||
})
|
||||
startJob(piece.id)
|
||||
return 'created'
|
||||
return { outcome: 'created', contentPieceId: piece.id }
|
||||
} catch (error) {
|
||||
// A concurrent import can still hit the unique index; it is the same
|
||||
// duplicate the identity probe answers.
|
||||
if (isContentPieceSourceUrlDuplicateError(error)) return 'existing'
|
||||
if (isContentPieceSourceUrlDuplicateError(error)) {
|
||||
return { outcome: 'existing', contentPieceId: null }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,7 +2,12 @@ import 'server-only'
|
|||
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { ARCHIVE_PHOTO_SLUG, archivePhotoAlt, type ArchivePhotoImport } from '@/lib/archivePhoto'
|
||||
import {
|
||||
ARCHIVE_PHOTO_SLUG,
|
||||
archivePhotoAlt,
|
||||
type ArchivePhotoExifEntry,
|
||||
type ArchivePhotoImport,
|
||||
} from '@/lib/archivePhoto'
|
||||
import type { ArchivePhoto } from '@/payload-types'
|
||||
import { withPayloadTransaction } from '@/utilities/payloadTransaction'
|
||||
|
||||
|
|
@ -142,3 +147,38 @@ export const ingestArchivePhoto = async (
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type ArchivePhotoExifUpdateResult =
|
||||
| { status: 'updated'; flickrId: string; id: number; entries: number }
|
||||
| { status: 'failed'; flickrId: string; error: string }
|
||||
|
||||
/**
|
||||
* C231 — rewrites ONLY the stored `exif` of one existing row: the
|
||||
* `--refresh-metadata` backfill for rows ingested before the mapper understood
|
||||
* the API's `{ _content }` leaves. The Flickr answer is the source of truth (an
|
||||
* empty answer clears the field), the deterministic order of
|
||||
* `archivePhotoExifEntries` makes an unchanged row comparable by the caller,
|
||||
* and every failure is returned, never thrown — the caller owns the receipt.
|
||||
* Same documented CLI bypass as the ingestion (trusted actor, no session).
|
||||
*/
|
||||
export const updateArchivePhotoExif = async (
|
||||
payload: Payload,
|
||||
{ id, flickrId, exif }: { id: number; flickrId: string; exif: ArchivePhotoExifEntry[] },
|
||||
): Promise<ArchivePhotoExifUpdateResult> => {
|
||||
try {
|
||||
await payload.update({
|
||||
collection: ARCHIVE_PHOTO_SLUG,
|
||||
id,
|
||||
data: { exif },
|
||||
// Intentional bypass: the maintenance CLI is a trusted actor with no session.
|
||||
overrideAccess: true,
|
||||
})
|
||||
return { status: 'updated', flickrId, id, entries: exif.length }
|
||||
} catch (error) {
|
||||
return {
|
||||
status: 'failed',
|
||||
flickrId,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,6 +14,14 @@ export const REVALIDATE_PRIVACY_POLICY_CACHE_TAG = getGlobalCacheTag('privacy-po
|
|||
*/
|
||||
const REVALIDATE_ARCHIVE_PHOTOS_TAG = getCollectionListingTag('archivePhoto')
|
||||
|
||||
/**
|
||||
* C230-followup — the Central de Conteúdos listing tag: the Instagram import
|
||||
* CLI writes straight to the DB (outside any request, so the collection hook's
|
||||
* `revalidateTag` is a no-op in that process) and busts it through this
|
||||
* endpoint after publishing. Derived from the same owner as the hook.
|
||||
*/
|
||||
export const REVALIDATE_CONTENT_PIECES_TAG = getCollectionListingTag('contentPiece')
|
||||
|
||||
/**
|
||||
* Cache tag of the campaign home content board's external feeds (`unstable_cache`
|
||||
* entry of `getYouTubeFeed`). The `SocialFeedSettings` global's `afterChange`
|
||||
|
|
@ -28,6 +36,7 @@ const ALLOWED_REVALIDATE_TAGS = [
|
|||
MUNICIPALITY_CATALOG_CACHE_TAG,
|
||||
REVALIDATE_SOCIAL_FEED_TAG,
|
||||
REVALIDATE_ARCHIVE_PHOTOS_TAG,
|
||||
REVALIDATE_CONTENT_PIECES_TAG,
|
||||
] as const
|
||||
|
||||
type AllowedRevalidateTag = (typeof ALLOWED_REVALIDATE_TAGS)[number]
|
||||
|
|
|
|||
|
|
@ -148,10 +148,12 @@ export const pickInstagramThumbnail = (item: {
|
|||
}
|
||||
|
||||
/**
|
||||
* Hard ceiling of pages one feed load may walk (defensive): the Graph API
|
||||
* returns `limit` items per page, so a 500-media window needs 10 — 20 covers
|
||||
* it with room, and a pathological API that always answers a cursor cannot
|
||||
* loop forever.
|
||||
* Default hard ceiling of pages one feed load may walk (defensive): the Graph
|
||||
* API returns `limit` items per page, so a 500-media window needs 10 — 20
|
||||
* covers it with room, and a pathological API that always answers a cursor
|
||||
* cannot loop forever. A caller asking for a deeper window (the C235 10K
|
||||
* period import) raises the ceiling implicitly through `maxResults`; the
|
||||
* default floor keeps the small windows exactly as before.
|
||||
*/
|
||||
const INSTAGRAM_MAX_MEDIA_PAGES = 20
|
||||
|
||||
|
|
@ -270,8 +272,14 @@ export const loadInstagramFeed = async ({
|
|||
|
||||
const pageSize = Math.min(Math.max(maxResults, 1), INSTAGRAM_MAX_RESULTS_CAP)
|
||||
const posts: InstagramPost[] = []
|
||||
// The defensive ceiling follows the requested window (never below the
|
||||
// C220/board default) so a 10K-media period walk is not cut at 1000.
|
||||
const pageCeiling = Math.max(
|
||||
INSTAGRAM_MAX_MEDIA_PAGES,
|
||||
Math.ceil(Math.max(maxResults, 1) / INSTAGRAM_MAX_RESULTS_CAP),
|
||||
)
|
||||
let after: string | undefined
|
||||
for (let page = 0; page < INSTAGRAM_MAX_MEDIA_PAGES; page += 1) {
|
||||
for (let page = 0; page < pageCeiling; page += 1) {
|
||||
const mediaParams = new URLSearchParams({
|
||||
fields: MEDIA_FIELDS,
|
||||
limit: String(pageSize),
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
findArchivePhotoByFlickrId,
|
||||
ingestArchivePhoto,
|
||||
listArchivePhotos,
|
||||
updateArchivePhotoExif,
|
||||
} from '@/utilities/flickr/archivePhotoIngest'
|
||||
|
||||
import { ARCHIVE_PHOTO_JPEG_BYTES } from '../helpers/archivePhotoFixture'
|
||||
|
|
@ -156,6 +157,47 @@ describe('ingestArchivePhoto (C231)', () => {
|
|||
expect(await findArchivePhotoByFlickrId(payload, item.flickrId)).toBeNull()
|
||||
})
|
||||
|
||||
it('refreshes only the stored exif of an existing row (C231 backfill)', async () => {
|
||||
const item = record('53123456794', { exif: [] })
|
||||
const created = await ingestArchivePhoto(payload, item, {
|
||||
filePath: await writeOriginal(item.flickrId),
|
||||
})
|
||||
if (created.status !== 'created') throw new Error('archive photo fixture was not created')
|
||||
|
||||
const refreshed = await updateArchivePhotoExif(payload, {
|
||||
id: created.id,
|
||||
flickrId: item.flickrId,
|
||||
exif: [
|
||||
{ tag: 'Make', label: 'Fabricante', value: 'Canon' },
|
||||
{ tag: 'Model', label: 'Modelo', value: 'Canon EOS R6' },
|
||||
],
|
||||
})
|
||||
expect(refreshed).toMatchObject({ status: 'updated', entries: 2 })
|
||||
|
||||
const found = await payload.find({
|
||||
collection: ARCHIVE_PHOTO_SLUG,
|
||||
where: { flickrId: { equals: item.flickrId } },
|
||||
depth: 0,
|
||||
limit: 1,
|
||||
overrideAccess: true,
|
||||
})
|
||||
expect(found.docs[0]?.exif).toEqual([
|
||||
{ tag: 'Make', label: 'Fabricante', value: 'Canon' },
|
||||
{ tag: 'Model', label: 'Modelo', value: 'Canon EOS R6' },
|
||||
])
|
||||
// Only the exif changed: the metadata ingested with the original stays.
|
||||
expect(found.docs[0]?.title).toBe(item.title)
|
||||
|
||||
const failed = await updateArchivePhotoExif(payload, {
|
||||
id: 9_999_999,
|
||||
flickrId: '53123456799',
|
||||
exif: [],
|
||||
})
|
||||
expect(failed).toMatchObject({ status: 'failed', flickrId: '53123456799' })
|
||||
if (failed.status !== 'failed') return
|
||||
expect(failed.error.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('reads only with the communication roles', async () => {
|
||||
const item = record('53123456792')
|
||||
await ingestArchivePhoto(payload, item, { filePath: await writeOriginal(item.flickrId) })
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ import {
|
|||
} from '@/lib/contentPieceFrame'
|
||||
import {
|
||||
CONTENT_PIECE_FORBIDDEN_MESSAGE,
|
||||
CONTENT_PIECE_GENERIC_ERROR_MESSAGE,
|
||||
CONTENT_PIECE_LINK_DUPLICATE_MESSAGE,
|
||||
CONTENT_PIECE_LINK_INVALID_MESSAGE,
|
||||
CONTENT_PIECE_NOT_FOUND_MESSAGE,
|
||||
|
|
@ -90,6 +91,7 @@ import {
|
|||
import { loadContentPieceListPageData } from '@/utilities/content/contentPiecePageData'
|
||||
import {
|
||||
CONTENT_PIECE_PROFILE_IMPORT_INSTAGRAM_WINDOW,
|
||||
CONTENT_PIECE_PROFILE_IMPORT_SCAN_LIMIT,
|
||||
createContentPieceFromProfilePost,
|
||||
listContentPieceProfileImportCandidates,
|
||||
} from '@/utilities/content/contentPieceProfileImport'
|
||||
|
|
@ -106,7 +108,7 @@ import {
|
|||
} from '@/utilities/content/contentPieceUpload'
|
||||
import { getCollectionListingTag } from '@/utilities/documents'
|
||||
import { runFfmpeg } from '@/utilities/media/ffmpeg'
|
||||
import type { InstagramPost } from '@/utilities/socialFeed/instagramFeed'
|
||||
import type { InstagramPost, LoadInstagramFeedArgs } from '@/utilities/socialFeed/instagramFeed'
|
||||
|
||||
import { installCampaignFixtures } from '../helpers/campaignFixtures'
|
||||
|
||||
|
|
@ -1739,13 +1741,14 @@ describe('content pieces (C211)', () => {
|
|||
const marker = Date.now().toString(36)
|
||||
const started: number[] = []
|
||||
|
||||
const outcome = await createContentPieceFromProfilePost({
|
||||
const result = await createContentPieceFromProfilePost({
|
||||
payload,
|
||||
actor: communicator,
|
||||
url: `https://www.instagram.com/reel/CR${marker}/`,
|
||||
startJob: (id) => started.push(id),
|
||||
})
|
||||
expect(outcome).toBe('created')
|
||||
expect(result.outcome).toBe('created')
|
||||
expect(result.contentPieceId).not.toBeNull()
|
||||
|
||||
const rows = await payload.find({
|
||||
collection: 'contentPiece',
|
||||
|
|
@ -1781,10 +1784,51 @@ describe('content pieces (C211)', () => {
|
|||
url: `https://www.instagram.com/p/CR${marker}/`,
|
||||
startJob: (id) => started.push(id),
|
||||
}),
|
||||
).resolves.toBe('existing')
|
||||
).resolves.toEqual({ outcome: 'existing', contentPieceId: null })
|
||||
expect(started).toHaveLength(1)
|
||||
})
|
||||
|
||||
// The ops import CLI creates without an actor (system mode) and needs the
|
||||
// created id to run the job inline: same shape, admin bypass, no stamp.
|
||||
it('creates in system mode without an actor and returns the created id', async () => {
|
||||
await setInstagramSettings(true)
|
||||
const marker = Date.now().toString(36)
|
||||
const started: number[] = []
|
||||
|
||||
const result = await createContentPieceFromProfilePost({
|
||||
payload,
|
||||
actor: null,
|
||||
url: `https://www.instagram.com/reel/SYS${marker}/`,
|
||||
startJob: (id) => started.push(id),
|
||||
})
|
||||
expect(result.outcome).toBe('created')
|
||||
expect(result.contentPieceId).not.toBeNull()
|
||||
|
||||
const row = await payload.findByID({
|
||||
collection: 'contentPiece',
|
||||
id: result.contentPieceId!,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
})
|
||||
createdPieceIds.add(row.id)
|
||||
expect(row).toMatchObject({
|
||||
title: `Instagram · SYS${marker}`,
|
||||
status: 'rascunho',
|
||||
processingStatus: 'processando',
|
||||
})
|
||||
expect(row.createdBy ?? null).toBeNull()
|
||||
expect(started).toEqual([row.id])
|
||||
|
||||
// The system probe shares the identity predicate: no twin on re-run.
|
||||
await expect(
|
||||
createContentPieceFromProfilePost({
|
||||
payload,
|
||||
actor: null,
|
||||
url: `https://www.instagram.com/p/SYS${marker}/`,
|
||||
}),
|
||||
).resolves.toEqual({ outcome: 'existing', contentPieceId: null })
|
||||
})
|
||||
|
||||
it('refuses a non-Instagram URL in the profile creator', async () => {
|
||||
await expect(
|
||||
createContentPieceFromProfilePost({
|
||||
|
|
@ -1886,6 +1930,168 @@ describe('content pieces (C211)', () => {
|
|||
})
|
||||
})
|
||||
|
||||
describe('C235 — import a chosen window', () => {
|
||||
it('scans the period with the date early-stop, the edge ceiling and the window filter', async () => {
|
||||
await setInstagramSettings(true)
|
||||
const marker = Date.now().toString(36)
|
||||
await createPiece({
|
||||
title: 'Peça já catalogada na janela',
|
||||
origin: 'instagram',
|
||||
withMedia: false,
|
||||
sourceUrl: `https://www.instagram.com/p/JA${marker}/`,
|
||||
})
|
||||
|
||||
const received: LoadInstagramFeedArgs[] = []
|
||||
const listing = await listContentPieceProfileImportCandidates({
|
||||
payload,
|
||||
actor: communicator,
|
||||
window: { mode: 'period', since: '2026-08-01', until: '2026-09-20' },
|
||||
now: new Date('2026-09-29T12:00:00.000Z'),
|
||||
loadFeed: async (feedArgs) => {
|
||||
received.push(feedArgs)
|
||||
return {
|
||||
username: 'depjorgesolla',
|
||||
posts: [
|
||||
instagramPost({
|
||||
id: 'dentro',
|
||||
permalink: `https://www.instagram.com/reel/DE${marker}/`,
|
||||
timestamp: '2026-09-15T12:00:00.000Z',
|
||||
}),
|
||||
// The same post the Central already has, served under another kind.
|
||||
instagramPost({
|
||||
id: 'ja',
|
||||
permalink: `https://www.instagram.com/reel/JA${marker}/`,
|
||||
timestamp: '2026-09-10T12:00:00.000Z',
|
||||
}),
|
||||
instagramPost({
|
||||
id: 'depois',
|
||||
permalink: `https://www.instagram.com/reel/DP${marker}/`,
|
||||
timestamp: '2026-09-25T12:00:00.000Z',
|
||||
}),
|
||||
// The early-stop proof: the page walked past the requested start.
|
||||
instagramPost({
|
||||
id: 'antes',
|
||||
permalink: `https://www.instagram.com/reel/AN${marker}/`,
|
||||
timestamp: '2026-07-20T12:00:00.000Z',
|
||||
}),
|
||||
],
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
expect(received).toHaveLength(1)
|
||||
expect(received[0]!.maxResults).toBe(CONTENT_PIECE_PROFILE_IMPORT_SCAN_LIMIT)
|
||||
const shouldStopAt = received[0]!.shouldStopAt!
|
||||
expect(shouldStopAt(instagramPost({ timestamp: '2026-07-31T23:59:59.000Z' }))).toBe(true)
|
||||
expect(shouldStopAt(instagramPost({ timestamp: '2026-08-01T03:00:00.000Z' }))).toBe(false)
|
||||
|
||||
expect(listing.found).toBe(2)
|
||||
expect(listing.existingCount).toBe(1)
|
||||
expect(listing.candidates).toEqual([
|
||||
{ url: `https://www.instagram.com/reel/DE${marker}/`, linkOnlyReason: null },
|
||||
])
|
||||
expect(listing.truncated).toBe(false)
|
||||
})
|
||||
|
||||
it('denounces the window when the official API did not reach its start', async () => {
|
||||
await setInstagramSettings(true)
|
||||
const marker = Date.now().toString(36)
|
||||
|
||||
const listing = await listContentPieceProfileImportCandidates({
|
||||
payload,
|
||||
actor: communicator,
|
||||
window: { mode: 'period', since: '2026-08-01' },
|
||||
now: new Date('2026-09-29T12:00:00.000Z'),
|
||||
loadFeed: async () => ({
|
||||
username: 'depjorgesolla',
|
||||
posts: [
|
||||
instagramPost({
|
||||
permalink: `https://www.instagram.com/reel/DS${marker}/`,
|
||||
timestamp: '2026-09-15T12:00:00.000Z',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
})
|
||||
|
||||
expect(listing.found).toBe(1)
|
||||
expect(listing.truncated).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the recency read as the default: 12 media, no scan bounds, never truncated', async () => {
|
||||
await setInstagramSettings(true)
|
||||
const received: LoadInstagramFeedArgs[] = []
|
||||
|
||||
const listing = await listContentPieceProfileImportCandidates({
|
||||
payload,
|
||||
actor: communicator,
|
||||
loadFeed: async (feedArgs) => {
|
||||
received.push(feedArgs)
|
||||
return { username: null, posts: [] }
|
||||
},
|
||||
})
|
||||
|
||||
expect(received[0]!.maxResults).toBe(CONTENT_PIECE_PROFILE_IMPORT_INSTAGRAM_WINDOW)
|
||||
expect(received[0]!.shouldStopAt).toBeUndefined()
|
||||
expect(listing).toEqual({ found: 0, existingCount: 0, candidates: [], truncated: false })
|
||||
})
|
||||
|
||||
it('refuses an impossible period before touching the feed', async () => {
|
||||
await setInstagramSettings(true)
|
||||
let called = false
|
||||
|
||||
await expect(
|
||||
listContentPieceProfileImportCandidates({
|
||||
payload,
|
||||
actor: communicator,
|
||||
window: { mode: 'period', since: '2026-02-30' },
|
||||
now: new Date('2026-09-29T12:00:00.000Z'),
|
||||
loadFeed: async () => {
|
||||
called = true
|
||||
return { username: null, posts: [] }
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow('Informe uma data inicial válida.')
|
||||
expect(called).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects an invalid period in the listing route without touching the feed', async () => {
|
||||
getCampaignUserMock.mockResolvedValue(communicator)
|
||||
await setInstagramSettings(true)
|
||||
|
||||
const response = await postProfileImport(
|
||||
new Request('http://localhost/campanha/comunicacao/conteudos/importar', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', origin: 'http://localhost' },
|
||||
body: JSON.stringify({
|
||||
mode: 'period',
|
||||
since: '2026-02-30',
|
||||
until: '2026-02-01',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
status: 'error',
|
||||
message: CONTENT_PIECE_GENERIC_ERROR_MESSAGE,
|
||||
})
|
||||
|
||||
// A body that forgot the mode is never silently downgraded to recents.
|
||||
const missingMode = await postProfileImport(
|
||||
new Request('http://localhost/campanha/comunicacao/conteudos/importar', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', origin: 'http://localhost' },
|
||||
body: JSON.stringify({ since: '2026-08-01', until: '2026-08-31' }),
|
||||
}),
|
||||
)
|
||||
expect(missingMode.status).toBe(400)
|
||||
await expect(missingMode.json()).resolves.toEqual({
|
||||
status: 'error',
|
||||
message: CONTENT_PIECE_GENERIC_ERROR_MESSAGE,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('filters and searches the list', async () => {
|
||||
const municipality = await payload.find({
|
||||
collection: 'municipality',
|
||||
|
|
|
|||
|
|
@ -139,6 +139,27 @@ describe('archivePhotoExifEntries (C231)', () => {
|
|||
])
|
||||
expect(archivePhotoExifEntries(null)).toEqual([])
|
||||
})
|
||||
|
||||
it("unwraps the JSON API's { _content } leaves and still accepts plain strings", () => {
|
||||
expect(
|
||||
archivePhotoExifEntries([
|
||||
{ tag: 'Make', label: 'Fabricante', raw: { _content: 'Canon' } },
|
||||
{
|
||||
tag: 'Model',
|
||||
label: 'Modelo',
|
||||
raw: { _content: 'Canon EOS' },
|
||||
clean: { _content: 'Canon EOS R6' },
|
||||
},
|
||||
{ tag: 'Artist', label: 'Autor', raw: { _content: ' ' } },
|
||||
{ tag: 'Unknown', label: 'Desconhecido', raw: { outro: 'x' } },
|
||||
{ tag: 'Software', label: 'Software', clean: 'Tezza' },
|
||||
]),
|
||||
).toEqual([
|
||||
{ tag: 'Make', label: 'Fabricante', value: 'Canon' },
|
||||
{ tag: 'Model', label: 'Modelo', value: 'Canon EOS R6' },
|
||||
{ tag: 'Software', label: 'Software', value: 'Tezza' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('archivePhotoImportFromFlickr (C231)', () => {
|
||||
|
|
|
|||
|
|
@ -8,9 +8,11 @@ import {
|
|||
formatBahiaCivilDate,
|
||||
formatBahiaCivilDateTimeLabel,
|
||||
formatBahiaEventDateLabel,
|
||||
formatCivilDateLabel,
|
||||
hourOptions,
|
||||
minuteOptionsForStep,
|
||||
subtractBahiaCivilDays,
|
||||
subtractBahiaCivilMonths,
|
||||
timeStepMinutes,
|
||||
} from '@/lib/campaignTime'
|
||||
|
||||
|
|
@ -23,6 +25,17 @@ describe('Bahia civil date helpers (B57)', () => {
|
|||
expect(subtractBahiaCivilDays('2026-08-08', 7)).toBe('2026-08-01')
|
||||
})
|
||||
|
||||
it('subtracts whole civil months, clamping the day to the target month', () => {
|
||||
expect(subtractBahiaCivilMonths('2026-08-31', 6)).toBe('2026-02-28')
|
||||
expect(subtractBahiaCivilMonths('2024-08-31', 6)).toBe('2024-02-29')
|
||||
expect(subtractBahiaCivilMonths('2026-03-15', 6)).toBe('2025-09-15')
|
||||
expect(subtractBahiaCivilMonths('2026-01-15', 1)).toBe('2025-12-15')
|
||||
})
|
||||
|
||||
it('formats a Bahia civil date anchor as a pt-BR day label', () => {
|
||||
expect(formatCivilDateLabel('2026-08-01')).toBe('01/08/2026')
|
||||
})
|
||||
|
||||
it('counts calendar days between civil dates', () => {
|
||||
expect(civilDateDaysBetween('2026-08-01', '2026-08-08')).toBe(7)
|
||||
})
|
||||
|
|
|
|||
223
tests/unit/contentPieceProfileWindow.unit.spec.ts
Normal file
223
tests/unit/contentPieceProfileWindow.unit.spec.ts
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
contentPieceProfileFeedIdentityUrls,
|
||||
contentPieceProfilePeriodBounds,
|
||||
contentPieceProfilePeriodError,
|
||||
contentPieceProfileWindowLabel,
|
||||
contentPieceProfileWindowStartReached,
|
||||
planContentPieceProfileWindow,
|
||||
} from '@/lib/contentPieceProfileWindow'
|
||||
|
||||
// C235 — the window owner: the civil-date bounds of the operator's period, the
|
||||
// recency filter over the feed timestamps, the identity dedupe (Central and
|
||||
// feed itself) and the honest coverage check. Pure: no Payload, no network.
|
||||
|
||||
const post = (
|
||||
shortcode: string,
|
||||
{
|
||||
mediaType = 'REEL',
|
||||
mediaUrl = `https://cdn.example/${shortcode}.mp4`,
|
||||
timestamp = '2026-09-20T12:00:00.000Z',
|
||||
permalink,
|
||||
}: {
|
||||
mediaType?: string
|
||||
mediaUrl?: string | null
|
||||
timestamp?: string
|
||||
permalink?: string
|
||||
} = {},
|
||||
) => ({
|
||||
id: shortcode,
|
||||
permalink: permalink ?? `https://www.instagram.com/reel/${shortcode}/`,
|
||||
mediaType,
|
||||
mediaUrl,
|
||||
timestamp,
|
||||
})
|
||||
|
||||
describe('planContentPieceProfileWindow', () => {
|
||||
const from = '2026-08-01T03:00:00.000Z'
|
||||
const to = '2026-09-21T03:00:00.000Z'
|
||||
|
||||
it('keeps the window novelties, newest first, and classifies each link-only kind', () => {
|
||||
const plan = planContentPieceProfileWindow({
|
||||
posts: [
|
||||
post('NOVO'),
|
||||
post('CARROSSEL', { mediaType: 'CAROUSEL_ALBUM', mediaUrl: null }),
|
||||
post('PROTEGIDO', { mediaUrl: null }),
|
||||
],
|
||||
from,
|
||||
to,
|
||||
})
|
||||
|
||||
expect(plan.found).toBe(3)
|
||||
expect(plan.existingCount).toBe(0)
|
||||
expect(plan.outsideWindow).toBe(0)
|
||||
expect(plan.malformed).toBe(0)
|
||||
expect(plan.window).toEqual({ from, to })
|
||||
expect(plan.candidates.map((candidate) => candidate.shortcode)).toEqual([
|
||||
'NOVO',
|
||||
'CARROSSEL',
|
||||
'PROTEGIDO',
|
||||
])
|
||||
expect(plan.candidates.map((candidate) => candidate.linkOnlyReason)).toEqual([
|
||||
null,
|
||||
'carrossel',
|
||||
'indisponivel',
|
||||
])
|
||||
})
|
||||
|
||||
it('drops what falls outside the window, the malformed and the feed twins', () => {
|
||||
const plan = planContentPieceProfileWindow({
|
||||
posts: [
|
||||
post('JA', { permalink: 'https://www.instagram.com/reel/JA/' }),
|
||||
post('ANTES', { timestamp: '2026-07-31T23:59:59.000Z' }),
|
||||
post('DEPOIS', { timestamp: '2026-09-22T00:00:00.000Z' }),
|
||||
post('SEMID', { permalink: 'https://example.com/no-id/' }),
|
||||
post('REPETIDA'),
|
||||
post('REPETIDA', { permalink: 'https://www.instagram.com/p/REPETIDA/' }),
|
||||
],
|
||||
existingSourceUrls: ['https://www.instagram.com/p/JA/'],
|
||||
from,
|
||||
to,
|
||||
})
|
||||
|
||||
expect(plan.found).toBe(3)
|
||||
expect(plan.existingCount).toBe(1)
|
||||
expect(plan.existingShortcodes).toEqual(['JA'])
|
||||
expect(plan.outsideWindow).toBe(2)
|
||||
expect(plan.malformed).toBe(1)
|
||||
expect(plan.feedDuplicates).toBe(1)
|
||||
expect(plan.candidates.map((candidate) => candidate.shortcode)).toEqual(['REPETIDA'])
|
||||
})
|
||||
|
||||
it('treats an unbounded window as the whole feed (the recency mode)', () => {
|
||||
const plan = planContentPieceProfileWindow({
|
||||
posts: [
|
||||
post('ANTIGA', { timestamp: '2020-01-01T00:00:00.000Z' }),
|
||||
post('NOVA', { timestamp: '2026-09-20T12:00:00.000Z' }),
|
||||
],
|
||||
})
|
||||
|
||||
expect(plan.window).toEqual({ from: null, to: null })
|
||||
expect(plan.found).toBe(2)
|
||||
expect(plan.outsideWindow).toBe(0)
|
||||
expect(plan.candidates.map((candidate) => candidate.shortcode)).toEqual(['ANTIGA', 'NOVA'])
|
||||
})
|
||||
|
||||
it('refuses an invalid bound', () => {
|
||||
expect(() => planContentPieceProfileWindow({ posts: [], from: 'ontem' })).toThrow(/janela/)
|
||||
expect(() => planContentPieceProfileWindow({ posts: [], to: 'amanhã' })).toThrow(/janela/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('contentPieceProfilePeriodError', () => {
|
||||
const today = '2026-09-29'
|
||||
|
||||
it('accepts a real, ordered, non-future period', () => {
|
||||
expect(contentPieceProfilePeriodError({ since: '2026-08-01', today })).toBeNull()
|
||||
expect(
|
||||
contentPieceProfilePeriodError({ since: '2026-08-01', until: '2026-08-31', today }),
|
||||
).toBeNull()
|
||||
expect(contentPieceProfilePeriodError({ since: today, today })).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects a malformed or impossible date', () => {
|
||||
expect(contentPieceProfilePeriodError({ since: '01/08/2026', today })).toBe(
|
||||
'Informe uma data inicial válida.',
|
||||
)
|
||||
expect(contentPieceProfilePeriodError({ since: '2026-02-30', today })).toBe(
|
||||
'Informe uma data inicial válida.',
|
||||
)
|
||||
expect(
|
||||
contentPieceProfilePeriodError({ since: '2026-08-01', until: '2026-02-30', today }),
|
||||
).toBe('Informe uma data final válida.')
|
||||
})
|
||||
|
||||
it('rejects an inverted or future period', () => {
|
||||
expect(
|
||||
contentPieceProfilePeriodError({ since: '2026-08-31', until: '2026-08-01', today }),
|
||||
).toBe('A data final não pode ser anterior à data inicial.')
|
||||
expect(contentPieceProfilePeriodError({ since: '2026-10-01', today })).toBe(
|
||||
'A data inicial não pode estar no futuro.',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('contentPieceProfilePeriodBounds', () => {
|
||||
it('resolves the start of the since day and the exclusive end of the until day in Bahia', () => {
|
||||
expect(contentPieceProfilePeriodBounds({ since: '2026-08-01' })).toEqual({
|
||||
fromIso: '2026-08-01T03:00:00.000Z',
|
||||
toIso: null,
|
||||
})
|
||||
expect(contentPieceProfilePeriodBounds({ since: '2026-08-01', until: '2026-08-31' })).toEqual({
|
||||
fromIso: '2026-08-01T03:00:00.000Z',
|
||||
toIso: '2026-09-01T03:00:00.000Z',
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses an impossible date defensively', () => {
|
||||
expect(() => contentPieceProfilePeriodBounds({ since: '2026-13-01' })).toThrow(
|
||||
'Informe uma data inicial válida.',
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('contentPieceProfileWindowStartReached', () => {
|
||||
const fromIso = '2026-08-01T03:00:00.000Z'
|
||||
|
||||
it('is reached when the walk got a post older than the window start', () => {
|
||||
expect(
|
||||
contentPieceProfileWindowStartReached({
|
||||
posts: [post('NOVA'), post('ANTES', { timestamp: '2026-07-31T23:59:59.000Z' })],
|
||||
fromIso,
|
||||
}),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('is not reached when every post is still inside the window', () => {
|
||||
expect(contentPieceProfileWindowStartReached({ posts: [post('NOVA')], fromIso })).toBe(false)
|
||||
expect(contentPieceProfileWindowStartReached({ posts: [], fromIso })).toBe(false)
|
||||
})
|
||||
|
||||
it('is reached when there is no bound to reach', () => {
|
||||
expect(contentPieceProfileWindowStartReached({ posts: [], fromIso: null })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('contentPieceProfileWindowLabel', () => {
|
||||
it('labels the recency and the civil period', () => {
|
||||
expect(contentPieceProfileWindowLabel({ mode: 'recent' })).toBe('Recentes')
|
||||
expect(contentPieceProfileWindowLabel({ mode: 'period', since: '2026-08-01' })).toBe(
|
||||
'01/08/2026 → hoje',
|
||||
)
|
||||
expect(
|
||||
contentPieceProfileWindowLabel({
|
||||
mode: 'period',
|
||||
since: '2026-08-01',
|
||||
until: '2026-08-31',
|
||||
}),
|
||||
).toBe('01/08/2026 → 31/08/2026')
|
||||
})
|
||||
})
|
||||
|
||||
describe('contentPieceProfileFeedIdentityUrls', () => {
|
||||
it('spells every canonical kind of each parseable post once', () => {
|
||||
expect(
|
||||
contentPieceProfileFeedIdentityUrls([
|
||||
post('A'),
|
||||
post('B', { permalink: 'https://www.instagram.com/p/B/' }),
|
||||
post('A', { permalink: 'https://www.instagram.com/p/A/' }),
|
||||
post('X', { permalink: 'https://example.com/x/' }),
|
||||
]),
|
||||
).toEqual([
|
||||
'https://www.instagram.com/p/A/',
|
||||
'https://www.instagram.com/reel/A/',
|
||||
'https://www.instagram.com/tv/A/',
|
||||
'https://www.instagram.com/p/B/',
|
||||
'https://www.instagram.com/reel/B/',
|
||||
'https://www.instagram.com/tv/B/',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
|
@ -74,6 +74,34 @@ describe('flickr:import write guards (C231)', () => {
|
|||
expect(output(result)).toContain('S3_BUCKET')
|
||||
})
|
||||
|
||||
it('refuses --refresh-metadata without the intent flag, before the key check', () => {
|
||||
const result = run(['--refresh-metadata'])
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('FLICKR_IMPORT_CONFIRM=1')
|
||||
expect(output(result)).toContain('--refresh-metadata')
|
||||
expect(output(result)).not.toContain('FLICKR_API_KEY')
|
||||
})
|
||||
|
||||
it('requires the declared TEQO_ENV for --refresh-metadata once the intent flag is set', () => {
|
||||
const result = run(['--refresh-metadata'], { FLICKR_IMPORT_CONFIRM: '1' })
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('TEQO_ENV')
|
||||
})
|
||||
|
||||
it('does not demand S3 for the metadata-only refresh (dies on the missing key instead)', () => {
|
||||
const result = run(['--refresh-metadata'], {
|
||||
FLICKR_IMPORT_CONFIRM: '1',
|
||||
TEQO_ENV: 'production',
|
||||
FLICKR_API_KEY: '',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('FLICKR_API_KEY')
|
||||
expect(output(result)).not.toContain('S3_BUCKET')
|
||||
})
|
||||
|
||||
it('refuses an unknown argument before touching anything', () => {
|
||||
const result = run(['--force'])
|
||||
|
||||
|
|
|
|||
|
|
@ -8,11 +8,13 @@ import {
|
|||
collectArchiveListing,
|
||||
formatArchiveBytes,
|
||||
formatArchiveInventory,
|
||||
formatArchiveRefresh,
|
||||
formatArchiveReport,
|
||||
parseArchiveCliArgs,
|
||||
planArchiveEntries,
|
||||
summarizeArchiveInventory,
|
||||
summarizeArchivePlan,
|
||||
summarizeArchiveRefresh,
|
||||
summarizeArchiveResults,
|
||||
} from '../../scripts/lib/flickrPlan.mjs'
|
||||
|
||||
|
|
@ -209,6 +211,23 @@ describe('summaries (C231)', () => {
|
|||
})
|
||||
})
|
||||
|
||||
it('summarizes the refresh results with the entries written and failures', () => {
|
||||
expect(
|
||||
summarizeArchiveRefresh([
|
||||
{ flickrId: '1', status: 'updated', entries: 42 },
|
||||
{ flickrId: '2', status: 'unchanged', entries: 0 },
|
||||
{ flickrId: '3', status: 'failed', error: 'HTTP 500' },
|
||||
{ flickrId: '4', status: 'updated', entries: 7 },
|
||||
]),
|
||||
).toEqual({
|
||||
updated: 2,
|
||||
unchanged: 1,
|
||||
failed: 1,
|
||||
entries: 49,
|
||||
failures: [{ flickrId: '3', error: 'HTTP 500' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('summarizes the stored inventory per album and per metadata gap', () => {
|
||||
const inventory = summarizeArchiveInventory([
|
||||
{
|
||||
|
|
@ -310,6 +329,25 @@ describe('receipt formatting (C231)', () => {
|
|||
expect(formatArchiveBytes(2 * 1024 * 1024)).toBe('2.0 MiB')
|
||||
})
|
||||
|
||||
it('formats the refresh report with the touched rows and the failures', () => {
|
||||
const lines = formatArchiveRefresh({
|
||||
durationMs: 2500,
|
||||
summary: {
|
||||
updated: 120,
|
||||
unchanged: 10,
|
||||
failed: 1,
|
||||
entries: 4200,
|
||||
failures: [{ flickrId: '9', error: 'HTTP 500' }],
|
||||
},
|
||||
})
|
||||
const text = lines.join('\n')
|
||||
expect(text).toContain('refresh (metadados): atualizadas: 120')
|
||||
expect(text).toContain('inalteradas: 10')
|
||||
expect(text).toContain('entradas EXIF: 4200')
|
||||
expect(text).toContain('tempo: 2.5s')
|
||||
expect(text).toContain('- 9: HTTP 500')
|
||||
})
|
||||
|
||||
it('stamps the report file name', () => {
|
||||
expect(archivePhotoReportStamp('2026-09-26T06:20:39.123Z')).toBe('2026-09-26T06-20-39-123Z')
|
||||
})
|
||||
|
|
@ -320,6 +358,7 @@ describe('parseArchiveCliArgs (C231)', () => {
|
|||
expect(parseArchiveCliArgs([])).toEqual({
|
||||
apply: false,
|
||||
verify: false,
|
||||
refreshMetadata: false,
|
||||
limit: null,
|
||||
page: 1,
|
||||
out: 'data/flickr',
|
||||
|
|
@ -332,11 +371,27 @@ describe('parseArchiveCliArgs (C231)', () => {
|
|||
parseArchiveCliArgs(['--apply', '--limit', '5', '--page', '3', '--out', 'data/fotos']),
|
||||
).toMatchObject({ apply: true, verify: false, limit: 5, page: 3, out: 'data/fotos' })
|
||||
expect(parseArchiveCliArgs(['--verify'])).toMatchObject({ verify: true, apply: false })
|
||||
expect(parseArchiveCliArgs(['--refresh-metadata'])).toMatchObject({
|
||||
refreshMetadata: true,
|
||||
apply: false,
|
||||
verify: false,
|
||||
})
|
||||
expect(parseArchiveCliArgs(['--refresh-metadata', '--limit', '5'])).toMatchObject({
|
||||
refreshMetadata: true,
|
||||
limit: 5,
|
||||
})
|
||||
expect(parseArchiveCliArgs(['--help'])).toMatchObject({ help: true })
|
||||
})
|
||||
|
||||
it('refuses exclusive modes, invalid numbers, escaping --out and unknown flags', () => {
|
||||
expect(() => parseArchiveCliArgs(['--apply', '--verify'])).toThrow(/mutuamente exclusivos/)
|
||||
expect(() => parseArchiveCliArgs(['--apply', '--refresh-metadata'])).toThrow(
|
||||
/mutuamente exclusivos/,
|
||||
)
|
||||
expect(() => parseArchiveCliArgs(['--verify', '--refresh-metadata'])).toThrow(
|
||||
/mutuamente exclusivos/,
|
||||
)
|
||||
expect(() => parseArchiveCliArgs(['--refresh-metadata', '--page', '2'])).toThrow(/--page/)
|
||||
expect(() => parseArchiveCliArgs(['--limit', '0'])).toThrow(/--limit/)
|
||||
expect(() => parseArchiveCliArgs(['--limit', 'abc'])).toThrow(/--limit/)
|
||||
expect(() => parseArchiveCliArgs(['--page', '0'])).toThrow(/--page/)
|
||||
|
|
|
|||
95
tests/unit/instagramContentImportCli.unit.spec.ts
Normal file
95
tests/unit/instagramContentImportCli.unit.spec.ts
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
import { spawnSync } from 'node:child_process'
|
||||
import { join } from 'node:path'
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
// C230-followup — the CLI's fail-closed write guards, exercised as a
|
||||
// subprocess: each refusal must happen before any Payload import, feedback
|
||||
// call, S3 write or DB connection.
|
||||
|
||||
const repoRoot = process.cwd()
|
||||
const scriptPath = join(repoRoot, 'scripts', 'import-instagram-content.mjs')
|
||||
|
||||
const run = (args: string[], env: Record<string, string> = {}) =>
|
||||
spawnSync(process.execPath, [scriptPath, ...args], {
|
||||
cwd: repoRoot,
|
||||
encoding: 'utf8',
|
||||
timeout: 30_000,
|
||||
env: {
|
||||
...process.env,
|
||||
NODE_OPTIONS: '--no-deprecation --import=tsx/esm --import=./scripts/seed-loader.mjs',
|
||||
NODE_ENV: 'production',
|
||||
VITEST: '',
|
||||
DATABASE_URL: 'postgresql://teqo:teqo@127.0.0.1:5432/teqo_1313',
|
||||
PAYLOAD_SECRET: 'test-secret',
|
||||
CONTENT_INSTAGRAM_IMPORT_CONFIRM: '',
|
||||
TEQO_ENV: '',
|
||||
ALLOW_REMOTE_DB: '',
|
||||
S3_BUCKET: '',
|
||||
S3_ENDPOINT: '',
|
||||
S3_ACCESS_KEY_ID: '',
|
||||
S3_SECRET_ACCESS_KEY: '',
|
||||
...env,
|
||||
},
|
||||
})
|
||||
|
||||
const output = (result: ReturnType<typeof run>) => `${result.stdout}${result.stderr}`
|
||||
|
||||
describe('content:instagram:import write guards (C230-followup)', () => {
|
||||
it('prints the help even without a database', () => {
|
||||
const result = run(['--help'], { DATABASE_URL: '' })
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toContain('CONTENT_INSTAGRAM_IMPORT_CONFIRM')
|
||||
expect(result.stdout).toContain('pnpm content:instagram:import')
|
||||
})
|
||||
|
||||
it('refuses --apply on a production target without the intent flag, before any DB import', () => {
|
||||
const result = run(['--apply'])
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('CONTENT_INSTAGRAM_IMPORT_CONFIRM=1')
|
||||
expect(output(result)).not.toContain('| modo:')
|
||||
})
|
||||
|
||||
it('requires the declared TEQO_ENV once the intent flag is set', () => {
|
||||
const result = run(['--apply'], { CONTENT_INSTAGRAM_IMPORT_CONFIRM: '1' })
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('TEQO_ENV')
|
||||
})
|
||||
|
||||
it('refuses a target database that does not match the declared environment', () => {
|
||||
const result = run(['--apply'], {
|
||||
CONTENT_INSTAGRAM_IMPORT_CONFIRM: '1',
|
||||
TEQO_ENV: 'staging',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('≠ "teqo_staging"')
|
||||
})
|
||||
|
||||
it('refuses --apply without the complete S3_* set on a declared production target', () => {
|
||||
const result = run(['--apply'], {
|
||||
CONTENT_INSTAGRAM_IMPORT_CONFIRM: '1',
|
||||
TEQO_ENV: 'production',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('S3_BUCKET')
|
||||
})
|
||||
|
||||
it('refuses --publish without --apply before touching anything', () => {
|
||||
const result = run(['--publish'])
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('--publish exige --apply')
|
||||
})
|
||||
|
||||
it('refuses an unknown argument before touching anything', () => {
|
||||
const result = run(['--force'])
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output(result)).toContain('argumento desconhecido')
|
||||
})
|
||||
})
|
||||
179
tests/unit/instagramContentPlan.unit.spec.ts
Normal file
179
tests/unit/instagramContentPlan.unit.spec.ts
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
contentPieceProfileFeedIdentityUrls,
|
||||
planContentPieceProfileWindow,
|
||||
} from '@/lib/contentPieceProfileWindow'
|
||||
|
||||
import {
|
||||
formatInstagramContentReport,
|
||||
instagramContentFeedIdentityUrls,
|
||||
instagramContentReportStamp,
|
||||
parseInstagramContentCliArgs,
|
||||
planInstagramContentWindow,
|
||||
shouldPublishImportedPiece,
|
||||
summarizeInstagramContentResults,
|
||||
} from '../../scripts/lib/instagramContentPlan.mjs'
|
||||
|
||||
// C230-followup — the import planner contract: the recency window filter, the
|
||||
// identity dedupe (in both directions: the feed against the Central and the
|
||||
// feed against itself), the link-only classification and the honest report.
|
||||
// The feed is always a plain array; no network, no Payload.
|
||||
|
||||
const post = (
|
||||
shortcode: string,
|
||||
{
|
||||
mediaType = 'REEL',
|
||||
mediaUrl = `https://cdn.example/${shortcode}.mp4`,
|
||||
timestamp = '2026-09-20T12:00:00.000Z',
|
||||
permalink,
|
||||
}: {
|
||||
mediaType?: string
|
||||
mediaUrl?: string | null
|
||||
timestamp?: string
|
||||
permalink?: string
|
||||
} = {},
|
||||
) => ({
|
||||
id: shortcode,
|
||||
permalink: permalink ?? `https://www.instagram.com/reel/${shortcode}/`,
|
||||
mediaType,
|
||||
mediaUrl,
|
||||
timestamp,
|
||||
})
|
||||
|
||||
describe('content:instagram:import arguments', () => {
|
||||
it('defaults to the 60-day plan with no writes', () => {
|
||||
expect(parseInstagramContentCliArgs([])).toEqual({
|
||||
apply: false,
|
||||
publish: false,
|
||||
days: 60,
|
||||
limit: null,
|
||||
out: 'data/content-instagram',
|
||||
help: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts the apply/publish pair and the window options', () => {
|
||||
expect(
|
||||
parseInstagramContentCliArgs([
|
||||
'--apply',
|
||||
'--publish',
|
||||
'--days',
|
||||
'45',
|
||||
'--limit',
|
||||
'3',
|
||||
'--out',
|
||||
'data/out',
|
||||
]),
|
||||
).toMatchObject({ apply: true, publish: true, days: 45, limit: 3, out: 'data/out' })
|
||||
})
|
||||
|
||||
it('refuses --publish without --apply', () => {
|
||||
expect(() => parseInstagramContentCliArgs(['--publish'])).toThrow(/exige --apply/)
|
||||
})
|
||||
|
||||
it('refuses an unknown argument', () => {
|
||||
expect(() => parseInstagramContentCliArgs(['--force'])).toThrow(/argumento desconhecido/)
|
||||
})
|
||||
|
||||
it('refuses an out-of-range window, a zero limit and an escaping out dir', () => {
|
||||
expect(() => parseInstagramContentCliArgs(['--days', '0'])).toThrow(/--days/)
|
||||
expect(() => parseInstagramContentCliArgs(['--days', '366'])).toThrow(/--days/)
|
||||
expect(() => parseInstagramContentCliArgs(['--limit', '0'])).toThrow(/--limit/)
|
||||
expect(() => parseInstagramContentCliArgs(['--out', '../etc'])).toThrow(/--out/)
|
||||
})
|
||||
|
||||
it('prints the help before any validation', () => {
|
||||
expect(parseInstagramContentCliArgs(['--help', '--days', '0'])).toMatchObject({ help: true })
|
||||
})
|
||||
})
|
||||
|
||||
describe('planner re-exports (C235)', () => {
|
||||
it('keeps the CLI names bound to the single owner in src/lib', () => {
|
||||
// The window policy is pinned by its owner spec; here only the delegation
|
||||
// contract of the CLI shell matters.
|
||||
expect(planInstagramContentWindow).toBe(planContentPieceProfileWindow)
|
||||
expect(instagramContentFeedIdentityUrls).toBe(contentPieceProfileFeedIdentityUrls)
|
||||
})
|
||||
})
|
||||
|
||||
describe('summaries and receipt', () => {
|
||||
it('publishes only a ready piece when the run asked for it', () => {
|
||||
expect(shouldPublishImportedPiece({ processingStatus: 'pronto', publish: true })).toBe(true)
|
||||
expect(shouldPublishImportedPiece({ processingStatus: 'pronto', publish: false })).toBe(false)
|
||||
expect(shouldPublishImportedPiece({ processingStatus: 'falhou', publish: true })).toBe(false)
|
||||
})
|
||||
|
||||
it('aggregates the run with the provider cost', () => {
|
||||
const summary = summarizeInstagramContentResults(
|
||||
[
|
||||
{
|
||||
outcome: 'created',
|
||||
processingStatus: 'pronto',
|
||||
durationSeconds: 60,
|
||||
published: true,
|
||||
linkFailureReason: null,
|
||||
},
|
||||
{
|
||||
outcome: 'created',
|
||||
processingStatus: 'pronto',
|
||||
durationSeconds: 30,
|
||||
published: true,
|
||||
linkFailureReason: 'carrossel',
|
||||
},
|
||||
{ outcome: 'created', processingStatus: 'falhou', error: 'ffmpeg' },
|
||||
{ outcome: 'existing' },
|
||||
],
|
||||
{ costPerMinuteUsd: 0.00045 },
|
||||
)
|
||||
|
||||
expect(summary).toMatchObject({
|
||||
attempted: 4,
|
||||
created: 3,
|
||||
existing: 1,
|
||||
ready: 2,
|
||||
failed: 1,
|
||||
published: 2,
|
||||
linkOnly: 1,
|
||||
asrSeconds: 90,
|
||||
})
|
||||
expect(summary.asrCostUsd).toBeCloseTo(0.0007, 4)
|
||||
})
|
||||
|
||||
it('reports the window, the plan and the named failures', () => {
|
||||
const plan = planInstagramContentWindow({
|
||||
posts: [post('A'), post('B', { mediaType: 'CAROUSEL_ALBUM', mediaUrl: null })],
|
||||
existingSourceUrls: [],
|
||||
from: '2026-08-01T00:00:00.000Z',
|
||||
to: '2026-09-30T00:00:00.000Z',
|
||||
})
|
||||
const lines = formatInstagramContentReport({
|
||||
target: '127.0.0.1/teqo_1313',
|
||||
mode: 'apply',
|
||||
window: { days: 60, from: '2026-08-01T00:00:00.000Z', to: '2026-09-30T00:00:00.000Z' },
|
||||
feedCount: 2,
|
||||
plan,
|
||||
summary: summarizeInstagramContentResults([
|
||||
{ outcome: 'created', processingStatus: 'falhou', error: 'ffmpeg ausente' },
|
||||
]),
|
||||
failures: [{ shortcode: 'A', error: 'ffmpeg ausente' }],
|
||||
candidatesRemaining: 1,
|
||||
reportPath: 'data/content-instagram/x.json',
|
||||
})
|
||||
|
||||
const text = lines.join('\n')
|
||||
expect(text).toContain('alvo: 127.0.0.1/teqo_1313 | modo: apply')
|
||||
expect(text).toContain('janela: 60 dias')
|
||||
expect(text).toContain('candidatos: 2 (peça-link previstos: 1)')
|
||||
expect(text).toContain('falha A: ffmpeg ausente')
|
||||
expect(text).toContain('peça-link B: carrossel')
|
||||
expect(text).toContain('restam 1 candidatos')
|
||||
expect(text).toContain('recibo: data/content-instagram/x.json')
|
||||
})
|
||||
|
||||
it('stamps the receipt with the run instant', () => {
|
||||
expect(instagramContentReportStamp('2026-09-29T12:34:56.789Z')).toBe('2026-09-29T12-34-56-789Z')
|
||||
})
|
||||
})
|
||||
|
|
@ -339,6 +339,35 @@ describe('loadInstagramFeed', () => {
|
|||
expect(mediaCalls[1]).toContain('limit=3')
|
||||
})
|
||||
|
||||
it('caps the walk at 20 pages by default and follows a deeper window (C235)', async () => {
|
||||
const pages = 22
|
||||
const deepFetch = async (input: string) => {
|
||||
calls.push(input)
|
||||
if (!input.includes('/media')) return fakeResponse({ username: 'depjorgesolla' })
|
||||
const after = /after=page-(\d+)/.exec(input)?.[1]
|
||||
const pageIndex = after ? Number(after) : 0
|
||||
const next = pageIndex + 1
|
||||
return fakeResponse({
|
||||
data: [MEDIA_ITEM(`post${pageIndex}`)],
|
||||
...(next < pages ? { paging: { cursors: { after: `page-${next}` } } } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
calls.length = 0
|
||||
const capped = await loadInstagramFeed({ ...args, maxResults: 100, fetchImpl: deepFetch })
|
||||
expect(capped.posts).toHaveLength(20)
|
||||
|
||||
calls.length = 0
|
||||
// A 1100-media window needs 22 pages of 50 — the ceiling follows it.
|
||||
const raised = await loadInstagramFeed({
|
||||
...args,
|
||||
maxResults: 1_100,
|
||||
fetchImpl: deepFetch,
|
||||
})
|
||||
expect(raised.posts).toHaveLength(pages)
|
||||
expect(calls.filter((call) => call.includes('/media'))).toHaveLength(pages)
|
||||
})
|
||||
|
||||
it('stops at the page that holds the searched post and never asks a deeper cursor', async () => {
|
||||
calls.length = 0
|
||||
const result = await loadInstagramFeed({
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest'
|
|||
import { getGlobalCacheTag } from '@/utilities/globals'
|
||||
import { MUNICIPALITY_CATALOG_CACHE_TAG } from '@/utilities/municipality/municipalityCatalogCache'
|
||||
import {
|
||||
REVALIDATE_CONTENT_PIECES_TAG,
|
||||
REVALIDATE_POSTS_TAG,
|
||||
REVALIDATE_PRIVACY_POLICY_CACHE_TAG,
|
||||
resolveRevalidateTag,
|
||||
|
|
@ -31,6 +32,11 @@ describe('resolveRevalidateTag', () => {
|
|||
ok: true,
|
||||
tag: MUNICIPALITY_CATALOG_CACHE_TAG,
|
||||
})
|
||||
// C230-followup — the import CLI busts the Central's listing through here.
|
||||
expect(resolveRevalidateTag(REVALIDATE_CONTENT_PIECES_TAG, null)).toEqual({
|
||||
ok: true,
|
||||
tag: REVALIDATE_CONTENT_PIECES_TAG,
|
||||
})
|
||||
})
|
||||
|
||||
it('prefers query tag over body tag', () => {
|
||||
|
|
|
|||
Loading…
Reference in a new issue