import{d as e,f as t,h as n,i as r,l as i,r as a,s as o,t as s,u as c}from"./useToast-CS8pZhce.js";import{t as l}from"./DynamicFormRenderer-0ioSXYKX.js";import{t as u}from"./building-BdUpGLM5.js";import{t as d}from"./file-text-DR21jZDS.js";import{$ as f,H as p,K as ee,L as te,Q as ne,S as re,T as m,U as ie,W as ae,_ as h,at as g,b as _,it as v,lt as y,m as b,n as oe,nt as x,pt as S,r as C,rt as w,t as T}from"./index-CrJKtV0u.js";import{t as E}from"./useOrders-TRZWcao8.js";import{t as D}from"./currency-DdDs82F5.js";var O={name:`cloud-upload`,size:24,node:[[`path`,{d:`M12 13v8`,key:`1l5pq0`}],[`path`,{d:`M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242`,key:`1pljnt`}],[`path`,{d:`m8 17 4-4 4 4`,key:`1quai1`}]],aliases:[`upload-cloud`]};O.node;var se=i(O),k=n(t(),1);function A(){let[e,t]=(0,k.useState)([]),[n,r]=(0,k.useState)([]),[i,a]=(0,k.useState)([]),[o,s]=(0,k.useState)([]),[c,l]=(0,k.useState)(!0),[u,d]=(0,k.useState)(null),f=(0,k.useCallback)(async()=>{try{l(!0),d(null);let[e,n,i,o]=await Promise.all([g.contacts.list({pageSize:100}),g.companies.list({pageSize:100}),g.leads.list({pageSize:100}),g.deals.list({pageSize:100})]);t(e.items),r(n.items),a(i.items),s(o.items)}catch(e){d(e instanceof Error?e:Error(String(e)))}finally{l(!1)}},[]);return(0,k.useEffect)(()=>{let e=!0;return Promise.resolve().then(()=>{e&&f()}),()=>{e=!1}},[f]),w(`records:changed`,e=>{(e.entityType===`contact`||e.entityType===`company`||e.entityType===`lead`||e.entityType===`deal`)&&f()}),w(`storage:reset`,f),w(`snapshot:imported`,f),{contacts:e,companies:n,leads:i,deals:o,loading:c,error:u,refetch:f,createContact:(0,k.useCallback)(async e=>g.contacts.create(e),[]),updateContact:(0,k.useCallback)(async(e,t)=>g.contacts.update(e,t),[]),deleteContact:(0,k.useCallback)(async e=>g.contacts.delete(e),[]),createCompany:(0,k.useCallback)(async e=>g.companies.create(e),[]),updateCompany:(0,k.useCallback)(async(e,t)=>g.companies.update(e,t),[]),deleteCompany:(0,k.useCallback)(async e=>g.companies.delete(e),[]),createDeal:(0,k.useCallback)(async e=>g.deals.create(e),[]),updateDeal:(0,k.useCallback)(async(e,t)=>g.deals.update(e,t),[]),deleteDeal:(0,k.useCallback)(async e=>g.deals.delete(e),[]),createLead:(0,k.useCallback)(async e=>g.leads.create(e),[]),updateLead:(0,k.useCallback)(async(e,t)=>g.leads.update(e,t),[]),deleteLead:(0,k.useCallback)(async e=>g.leads.delete(e),[]),convertLead:(0,k.useCallback)(async(e,t)=>g.convertLeadToDeal(e,t),[]),getTimeline:(0,k.useCallback)(async(e,t)=>g.getTimeline(e,t),[]),createActivity:(0,k.useCallback)(async e=>g.activities.create(e),[]),createNote:(0,k.useCallback)(async e=>g.notes.create(e),[])}}var j=o(),ce=`Имя,Фамилия,Телефон,Email,Компания,Должность Владимир,Ковалев,+7 (916) 123-45-67,kovalev@partner.ru,ООО «СеверТорг»,Коммерческий директор Елена,Васильева,+7 (903) 987-65-43,elena.v@iceberg.ru,ГК «Айсберг Логистик»,Руководитель закупок Дмитрий,Смирнов,,dmitry@corp.ru,,Менеджер Иван,,+7 (999) 888-77-66,invalid-email-address,ИП «Михайлов»,Инженер Анна,Кузнецова,+7 (926) 111-22-33,anna.k@beautyshop.ru,ООО «Бьюти Групп»,Директор по маркетингу`,M=`Артикул,Наименование,Категория,Цена (коп),Единица COF-ETH-01,Кофе зерновой Эфиопия Иргачефф 1кг,Кофе,185000,уп COF-BRZ-02,Кофе зерновой Бразилия Сантос 1кг,Кофе,145000,уп SYR-VAN-01,Сироп Ваниль 1000мл,Сиропы,65000,бут ,,Расходники,25000,уп CUP-PAP-300,Стакан бумажный 300мл 50шт,Упаковка,-5000,уп TEA-SEN-01,Чай зеленый Сенча 500г,Чай,95000,уп`,N=[{key:`firstName`,label:`Имя`,required:!0},{key:`lastName`,label:`Фамилия`,required:!0},{key:`phone`,label:`Телефон`,required:!1},{key:`email`,label:`Email`,required:!1},{key:`companyName`,label:`Компания`,required:!1},{key:`jobTitle`,label:`Должность`,required:!1}],P=[{key:`sku`,label:`Артикул (SKU)`,required:!0},{key:`name`,label:`Наименование`,required:!0},{key:`category`,label:`Категория`,required:!1},{key:`price`,label:`Цена (копейки)`,required:!0},{key:`unit`,label:`Единица измерения`,required:!1}],le=({initialEntityType:e=`contact`,onComplete:t,onClose:n})=>{let{showToast:i}=s(),[o,l]=(0,k.useState)(1),[u,m]=(0,k.useState)(e),[ae,h]=(0,k.useState)(``),[_,y]=(0,k.useState)(``),[oe,x]=(0,k.useState)([]),[S,C]=(0,k.useState)([]),[w,T]=(0,k.useState)({}),[E,D]=(0,k.useState)(!0),[O,A]=(0,k.useState)(!1),[le,F]=(0,k.useState)(0),I=e=>{let t=e.trim().split(/\r?\n/).filter(Boolean);if(t.length<2)return;let n=e=>{let t=[],n=``,r=!1;for(let i=0;i{o[e]=a[t]||``}),i.push(o)}x(r),C(i);let a={},o=u===`contact`?N:P;r.forEach(e=>{let t=e.toLowerCase(),n=o.find(e=>{let n=e.label.toLowerCase();return t===e.key.toLowerCase()||t===n||t.includes(n)||n.includes(t)});n?a[e]=n.key:a[e]=``}),T(a)},L=e=>{m(e);let t=e===`contact`?ce:M;h(t),y(`образец_${e===`contact`?`контактов`:`товаров`}.csv`),I(t),l(2)},R=e=>{let t=e.target.files?.[0];if(!t)return;y(t.name);let n=new FileReader;n.onload=e=>{let t=e.target?.result;h(t),I(t),l(2)},n.readAsText(t)},z=S.map((e,t)=>{let n={};Object.entries(w).forEach(([t,r])=>{r&&(n[r]=e[t]||``)});let r=[];if(u===`contact`)n.firstName?.trim()||r.push(`Имя обязательно`),n.lastName?.trim()||r.push(`Фамилия обязательна`),n.email&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n.email)&&r.push(`Некорректный email: "${n.email}"`);else if(n.sku?.trim()||r.push(`Артикул (SKU) обязателен`),n.name?.trim()||r.push(`Наименование обязательно`),n.price){let e=Number(n.price);(isNaN(e)||e<=0)&&r.push(`Цена должна быть положительным числом: "${n.price}"`)}else r.push(`Цена обязательна`);return{rowIndex:t+1,raw:e,mapped:n,isValid:r.length===0,errors:r}}),B=z.filter(e=>e.isValid).length,ue=z.filter(e=>!e.isValid).length,V=async()=>{A(!0);try{let e=E?z.filter(e=>e.isValid):z,n=0;if(u===`contact`)for(let t of e)await g.contacts.create({firstName:t.mapped.firstName||`Контакт`,lastName:t.mapped.lastName||``,phone:t.mapped.phone||``,email:t.mapped.email||``,roles:[`client`],status:`active`}),n++;else for(let t of e){let e=Math.round(Number(t.mapped.price)||1e4);await v.products.create({sku:t.mapped.sku||`SKU-${c()}`,name:t.mapped.name||`Товар`,categoryId:`cat_default`,isService:!1,trackInventory:!0,status:`active`,price:{minor:e,currency:`RUB`},costPrice:{minor:Math.round(e*.6),currency:`RUB`},unit:t.mapped.unit||`шт`}),n++}F(n),l(4),i(`Успешно импортировано ${n} записей в IndexedDB!`,`success`),t&&t(n)}catch(e){i(`Ошибка импорта: ${e instanceof Error?e.message:String(e)}`,`error`)}finally{A(!1)}},H=u===`contact`?N:P;return(0,j.jsxs)(`div`,{className:`bg-krona-surface border border-krona-border rounded-xl shadow-krona-soft p-5 space-y-6`,children:[(0,j.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-krona-border pb-4`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,j.jsx)(`h2`,{className:`text-base font-bold text-krona-primary`,children:`Мастер импорта данных из CSV`}),(0,j.jsx)(a,{variant:`gold`,size:`sm`,children:u===`contact`?`Контакты CRM`:`Товары`})]}),(0,j.jsx)(`p`,{className:`text-xs text-krona-secondary mt-0.5`,children:`Пакетная загрузка записей с проверкой форматов, сопоставлением колонок и отчетом валидации`})]}),(0,j.jsx)(`div`,{className:`flex items-center gap-2 text-xs`,children:[{num:1,label:`Файл`},{num:2,label:`Сопоставление`},{num:3,label:`Валидация`},{num:4,label:`Готово`}].map(e=>(0,j.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,j.jsx)(`span`,{className:`w-6 h-6 rounded-full flex items-center justify-center font-bold text-xs ${o===e.num?`bg-krona-green text-white shadow-sm`:o>e.num?`bg-[#2F684C]/20 text-krona-green`:`bg-krona-workspace text-krona-secondary border border-krona-border`}`,children:o>e.num?(0,j.jsx)(ee,{className:`w-3.5 h-3.5`}):e.num}),(0,j.jsx)(`span`,{className:`hidden sm:inline font-medium ${o===e.num?`text-krona-primary`:`text-krona-secondary`}`,children:e.label}),e.num<4&&(0,j.jsx)(`div`,{className:`w-4 h-0.5 bg-krona-border`})]},e.num))})]}),o===1&&(0,j.jsxs)(`div`,{className:`space-y-5 animate-fade-in`,children:[(0,j.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`label`,{className:`block text-xs font-semibold text-krona-primary mb-1.5`,children:`Целевая сущность`}),(0,j.jsxs)(`div`,{className:`flex gap-2`,children:[(0,j.jsxs)(`button`,{type:`button`,onClick:()=>m(`contact`),className:`flex-1 p-3 rounded-lg border text-left text-xs transition-all ${u===`contact`?`border-krona-green bg-krona-green/10 text-krona-primary font-semibold`:`border-krona-border bg-krona-workspace text-krona-secondary hover:border-krona-border/80`}`,children:[(0,j.jsx)(`div`,{className:`font-bold text-sm text-krona-primary`,children:`Контакты`}),(0,j.jsx)(`div`,{className:`text-xs text-krona-secondary mt-0.5`,children:`Физлица, клиенты, сотрудники контрагентов`})]}),(0,j.jsxs)(`button`,{type:`button`,onClick:()=>m(`product`),className:`flex-1 p-3 rounded-lg border text-left text-xs transition-all ${u===`product`?`border-krona-green bg-krona-green/10 text-krona-primary font-semibold`:`border-krona-border bg-krona-workspace text-krona-secondary hover:border-krona-border/80`}`,children:[(0,j.jsx)(`div`,{className:`font-bold text-sm text-krona-primary`,children:`Товары`}),(0,j.jsx)(`div`,{className:`text-xs text-krona-secondary mt-0.5`,children:`Номенклатура, артикулы, цены и остатки`})]})]})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`label`,{className:`block text-xs font-semibold text-krona-primary mb-1.5`,children:`Быстрый старт с образцами данных`}),(0,j.jsxs)(`div`,{className:`space-y-2`,children:[(0,j.jsxs)(r,{variant:`secondary`,size:`sm`,className:`w-full justify-start text-xs`,onClick:()=>L(`contact`),children:[(0,j.jsx)(b,{className:`w-3.5 h-3.5 text-amber-500 mr-2`}),`Загрузить образец контактов (с корректными и ошибочными строками)`]}),(0,j.jsxs)(r,{variant:`secondary`,size:`sm`,className:`w-full justify-start text-xs`,onClick:()=>L(`product`),children:[(0,j.jsx)(b,{className:`w-3.5 h-3.5 text-emerald-500 mr-2`}),`Загрузить образец товаров (с корректными и ошибочными строками)`]})]})]})]}),(0,j.jsxs)(`div`,{className:`border-2 border-dashed border-krona-border hover:border-krona-green rounded-xl p-8 text-center transition-colors bg-krona-workspace/40`,children:[(0,j.jsx)(se,{className:`w-10 h-10 text-krona-secondary mx-auto mb-2`}),(0,j.jsx)(`div`,{className:`text-xs font-medium text-krona-primary`,children:`Перетащите сюда файл .csv или выберите на диске`}),(0,j.jsx)(`p`,{className:`text-[11px] text-krona-secondary mt-1`,children:`Поддерживается разделитель запятая (,), кодировка UTF-8`}),(0,j.jsxs)(`label`,{className:`mt-3 inline-block cursor-pointer`,children:[(0,j.jsxs)(`span`,{className:`px-3.5 py-1.5 rounded-lg bg-krona-green text-white text-xs font-medium hover:bg-krona-green/90 transition-colors shadow-sm inline-flex items-center gap-1.5`,children:[(0,j.jsx)(d,{className:`w-3.5 h-3.5`}),` Выбрать файл на компьютере`]}),(0,j.jsx)(`input`,{type:`file`,accept:`.csv,text/csv`,onChange:R,className:`hidden`})]})]})]}),o===2&&(0,j.jsxs)(`div`,{className:`space-y-4 animate-fade-in`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between text-xs bg-krona-workspace p-3 rounded-lg border border-krona-border`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`Файл: `}),(0,j.jsx)(`span`,{className:`font-semibold text-krona-primary`,children:_}),(0,j.jsx)(`span`,{className:`text-krona-secondary ml-3`,children:`Строк: `}),(0,j.jsx)(`span`,{className:`font-semibold text-krona-primary`,children:S.length})]}),(0,j.jsx)(r,{variant:`ghost`,size:`sm`,onClick:()=>l(1),children:`Выбрать другой файл`})]}),(0,j.jsx)(`div`,{className:`border border-krona-border rounded-lg overflow-hidden`,children:(0,j.jsxs)(`table`,{className:`w-full text-xs text-left`,children:[(0,j.jsx)(`thead`,{className:`bg-krona-workspace text-krona-secondary border-b border-krona-border`,children:(0,j.jsxs)(`tr`,{children:[(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Колонка в CSV-файле`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Пример значения (первая строка)`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Поле в системе Krona`})]})}),(0,j.jsx)(`tbody`,{className:`divide-y divide-krona-border`,children:oe.map(e=>(0,j.jsxs)(`tr`,{className:`hover:bg-krona-workspace/50`,children:[(0,j.jsx)(`td`,{className:`p-3 font-semibold text-krona-primary`,children:e}),(0,j.jsx)(`td`,{className:`p-3 font-mono text-krona-secondary truncate max-w-xs`,children:S[0]?.[e]||`—`}),(0,j.jsx)(`td`,{className:`p-3`,children:(0,j.jsxs)(`select`,{value:w[e]||``,onChange:t=>T({...w,[e]:t.target.value}),className:`w-64 px-2.5 py-1 text-xs bg-krona-workspace border border-krona-border rounded-md text-krona-primary focus:outline-none focus:border-krona-green`,children:[(0,j.jsx)(`option`,{value:``,children:`-- Не импортировать --`}),H.map(e=>(0,j.jsxs)(`option`,{value:e.key,children:[e.label,` `,e.required?`*`:``]},e.key))]})})]},e))})]})}),(0,j.jsxs)(`div`,{className:`flex justify-between items-center pt-2`,children:[(0,j.jsxs)(r,{variant:`secondary`,size:`sm`,onClick:()=>l(1),children:[(0,j.jsx)(f,{className:`w-3.5 h-3.5 mr-1`}),` Назад`]}),(0,j.jsxs)(r,{variant:`primary`,size:`sm`,onClick:()=>l(3),children:[`Перейти к валидации `,(0,j.jsx)(ne,{className:`w-3.5 h-3.5 ml-1`})]})]})]}),o===3&&(0,j.jsxs)(`div`,{className:`space-y-4 animate-fade-in`,children:[(0,j.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-3 gap-3`,children:[(0,j.jsxs)(`div`,{className:`p-3 rounded-lg border border-krona-border bg-krona-workspace/60`,children:[(0,j.jsx)(`div`,{className:`text-[11px] text-krona-secondary uppercase font-semibold`,children:`Всего строк в файле`}),(0,j.jsx)(`div`,{className:`text-xl font-bold text-krona-primary mt-1`,children:z.length})]}),(0,j.jsxs)(`div`,{className:`p-3 rounded-lg border border-emerald-500/30 bg-emerald-500/10`,children:[(0,j.jsxs)(`div`,{className:`text-[11px] text-emerald-700 dark:text-emerald-300 uppercase font-semibold flex items-center gap-1`,children:[(0,j.jsx)(p,{className:`w-3.5 h-3.5`}),` Корректные строки`]}),(0,j.jsx)(`div`,{className:`text-xl font-bold text-emerald-600 dark:text-emerald-400 mt-1`,children:B})]}),(0,j.jsxs)(`div`,{className:`p-3 rounded-lg border border-rose-500/30 bg-rose-500/10`,children:[(0,j.jsxs)(`div`,{className:`text-[11px] text-rose-700 dark:text-rose-300 uppercase font-semibold flex items-center gap-1`,children:[(0,j.jsx)(ie,{className:`w-3.5 h-3.5`}),` Строки с ошибками`]}),(0,j.jsx)(`div`,{className:`text-xl font-bold text-rose-600 dark:text-rose-400 mt-1`,children:ue})]})]}),(0,j.jsxs)(`div`,{className:`flex items-center gap-2 text-xs bg-krona-workspace p-3 rounded-lg border border-krona-border`,children:[(0,j.jsx)(`input`,{type:`checkbox`,id:`skipErrors`,checked:E,onChange:e=>D(e.target.checked),className:`rounded border-krona-border text-krona-green focus:ring-krona-green`}),(0,j.jsxs)(`label`,{htmlFor:`skipErrors`,className:`text-krona-primary font-medium cursor-pointer`,children:[`Импортировать только корректные строки (`,B,` из `,z.length,`), пропуская ошибочные`]})]}),(0,j.jsx)(`div`,{className:`border border-krona-border rounded-lg overflow-x-auto max-h-80`,children:(0,j.jsxs)(`table`,{className:`w-full text-xs text-left`,children:[(0,j.jsx)(`thead`,{className:`bg-krona-workspace text-krona-secondary border-b border-krona-border sticky top-0`,children:(0,j.jsxs)(`tr`,{children:[(0,j.jsx)(`th`,{className:`p-2.5 font-semibold w-12`,children:`№`}),(0,j.jsx)(`th`,{className:`p-2.5 font-semibold w-24`,children:`Статус`}),H.map(e=>(0,j.jsx)(`th`,{className:`p-2.5 font-semibold`,children:e.label},e.key)),(0,j.jsx)(`th`,{className:`p-2.5 font-semibold`,children:`Ошибки / Замечания`})]})}),(0,j.jsx)(`tbody`,{className:`divide-y divide-krona-border`,children:z.map(e=>(0,j.jsxs)(`tr`,{className:`transition-colors ${e.isValid?`hover:bg-krona-workspace/40`:`bg-rose-500/5 hover:bg-rose-500/10`}`,children:[(0,j.jsx)(`td`,{className:`p-2.5 font-mono text-krona-secondary`,children:e.rowIndex}),(0,j.jsx)(`td`,{className:`p-2.5`,children:e.isValid?(0,j.jsx)(a,{variant:`green`,size:`sm`,children:`Корректно`}):(0,j.jsx)(a,{variant:`danger`,size:`sm`,children:`Ошибка`})}),H.map(t=>(0,j.jsx)(`td`,{className:`p-2.5 text-krona-primary font-medium`,children:e.mapped[t.key]||(0,j.jsx)(`span`,{className:`text-krona-secondary italic`,children:`—`})},t.key)),(0,j.jsx)(`td`,{className:`p-2.5 text-xs text-rose-600 dark:text-rose-400`,children:e.errors.length>0?(0,j.jsx)(`ul`,{className:`list-disc pl-4 space-y-0.5`,children:e.errors.map((e,t)=>(0,j.jsx)(`li`,{children:e},t))}):(0,j.jsxs)(`span`,{className:`text-emerald-600 dark:text-emerald-400 flex items-center gap-1`,children:[(0,j.jsx)(ee,{className:`w-3 h-3`}),` Проверка пройдена`]})})]},e.rowIndex))})]})}),(0,j.jsxs)(`div`,{className:`flex justify-between items-center pt-2`,children:[(0,j.jsxs)(r,{variant:`secondary`,size:`sm`,onClick:()=>l(2),children:[(0,j.jsx)(f,{className:`w-3.5 h-3.5 mr-1`}),` Назад`]}),(0,j.jsx)(r,{variant:`primary`,size:`sm`,disabled:O||E&&B===0,onClick:V,children:O?(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(re,{className:`w-3.5 h-3.5 mr-1.5 animate-spin`}),` Выполняется импорт...`]}):(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)(te,{className:`w-3.5 h-3.5 mr-1.5`}),` Импортировать `,E?B:z.length,` записей в базу`]})})]})]}),o===4&&(0,j.jsxs)(`div`,{className:`text-center py-8 space-y-4 animate-fade-in`,children:[(0,j.jsx)(`div`,{className:`w-14 h-14 rounded-full bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 flex items-center justify-center mx-auto`,children:(0,j.jsx)(p,{className:`w-8 h-8`})}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`h3`,{className:`text-lg font-bold text-krona-primary`,children:`Импорт успешно завершен!`}),(0,j.jsxs)(`p`,{className:`text-xs text-krona-secondary max-w-md mx-auto mt-1`,children:[`В локальную базу данных IndexedDB успешно добавлено`,` `,(0,j.jsx)(`strong`,{className:`text-krona-primary font-semibold`,children:le}),` записей`,` `,`(`,u===`contact`?`контактов`:`товаров`,`). Данные мгновенно доступны для использования во всех модулях платформы.`]})]}),(0,j.jsxs)(`div`,{className:`flex justify-center gap-2 pt-3`,children:[n&&(0,j.jsx)(r,{variant:`secondary`,size:`sm`,onClick:n,children:`Закрыть мастер`}),(0,j.jsx)(r,{variant:`primary`,size:`sm`,onClick:()=>{l(1),h(``),y(``),C([])},children:`Импортировать еще файл`})]})]})]})},F=[{key:`prospecting`,label:`Первичный контакт`,color:`border-sky-500/40`},{key:`discovery`,label:`Квалификация`,color:`border-indigo-500/40`},{key:`proposal`,label:`Предложение`,color:`border-amber-500/40`},{key:`negotiation`,label:`Переговоры`,color:`border-orange-500/40`},{key:`contract`,label:`Согласование`,color:`border-purple-500/40`},{key:`won`,label:`Выиграна`,color:`border-emerald-500/60 bg-emerald-500/5`},{key:`lost`,label:`Проиграна`,color:`border-rose-500/40 bg-rose-500/5`}],I=()=>{let t=S(),{showToast:n}=s(),{contacts:i,companies:o,leads:c,deals:d,createContact:f,createCompany:p,createDeal:te,createLead:re,updateDeal:ie,convertLead:g,getTimeline:v,createActivity:w}=A(),{orders:O,createOrder:ce}=E(),M=x(`contact`),N=x(`company`),P=x(`deal`),I=x(`lead`),[L,R]=(0,k.useState)(()=>{let e=t.pathname;return e.includes(`/crm/deals`)?`deals`:e.includes(`/crm/leads`)?`leads`:e.includes(`/crm/companies`)?`companies`:e.includes(`/crm/import`)?`import`:e.includes(`/crm/contacts`)||e===`/crm`?`contacts`:`deals`}),[z,B]=(0,k.useState)(``),[ue,V]=(0,k.useState)(!1),[H,U]=(0,k.useState)(!1),[de,W]=(0,k.useState)(!1),[fe,G]=(0,k.useState)(!1),[pe,K]=(0,k.useState)(!1),[me,he]=(0,k.useState)(null),[ge,_e]=(0,k.useState)(``),[ve,q]=(0,k.useState)(!1),[J,ye]=(0,k.useState)(null),[be,xe]=(0,k.useState)(``),[Se,Ce]=(0,k.useState)(`wh_main`),[Y,we]=(0,k.useState)(null),[X,Te]=(0,k.useState)(null),[Z,Ee]=(0,k.useState)(`overview`),[De,Q]=(0,k.useState)([]),[Oe,ke]=(0,k.useState)(``),[Ae,je]=(0,k.useState)(`call`),[Me,Ne]=(0,k.useState)(null),[Pe,Fe]=(0,k.useState)(t.pathname);if(Pe!==t.pathname){Fe(t.pathname);let e=t.pathname;e.includes(`/crm/deals`)?R(`deals`):e.includes(`/crm/leads`)?R(`leads`):e.includes(`/crm/companies`)?R(`companies`):e.includes(`/crm/import`)?R(`import`):(e.includes(`/crm/contacts`)||e===`/crm`)&&R(`contacts`)}k.useEffect(()=>{let e=!0;return Y?v(`contact`,Y.id).then(t=>{e&&Q(t)}).catch(()=>{}):X&&v(`company`,X.id).then(t=>{e&&Q(t)}).catch(()=>{}),()=>{e=!1}},[Y,X,v]);let Ie=async(e,t)=>{let r=d.find(t=>t.id===e);r&&(await ie(e,{stage:t}),n(`Сделка «${r.title}» переведена на этап: ${F.find(e=>e.key===t)?.label}`,`info`),t===`won`&&(ye(r),xe(`Заказ по сделке: ${r.title}`),q(!0)))},Le=(e,t)=>{e.dataTransfer.setData(`text/plain`,t),Ne(t)},Re=e=>{e.preventDefault()},ze=async(e,t)=>{e.preventDefault();let n=e.dataTransfer.getData(`text/plain`)||Me;n&&await Ie(n,t),Ne(null)},Be=async()=>{if(J)try{let t=i.find(e=>e.id===J.contactId),r=o.find(e=>e.id===J.companyId),a=t?`${t.firstName} ${t.lastName}`:r?.name||`Клиент`,s=J.contactId||J.companyId||`cnt_default`,c=`ORD-${e().slice(-6)}`;await ce({orderNumber:c,customerType:J.contactId?`contact`:`company`,customerId:s,customerName:a,status:`draft`,paymentStatus:`pending`,fulfillmentStatus:`unfulfilled`,items:[{id:`item_${e()}`,productId:`prd_coffee_beans`,sku:`COF-100`,name:J.title,quantity:1,unitPrice:J.amount,discountMinor:0,totalPrice:J.amount}],subtotal:J.amount,discountMinor:0,taxMinor:Math.round(J.amount.minor*.2),shippingMinor:0,total:J.amount,channel:`b2b`}),n(`Связанный Заказ ${c} успешно создан в Коммерции!`,`success`),q(!1),ye(null)}catch(e){n(`Ошибка создания заказа: ${e instanceof Error?e.message:String(e)}`,`error`)}},Ve=async()=>{if(me)try{let e=await g(me.id,ge);n(`Лид конвертирован! Создана сделка «${e.deal.title}»`,`success`),K(!1),he(null)}catch(e){n(`Ошибка конвертации: ${e instanceof Error?e.message:String(e)}`,`error`)}},He=async e=>{if(e.preventDefault(),!Oe)return;let t=Y?`contact`:`company`,r=Y?.id||X?.id||``;await w({targetEntityType:t,targetEntityId:r,type:Ae,title:Oe,completed:!1,dueDate:new Date(Date.now()+864e5).toISOString()}),ke(``),n(`Активность запланирована`,`success`),v(t,r).then(Q).catch(()=>{})},$=Y?.id||X?.id||``,Ue=(0,k.useMemo)(()=>d.filter(e=>e.contactId===$||e.companyId===$),[d,$]),We=(0,k.useMemo)(()=>O.filter(e=>e.customerId===$),[O,$]);return(0,j.jsxs)(`div`,{className:`space-y-4 animate-fade-in`,children:[(0,j.jsxs)(`div`,{className:`flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-krona-surface p-3.5 rounded-xl border border-krona-border shadow-krona-soft`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,j.jsx)(`h1`,{className:`text-sm font-bold text-krona-primary`,children:`CRM: Клиенты, Воронка продаж & Сделки`}),(0,j.jsx)(T,{level:`pilot1`,size:`sm`})]}),(0,j.jsx)(`p`,{className:`text-xs text-krona-secondary mt-0.5`,children:`Сквозной процесс: Лид → Контакт/Компания → Сделка (Kanban) → Выиграна → Заказ в Коммерции`})]}),(0,j.jsxs)(`div`,{className:`flex items-center gap-1.5 overflow-x-auto text-xs`,children:[(0,j.jsxs)(`button`,{onClick:()=>R(`deals`),className:`px-3 py-1.5 rounded-lg font-medium transition-all ${L===`deals`?`bg-krona-green text-white shadow-sm`:`bg-krona-workspace text-krona-secondary hover:text-krona-primary border border-krona-border`}`,children:[`Воронка сделок (`,d.length,`)`]}),(0,j.jsxs)(`button`,{onClick:()=>R(`contacts`),className:`px-3 py-1.5 rounded-lg font-medium transition-all ${L===`contacts`?`bg-krona-green text-white shadow-sm`:`bg-krona-workspace text-krona-secondary hover:text-krona-primary border border-krona-border`}`,children:[`Контакты (`,i.length,`)`]}),(0,j.jsxs)(`button`,{onClick:()=>R(`companies`),className:`px-3 py-1.5 rounded-lg font-medium transition-all ${L===`companies`?`bg-krona-green text-white shadow-sm`:`bg-krona-workspace text-krona-secondary hover:text-krona-primary border border-krona-border`}`,children:[`Компании (`,o.length,`)`]}),(0,j.jsxs)(`button`,{onClick:()=>R(`leads`),className:`px-3 py-1.5 rounded-lg font-medium transition-all ${L===`leads`?`bg-krona-green text-white shadow-sm`:`bg-krona-workspace text-krona-secondary hover:text-krona-primary border border-krona-border`}`,children:[`Лиды (`,c.length,`)`]}),(0,j.jsxs)(`button`,{onClick:()=>R(`import`),className:`px-3 py-1.5 rounded-lg font-medium transition-all flex items-center gap-1 ${L===`import`?`bg-krona-green text-white shadow-sm`:`bg-krona-workspace text-krona-secondary hover:text-krona-primary border border-krona-border`}`,children:[(0,j.jsx)(se,{className:`w-3.5 h-3.5`}),` Импорт CSV`]})]})]}),L===`deals`&&(0,j.jsxs)(`div`,{className:`space-y-3`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,j.jsxs)(`div`,{className:`relative w-64`,children:[(0,j.jsx)(_,{className:`w-3.5 h-3.5 absolute left-2.5 top-2.5 text-krona-secondary`}),(0,j.jsx)(`input`,{type:`text`,value:z,onChange:e=>B(e.target.value),placeholder:`Поиск по сделкам...`,className:`w-full pl-8 pr-3 py-1.5 text-xs bg-krona-surface border border-krona-border rounded-lg text-krona-primary focus:outline-none focus:border-krona-green`})]}),(0,j.jsxs)(r,{variant:`primary`,size:`sm`,onClick:()=>W(!0),children:[(0,j.jsx)(m,{className:`w-3.5 h-3.5 mr-1`}),` Новая сделка`]})]}),(0,j.jsx)(`div`,{className:`grid grid-cols-1 md:grid-cols-4 lg:grid-cols-7 gap-2.5 overflow-x-auto pb-4`,children:F.map(e=>{let t=d.filter(t=>t.stage===e.key&&(t.title.toLowerCase().includes(z.toLowerCase())||!z)),n=t.reduce((e,t)=>e+t.amount.minor,0);return(0,j.jsxs)(`div`,{"data-testid":`kanban-column-${e.key}`,onDragOver:Re,onDrop:t=>ze(t,e.key),className:`bg-krona-surface/70 border rounded-xl p-2.5 flex flex-col min-w-[200px] max-h-[750px] shadow-krona-soft transition-all ${e.color}`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between border-b border-krona-border/60 pb-2 mb-2`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`div`,{className:`text-xs font-bold text-krona-primary`,children:e.label}),(0,j.jsx)(`div`,{className:`text-[11px] font-medium text-krona-green mt-0.5`,children:D(n)})]}),(0,j.jsx)(`span`,{className:`text-[11px] px-1.5 py-0.5 rounded-full bg-krona-workspace text-krona-secondary font-bold`,children:t.length})]}),(0,j.jsxs)(`div`,{className:`space-y-2 overflow-y-auto flex-1 pr-0.5`,children:[t.map(e=>{let t=i.find(t=>t.id===e.contactId),n=o.find(t=>t.id===e.companyId),r=F.findIndex(t=>t.key===e.stage)+1,a=F[r]?.key;return(0,j.jsxs)(`div`,{"data-testid":`deal-card-${e.id}`,"data-deal-id":e.id,"data-deal-stage":e.stage,draggable:!0,onDragStart:t=>Le(t,e.id),className:`bg-krona-workspace border border-krona-border hover:border-krona-green/60 p-2.5 rounded-lg text-xs space-y-2 shadow-xs cursor-grab active:cursor-grabbing transition-all`,children:[(0,j.jsx)(`div`,{className:`font-semibold text-krona-primary line-clamp-2`,children:e.title}),(0,j.jsxs)(`div`,{className:`flex items-center justify-between text-[11px]`,children:[(0,j.jsx)(`span`,{className:`font-bold text-krona-primary`,children:D(e.amount.minor)}),(0,j.jsxs)(`span`,{className:`px-1.5 py-0.2 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 rounded font-medium`,children:[e.probability,`% вер.`]})]}),(t||n)&&(0,j.jsxs)(`div`,{className:`text-[11px] text-krona-secondary truncate flex items-center gap-1`,children:[(0,j.jsx)(u,{className:`w-3 h-3`}),n?.name||`${t?.firstName} ${t?.lastName}`]}),a&&e.stage!==`won`&&e.stage!==`lost`&&(0,j.jsxs)(`button`,{type:`button`,onClick:()=>Ie(e.id,a),className:`w-full mt-1 py-1 text-[11px] bg-krona-surface hover:bg-krona-green/10 text-krona-secondary hover:text-krona-green border border-krona-border rounded flex items-center justify-center gap-1 transition-colors`,children:[`Далее: `,F[r]?.label,` `,(0,j.jsx)(ne,{className:`w-3 h-3`})]})]},e.id)}),t.length===0&&(0,j.jsx)(`div`,{className:`text-center py-6 text-[11px] text-krona-secondary italic`,children:`Пусто`})]})]},e.key)})})]}),L===`contacts`&&(0,j.jsxs)(`div`,{className:`space-y-3`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,j.jsxs)(`div`,{className:`relative w-64`,children:[(0,j.jsx)(_,{className:`w-3.5 h-3.5 absolute left-2.5 top-2.5 text-krona-secondary`}),(0,j.jsx)(`input`,{type:`text`,value:z,onChange:e=>B(e.target.value),placeholder:`Поиск по имени, телефону, email...`,className:`w-full pl-8 pr-3 py-1.5 text-xs bg-krona-surface border border-krona-border rounded-lg text-krona-primary focus:outline-none focus:border-krona-green`})]}),(0,j.jsxs)(r,{variant:`primary`,size:`sm`,onClick:()=>V(!0),children:[(0,j.jsx)(m,{className:`w-3.5 h-3.5 mr-1`}),` Новый контакт`]})]}),(0,j.jsx)(`div`,{className:`bg-krona-surface border border-krona-border rounded-xl shadow-krona-soft overflow-hidden`,children:(0,j.jsxs)(`table`,{className:`w-full text-xs text-left`,children:[(0,j.jsx)(`thead`,{className:`bg-krona-workspace text-krona-secondary border-b border-krona-border`,children:(0,j.jsxs)(`tr`,{children:[(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`ФИО / Контакт`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Компания`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Телефон`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Email`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Роли`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold text-right`,children:`Действие`})]})}),(0,j.jsx)(`tbody`,{className:`divide-y divide-krona-border`,children:i.filter(e=>`${e.firstName} ${e.lastName}`.toLowerCase().includes(z.toLowerCase())||e.phone?.includes(z)||e.email?.toLowerCase().includes(z.toLowerCase())).map(e=>{let t=o.find(t=>t.id===e.companyId);return(0,j.jsxs)(`tr`,{onClick:()=>{we(e),Te(null)},className:`hover:bg-krona-workspace/50 cursor-pointer transition-colors`,children:[(0,j.jsx)(`td`,{className:`p-3 font-medium text-krona-primary`,children:(0,j.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,j.jsxs)(`div`,{className:`w-7 h-7 rounded-full bg-krona-green/10 text-krona-green flex items-center justify-center font-bold text-xs`,children:[e.firstName[0],e.lastName?.[0]]}),(0,j.jsxs)(`div`,{children:[(0,j.jsxs)(`div`,{children:[e.firstName,` `,e.lastName]}),e.jobTitle&&(0,j.jsx)(`div`,{className:`text-[11px] text-krona-secondary`,children:e.jobTitle})]})]})}),(0,j.jsx)(`td`,{className:`p-3 text-krona-secondary`,children:t?.name||`—`}),(0,j.jsx)(`td`,{className:`p-3 font-mono text-krona-secondary`,children:e.phone||`—`}),(0,j.jsx)(`td`,{className:`p-3 text-krona-secondary`,children:e.email||`—`}),(0,j.jsx)(`td`,{className:`p-3`,children:(0,j.jsx)(`div`,{className:`flex gap-1`,children:e.roles?.map(e=>(0,j.jsx)(a,{variant:`gold`,size:`sm`,children:e},e))})}),(0,j.jsx)(`td`,{className:`p-3 text-right`,children:(0,j.jsxs)(r,{variant:`ghost`,size:`sm`,children:[`Карточка 360 `,(0,j.jsx)(ae,{className:`w-3.5 h-3.5 ml-1`})]})})]},e.id)})})]})})]}),L===`companies`&&(0,j.jsxs)(`div`,{className:`space-y-3`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,j.jsxs)(`div`,{className:`relative w-64`,children:[(0,j.jsx)(_,{className:`w-3.5 h-3.5 absolute left-2.5 top-2.5 text-krona-secondary`}),(0,j.jsx)(`input`,{type:`text`,value:z,onChange:e=>B(e.target.value),placeholder:`Поиск по названию, ИНН...`,className:`w-full pl-8 pr-3 py-1.5 text-xs bg-krona-surface border border-krona-border rounded-lg text-krona-primary focus:outline-none focus:border-krona-green`})]}),(0,j.jsxs)(r,{variant:`primary`,size:`sm`,onClick:()=>U(!0),children:[(0,j.jsx)(m,{className:`w-3.5 h-3.5 mr-1`}),` Новая компания`]})]}),(0,j.jsx)(`div`,{className:`bg-krona-surface border border-krona-border rounded-xl shadow-krona-soft overflow-hidden`,children:(0,j.jsxs)(`table`,{className:`w-full text-xs text-left`,children:[(0,j.jsx)(`thead`,{className:`bg-krona-workspace text-krona-secondary border-b border-krona-border`,children:(0,j.jsxs)(`tr`,{children:[(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Название компании`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`ИНН`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Город`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Телефон`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Роли`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold text-right`,children:`Действие`})]})}),(0,j.jsx)(`tbody`,{className:`divide-y divide-krona-border`,children:o.filter(e=>e.name.toLowerCase().includes(z.toLowerCase())||e.inn?.includes(z)||e.address?.toLowerCase().includes(z.toLowerCase())).map(e=>(0,j.jsxs)(`tr`,{onClick:()=>{Te(e),we(null)},className:`hover:bg-krona-workspace/50 cursor-pointer transition-colors`,children:[(0,j.jsx)(`td`,{className:`p-3 font-medium text-krona-primary`,children:(0,j.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,j.jsx)(u,{className:`w-4 h-4 text-krona-secondary`}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`div`,{className:`font-bold`,children:e.name}),e.legalName&&(0,j.jsx)(`div`,{className:`text-[11px] text-krona-secondary`,children:e.legalName})]})]})}),(0,j.jsx)(`td`,{className:`p-3 font-mono text-krona-secondary`,children:e.inn||`—`}),(0,j.jsx)(`td`,{className:`p-3 text-krona-secondary`,children:e.address||`—`}),(0,j.jsx)(`td`,{className:`p-3 font-mono text-krona-secondary`,children:e.phone||`—`}),(0,j.jsx)(`td`,{className:`p-3`,children:(0,j.jsx)(`div`,{className:`flex gap-1`,children:e.roles?.map(e=>(0,j.jsx)(a,{variant:`gold`,size:`sm`,children:e},e))})}),(0,j.jsx)(`td`,{className:`p-3 text-right`,children:(0,j.jsxs)(r,{variant:`ghost`,size:`sm`,children:[`Карточка 360 `,(0,j.jsx)(ae,{className:`w-3.5 h-3.5 ml-1`})]})})]},e.id))})]})})]}),L===`leads`&&(0,j.jsxs)(`div`,{className:`space-y-3`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,j.jsxs)(`div`,{className:`relative w-64`,children:[(0,j.jsx)(_,{className:`w-3.5 h-3.5 absolute left-2.5 top-2.5 text-krona-secondary`}),(0,j.jsx)(`input`,{type:`text`,value:z,onChange:e=>B(e.target.value),placeholder:`Поиск лидов...`,className:`w-full pl-8 pr-3 py-1.5 text-xs bg-krona-surface border border-krona-border rounded-lg text-krona-primary focus:outline-none focus:border-krona-green`})]}),(0,j.jsxs)(r,{variant:`primary`,size:`sm`,"data-testid":`new-lead-btn`,onClick:()=>G(!0),children:[(0,j.jsx)(m,{className:`w-3.5 h-3.5 mr-1`}),` Новый лид`]})]}),(0,j.jsx)(`div`,{className:`bg-krona-surface border border-krona-border rounded-xl shadow-krona-soft overflow-hidden`,children:(0,j.jsxs)(`table`,{className:`w-full text-xs text-left`,children:[(0,j.jsx)(`thead`,{className:`bg-krona-workspace text-krona-secondary border-b border-krona-border`,children:(0,j.jsxs)(`tr`,{children:[(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Название лида`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Контактное лицо`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Контакты`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Оценка бюджета`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold`,children:`Статус`}),(0,j.jsx)(`th`,{className:`p-3 font-semibold text-right`,children:`Конвертация`})]})}),(0,j.jsx)(`tbody`,{className:`divide-y divide-krona-border`,children:c.map(e=>(0,j.jsxs)(`tr`,{className:`hover:bg-krona-workspace/50 transition-colors`,children:[(0,j.jsx)(`td`,{className:`p-3 font-bold text-krona-primary`,children:e.title}),(0,j.jsx)(`td`,{className:`p-3 font-medium text-krona-primary`,children:e.contactName}),(0,j.jsxs)(`td`,{className:`p-3 text-krona-secondary`,children:[(0,j.jsx)(`div`,{children:e.phone}),(0,j.jsx)(`div`,{className:`text-[11px]`,children:e.email})]}),(0,j.jsx)(`td`,{className:`p-3 font-bold text-krona-green`,children:e.estimatedValue?D(e.estimatedValue.minor):`—`}),(0,j.jsx)(`td`,{className:`p-3`,children:(0,j.jsx)(a,{variant:e.status===`converted`?`green`:e.status===`disqualified`?`danger`:`warning`,size:`sm`,children:e.status===`converted`?`Конвертирован`:e.status===`new`?`Новый`:e.status})}),(0,j.jsx)(`td`,{className:`p-3 text-right`,children:e.status===`converted`?(0,j.jsxs)(`span`,{className:`text-emerald-600 dark:text-emerald-400 text-xs font-semibold flex items-center justify-end gap-1`,children:[(0,j.jsx)(ee,{className:`w-3.5 h-3.5`}),` Сделка создана`]}):(0,j.jsxs)(r,{variant:`primary`,size:`sm`,"data-testid":`convert-lead-btn`,onClick:()=>{he(e),_e(`Сделка: ${e.title}`),K(!0)},children:[(0,j.jsx)(b,{className:`w-3.5 h-3.5 mr-1`}),` Конвертировать в сделку`]})})]},e.id))})]})})]}),L===`import`&&(0,j.jsx)(le,{initialEntityType:`contact`}),(0,j.jsx)(oe,{isOpen:!!(Y||X),onClose:()=>{we(null),Te(null),Q([])},title:Y?`${Y.firstName} ${Y.lastName} (Customer 360)`:`${X?.name} (Company 360)`,size:`lg`,children:(0,j.jsxs)(`div`,{className:`space-y-4`,children:[(0,j.jsx)(`div`,{className:`flex border-b border-krona-border text-xs`,children:[`overview`,`deals`,`orders`,`activities`,`timeline`].map(e=>(0,j.jsxs)(`button`,{onClick:()=>Ee(e),className:`px-3.5 py-2 font-semibold capitalize transition-colors border-b-2 ${Z===e?`border-krona-green text-krona-green`:`border-transparent text-krona-secondary hover:text-krona-primary`}`,children:[e===`overview`&&`Обзор`,e===`deals`&&`Сделки (${Ue.length})`,e===`orders`&&`Заказы (${We.length})`,e===`activities`&&`Задачи & Звонки`,e===`timeline`&&`Таймлайн (${De.length})`]},e))}),Z===`overview`&&(0,j.jsxs)(`div`,{className:`space-y-3 text-xs`,children:[(0,j.jsxs)(`div`,{className:`grid grid-cols-2 gap-3 bg-krona-workspace p-3.5 rounded-lg border border-krona-border`,children:[Y&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`ФИО:`}),` `,(0,j.jsxs)(`strong`,{className:`text-krona-primary`,children:[Y.firstName,` `,Y.lastName]})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`Телефон:`}),` `,(0,j.jsx)(`strong`,{className:`text-krona-primary`,children:Y.phone||`—`})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`Email:`}),` `,(0,j.jsx)(`strong`,{className:`text-krona-primary`,children:Y.email||`—`})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`Должность:`}),` `,(0,j.jsx)(`strong`,{className:`text-krona-primary`,children:Y.jobTitle||`—`})]})]}),X&&(0,j.jsxs)(j.Fragment,{children:[(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`Название:`}),` `,(0,j.jsx)(`strong`,{className:`text-krona-primary`,children:X.name})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`ИНН:`}),` `,(0,j.jsx)(`strong`,{className:`text-krona-primary`,children:X.inn||`—`})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`Адрес:`}),` `,(0,j.jsx)(`strong`,{className:`text-krona-primary`,children:X.address||`—`})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`span`,{className:`text-krona-secondary`,children:`Телефон:`}),` `,(0,j.jsx)(`strong`,{className:`text-krona-primary`,children:X.phone||`—`})]})]})]}),(0,j.jsxs)(`div`,{className:`p-3 bg-krona-workspace/40 rounded-lg border border-krona-border`,children:[(0,j.jsx)(`div`,{className:`font-semibold text-krona-primary mb-1`,children:`Кастомные атрибуты (Схема Krona Studio):`}),Y?.customFields&&Object.keys(Y.customFields).length>0||X?.customFields&&Object.keys(X.customFields).length>0?(0,j.jsx)(`div`,{className:`grid grid-cols-2 gap-2 mt-2`,children:Object.entries(Y?.customFields||X?.customFields).map(([e,t])=>(0,j.jsxs)(`div`,{className:`text-xs`,children:[(0,j.jsxs)(`span`,{className:`text-krona-secondary`,children:[e,`:`]}),` `,(0,j.jsx)(`strong`,{className:`text-krona-primary`,children:String(t)})]},e))}):(0,j.jsx)(`p`,{className:`text-krona-secondary text-[11px]`,children:`Дополнительные поля из Конструктора полей отображаются здесь в реальном времени.`})]})]}),Z===`deals`&&(0,j.jsxs)(`div`,{className:`space-y-2`,children:[Ue.map(e=>(0,j.jsxs)(`div`,{className:`p-3 rounded-lg border border-krona-border bg-krona-workspace flex items-center justify-between text-xs`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`div`,{className:`font-bold text-krona-primary`,children:e.title}),(0,j.jsxs)(`div`,{className:`text-[11px] text-krona-secondary`,children:[`Этап:`,` `,(0,j.jsx)(`span`,{className:`font-semibold`,children:F.find(t=>t.key===e.stage)?.label})]})]}),(0,j.jsxs)(`div`,{className:`text-right`,children:[(0,j.jsx)(`div`,{className:`font-bold text-krona-green`,children:D(e.amount.minor)}),(0,j.jsxs)(`div`,{className:`text-[11px] text-krona-secondary`,children:[e.probability,`% вер.`]})]})]},e.id)),Ue.length===0&&(0,j.jsx)(`div`,{className:`text-center py-6 text-krona-secondary text-xs italic`,children:`Нет связанных сделок`})]}),Z===`orders`&&(0,j.jsxs)(`div`,{className:`space-y-2`,children:[We.map(e=>(0,j.jsxs)(`div`,{className:`p-3 rounded-lg border border-krona-border bg-krona-workspace flex items-center justify-between text-xs`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`div`,{className:`font-bold font-mono text-krona-primary`,children:e.orderNumber}),(0,j.jsxs)(`div`,{className:`text-[11px] text-krona-secondary`,children:[e.items.length,` поз. • Статус: `,e.status]})]}),(0,j.jsxs)(`div`,{className:`text-right`,children:[(0,j.jsx)(`div`,{className:`font-bold text-krona-green`,children:D(e.total.minor)}),(0,j.jsx)(a,{variant:e.paymentStatus===`paid`?`green`:`warning`,size:`sm`,children:e.paymentStatus})]})]},e.id)),We.length===0&&(0,j.jsx)(`div`,{className:`text-center py-6 text-krona-secondary text-xs italic`,children:`Нет связанных заказов`})]}),Z===`activities`&&(0,j.jsx)(`div`,{className:`space-y-3`,children:(0,j.jsxs)(`form`,{onSubmit:He,className:`p-3 bg-krona-workspace rounded-lg border border-krona-border space-y-2`,children:[(0,j.jsx)(`div`,{className:`text-xs font-semibold text-krona-primary`,children:`Запланировать активность:`}),(0,j.jsxs)(`div`,{className:`flex gap-2`,children:[(0,j.jsxs)(`select`,{value:Ae,onChange:e=>je(e.target.value),className:`px-2.5 py-1 text-xs bg-krona-surface border border-krona-border rounded-md text-krona-primary`,children:[(0,j.jsx)(`option`,{value:`call`,children:`Звонок`}),(0,j.jsx)(`option`,{value:`meeting`,children:`Встреча`}),(0,j.jsx)(`option`,{value:`task`,children:`Задача`}),(0,j.jsx)(`option`,{value:`email`,children:`Email`})]}),(0,j.jsx)(`input`,{type:`text`,value:Oe,onChange:e=>ke(e.target.value),placeholder:`Например: Обсудить коммерческое предложение...`,className:`flex-1 px-3 py-1 text-xs bg-krona-surface border border-krona-border rounded-md text-krona-primary`}),(0,j.jsx)(r,{type:`submit`,variant:`primary`,size:`sm`,children:`Добавить`})]})]})}),Z===`timeline`&&(0,j.jsxs)(`div`,{className:`space-y-2.5 max-h-96 overflow-y-auto pr-1`,children:[De.map(e=>(0,j.jsxs)(`div`,{className:`p-3 rounded-lg border border-krona-border bg-krona-workspace text-xs space-y-1`,children:[(0,j.jsxs)(`div`,{className:`flex items-center justify-between`,children:[(0,j.jsx)(`span`,{className:`font-bold text-krona-primary`,children:e.title}),(0,j.jsx)(`span`,{className:`text-[10px] text-krona-secondary`,children:y(e.timestamp)})]}),e.description&&(0,j.jsx)(`p`,{className:`text-krona-secondary text-[11px]`,children:e.description}),(0,j.jsxs)(`div`,{className:`text-[10px] text-krona-green font-medium`,children:[`Автор: `,e.actor]})]},e.id)),De.length===0&&(0,j.jsx)(`div`,{className:`text-center py-6 text-krona-secondary text-xs italic`,children:`Таймлайн пуст`})]})]})}),(0,j.jsx)(C,{isOpen:ve,onClose:()=>q(!1),title:`Сделка выиграна! Создать заказ в Коммерции?`,size:`md`,children:(0,j.jsxs)(`div`,{className:`space-y-4 text-xs`,children:[(0,j.jsxs)(`div`,{className:`p-3 bg-emerald-500/10 border border-emerald-500/30 rounded-lg text-emerald-800 dark:text-emerald-300`,children:[(0,j.jsx)(`strong`,{children:`Поздравляем с успехом!`}),` Сделка «`,J?.title,`» переведена в статус «Выиграна». Система предлагает автоматически сформировать коммерческий Заказ.`]}),(0,j.jsxs)(`div`,{className:`space-y-3`,children:[(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`label`,{className:`block font-semibold text-krona-primary mb-1`,children:`Наименование заказа:`}),(0,j.jsx)(`input`,{type:`text`,value:be,onChange:e=>xe(e.target.value),className:`w-full px-3 py-1.5 bg-krona-workspace border border-krona-border rounded-lg text-krona-primary`})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`label`,{className:`block font-semibold text-krona-primary mb-1`,children:`Сумма заказа (RUB):`}),(0,j.jsx)(`div`,{className:`font-bold text-sm text-krona-green py-1`,children:J?D(J.amount.minor):`0 ₽`})]}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`label`,{className:`block font-semibold text-krona-primary mb-1`,children:`Склад отгрузки:`}),(0,j.jsxs)(`select`,{value:Se,onChange:e=>Ce(e.target.value),className:`w-full px-3 py-1.5 bg-krona-workspace border border-krona-border rounded-lg text-krona-primary`,children:[(0,j.jsx)(`option`,{value:`wh_main`,children:`Основной распределительный склад (Москва)`}),(0,j.jsx)(`option`,{value:`wh_spb`,children:`Склад Санкт-Петербург`})]})]})]}),(0,j.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2 border-t border-krona-border`,children:[(0,j.jsx)(r,{variant:`secondary`,size:`sm`,onClick:()=>q(!1),children:`Не создавать сейчас`}),(0,j.jsxs)(r,{variant:`primary`,size:`sm`,"data-testid":`create-order-confirm-btn`,onClick:Be,children:[(0,j.jsx)(h,{className:`w-3.5 h-3.5 mr-1`}),` Создать заказ в Коммерции`]})]})]})}),(0,j.jsx)(C,{isOpen:pe,onClose:()=>K(!1),title:`Конвертация лида в сделку и контакт`,size:`md`,children:(0,j.jsxs)(`div`,{className:`space-y-4 text-xs`,children:[(0,j.jsx)(`p`,{className:`text-krona-secondary`,children:`При конвертации будет автоматически создан Контакт клиента и новая Сделка на этапе «Предложение».`}),(0,j.jsxs)(`div`,{children:[(0,j.jsx)(`label`,{className:`block font-semibold text-krona-primary mb-1`,children:`Название новой сделки:`}),(0,j.jsx)(`input`,{type:`text`,value:ge,onChange:e=>_e(e.target.value),className:`w-full px-3 py-1.5 bg-krona-workspace border border-krona-border rounded-lg text-krona-primary`})]}),(0,j.jsxs)(`div`,{className:`flex justify-end gap-2 pt-2 border-t border-krona-border`,children:[(0,j.jsx)(r,{variant:`secondary`,size:`sm`,onClick:()=>K(!1),children:`Отмена`}),(0,j.jsx)(r,{variant:`primary`,size:`sm`,"data-testid":`confirm-convert-lead-btn`,onClick:Ve,children:`Подтвердить конвертацию`})]})]})}),(0,j.jsx)(C,{isOpen:fe,onClose:()=>G(!1),title:`Создание нового лида`,size:`lg`,children:I.currentEntity?(0,j.jsx)(l,{entity:I.currentEntity,layout:I.layouts?.[0]||null,mode:`create`,onSave:async e=>{await re({title:String(e.title||`Новый лид`),contactName:String(e.contactName||e.title||`Контактное лицо`),phone:String(e.phone||`+7 (999) 000-00-00`),email:String(e.email||`lead@example.com`),companyName:String(e.companyName||``),status:`new`,source:`website`,estimatedValue:e.estimatedValue?{minor:Number(e.estimatedValue)||1e6,currency:`RUB`}:{minor:15e5,currency:`RUB`},customFields:e}),G(!1),n(`Лид успешно создан!`,`success`)},onCancel:()=>G(!1)}):(0,j.jsx)(`div`,{className:`p-4 text-center text-krona-secondary`,children:`Загрузка схемы...`})}),(0,j.jsx)(C,{isOpen:ue,onClose:()=>V(!1),title:`Создание нового контакта`,size:`lg`,children:M.currentEntity?(0,j.jsx)(l,{entity:M.currentEntity,layout:M.layouts?.[0]||null,mode:`create`,onSave:async e=>{await f({firstName:String(e.firstName||`Новый`),lastName:String(e.lastName||`Контакт`),phone:String(e.phone||``),email:String(e.email||``),jobTitle:String(e.jobTitle||``),roles:[`client`],status:`active`,customFields:e}),V(!1),n(`Контакт успешно создан!`,`success`)},onCancel:()=>V(!1)}):(0,j.jsx)(`div`,{className:`p-4 text-center text-krona-secondary`,children:`Загрузка схемы...`})}),(0,j.jsx)(C,{isOpen:H,onClose:()=>U(!1),title:`Создание новой компании`,size:`lg`,children:N.currentEntity?(0,j.jsx)(l,{entity:N.currentEntity,layout:N.layouts?.[0]||null,mode:`create`,onSave:async e=>{await p({name:String(e.name||`Новая компания`),inn:String(e.inn||``),address:String(e.city||e.address||`г. Москва`),phone:String(e.phone||``),roles:[`client`],status:`active`,customFields:e}),U(!1),n(`Компания успешно создана!`,`success`)},onCancel:()=>U(!1)}):(0,j.jsx)(`div`,{className:`p-4 text-center text-krona-secondary`,children:`Загрузка схемы...`})}),(0,j.jsx)(C,{isOpen:de,onClose:()=>W(!1),title:`Создание новой сделки`,size:`lg`,children:P.currentEntity?(0,j.jsx)(l,{entity:P.currentEntity,layout:P.layouts?.[0]||null,mode:`create`,onSave:async e=>{let t=typeof e.amount==`number`?e.amount:5e6;await te({title:String(e.title||`Новая сделка`),pipelineId:`pipe_default`,stage:`prospecting`,amount:{minor:t,currency:`RUB`},probability:20,contactId:i[0]?.id,companyId:o[0]?.id,customFields:e}),W(!1),n(`Сделка успешно создана в воронке!`,`success`)},onCancel:()=>W(!1)}):(0,j.jsx)(`div`,{className:`p-4 text-center text-krona-secondary`,children:`Загрузка схемы...`})})]})};export{I as CrmModule};