6 lines
27 KiB
JavaScript
6 lines
27 KiB
JavaScript
import{r as n,j as e}from"./chunk-UIGDSWPH-BhuNDbxn.js";import{a as Me,T as Ue,S as Te}from"./TablePageTemplate-BEWe6AkV.js";import{g as Ee,T as $e,O as me,L as Pe,B as pe,u as Fe,m as Le,U as Ae,V as De,W as Qe}from"./main-af3pcbZa.js";import{S as fe}from"./file-CeG1FbGg.js";import{B as he}from"./Badge-DM3morB7.js";import{M as ae}from"./index-ju2wdkG8.js";import{S as Ge}from"./check-circle--AtVWUy0.js";import{S as Oe}from"./info-error-ByXER0wM.js";import{S as Re}from"./SelectDropdown-C8sZwHi_.js";import{u as Be}from"./useResourceDebug-Dza3x9eP.js";import{P as We}from"./PageHeader-iXTYKDGo.js";import"./AlertModal-BhtTtzZV.js";import"./plus-2WF6_FMG.js";import"./arrow-right-DC7G5FiV.js";import"./pencil-CuC2vg9I.js";import"./angle-left-CYBnq6Pg.js";function xe({image:l,maxPromptLength:T=100}){const[M,u]=n.useState(!1),c=i=>i.startsWith("http://")||i.startsWith("https://")?!1:i.includes("ai-images"),h=i=>{if(i.includes("ai-images")){const y=i.split("ai-images/")[1]||i.split("ai-images\\")[1];if(y)return`/images/ai-images/${y}`}return i.startsWith("/images/")?i:`/images/ai-images/${i.split("/").pop()||i.split("\\").pop()}`};if(!l)return e.jsx("div",{className:"text-gray-400 dark:text-gray-500 text-sm",children:"-"});const I=l.prompt||"",U=I.length>T,N=M||!U?I:`${I.substring(0,T)}...`;return e.jsxs("div",{className:"space-y-2",children:[I&&e.jsx("div",{className:"text-sm",children:e.jsxs("p",{className:"text-gray-700 dark:text-gray-300",children:[N,U&&e.jsx("button",{onClick:()=>u(!M),className:"ml-1 text-brand-500 hover:text-brand-600 text-xs",children:M?"Show less":"Show more"})]})}),e.jsxs("div",{className:"relative",children:[l.status==="pending"&&e.jsx("div",{className:"w-full h-24 bg-gray-200 dark:bg-gray-700 rounded border-2 border-dashed border-gray-300 dark:border-gray-600 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("svg",{className:"w-8 h-8 mx-auto text-gray-400 dark:text-gray-500 mb-1",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}),e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"Pending"})]})}),l.status==="generated"&&e.jsx("div",{className:"space-y-1",children:l.image_path&&l.image_path.trim()&&c(l.image_path)?e.jsx(e.Fragment,{children:e.jsx("img",{src:h(l.image_path),alt:I||"Generated image",className:"w-full h-24 object-cover rounded border border-gray-300 dark:border-gray-600",onError:i=>{const S=i.target;S.style.display="none";const y=S.parentElement;y&&(y.innerHTML=`
|
|
<div class="w-full h-24 bg-gray-200 dark:bg-gray-700 rounded border-2 border-dashed border-gray-300 dark:border-gray-600 flex items-center justify-center">
|
|
<p class="text-xs text-gray-500 dark:text-gray-400">Image not available</p>
|
|
</div>
|
|
`)}})}):e.jsx("div",{className:"w-full h-24 bg-gray-200 dark:bg-gray-700 rounded border-2 border-dashed border-gray-300 dark:border-gray-600 flex items-center justify-center",children:e.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:"No image available"})})}),l.status==="failed"&&e.jsx("div",{className:"w-full h-24 bg-red-100 dark:bg-red-900/20 rounded border border-red-300 dark:border-red-700 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("svg",{className:"w-6 h-6 mx-auto text-red-500 mb-1",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),e.jsx("p",{className:"text-xs text-red-700 dark:text-red-400",children:"Failed"})]})}),e.jsx("div",{className:"absolute top-1 right-1",children:e.jsx(he,{color:l.status==="generated"?"success":l.status==="failed"?"error":"warning",size:"xs",variant:"light",children:l.status})})]})]})}const qe=l=>{const T=l.maxInArticleImages||5,M=[{key:"content_title",label:"Content Title",sortable:!0,sortField:"content_title",width:"250px",render:(u,c)=>e.jsxs("div",{children:[e.jsx("a",{href:`/writer/content/${c.content_id}`,className:"font-medium text-brand-500 hover:text-brand-600 dark:text-brand-400",children:c.content_title}),e.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:["ID: ",c.content_id]})]})},{key:"featured_image",label:"Featured Image",sortable:!1,width:"200px",render:(u,c)=>e.jsx(xe,{image:c.featured_image,onImageClick:l.onImageClick?()=>l.onImageClick(c.content_id,"featured"):void 0})}];for(let u=1;u<=T;u++)M.push({key:`in_article_${u}`,label:`In-Article ${u}`,sortable:!1,width:"200px",render:(c,h)=>{const I=h.in_article_images.find(U=>U.position===u);return e.jsx(xe,{image:I||null,onImageClick:l.onImageClick&&I?()=>l.onImageClick(h.content_id,"in_article",u):void 0})}});return M.push({key:"overall_status",label:"Status",sortable:!0,sortField:"overall_status",width:"180px",render:(u,c)=>{var N,i;const h={complete:"success",partial:"info",pending:"warning",failed:"error"},I={complete:"Complete",partial:"Partial",pending:"Pending",failed:"Failed"},U=((N=c.featured_image)==null?void 0:N.status)==="pending"&&((i=c.featured_image)==null?void 0:i.prompt)||c.in_article_images.some(S=>S.status==="pending"&&S.prompt);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(he,{color:h[u]||"warning",size:"sm",children:I[u]||u}),U&&l.onGenerateImages&&e.jsxs("button",{onClick:S=>{S.stopPropagation(),l.onGenerateImages(c.content_id)},className:"inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-white bg-brand-500 hover:bg-brand-600 rounded transition-colors",title:"Generate Images",children:[e.jsx(Ee,{className:"w-3 h-3"}),"Generate"]})]})}}),{columns:M,filters:[{key:"search",label:"Search",type:"text",placeholder:"Search by content title..."},{key:"status",label:"Status",type:"select",options:[{value:"",label:"All Status"},{value:"complete",label:"Complete"},{value:"partial",label:"Partial"},{value:"pending",label:"Pending"},{value:"failed",label:"Failed"}]}],headerMetrics:[{label:"Total Content",value:0,accentColor:"blue",calculate:u=>u.totalCount||0},{label:"Complete",value:0,accentColor:"green",calculate:u=>u.images.filter(c=>c.overall_status==="complete").length},{label:"Partial",value:0,accentColor:"info",calculate:u=>u.images.filter(c=>c.overall_status==="partial").length},{label:"Pending",value:0,accentColor:"amber",calculate:u=>u.images.filter(c=>c.overall_status==="pending").length}],maxInArticleImages:T}};function Ve({isOpen:l,onClose:T,queue:M,totalImages:u,taskId:c,model:h,provider:I,onUpdateQueue:U,onLog:N}){const[i,S]=n.useState(M),[y,F]=n.useState({}),d=n.useRef({});n.useEffect(()=>{S(M)},[M]),n.useEffect(()=>{U&&U(i)},[i,U]),n.useEffect(()=>{const a=(s,g)=>{d.current[s]&&(clearInterval(d.current[s]),delete d.current[s]);let r=Math.max(g,50);const m=setInterval(()=>{F(p=>{const _=p[s]??r,w=i.find(x=>x.index===s);if(_<80&&(w==null?void 0:w.status)==="processing"){const x=Math.min(_+2,80);return r=x,x>=80&&(clearInterval(m),delete d.current[s]),{...p,[s]:x}}else return clearInterval(m),delete d.current[s],p})},200);d.current[s]=m},v=[];return i.forEach(s=>{if(s.status==="processing"){const g=y[s.index]??(s.progress>0?s.progress:1);if(g<50&&!d.current[s.index]){let r=Math.max(g,1);const m=setInterval(()=>{F(p=>{const _=p[s.index]??r;if(_<50&&s.status==="processing"){const w=Math.min(_+1,50);return r=w,w>=50&&(clearInterval(m),delete d.current[s.index],w<80&&a(s.index,w)),{...p,[s.index]:w}}else return clearInterval(m),delete d.current[s.index],p})},200);d.current[s.index]=m}else if(g>=50&&g<80&&!d.current[s.index])a(s.index,g);else if(s.imageUrl&&g<100&&!d.current[s.index]){d.current[s.index]&&(clearInterval(d.current[s.index]),delete d.current[s.index]);let r=Math.max(g,80);const m=r,p=100,_=800,w=Date.now(),x=setInterval(()=>{const R=Date.now()-w,C=Math.min(1,R/_),A=1-Math.pow(1-C,2);r=m+(p-m)*A,(r>=100||R>=_)&&(r=100,clearInterval(x),delete d.current[s.index]),F(B=>({...B,[s.index]:Math.round(r)}))},16);d.current[s.index]=x}}else d.current[s.index]&&(clearInterval(d.current[s.index]),delete d.current[s.index]),y[s.index]!==void 0&&v.push(s.index)}),v.length>0&&F(s=>{const g={...s};return v.forEach(r=>{delete g[r]}),g}),()=>{Object.values(d.current).forEach(s=>clearInterval(s)),d.current={}}},[i,y]),n.useEffect(()=>{if(!l||!c)return;let a=0;const v=300,s=setInterval(async()=>{var g;if(a++,a>v){console.warn("Polling timeout reached, stopping"),clearInterval(s);return}try{console.log(`[ImageQueueModal] Polling task status (attempt ${a}):`,c);const r=await $e(`/v1/system/settings/task_progress/${c}/`);if(console.log("[ImageQueueModal] Task status response:",r),!r||typeof r!="object"){console.warn("Invalid task status response:",r);return}const m=r.state||r.status;if(console.log("[ImageQueueModal] Task state:",m),m==="SUCCESS"||m==="FAILURE"){if(console.log("[ImageQueueModal] Task completed with state:",m),clearInterval(s),N)if(m==="SUCCESS"){const p=r.result||r.meta&&r.meta.result,_=(p==null?void 0:p.completed)||0,w=(p==null?void 0:p.failed)||0,x=(p==null?void 0:p.total_images)||u;N({timestamp:new Date().toISOString(),type:w>0?"error":"success",action:"generate_images",stepName:"Task Completed",data:{state:"SUCCESS",completed:_,failed:w,total:x,results:(p==null?void 0:p.results)||[]}})}else N({timestamp:new Date().toISOString(),type:"error",action:"generate_images",stepName:"Task Failed",data:{state:"FAILURE",error:r.error||((g=r.meta)==null?void 0:g.error)||"Task failed",meta:r.meta}});m==="SUCCESS"&&r.result?(console.log("[ImageQueueModal] Updating queue from result:",r.result),L(r.result)):m==="SUCCESS"&&r.meta&&r.meta.result&&(console.log("[ImageQueueModal] Updating queue from meta result:",r.meta.result),L(r.meta.result));return}r.meta?(console.log("[ImageQueueModal] Updating queue from meta:",r.meta),Q(r.meta)):console.log("[ImageQueueModal] No meta data in response")}catch(r){if(r.message&&(r.message.includes("JSON")||r.message.includes("API Error"))){if(console.error("Task status endpoint error:",{message:r.message,status:r.status,taskId:c,endpoint:`/v1/system/settings/task_progress/${c}/`,error:r}),r.status===404){console.error("Task progress endpoint not found (404). Stopping polling."),clearInterval(s);return}}else console.error("Error polling task status:",r)}},1e3);return()=>clearInterval(s)},[l,c]);const V=a=>{if(!a)return null;if(a.includes("ai-images")){const s=a.split("ai-images/")[1]||a.split("ai-images\\")[1];if(s)return`/images/ai-images/${s}`}if(a.startsWith("/images/"))return a;const v=a.split("/").pop()||a.split("\\").pop();return v?`/images/ai-images/${v}`:null},Q=a=>{const{current_image:v,total_images:s,completed:g,failed:r,results:m,current_image_progress:p,current_image_id:_}=a;S(w=>w.map((x,R)=>{const C=m==null?void 0:m.find(A=>A.image_id===x.imageId);if(C){(C.status==="completed"||C.status==="failed")&&d.current[x.index]&&(clearInterval(d.current[x.index]),delete d.current[x.index]);const A=C.status==="completed"&&C.image_path?V(C.image_path):null,B=_===x.imageId&&p!==void 0?p:C.status==="completed"?100:C.status==="failed"?0:x.progress;return{...x,status:C.status==="completed"?"completed":C.status==="failed"?"failed":"processing",progress:B,imageUrl:A||x.imageUrl,error:C.error||null}}if(R+1<v)return d.current[x.index]&&(clearInterval(d.current[x.index]),delete d.current[x.index]),{...x,status:"completed",progress:100};if(_===x.imageId){const A=p!==void 0?p:y[x.index]??0;return{...x,status:"processing",progress:A}}return x}))},L=a=>{const{results:v}=a;S(s=>s.map(g=>{const r=v==null?void 0:v.find(m=>m.image_id===g.imageId);if(r){d.current[g.index]&&(clearInterval(d.current[g.index]),delete d.current[g.index]);const m=r.status==="completed"&&r.image_path?V(r.image_path):null;return{...g,status:r.status==="completed"?"completed":"failed",progress:r.status==="completed"?100:0,imageUrl:m||g.imageUrl,error:r.error||null}}return g}))};if(!l)return null;const H=a=>{switch(a){case"pending":return e.jsx(me,{className:"w-4 h-4"});case"processing":return e.jsxs("svg",{className:"w-4 h-4 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]});case"completed":return e.jsx(Ge,{className:"w-4 h-4"});case"failed":return e.jsx(Oe,{className:"w-4 h-4"});default:return e.jsx(me,{className:"w-4 h-4"})}},J=a=>{switch(a){case"pending":return"Pending";case"processing":return"Generating...";case"completed":return"Complete";case"failed":return"Failed";default:return"Pending"}},W=a=>{switch(a){case"completed":return"bg-green-500";case"failed":return"bg-red-500";case"processing":return"bg-blue-500";default:return"bg-gray-300"}},K=i.some(a=>a.status==="processing"),q=i.filter(a=>a.status==="completed").length,O=i.filter(a=>a.status==="failed").length,X=i.every(a=>a.status==="completed"||a.status==="failed");return e.jsxs(ae,{isOpen:l,onClose:T,className:"max-w-4xl w-full max-h-[80vh] overflow-hidden flex flex-col",showCloseButton:!K,children:[e.jsx("div",{className:"px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fe,{className:"w-6 h-6 text-blue-500"}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:"Generating Images"}),e.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:["Total: ",u," image",u!==1?"s":""," in queue"]}),h&&e.jsxs("p",{className:"text-xs text-gray-400 dark:text-gray-500 mt-1",children:["Model: ",I==="openai"?"OpenAI":I==="runware"?"Runware":I||"Unknown"," ",h==="dall-e-2"?"DALL·E 2":h==="dall-e-3"?"DALL·E 3":h]})]})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-4",children:e.jsx("div",{className:"space-y-3",children:i.map(a=>e.jsx("div",{className:`p-4 rounded-lg border-2 transition-colors ${a.status==="processing"?"bg-blue-50 dark:bg-blue-900/20 border-blue-500":a.status==="completed"?"bg-green-50 dark:bg-green-900/20 border-green-500":a.status==="failed"?"bg-red-50 dark:bg-red-900/20 border-red-500":"bg-gray-50 dark:bg-gray-700/50 border-gray-300 dark:border-gray-600"}`,children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("span",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-500 text-white text-xs font-bold",children:a.index}),e.jsx("span",{className:"font-semibold text-sm text-gray-900 dark:text-white",children:a.label}),e.jsx("span",{className:"flex-1 text-xs text-gray-500 dark:text-gray-400 truncate",children:a.prompt?(()=>{const v=a.prompt.split(" "),s=v.slice(0,10).join(" ");return v.length>10?`${s}...`:a.prompt})():a.contentTitle}),e.jsxs("span",{className:"text-xs font-semibold text-gray-600 dark:text-gray-300 whitespace-nowrap flex items-center gap-1",children:[H(a.status),e.jsx("span",{children:J(a.status)})]})]}),e.jsxs("div",{className:"relative h-5 bg-gray-200 dark:bg-gray-600 rounded-full overflow-hidden",children:[e.jsx("div",{className:`h-full ${W(a.status)} transition-all duration-150 ease-out`,style:{width:`${y[a.index]??a.progress??0}%`}}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{className:`text-xs font-bold ${(y[a.index]??a.progress??0)>=50?"text-white":"text-gray-700 dark:text-gray-200"}`,children:[y[a.index]??a.progress??0,"%"]})})]}),a.error&&e.jsx("div",{className:"mt-2 p-2 bg-red-100 dark:bg-red-900/30 border-l-4 border-red-500 rounded text-xs text-red-700 dark:text-red-300",children:a.error})]}),e.jsx("div",{className:"w-20 h-20 bg-gray-100 dark:bg-gray-700 rounded-lg overflow-hidden flex-shrink-0 flex items-center justify-center",children:a.status==="completed"&&a.imageUrl?e.jsx("img",{src:a.imageUrl,alt:a.label,className:"w-full h-full object-cover",onError:v=>{const s=v.target;s.style.display="none";const g=s.parentElement;g&&(g.innerHTML='<span class="text-xs text-gray-400 dark:text-gray-500">No image</span>')}}):e.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:"No image"})})]})},a.index))})}),e.jsx("div",{className:"px-6 py-4 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[q," completed",O>0?`, ${O} failed`:""," of ",u," total"]}),X&&e.jsx("button",{onClick:T,className:"px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors",children:"Close"})]})})]})}function ze({isOpen:l,onClose:T,onConfirm:M,title:u,recordName:c,confirmText:h="Update Status",statusOptions:I,isLoading:U=!1}){const[N,i]=n.useState(""),S=async()=>{N&&(await M(N),i(""))},y=()=>{i(""),T()};return e.jsx(ae,{isOpen:l,onClose:y,className:"max-w-md",children:e.jsxs("div",{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"flex items-center justify-center w-10 h-10 bg-blue-50 rounded-xl dark:bg-blue-500/10",children:e.jsx(Me,{className:"w-5 h-5 text-blue-500"})}),e.jsx("h2",{className:"text-xl font-bold text-gray-800 dark:text-white",children:u})]}),e.jsxs("p",{className:"text-gray-600 dark:text-gray-400 mb-4",children:["Update status for all images in ",e.jsx("span",{className:"font-semibold text-gray-900 dark:text-white",children:c})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx(Pe,{className:"mb-2",children:"New Status"}),e.jsx(Re,{options:I,placeholder:"Select status",value:N,onChange:F=>i(F||""),className:"w-full"})]}),e.jsxs("div",{className:"flex justify-end gap-4",children:[e.jsx(pe,{variant:"outline",onClick:y,disabled:U,children:"Cancel"}),e.jsx(pe,{variant:"primary",onClick:S,disabled:U||!N,children:U?"Updating...":h})]})]})})}function dt(){const l=Fe(),T=Be(),[M,u]=n.useState([]),c=n.useCallback(t=>{T&&u(o=>[...o,t])},[T]),[h,I]=n.useState([]),[U,N]=n.useState(!0),[i,S]=n.useState(""),[y,F]=n.useState(""),[d,V]=n.useState([]),[Q,L]=n.useState(1),[H,J]=n.useState(1),[W,K]=n.useState(0),q=10,[O,X]=n.useState("content_title"),[a,v]=n.useState("asc"),[s,g]=n.useState(!1),[r,m]=n.useState(!1),[p,_]=n.useState([]),[w,x]=n.useState(null),[R,C]=n.useState(null),[A,B]=n.useState(null),[be,se]=n.useState(null),[ye,Y]=n.useState(!1),[Z,ee]=n.useState(null),[ve,te]=n.useState(""),[ke,re]=n.useState(!1),[je,ne]=n.useState(!1),[le,oe]=n.useState(null),G=n.useCallback(async()=>{N(!0),g(!1);try{let o=(await Le({})).results||[];i&&(o=o.filter(j=>{var P;return(P=j.content_title)==null?void 0:P.toLowerCase().includes(i.toLowerCase())})),y&&(o=o.filter(j=>j.overall_status===y)),o.sort((j,P)=>{let E=j.content_title,f=P.content_title;return O==="overall_status"&&(E=j.overall_status,f=P.overall_status),E<f?a==="asc"?-1:1:E>f?a==="asc"?1:-1:0});const b=(Q-1)*q,k=b+q,$=o.slice(b,k);I($),K(o.length),J(Math.ceil(o.length/q)),setTimeout(()=>{g(!0),N(!1)},100)}catch(t){console.error("Error loading images:",t),l.error(`Failed to load images: ${t.message}`),g(!0),N(!1)}},[Q,y,O,a,i,l]);n.useEffect(()=>{G()},[G]),n.useEffect(()=>{const t=setTimeout(()=>{Q===1?G():L(1)},500);return()=>clearTimeout(t)},[i,Q,G]);const Ie=(t,o)=>{X(t||"content_title"),v(o),L(1)},Se=n.useCallback(async t=>{try{if(!t||t.length===0)throw new Error("No records selected for export");l.info("Export functionality coming soon")}catch(o){throw o}},[l]),Ne=n.useCallback(async(t,o)=>{l.info(`Bulk action "${t}" for ${o.length} items`)},[l]),_e=n.useCallback(async(t,o)=>{t==="update_status"&&(ee(o.content_id),te(o.content_title||`Content #${o.content_id}`),Y(!0))},[]),we=n.useCallback(async t=>{if(Z){re(!0);try{const o=await Ae(Z,t);l.success(`Successfully updated ${o.updated_count} image(s) status to ${t}`),Y(!1),ee(null),te(""),G()}catch(o){l.error(`Failed to update status: ${o.message}`)}finally{re(!1)}}},[Z,l,G]),ie=n.useCallback((t,o)=>{var P,E;const b=h.find(f=>f.content_id===t);if(!b)return[];const k=[];let $=1;return((P=b.featured_image)==null?void 0:P.status)==="pending"&&((E=b.featured_image)!=null&&E.prompt)&&k.push({imageId:b.featured_image.id||null,index:$++,label:"Featured Image",type:"featured",contentTitle:b.content_title||`Content #${t}`,prompt:b.featured_image.prompt,status:"pending",progress:0,imageUrl:null,error:null}),b.in_article_images.filter(f=>f.status==="pending"&&f.prompt).slice(0,o).sort((f,z)=>(f.position||0)-(z.position||0)).forEach((f,z)=>{k.push({imageId:f.id||null,index:$++,label:`In-Article Image ${f.position||z+1}`,type:"in_article",position:f.position||z+1,contentTitle:b.content_title||`Content #${t}`,prompt:f.prompt,status:"pending",progress:0,imageUrl:null,error:null})}),k},[h]),ce=n.useCallback(async t=>{try{if(!h.find(f=>f.content_id===t)){l.error("Content not found");return}let b=2,k=null,$=null;try{const f=await De();f.success&&f.config&&(b=f.config.max_in_article_images||2,k=f.config.model||null,$=f.config.provider||null)}catch(f){console.warn("Failed to fetch image settings, using default:",f)}B(k),se($);const j=ie(t,b);if(j.length===0){l.info("No pending images with prompts found for this content");return}_(j),x(t),m(!0);const P=j.map(f=>f.imageId).filter(f=>f!==null);console.log("[Generate Images] Stage 1 Complete: Modal opened with",j.length,"images"),console.log("[Generate Images] Image IDs to generate:",P),console.log("[Generate Images] Max in-article images from settings:",b),c({timestamp:new Date().toISOString(),type:"request",action:"generate_images",data:{imageIds:P,contentId:t,totalImages:P.length}});const E=await Qe(P,t);E.success&&E.task_id?(C(E.task_id),console.log("[Generate Images] Stage 2: Task started with ID:",E.task_id),c({timestamp:new Date().toISOString(),type:"step",action:"generate_images",stepName:"Task Queued",data:{task_id:E.task_id,message:"Image generation task queued"}})):(l.error(E.error||"Failed to start image generation"),m(!1),C(null),c({timestamp:new Date().toISOString(),type:"error",action:"generate_images",data:{error:E.error||"Failed to start image generation"}}))}catch(o){console.error("[Generate Images] Exception:",o),l.error(`Failed to initialize image generation: ${o.message}`)}},[l,h,ie]),de=n.useCallback(t=>{if(!t||!t.image_path||!(k=>k.startsWith("http://")||k.startsWith("https://")?!1:k.includes("ai-images"))(t.image_path))return null;if(t.image_path.includes("ai-images")){const k=t.image_path.split("ai-images/")[1]||t.image_path.split("ai-images\\")[1];if(k)return`/images/ai-images/${k}`}if(t.image_path.startsWith("/images/"))return t.image_path;const b=t.image_path.split("/").pop()||t.image_path.split("\\").pop();return b?`/images/ai-images/${b}`:null},[]),ue=n.useCallback((t,o,b)=>{const k=h.find(j=>j.content_id===t);if(!k)return;let $=null;if(o==="featured"&&k.featured_image?$=k.featured_image:o==="in_article"&&b&&($=k.in_article_images.find(j=>j.position===b)||null),$&&$.status==="generated"){const j=de($);j&&(oe(j),ne(!0))}},[h,de]),ge=n.useMemo(()=>{if(h.length===0)return 5;const t=Math.max(...h.map(o=>o.in_article_images.length));return Math.max(t,5)},[h]),D=n.useMemo(()=>qe({searchTerm:i,setSearchTerm:S,statusFilter:y,setStatusFilter:F,setCurrentPage:L,maxInArticleImages:ge,onGenerateImages:ce,onImageClick:ue}),[i,y,ge,ce,ue]),Ce=n.useMemo(()=>D!=null&&D.headerMetrics?D.headerMetrics.map(t=>({label:t.label,value:t.calculate({images:h,totalCount:W}),accentColor:t.accentColor})):[],[D==null?void 0:D.headerMetrics,h,W]);return e.jsxs(e.Fragment,{children:[e.jsx(We,{title:"Content Images",badge:{icon:e.jsx(fe,{}),color:"orange"}}),e.jsx(Ue,{columns:D.columns,data:h,loading:U,showContent:s,filters:D.filters,filterValues:{search:i,status:y},onFilterChange:(t,o)=>{const b=o==null?"":String(o);t==="search"?S(b):t==="status"&&F(b),L(1)},onBulkExport:Se,onBulkAction:Ne,getItemDisplayName:t=>t.content_title||`Content #${t.content_id}`,onExport:async()=>{l.info("Export functionality coming soon")},onExportIcon:e.jsx(Te,{}),selectionLabel:"content",pagination:{currentPage:Q,totalPages:H,totalCount:W,onPageChange:L},selection:{selectedIds:d,onSelectionChange:V},sorting:{sortBy:O,sortDirection:a,onSort:Ie},headerMetrics:Ce,onFilterReset:()=>{S(""),F(""),L(1)},onRowAction:_e}),e.jsx(Ve,{isOpen:r,onClose:()=>{m(!1),_([]),x(null),C(null),B(null),se(null),G()},queue:p,totalImages:p.length,taskId:R,model:A||void 0,provider:be||void 0,onUpdateQueue:_,onLog:c}),e.jsx(ze,{isOpen:ye,onClose:()=>{Y(!1),ee(null),te("")},onConfirm:we,title:"Update Image Status",recordName:ve,statusOptions:[{value:"pending",label:"Pending"},{value:"generated",label:"Generated"},{value:"failed",label:"Failed"}],isLoading:ke}),e.jsx(ae,{isOpen:je,onClose:()=>{ne(!1),oe(null)},className:"max-w-[800px] w-full mx-4",children:le&&e.jsx("div",{className:"p-6",children:e.jsx("img",{src:le,alt:"Content image",className:"w-full h-auto object-contain rounded-lg",style:{maxHeight:"90vh"}})})}),T&&M.length>0&&e.jsxs("div",{className:"mt-6 bg-gray-50 dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"AI Function Logs"}),e.jsx("button",{onClick:()=>u([]),className:"text-xs text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200",children:"Clear Logs"})]}),e.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:M.slice().reverse().map((t,o)=>e.jsxs("div",{className:`p-3 rounded border text-xs font-mono ${t.type==="request"?"bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800":t.type==="success"?"bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800":t.type==="error"?"bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800":"bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:`font-semibold ${t.type==="request"?"text-blue-700 dark:text-blue-300":t.type==="success"?"text-green-700 dark:text-green-300":t.type==="error"?"text-red-700 dark:text-red-300":"text-purple-700 dark:text-purple-300"}`,children:["[",t.type.toUpperCase(),"]"]}),e.jsx("span",{className:"text-gray-700 dark:text-gray-300",children:t.action}),t.stepName&&e.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-gray-200 dark:bg-gray-700 text-gray-600 dark:text-gray-400",children:t.stepName}),t.percentage!==void 0&&e.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[t.percentage,"%"]})]}),e.jsx("span",{className:"text-gray-500 dark:text-gray-400",children:new Date(t.timestamp).toLocaleTimeString()})]}),e.jsx("pre",{className:"text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words",children:JSON.stringify(t.data,null,2)})]},o))})]})]})}export{dt as default};
|