1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[84881],{84881:function(e,a,t){t.d(a,{H:function(){return d},a:function(){return u}});var o=t(57437),r=t(2265),n=t(99376),s=t(71837),i=t(69064),l=t(5442);let c=(0,r.createContext)(void 0);function d(e){let{children:a}=e,[t,d]=(0,r.useState)(null),[u,m]=(0,r.useState)(!0),[g,p]=(0,r.useState)(null),[h,f]=(0,r.useState)([]),[y,v]=(0,r.useState)(null),[_,w]=(0,r.useState)(null),[b,P]=(0,r.useState)(null),[E,S]=(0,r.useState)([]),k=(0,n.useRouter)(),I=(0,r.useMemo)(()=>(null==t?void 0:t.user_type)||null,[t]),A=(0,r.useMemo)(()=>(null==t?void 0:t.organization_type)||null,[t]),T=(0,r.useMemo)(()=>"internal"===A||(null==I?void 0:I.startsWith("internal_"))||!1,[A,I]),x=(0,r.useMemo)(()=>"customer"===A||(null==I?void 0:I.startsWith("customer_"))||!1,[A,I]),q=(0,r.useMemo)(()=>"internal_superadmin"===I||"customer_superadmin"===I||"super_admin"===I,[I]),C=(0,r.useMemo)(()=>"customer_superadmin"===I||"super_admin"===I||h.includes("users:write")||!1,[I,h]),L=(0,r.useMemo)(()=>"super_admin"===y||"admin"===y,[y]),Y=(0,r.useMemo)(()=>"super_admin"===y,[y]),U=(0,r.useMemo)(()=>e=>h.includes(e),[h]),M=(0,r.useMemo)(()=>function(){for(var e=arguments.length,a=Array(e),t=0;t<e;t++)a[t]=arguments[t];return a.some(e=>h.includes(e))},[h]),N=(0,r.useMemo)(()=>function(){for(var e=arguments.length,a=Array(e),t=0;t<e;t++)a[t]=arguments[t];return a.every(e=>h.includes(e))},[h]);(0,r.useEffect)(()=>{R()},[]);let R=async()=>{var e,a;try{{let e=new URLSearchParams(window.location.search),a=e.get("access_token"),t=e.get("refresh_token"),o=e.get("oauth_success");a&&t&&"true"===o&&(localStorage.setItem("access_token",a),localStorage.setItem("refresh_token",t),console.log("OAuth tokens captured from URL"),window.history.replaceState({},"",window.location.pathname))}let a=localStorage.getItem("access_token");if(!a){m(!1);return}p(a),s.api.defaults.headers.common.Authorization="Bearer ".concat(a);try{let e=await s.api.get("/auth/me");console.log("User authenticated:",e.data),d(e.data),localStorage.setItem("user",JSON.stringify(e.data)),e.data.workspace_id&&localStorage.setItem("workspace_id",e.data.workspace_id);try{let e=(await s.api.get("/auth/me/role-info")).data;f(e.permissions||[]),v(e.enterprise_role||null),w(e.enterprise_tier||null),S(e.accessible_workspaces||[]),e.custom_role&&P({id:e.custom_role.id,name:e.custom_role.name,permissions:e.custom_role.permissions||[],color:e.custom_role.color})}catch(e){console.warn("Failed to fetch role info:",e)}}catch(a){if((null==a?void 0:null===(e=a.response)||void 0===e?void 0:e.status)!==401){let e=localStorage.getItem("user");if(e)try{let a=JSON.parse(e);console.warn("Backend unreachable, using cached user data"),d(a),m(!1);return}catch(e){}if(g&&g.startsWith("demo_token_")){m(!1);return}}throw a}}catch(e){(null==e?void 0:null===(a=e.response)||void 0===a?void 0:a.status)===401?(localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),delete s.api.defaults.headers.common.Authorization,p(null)):console.warn("Auth check failed (backend may be restarting):",null==e?void 0:e.message)}finally{m(!1)}},W=async(e,a)=>{console.log("Login attempt with email:",e);try{var t;if(console.log("Checking demo credentials..."),"[email protected]"===e&&"AdminPass123!"===a){console.log("Demo credentials matched!");let e={id:"1",email:"[email protected]",username:"admin",full_name:"Admin User",is_active:!0,is_verified:!0,is_superuser:!0,created_at:new Date().toISOString()};localStorage.setItem("access_token","demo_token_"+Date.now()),localStorage.setItem("refresh_token","demo_refresh_"+Date.now()),localStorage.setItem("user",JSON.stringify(e)),localStorage.setItem("onboarding_completed","true"),localStorage.setItem("setup_completed","true"),localStorage.removeItem("needs_onboarding"),d(e),console.log("User set, showing toast and redirecting..."),i.default.success("Login successful!"),k.push("/dashboard");return}console.log("Demo credentials did not match, trying backend...");let o=new URLSearchParams;o.append("username",e),o.append("password",a);let r=await s.api.post("/auth/login",o,{headers:{"Content-Type":"application/x-www-form-urlencoded"}}),{access_token:n,refresh_token:l}=r.data;localStorage.setItem("access_token",n),localStorage.setItem("refresh_token",l),p(n),s.api.defaults.headers.common.Authorization="Bearer ".concat(n);let c=r.data.requires_onboarding,u=r.data.onboarding_redirect,m=r.data.onboarding_progress,g=(await s.api.get("/auth/me")).data;d(g);try{await s.api.post("/agent-status/go-online")}catch(e){console.warn("Failed to set online status:",e)}let h=g.onboarding_status;i.default.success("Login successful!");let f=((null==g?void 0:g.role)||"").toLowerCase(),y=((null==g?void 0:null===(t=g.settings)||void 0===t?void 0:t.dashboard_role)||"").toLowerCase(),v=["sales_agent","agent","employee","staff"],_=v.includes(f)||v.includes(y),w=((null==g?void 0:g.email)||"").toLowerCase(),b="[email protected]"===w?"/dashboard/ai-poc":_?"/dashboard/staff-dashboard":"/dashboard";!0===c?(localStorage.removeItem("onboarding_completed"),localStorage.setItem("needs_onboarding","true"),m&&localStorage.setItem("onboarding_progress",JSON.stringify(m)),
1k.push(u||"/onboarding")):"completed"===h||!1===c?(localStorage.setItem("onboarding_completed","true"),localStorage.removeItem("needs_onboarding"),localStorage.removeItem("onboarding_progress"),k.push(b)):"completed"===h?(localStorage.setItem("onboarding_completed","true"),localStorage.removeItem("needs_onboarding"),k.push(b)):(localStorage.removeItem("onboarding_completed"),localStorage.setItem("needs_onboarding","true"),k.push("/onboarding"))}catch(a){console.error("Login error:",a);let e=(0,l.Yo)(a);throw i.default.error(e),a}},z=async e=>{try{let{access_token:a,refresh_token:t,user:o}=(await s.api.post("/auth/register",e)).data;localStorage.setItem("access_token",a||""),localStorage.setItem("refresh_token",t||""),p(a||null),localStorage.removeItem("onboarding_completed"),localStorage.removeItem("setup_completed"),localStorage.removeItem("post_registration_onboarding_completed"),localStorage.setItem("needs_onboarding","true"),a&&(s.api.defaults.headers.common.Authorization="Bearer ".concat(a),d(o)),i.default.success("Registration successful! Let's set up your account."),k.push("/onboarding")}catch(a){let e=(0,l.Yo)(a);throw i.default.error(e),a}},O=async()=>{try{try{await s.api.post("/agent-status/go-offline")}catch(e){console.warn("Failed to set offline status:",e)}await s.api.post("/auth/logout")}catch(e){console.error("Logout error:",e)}finally{localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),localStorage.removeItem("completed_tours"),delete s.api.defaults.headers.common.Authorization,d(null),p(null),k.push("/login"),i.default.success("Logged out successfully")}},B=async()=>{try{let e=localStorage.getItem("refresh_token");if(!e)throw Error("No refresh token");let{access_token:a,refresh_token:t}=(await s.api.post("/auth/refresh",{refresh_token:e})).data;localStorage.setItem("access_token",a),localStorage.setItem("refresh_token",t),p(a),s.api.defaults.headers.common.Authorization="Bearer ".concat(a)}catch(e){throw await O(),e}},F=async()=>{try{let e=(await s.api.get("/auth/me")).data;return d(e),localStorage.setItem("user",JSON.stringify(e)),e.workspace_id&&localStorage.setItem("workspace_id",e.workspace_id),await D(),e}catch(e){return console.error("Failed to refresh user:",e),null}},D=async()=>{try{let e=(await s.api.get("/auth/me/role-info")).data;f(e.permissions||[]),v(e.enterprise_role||null),w(e.enterprise_tier||null),S(e.accessible_workspaces||[]),e.custom_role?P({id:e.custom_role.id,name:e.custom_role.name,permissions:e.custom_role.permissions||[],color:e.custom_role.color}):P(null)}catch(e){console.warn("Failed to fetch role info, using defaults:",e),f([]),v(null),w(null),P(null),S([])}},J=async(e,a)=>{try{var t;let{access_token:o,refresh_token:r,user:n}=(await s.api.post("/auth/login/local",{email:e,password:a})).data;localStorage.setItem("access_token",o),localStorage.setItem("refresh_token",r),p(o),s.api.defaults.headers.common.Authorization="Bearer ".concat(o),d(n),localStorage.setItem("user",JSON.stringify(n)),n.workspace_id&&localStorage.setItem("workspace_id",n.workspace_id);try{await s.api.post("/agent-status/go-online")}catch(e){console.warn("Failed to set online status:",e)}let l=n.onboarding_status;i.default.success("Login successful!");let c=((null==n?void 0:n.role)||"").toLowerCase(),u=((null==n?void 0:null===(t=n.settings)||void 0===t?void 0:t.dashboard_role)||"").toLowerCase(),m=["sales_agent","agent","employee","staff"],g=m.includes(c)||m.includes(u),h=((null==n?void 0:n.email)||"").toLowerCase();"completed"===l?(localStorage.setItem("onboarding_completed","true"),localStorage.removeItem("needs_onboarding"),k.push("[email protected]"===h?"/dashboard/ai-poc":g?"/dashboard/staff-dashboard":"/dashboard")):(localStorage.removeItem("onboarding_completed"),localStorage.setItem("needs_onboarding","true"),k.push("/onboarding"))}catch(a){console.error("Local login error:",a);let e=(0,l.Yo)(a);throw i.default.error(e),a}};return(0,o.jsx)(c.Provider,{value:{user:t,loading:u,token:g,userType:I,organizationType:A,isInternalUser:T,isCustomerUser:x,isSuperAdmin:q,canManageUsers:C,permissions:h,hasPermission:U,hasAnyPermission:M,hasAllPermissions:N,enterpriseRole:y,enterpriseTier:_,customRole:b,accessibleWorksp
1aces:E,canManageRoles:L,canGrantWorkspaceAccess:Y,login:W,loginLocal:J,register:z,logout:O,refreshToken:B,refreshUser:F,refreshPermissions:D,setUser:d},children:a})}let u=()=>{let e=(0,r.useContext)(c);if(void 0===e)throw Error("useAuth must be used within an AuthProvider");return e}},5442:function(e,a,t){t.d(a,{Yo:function(){return s},_V:function(){return n}});let o={E1001:"Your session has expired. Please log in again.",E1002:"Invalid authentication. Please log in again.",E1003:"Please log in to continue.",E1004:"You do not have permission to perform this action.",E1005:"Your account has been suspended. Please contact support.",E1006:"Your session has expired. Please log in again.",E1007:"Two-factor authentication is required.",E1008:"Invalid password.",E2001:"Please check your input and try again.",E2002:"This field is required.",E2003:"Invalid value provided.",E2004:"Invalid format. Please check your input.",E2005:"This value already exists.",E2006:"Value length is invalid.",E3001:"The requested item was not found.",E3002:"This item already exists.",E3003:"This item has been deleted.",E3004:"This item is currently locked. Please try again later.",E3005:"A conflict occurred. This item may already exist.",E3006:"Workspace not found.",E3007:"Lead not found.",E3008:"Campaign not found.",E3009:"Contact not found.",E3010:"Template not found.",E4001:"You don't have enough credits for this action.",E4002:"Credit service is temporarily unavailable. Please try again.",E4003:"Credit limit exceeded.",E4004:"You've reached your plan limit. Please upgrade to continue.",E4005:"This feature is not available on your current plan.",E4006:"Your subscription has expired. Please renew to continue.",E4007:"Payment failed. Please try again or use a different payment method.",E4008:"Payment is required to continue.",E4009:"Your trial has expired. Please upgrade to continue.",E4010:"You've exceeded your quota.",E5001:"Unable to connect to external service. Please try again.",E5003:"Unable to connect to Meta. Please try again later.",E5004:"Rate limit reached. Please wait a moment and try again.",E5007:"WhatsApp service error. Please try again.",E5008:"Email service error. Please try again.",E5009:"SMS service error. Please try again.",E5010:"AI service error. Please try again.",E5013:"External service timed out. Please try again.",E5014:"External service is unavailable. Please try again later.",E6001:"Too many requests. Please wait a moment.",E6002:"Hourly limit reached. Please try again later.",E6003:"Daily limit reached. Please try again tomorrow.",E6004:"Too many requests. Please slow down.",E6005:"API rate limit reached.",E6006:"Too many concurrent requests.",E7001:"Database error occurred. Please try again.",E7002:"Sync conflict detected. Please refresh and try again.",E7003:"Sync failed. Please try again.",E7004:"Transaction failed. Please try again.",E7005:"Connection error. Please try again.",E8001:"Failed to create payment order. Please try again.",E8002:"Payment verification failed. Please contact support if you were charged.",E8003:"A similar payment was recently completed. Please wait before retrying.",E8004:"Another payment operation is in progress. Please wait.",E8005:"Payment order has expired. Please create a new order.",E8006:"Payment amount does not match the order.",E8007:"This payment has already been processed.",E8008:"Payment gateway error. Please try again.",E8009:"Payment signature verification failed.",E8010:"Payment order not found.",E8011:"Refund processing failed. Please contact support.",E8012:"Insufficient balance for this operation.",E8013:"A payment request is already being processed. Please wait.",E9001:"Something went wrong. Please try again later.",E9002:"Service temporarily unavailable. Please try again later.",E9003:"Configuration error. Please contact support.",E9004:"System is under maintenance. Please try again later.",E9999:"Network error. Please check your internet connection."},r={sqlalchemy:"Service temporarily unavailable. Please try again later.",database:"Service temporarily unavailable. Please try again later.",psycopg:"Service temporarily unavailable. Please try again later.",mysql:"Service temporarily unavailable. Please try again later.",mongodb:"Service temporarily unavailable. Please try again later.",redis:"Service temporarily unavailable. Please try again later.","connection refused":"Service temporarily unavailable. Please try again later.","connection error":"Unable to connect to server. Please check your internet connection.","connection reset":"Connection interrupted. Please try again.",timeout:"Request timed out. Please try again.","timed out":"Request timed out. Please try again.",unauthorized:"Your session has expired. Please log in again.","invali
1d credentials":"Invalid email or password. Please try again.","invalid token":"Your session has expired. Please log in again.","token expired":"Your session has expired. Please log in again.",forbidden:"You do not have permission to perform this action.","access denied":"You do not have permission to perform this action.","already exists":"This email is already registered. Please sign in or use a different email.","already registered":"This email is already registered. Please sign in or use a different email.","email already":"This email is already registered. Please sign in or use a different email.",duplicate_email:"This email is already registered. Please sign in or use a different email.",duplicate_username:"This email is already registered. Please sign in or use a different email.","email does not match":"The email does not match the invitation. Please use the invited email address.","invalid invitation":"This invitation link is invalid or has expired.","invitation has expired":"This invitation link has expired. Please request a new one.","invitation has already been used":"This invitation has already been used.","invitation has been cancelled":"This invitation has been cancelled.","whatsapp not connected":"WhatsApp is not connected. Please connect your WhatsApp Business account first.","whatsapp business account id not configured":"WhatsApp Business Account is not configured. Please set up WhatsApp in settings.","template not found":"Template not found. It may have been deleted.","failed to delete template":"Failed to delete template. Please try again.","meta api error":"WhatsApp API error. Please check your template format and try again.","whatsapp api error":"WhatsApp API error. Please try again later.","template name already exists":"A template with this name already exists. Please use a different name.","invalid template name":"Invalid template name. Use only lowercase letters, numbers, and underscores.","template body too long":"Template body is too long. Please shorten your message.","invalid parameter format":"Invalid parameter format. Use {{1}}, {{2}}, etc. for variables.","too many buttons":"Too many buttons. Maximum 3 buttons allowed.","invalid button type":"Invalid button type. Use URL, PHONE_NUMBER, or QUICK_REPLY.","missing required field":"Missing required field. Please fill in all required fields.","network error":"Unable to connect. Please check your internet connection.","fetch failed":"Unable to connect. Please check your internet connection.","failed to fetch":"Unable to connect. Please check your internet connection.",econnrefused:"Service temporarily unavailable. Please try again later.",enotfound:"Service temporarily unavailable. Please try again later.","socket hang up":"Connection interrupted. Please try again.","internal server error":"Something went wrong on our end. Please try again later.","server error":"Something went wrong on our end. Please try again later.","rate limit":"Too many requests. Please wait a moment and try again.","too many requests":"Too many requests. Please wait a moment and try again.","not found":"The requested resource was not found."};function n(e){var a,t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"Something went wrong. Please try again.",i=(null==e?void 0:null===(a=e.response)||void 0===a?void 0:a.data)||e;if(i&&!1===i.success&&i.error){let e=i.error;if(o[e])return o[e];if(i.message&&!/^E\d+$/.test(i.message)&&i.message.length>3){let e=i.message.replace(/\bE\d{4}\b/g,"").trim();if(e&&e.length>3)return e}}let l=s(e),c=l.toLowerCase();if(/^E\d+$/.test(l))return o[l]||n;let d=l.match(/^(E\d+)[:\s]*/);if(d){let e=d[1];if(o[e])return o[e];let a=l.replace(/^E\d+[:\s]*/,"").trim();if(a&&a.length>3&&!/^E\d+$/.test(a))return a}for(let[e,a]of Object.entries(r))if(c.includes(e.toLowerCase()))return a;let u=(null==e?void 0:null===(t=e.response)||void 0===t?void 0:t.status)||(null==e?void 0:e.status);if(u){if(401===u)return r.unauthorized;if(403===u)return r.forbidden;if(404===u)return r["not found"];if(429===u)return r["rate limit"];if(u>=500)return r["internal server error"]}return[/traceback/i,/exception/i,/error\s+at\s+line/i,/stack\s*trace/i,/file\s+"[^"]+",\s+line\s+\d+/i,/\w+Error:/,/\w+Exception:/,/at\s+\w+\.\w+\s*\(/,/sqlalchemy\./i,/psycopg2?\./i,/mysql\./i,/mongodb\./i,/redis\./i,/operationalerror/i,/programmingerror/i,/integrityerror/i].some(e=>e.test(l))||l.length>150?n:l.replace(/\bE\d{4}\b/g,"").trim()||n}function s(e){var a;return(null==e?void 0:e.detail)&&Array.isArray(e.detail)?e.detail.map(e=>"string"==typeof e?e:(null==e?void 0:e.msg)?e.msg:(null==e?void 0:e.message)?e.message:"Validation error").join(", "):"str
1ing"==typeof(null==e?void 0:e.detail)?e.detail:"string"==typeof(null==e?void 0:e.message)||e instanceof Error?e.message:"string"==typeof e?e:(null==e?void 0:null===(a=e.response)||void 0===a?void 0:a.data)?s(e.response.data):"An unexpected error occurred"}}}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.