768628d914
7-фичный auto-mode пакет согласно «карте что осталось» (после v1.54).
(1) Bulk-actions DealsView:
- dealsState reactive-копия MOCK_DEALS (deep-clone) для безопасного bulk-edit.
- Bulk-bar (sticky, теало-нуар, theme=dark) при selected.length > 0:
count + Сменить статус (v-menu × 14 lead_statuses) + Экспорт (snackbar) +
Удалить (v-dialog confirm) + ✕ clear.
- На production: smart status-transition с проверкой allowed-переходов;
soft-delete (архив 30 дней); реальный CSV/XLSX export через xlsx-lib.
(2) NewDealDialog (used in DealsView+KanbanView):
- 6 полей: name/phone/project (MOCK_PROJECTS) / manager (MOCK_MANAGERS) /
cost / status (default 'new' или presetStatus). Phone-валидация ≥10 цифр.
- emit('created', deal) → DealsView push в начало dealsState; KanbanView push
в правильную колонку по statusSlug + totalDeals++.
(3) AdminTenantDetailView (/admin/tenants/:code):
- 4 KPI cards (Баланс/runway / Тариф+MRR/мес / Лиды сегодня+неделя+месяц /
Средняя цена). 4 v-tabs: Финансы (balance-history) / Пользователи /
Проекты / Активность с event-кодами.
- Кнопка «Войти как клиент» (использует ImpersonationDialog из v1.54).
404-fallback. composables/mockTenantDetail.ts с expandTenantDetail.
- AdminTenantsView получил @click:row → router.push.
(4) Edit-flow AdminSystemView (audit-log + 2-step):
- Backend: SystemSetting + SaasAdminAuditLog Eloquent (append-only,
payload_before/after JSONB casts).
- AdminSystemSettingsController с GET (list) + PUT (update в DB::transaction
+ INSERT в saas_admin_audit_log; hash-chain trigger BEFORE INSERT
заполняет log_hash).
- Type-validation: int/decimal/bool/json. Reason ≥30 chars. No-op → 422.
- Frontend SystemSettingEditDialog — 3-step (edit → confirm с diff
before/after → done).
(5) Webhook receive endpoint (POST /api/webhook/{token}):
- WebhookReceiveController::receive. Token = tenants.webhook_token.
- 404 unknown / 422 bad payload / 202 success + dispatch ProcessWebhookJob.
- Stub-INSERT в webhook_log через DB::table обёрнут в DB::transaction +
SET LOCAL app.current_tenant_id для RLS.
- CSRF-исключение для api/webhook/* в bootstrap/app.php.
- На prod: + HMAC X-Webhook-Signature + per-token rate-limit.
(6) Smart-filters:
- DealsView: multi-select v-select Проект+Менеджер с auto availableProjects/
availableManagers computed.
- AdminTenantsView: filterStatuses (4 STATUS_OPTIONS) + filterTariffs
(computed availableTariffs).
- Кнопка «Сбросить» появляется только когда фильтры активны.
(7) AdminImpersonationView (/admin/impersonation):
- Backend +2 GET endpoints: /active (used_at != null AND session_ended_at
== null) + /recent (last 20 завершённых с duration_seconds через
abs(diffInSeconds) — Carbon signed по умолчанию).
- ImpersonationToken получил belongsTo(Tenant).
- Frontend view: 2 секции (Активные с end-кнопкой / Недавно завершённые
read-only) + refresh + onMounted load.
- Маршрут /admin/impersonation + 5-й nav-пункт «Impersonation» в AdminLayout.
Vitest +48 (всего 238/238 за 15.31 сек).
Pest +16 (всего 136/136 за 15.8 сек, 495 assertions).
PHPStan baseline регенерирован (0 errors после фикса nullsafe.neverNull).
Регресс: lint+type-check+format ✅; vite build 937 ms; Pint+PHPStan passed;
Pest 136/136. Реестр v1.54→v1.55, CLAUDE.md v1.45→v1.46.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
134 lines
5.4 KiB
TypeScript
134 lines
5.4 KiB
TypeScript
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
|
import { mount, flushPromises } from '@vue/test-utils';
|
|
import { createVuetify } from 'vuetify';
|
|
import { createRouter, createMemoryHistory } from 'vue-router';
|
|
|
|
vi.mock('../../resources/js/api/admin', () => ({
|
|
impersonationActive: vi.fn(),
|
|
impersonationRecent: vi.fn(),
|
|
impersonationEnd: vi.fn(),
|
|
}));
|
|
vi.mock('../../resources/js/api/client', () => ({
|
|
extractErrorMessage: vi.fn((_e, fb?: string) => fb ?? 'err'),
|
|
apiClient: {},
|
|
ensureCsrfCookie: vi.fn(),
|
|
}));
|
|
|
|
import * as adminApi from '../../resources/js/api/admin';
|
|
import AdminImpersonationView from '../../resources/js/views/admin/AdminImpersonationView.vue';
|
|
|
|
const mountView = async () => {
|
|
const router = createRouter({
|
|
history: createMemoryHistory(),
|
|
routes: [{ path: '/admin/impersonation', component: AdminImpersonationView }],
|
|
});
|
|
await router.push('/admin/impersonation');
|
|
await router.isReady();
|
|
const wrapper = mount(AdminImpersonationView, {
|
|
global: { plugins: [createVuetify(), router] },
|
|
});
|
|
await flushPromises();
|
|
return wrapper;
|
|
};
|
|
|
|
describe('AdminImpersonationView.vue', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
vi.mocked(adminApi.impersonationActive).mockResolvedValue([]);
|
|
vi.mocked(adminApi.impersonationRecent).mockResolvedValue([]);
|
|
});
|
|
|
|
it('загружает active + recent на mount', async () => {
|
|
await mountView();
|
|
expect(adminApi.impersonationActive).toHaveBeenCalledTimes(1);
|
|
expect(adminApi.impersonationRecent).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('показывает empty-state когда обе secции пустые', async () => {
|
|
const wrapper = await mountView();
|
|
expect(wrapper.find('[data-testid="active-empty"]').exists()).toBe(true);
|
|
expect(wrapper.find('[data-testid="recent-empty"]').exists()).toBe(true);
|
|
});
|
|
|
|
it('рендерит active-row для каждой активной сессии', async () => {
|
|
vi.mocked(adminApi.impersonationActive).mockResolvedValue([
|
|
{
|
|
token_id: 42,
|
|
tenant_id: 1,
|
|
tenant_name: 'Окна Москва ООО',
|
|
requested_by: 1,
|
|
reason: 'Тикет SUP-12345 — клиент сообщил…',
|
|
sent_to_email: 'admin@okna.ru',
|
|
used_at: '2026-05-09T11:00:00',
|
|
expires_at: '2026-05-09T11:15:00',
|
|
},
|
|
]);
|
|
const wrapper = await mountView();
|
|
const rows = wrapper.findAll('[data-testid="active-row"]');
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0].text()).toContain('Окна Москва ООО');
|
|
expect(rows[0].text()).toContain('Тикет SUP-12345');
|
|
expect(wrapper.find('[data-testid="end-btn-42"]').exists()).toBe(true);
|
|
});
|
|
|
|
it('click на «Завершить» вызывает API + перезагружает оба списка', async () => {
|
|
vi.mocked(adminApi.impersonationActive).mockResolvedValue([
|
|
{
|
|
token_id: 42,
|
|
tenant_id: 1,
|
|
tenant_name: 'Окна Москва ООО',
|
|
requested_by: 1,
|
|
reason: 'reason ' + 'x'.repeat(30),
|
|
sent_to_email: 'a@b.ru',
|
|
used_at: '2026-05-09T11:00:00',
|
|
expires_at: '2026-05-09T11:15:00',
|
|
},
|
|
]);
|
|
vi.mocked(adminApi.impersonationEnd).mockResolvedValue({
|
|
token_id: 42,
|
|
session_ended_at: '2026-05-09T11:30:00',
|
|
message: 'OK',
|
|
});
|
|
const wrapper = await mountView();
|
|
|
|
// Сбрасываем счётчики после initial mount-loadOnMount
|
|
vi.mocked(adminApi.impersonationActive).mockClear();
|
|
vi.mocked(adminApi.impersonationRecent).mockClear();
|
|
|
|
await wrapper.find('[data-testid="end-btn-42"]').trigger('click');
|
|
await flushPromises();
|
|
|
|
expect(adminApi.impersonationEnd).toHaveBeenCalledWith(42);
|
|
// Обе функции перезагружаются после end
|
|
expect(adminApi.impersonationActive).toHaveBeenCalledTimes(1);
|
|
expect(adminApi.impersonationRecent).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('показывает error-alert если loadActive падает', async () => {
|
|
vi.mocked(adminApi.impersonationActive).mockRejectedValueOnce(new Error('Network down'));
|
|
const wrapper = await mountView();
|
|
expect(wrapper.find('[data-testid="error-alert"]').exists()).toBe(true);
|
|
});
|
|
|
|
it('рендерит recent-row с длительностью', async () => {
|
|
vi.mocked(adminApi.impersonationRecent).mockResolvedValue([
|
|
{
|
|
token_id: 100,
|
|
tenant_id: 5,
|
|
tenant_name: 'Двери Премиум',
|
|
requested_by: 1,
|
|
reason: 'historical reason ' + 'y'.repeat(30),
|
|
used_at: '2026-05-08T10:00:00',
|
|
session_ended_at: '2026-05-08T10:45:00',
|
|
duration_seconds: 2700,
|
|
},
|
|
]);
|
|
const wrapper = await mountView();
|
|
const rows = wrapper.findAll('[data-testid="recent-row"]');
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0].text()).toContain('Двери Премиум');
|
|
// 2700 сек = 45 мин 0 сек
|
|
expect(rows[0].text()).toContain('45 мин');
|
|
});
|
|
});
|