@dropins/storefront-company-management 1.0.0-beta22 → 1.0.0-beta24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
1
  /*! Copyright 2025 Adobe
2
2
  All Rights Reserved. */
3
- import{f as d,h as a}from"./network-error.js";import{h as l}from"./fetch-error.js";import{t as g}from"./validateCompanyEmail.js";const u=`
3
+ import{f as m,h as p}from"./network-error.js";import{h as u}from"./fetch-error.js";import{t as _}from"./validateCompanyEmail.js";const y=`
4
4
  query getStoreConfig {
5
5
  storeConfig {
6
6
  default_country
7
7
  store_code
8
8
  }
9
9
  }
10
- `,p="US",s={defaultCountry:p,storeCode:""},T=async()=>await d(u,{method:"GET"}).then(e=>{var r;return(r=e.errors)!=null&&r.length?l(e.errors):m(e)}).catch(a),m=e=>{var t;if(!((t=e==null?void 0:e.data)!=null&&t.storeConfig))return s;const{default_country:r,store_code:o}=e.data.storeConfig;return{defaultCountry:r||s.defaultCountry,storeCode:o||s.storeCode}},_=`
10
+ `,C="US",d={defaultCountry:C,storeCode:""},G=async()=>await m(y,{method:"GET"}).then(e=>{var n;return(n=e.errors)!=null&&n.length?u(e.errors):h(e)}).catch(p),h=e=>{var t;if(!((t=e==null?void 0:e.data)!=null&&t.storeConfig))return d;const{default_country:n,store_code:r}=e.data.storeConfig;return{defaultCountry:n||d.defaultCountry,storeCode:r||d.storeCode}},T=`
11
11
  mutation CreateCompany($input: CompanyCreateInput!) {
12
12
  createCompany(input: $input) {
13
13
  company {
@@ -40,5 +40,5 @@ import{f as d,h as a}from"./network-error.js";import{h as l}from"./fetch-error.j
40
40
  }
41
41
  }
42
42
  }
43
- `,y=e=>{var o,t,i;const r={};if(e.regionCode&&e.regionCode.trim())r.region_code=e.regionCode.trim(),e.regionId&&(r.region_id=typeof e.regionId=="string"?parseInt(e.regionId,10):e.regionId);else if(e.region&&typeof e.region=="string"&&e.region.includes(",")){const[n,c]=e.region.split(",");r.region_code=n.trim(),r.region_id=parseInt(c.trim(),10)}else if(e.region&&e.region.trim()){const n=e.region.trim();if(/^\d+$/.test(n))throw new Error("Region selection error: Missing region code. Please ensure regions are properly loaded.");r.region=n,r.region_code=n}if(!r.region_code)throw new Error("Region code is required. Please select a state/province or enter a region name.");return{company_name:e.companyName,company_email:e.companyEmail,legal_name:e.legalName,vat_tax_id:e.vatTaxId,reseller_id:e.resellerId,legal_address:{street:Array.isArray(e.street)?e.street.filter(n=>n&&n.trim()!==""):[e.street].filter(n=>n&&n.trim()!==""),city:e.city,region:r,postcode:e.postcode,country_id:e.countryCode,telephone:e.addressTelephone},company_admin:{email:e.adminEmail,firstname:((o=e.adminFirstname)==null?void 0:o.trim())||"",lastname:((t=e.adminLastname)==null?void 0:t.trim())||"",job_title:e.adminJobTitle,telephone:e.adminWorkTelephone,gender:e.adminGender?typeof e.adminGender=="string"?parseInt(e.adminGender,10):e.adminGender:void 0,custom_attributes:((i=e.adminCustomAttributes)==null?void 0:i.map(n=>({attribute_code:n.attribute_code,value:n.value})))||[]}}},E=async e=>{var r;try{const o=y(e),t=await d(_,{method:"POST",variables:{input:o}});return(r=t.errors)!=null&&r.length?{success:!1,errors:t.errors.map(n=>n.message)}:{success:!0,company:g(t)}}catch(o){return console.error("Failed to create company:",o),{success:!1,errors:["Failed to create company. Please try again."]}}};export{p as D,s as S,E as c,T as g};
43
+ `,E=e=>{var s,i,a,c,l;const n=(s=e.regionCode)==null?void 0:s.trim(),r=(i=e.region)==null?void 0:i.trim();let t;if(n)t={region_code:n,...e.regionId&&{region_id:typeof e.regionId=="string"?parseInt(e.regionId,10):e.regionId}};else if(r!=null&&r.includes(",")){const[o,g]=r.split(",");t={region_code:o.trim(),region_id:parseInt(g.trim(),10)}}else{if(r&&/^\d+$/.test(r))throw new Error("Region selection error: Missing region code. Please ensure regions are properly loaded.");r?t={region:r,region_code:r}:t={region:"",region_code:"",region_id:0}}return{company_name:e.companyName||"",company_email:e.companyEmail||"",legal_name:e.legalName,vat_tax_id:e.vatTaxId,reseller_id:e.resellerId,legal_address:{street:Array.isArray(e.street)?e.street.filter(o=>typeof o=="string"&&o.trim()!==""):[e.street].filter(o=>typeof o=="string"&&o.trim()!==""),city:e.city||"",region:t,postcode:e.postcode||"",country_id:e.countryCode||"",telephone:e.addressTelephone},company_admin:{email:e.adminEmail||"",firstname:((a=e.adminFirstname)==null?void 0:a.trim())||"",lastname:((c=e.adminLastname)==null?void 0:c.trim())||"",job_title:e.adminJobTitle,telephone:e.adminWorkTelephone,gender:e.adminGender?typeof e.adminGender=="string"?parseInt(e.adminGender,10):e.adminGender:void 0,custom_attributes:((l=e.adminCustomAttributes)==null?void 0:l.map(o=>({attribute_code:o.attribute_code,value:o.value})))||[]}}},S=async e=>{var n;try{const r=E(e),t=await m(T,{method:"POST",variables:{input:r}});return(n=t.errors)!=null&&n.length?{success:!1,errors:t.errors.map(i=>i.message)}:{success:!0,company:_(t)}}catch(r){return console.error("Failed to create company:",r),{success:!1,errors:["Failed to create company. Please try again."]}}};export{C as D,d as S,S as c,G as g};
44
44
  //# sourceMappingURL=createCompany.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"createCompany.js","sources":["/@dropins/storefront-company-management/src/api/getStoreConfig/graphql/getStoreConfig.graphql.ts","/@dropins/storefront-company-management/src/api/getStoreConfig/getStoreConfig.ts","/@dropins/storefront-company-management/src/data/transforms/transform-store-config.ts","/@dropins/storefront-company-management/src/api/createCompany/graphql/createCompany.graphql.ts","/@dropins/storefront-company-management/src/data/transforms/company.ts","/@dropins/storefront-company-management/src/api/createCompany/createCompany.ts"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nexport const GET_STORE_CONFIG_QUERY = /* GraphQL */ `\n query getStoreConfig {\n storeConfig {\n default_country\n store_code\n }\n }\n`;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { fetchGraphQl } from '../fetch-graphql';\nimport { GET_STORE_CONFIG_QUERY } from './graphql/getStoreConfig.graphql';\nimport { handleNetworkError } from '@/company-management/lib/network-error';\nimport { handleFetchError } from '@/company-management/lib/fetch-error';\nimport { GetStoreConfigResponse, StoreConfigModel } from '@/company-management/types';\nimport { transformStoreConfig } from '@/company-management/data/transforms';\n\nexport const DEFAULT_COUNTRY = 'US';\n\nexport const STORE_CONFIG_DEFAULTS: StoreConfigModel = {\n defaultCountry: DEFAULT_COUNTRY,\n storeCode: '',\n};\n\nexport const getStoreConfig = async (): Promise<StoreConfigModel> => {\n return await fetchGraphQl(GET_STORE_CONFIG_QUERY, {\n method: 'GET',\n })\n .then((response: GetStoreConfigResponse) => {\n if (response.errors?.length) return handleFetchError(response.errors);\n\n return transformStoreConfig(response);\n })\n .catch(handleNetworkError);\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { GetStoreConfigResponse, StoreConfigModel } from '@/company-management/types';\nimport { STORE_CONFIG_DEFAULTS } from '@/company-management/api/getStoreConfig/getStoreConfig';\n\nexport const transformStoreConfig = (\n response: GetStoreConfigResponse\n): StoreConfigModel => {\n if (!response?.data?.storeConfig) return STORE_CONFIG_DEFAULTS;\n\n const { default_country, store_code } = response.data.storeConfig;\n\n return {\n defaultCountry: default_country || STORE_CONFIG_DEFAULTS.defaultCountry,\n storeCode: store_code || STORE_CONFIG_DEFAULTS.storeCode,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nexport const CREATE_COMPANY_MUTATION = /* GraphQL */ `\n mutation CreateCompany($input: CompanyCreateInput!) {\n createCompany(input: $input) {\n company {\n id\n name\n email\n legal_name\n vat_tax_id\n reseller_id\n legal_address {\n street\n city\n region {\n region_code\n region\n region_id\n }\n postcode\n country_code\n telephone\n }\n company_admin {\n id\n firstname\n lastname\n email\n job_title\n telephone\n }\n }\n }\n }\n`;","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { CompanyFormData } from '../models/company';\nimport { CompanyCreateInput } from '@/company-management/api/createCompany';\n\nexport const transformFormDataToCreateInput = (formData: CompanyFormData): CompanyCreateInput => {\n // Build region object - ensure we have at least one region field\n const regionInput: any = {};\n \n // Handle region data based on what we receive from the form\n if (formData.regionCode && formData.regionCode.trim()) {\n // We have regionCode (preferred path)\n regionInput.region_code = formData.regionCode.trim();\n if (formData.regionId) {\n regionInput.region_id = typeof formData.regionId === 'string' ? parseInt(formData.regionId, 10) : formData.regionId;\n }\n } else if (formData.region && typeof formData.region === 'string' && formData.region.includes(',')) {\n // Dropdown selection: parse \"AL,4\" format as fallback\n const [regionCode, regionId] = formData.region.split(',');\n regionInput.region_code = regionCode.trim();\n regionInput.region_id = parseInt(regionId.trim(), 10);\n } else if (formData.region && formData.region.trim()) {\n const regionValue = formData.region.trim();\n // Check if this is a numeric regionId (from dropdown) or text region name\n if (/^\\d+$/.test(regionValue)) {\n // This is likely a regionId from dropdown, but we only have the ID\n // We need both region_code and region_id for GraphQL, but we can't proceed without region_code\n throw new Error('Region selection error: Missing region code. Please ensure regions are properly loaded.');\n } else {\n // Text input: free-form region name (countries without predefined regions)\n regionInput.region = regionValue;\n regionInput.region_code = regionValue;\n }\n }\n \n // Ensure we have at least region_code (required by GraphQL)\n if (!regionInput.region_code) {\n throw new Error('Region code is required. Please select a state/province or enter a region name.');\n }\n\n return {\n company_name: formData.companyName,\n company_email: formData.companyEmail,\n legal_name: formData.legalName,\n vat_tax_id: formData.vatTaxId,\n reseller_id: formData.resellerId,\n legal_address: {\n street: Array.isArray(formData.street) \n ? formData.street.filter((line: string) => line && line.trim() !== '') // Remove empty lines\n : [formData.street].filter((line: string) => line && line.trim() !== ''), // Handle case where street is not an array\n city: formData.city,\n region: regionInput,\n postcode: formData.postcode,\n country_id: formData.countryCode,\n telephone: formData.addressTelephone,\n },\n company_admin: {\n email: formData.adminEmail,\n firstname: formData.adminFirstname?.trim() || '',\n lastname: formData.adminLastname?.trim() || '',\n job_title: formData.adminJobTitle,\n telephone: formData.adminWorkTelephone,\n gender: formData.adminGender ? (typeof formData.adminGender === 'string' ? parseInt(formData.adminGender, 10) : formData.adminGender) : undefined,\n custom_attributes: formData.adminCustomAttributes?.map(attr => ({\n attribute_code: attr.attribute_code,\n value: attr.value,\n })) || [],\n },\n };\n};","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { fetchGraphQl } from '@/company-management/api/fetch-graphql';\nimport { CREATE_COMPANY_MUTATION } from './graphql/createCompany.graphql';\nimport { CompanyRegistrationModel } from '@/company-management/data/models/company';\nimport { transformFormDataToCreateInput } from '@/company-management/data/transforms/company';\nimport { transformCreateCompanyResponse } from '@/company-management/data/transforms/transform-company';\n\nexport interface CompanyCreateInput {\n company_name: string;\n company_email: string;\n legal_name?: string;\n vat_tax_id?: string;\n reseller_id?: string;\n legal_address: {\n street: string[];\n city: string;\n region: {\n region_code: string;\n region?: string;\n region_id?: number;\n };\n postcode: string;\n country_id: string;\n telephone?: string;\n };\n company_admin: {\n email: string;\n firstname: string;\n lastname: string;\n job_title?: string;\n telephone?: string;\n gender?: number;\n custom_attributes?: Array<{\n attribute_code: string;\n value: string;\n }>;\n };\n}\n\n\nexport const createCompany = async (formData: any): Promise<{ success: boolean; company?: CompanyRegistrationModel; errors?: string[] }> => {\n try {\n const input = transformFormDataToCreateInput(formData);\n const response = await fetchGraphQl(CREATE_COMPANY_MUTATION, {\n method: 'POST',\n variables: { input },\n });\n\n if (response.errors?.length) {\n return {\n success: false,\n errors: response.errors.map((error: any) => error.message),\n };\n }\n\n // Transform the GraphQL response using the dedicated transformer\n const transformedCompany = transformCreateCompanyResponse(response);\n\n return {\n success: true,\n company: transformedCompany,\n };\n } catch (error) {\n console.error('Failed to create company:', error);\n return {\n success: false,\n errors: ['Failed to create company. Please try again.'],\n };\n }\n};"],"names":["GET_STORE_CONFIG_QUERY","DEFAULT_COUNTRY","STORE_CONFIG_DEFAULTS","getStoreConfig","fetchGraphQl","response","_a","handleFetchError","transformStoreConfig","handleNetworkError","default_country","store_code","CREATE_COMPANY_MUTATION","transformFormDataToCreateInput","formData","regionInput","regionCode","regionId","regionValue","line","_b","_c","attr","createCompany","input","error","transformCreateCompanyResponse"],"mappings":"iIAiBO,MAAMA,EAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,ECOvCC,EAAkB,KAElBC,EAA0C,CACrD,eAAgBD,EAChB,UAAW,EACb,EAEaE,EAAiB,SACrB,MAAMC,EAAaJ,EAAwB,CAChD,OAAQ,KAAA,CACT,EACE,KAAMK,GAAqC,OAC1C,OAAIC,EAAAD,EAAS,SAAT,MAAAC,EAAiB,OAAeC,EAAiBF,EAAS,MAAM,EAE7DG,EAAqBH,CAAQ,CACtC,CAAC,EACA,MAAMI,CAAkB,ECpBhBD,EACXH,GACqB,OACrB,GAAI,GAACC,EAAAD,GAAA,YAAAA,EAAU,OAAV,MAAAC,EAAgB,aAAa,OAAOJ,EAEzC,KAAM,CAAE,gBAAAQ,EAAiB,WAAAC,CAAA,EAAeN,EAAS,KAAK,YAEtD,MAAO,CACL,eAAgBK,GAAmBR,EAAsB,eACzD,UAAWS,GAAcT,EAAsB,SAAA,CAEnD,ECdaU,EAAwC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,ECGxCC,EAAkCC,GAAkD,WAE/F,MAAMC,EAAmB,CAAA,EAGzB,GAAID,EAAS,YAAcA,EAAS,WAAW,OAE7CC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SAAW,SAASA,EAAS,YAAa,EAAE,EAAIA,EAAS,YAAe,OACxI,oBAAmBO,EAAAP,EAAS,wBAAT,YAAAO,EAAgC,IAAIC,IAAS,CAC9D,eAAgBA,EAAK,eACrB,MAAOA,EAAK,KAAA,MACP,CAAA,CAAC,CACV,CAEJ,EC5BaC,EAAgB,MAAOT,GAAwG,OAC1I,GAAI,CACF,MAAMU,EAAQX,EAA+BC,CAAQ,EAC/CT,EAAW,MAAMD,EAAaQ,EAAyB,CAC3D,OAAQ,OACR,UAAW,CAAE,MAAAY,CAAA,CAAM,CACpB,EAED,OAAIlB,EAAAD,EAAS,SAAT,MAAAC,EAAiB,OACZ,CACL,QAAS,GACT,OAAQD,EAAS,OAAO,IAAKoB,GAAeA,EAAM,OAAO,CAAA,EAOtD,CACL,QAAS,GACT,QAJyBC,EAA+BrB,CAAQ,CAIvD,CAEb,OAASoB,EAAO,CACd,eAAQ,MAAM,4BAA6BA,CAAK,EACzC,CACL,QAAS,GACT,OAAQ,CAAC,6CAA6C,CAAA,CAE1D,CACF"}
1
+ {"version":3,"file":"createCompany.js","sources":["/@dropins/storefront-company-management/src/api/getStoreConfig/graphql/getStoreConfig.graphql.ts","/@dropins/storefront-company-management/src/api/getStoreConfig/getStoreConfig.ts","/@dropins/storefront-company-management/src/data/transforms/transform-store-config.ts","/@dropins/storefront-company-management/src/api/createCompany/graphql/createCompany.graphql.ts","/@dropins/storefront-company-management/src/data/transforms/company.ts","/@dropins/storefront-company-management/src/api/createCompany/createCompany.ts"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nexport const GET_STORE_CONFIG_QUERY = /* GraphQL */ `\n query getStoreConfig {\n storeConfig {\n default_country\n store_code\n }\n }\n`;\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { fetchGraphQl } from '../fetch-graphql';\nimport { GET_STORE_CONFIG_QUERY } from './graphql/getStoreConfig.graphql';\nimport { handleNetworkError } from '@/company-management/lib/network-error';\nimport { handleFetchError } from '@/company-management/lib/fetch-error';\nimport { GetStoreConfigResponse, StoreConfigModel } from '@/company-management/types';\nimport { transformStoreConfig } from '@/company-management/data/transforms';\n\nexport const DEFAULT_COUNTRY = 'US';\n\nexport const STORE_CONFIG_DEFAULTS: StoreConfigModel = {\n defaultCountry: DEFAULT_COUNTRY,\n storeCode: '',\n};\n\nexport const getStoreConfig = async (): Promise<StoreConfigModel> => {\n return await fetchGraphQl(GET_STORE_CONFIG_QUERY, {\n method: 'GET',\n })\n .then((response: GetStoreConfigResponse) => {\n if (response.errors?.length) return handleFetchError(response.errors);\n\n return transformStoreConfig(response);\n })\n .catch(handleNetworkError);\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { GetStoreConfigResponse, StoreConfigModel } from '@/company-management/types';\nimport { STORE_CONFIG_DEFAULTS } from '@/company-management/api/getStoreConfig/getStoreConfig';\n\nexport const transformStoreConfig = (\n response: GetStoreConfigResponse\n): StoreConfigModel => {\n if (!response?.data?.storeConfig) return STORE_CONFIG_DEFAULTS;\n\n const { default_country, store_code } = response.data.storeConfig;\n\n return {\n defaultCountry: default_country || STORE_CONFIG_DEFAULTS.defaultCountry,\n storeCode: store_code || STORE_CONFIG_DEFAULTS.storeCode,\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nexport const CREATE_COMPANY_MUTATION = /* GraphQL */ `\n mutation CreateCompany($input: CompanyCreateInput!) {\n createCompany(input: $input) {\n company {\n id\n name\n email\n legal_name\n vat_tax_id\n reseller_id\n legal_address {\n street\n city\n region {\n region_code\n region\n region_id\n }\n postcode\n country_code\n telephone\n }\n company_admin {\n id\n firstname\n lastname\n email\n job_title\n telephone\n }\n }\n }\n }\n`;","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { CompanyFormData } from '../models/company';\nimport { CompanyCreateInput } from '@/company-management/api/createCompany';\n\nexport const transformFormDataToCreateInput = (formData: CompanyFormData): CompanyCreateInput => {\n // Build region object based on form data\n // Backend GraphQL schema requires region (CustomerAddressRegionInput!)\n const regionCode = formData.regionCode?.trim();\n const region = formData.region?.trim();\n \n let finalRegion: { region?: string; region_code: string; region_id?: number };\n \n if (regionCode) {\n // Preferred path: explicit regionCode from dropdown selection\n finalRegion = {\n region_code: regionCode,\n ...(formData.regionId && { \n region_id: typeof formData.regionId === 'string' ? parseInt(formData.regionId, 10) : formData.regionId \n }),\n };\n } else if (region?.includes(',')) {\n // Dropdown selection fallback: parse \"AL,4\" format\n const [code, id] = region.split(',');\n finalRegion = { region_code: code.trim(), region_id: parseInt(id.trim(), 10) };\n } else if (region && /^\\d+$/.test(region)) {\n // Numeric-only region without code - invalid state\n throw new Error('Region selection error: Missing region code. Please ensure regions are properly loaded.');\n } else if (region) {\n // Text input: free-form region name (countries without predefined regions)\n finalRegion = { region, region_code: region };\n } else {\n // No region data: countries like UK that don't require regions\n finalRegion = { region: '', region_code: '', region_id: 0 };\n }\n\n return {\n company_name: formData.companyName || '',\n company_email: formData.companyEmail || '',\n legal_name: formData.legalName,\n vat_tax_id: formData.vatTaxId,\n reseller_id: formData.resellerId,\n legal_address: {\n street: Array.isArray(formData.street) \n ? formData.street.filter((line): line is string => typeof line === 'string' && line.trim() !== '') // Remove empty lines\n : [formData.street].filter((line): line is string => typeof line === 'string' && line.trim() !== ''), // Handle case where street is not an array\n city: formData.city || '',\n region: finalRegion,\n postcode: formData.postcode || '',\n country_id: formData.countryCode || '',\n telephone: formData.addressTelephone,\n },\n company_admin: {\n email: formData.adminEmail || '',\n firstname: formData.adminFirstname?.trim() || '',\n lastname: formData.adminLastname?.trim() || '',\n job_title: formData.adminJobTitle,\n telephone: formData.adminWorkTelephone,\n gender: formData.adminGender ? (typeof formData.adminGender === 'string' ? parseInt(formData.adminGender, 10) : formData.adminGender) : undefined,\n custom_attributes: formData.adminCustomAttributes?.map((attr: { attribute_code: string; value: string }) => ({\n attribute_code: attr.attribute_code,\n value: attr.value,\n })) || [],\n },\n };\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { fetchGraphQl } from '@/company-management/api/fetch-graphql';\nimport { CREATE_COMPANY_MUTATION } from './graphql/createCompany.graphql';\nimport { CompanyRegistrationModel } from '@/company-management/data/models/company';\nimport { transformFormDataToCreateInput } from '@/company-management/data/transforms/company';\nimport { transformCreateCompanyResponse } from '@/company-management/data/transforms/transform-company';\n\nexport interface CompanyCreateInput {\n company_name: string;\n company_email: string;\n legal_name?: string;\n vat_tax_id?: string;\n reseller_id?: string;\n legal_address: {\n street: string[];\n city: string;\n region: {\n region_code: string;\n region?: string;\n region_id?: number;\n };\n postcode: string;\n country_id: string;\n telephone?: string;\n };\n company_admin: {\n email: string;\n firstname: string;\n lastname: string;\n job_title?: string;\n telephone?: string;\n gender?: number;\n custom_attributes?: Array<{\n attribute_code: string;\n value: string;\n }>;\n };\n}\n\n\nexport const createCompany = async (formData: any): Promise<{ success: boolean; company?: CompanyRegistrationModel; errors?: string[] }> => {\n try {\n const input = transformFormDataToCreateInput(formData);\n const response = await fetchGraphQl(CREATE_COMPANY_MUTATION, {\n method: 'POST',\n variables: { input },\n });\n\n if (response.errors?.length) {\n return {\n success: false,\n errors: response.errors.map((error: any) => error.message),\n };\n }\n\n // Transform the GraphQL response using the dedicated transformer\n const transformedCompany = transformCreateCompanyResponse(response);\n\n return {\n success: true,\n company: transformedCompany,\n };\n } catch (error) {\n console.error('Failed to create company:', error);\n return {\n success: false,\n errors: ['Failed to create company. Please try again.'],\n };\n }\n};"],"names":["GET_STORE_CONFIG_QUERY","DEFAULT_COUNTRY","STORE_CONFIG_DEFAULTS","getStoreConfig","fetchGraphQl","response","_a","handleFetchError","transformStoreConfig","handleNetworkError","default_country","store_code","CREATE_COMPANY_MUTATION","transformFormDataToCreateInput","formData","regionCode","region","_b","finalRegion","code","id","line","_c","_d","_e","attr","createCompany","input","error","transformCreateCompanyResponse"],"mappings":"iIAiBO,MAAMA,EAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,ECOvCC,EAAkB,KAElBC,EAA0C,CACrD,eAAgBD,EAChB,UAAW,EACb,EAEaE,EAAiB,SACrB,MAAMC,EAAaJ,EAAwB,CAChD,OAAQ,KAAA,CACT,EACE,KAAMK,GAAqC,OAC1C,OAAIC,EAAAD,EAAS,SAAT,MAAAC,EAAiB,OAAeC,EAAiBF,EAAS,MAAM,EAE7DG,EAAqBH,CAAQ,CACtC,CAAC,EACA,MAAMI,CAAkB,ECpBhBD,EACXH,GACqB,OACrB,GAAI,GAACC,EAAAD,GAAA,YAAAA,EAAU,OAAV,MAAAC,EAAgB,aAAa,OAAOJ,EAEzC,KAAM,CAAE,gBAAAQ,EAAiB,WAAAC,CAAA,EAAeN,EAAS,KAAK,YAEtD,MAAO,CACL,eAAgBK,GAAmBR,EAAsB,eACzD,UAAWS,GAAcT,EAAsB,SAAA,CAEnD,ECdaU,EAAwC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,ECGxCC,EAAkCC,GAAkD,eAG/F,MAAMC,GAAaT,EAAAQ,EAAS,aAAT,YAAAR,EAAqB,OAClCU,GAASC,EAAAH,EAAS,SAAT,YAAAG,EAAiB,OAEhC,IAAIC,EAEJ,GAAIH,EAEFG,EAAc,CACZ,YAAaH,EACb,GAAID,EAAS,UAAY,CACvB,UAAW,OAAOA,EAAS,UA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C,IAAKC,IAAqD,CAC3G,eAAgBA,EAAK,eACrB,MAAOA,EAAK,KAAA,MACP,CAAA,CAAC,CACV,CAEJ,ECxBaC,EAAgB,MAAOZ,GAAwG,OAC1I,GAAI,CACF,MAAMa,EAAQd,EAA+BC,CAAQ,EAC/CT,EAAW,MAAMD,EAAaQ,EAAyB,CAC3D,OAAQ,OACR,UAAW,CAAE,MAAAe,CAAA,CAAM,CACpB,EAED,OAAIrB,EAAAD,EAAS,SAAT,MAAAC,EAAiB,OACZ,CACL,QAAS,GACT,OAAQD,EAAS,OAAO,IAAKuB,GAAeA,EAAM,OAAO,CAAA,EAOtD,CACL,QAAS,GACT,QAJyBC,EAA+BxB,CAAQ,CAIvD,CAEb,OAASuB,EAAO,CACd,eAAQ,MAAM,4BAA6BA,CAAK,EACzC,CACL,QAAS,GACT,OAAQ,CAAC,6CAA6C,CAAA,CAE1D,CACF"}
@@ -1,4 +1,4 @@
1
1
  /*! Copyright 2025 Adobe
2
2
  All Rights Reserved. */
3
- import{useState as a,useEffect as m}from"@dropins/tools/preact-hooks.js";import{u}from"./useCompanyContextListener.js";import{g as f}from"./getCustomerCompany.js";const i=()=>{const[s,o]=a(null),[r,t]=a(!0),n=async()=>{try{t(!0);const e=await f();o(e)}catch{o(null)}finally{t(!1)}};return m(()=>{n()},[]),u(n),{companyInfo:s,loading:r}};export{i as u};
3
+ import{useState as a,useEffect as m}from"@dropins/tools/preact-hooks.js";import{g as u}from"./getCustomerCompany.js";import{u as f}from"./useCompanyContextListener.js";const i=()=>{const[s,o]=a(null),[r,t]=a(!0),n=async()=>{try{t(!0);const e=await u();o(e)}catch{o(null)}finally{t(!1)}};return m(()=>{n()},[]),f(n),{companyInfo:s,loading:r}};export{i as u};
4
4
  //# sourceMappingURL=useCustomerCompanyInfo.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useCustomerCompanyInfo.js","sources":["/@dropins/storefront-company-management/src/hooks/containers/useCustomerCompanyInfo.ts"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\nimport { useState, useEffect } from 'preact/hooks';\nimport { getCustomerCompany } from '@/company-management/api/getCustomerCompany';\nimport { CustomerCompanyInfo } from '@/company-management/data/models/customer-company-info';\nimport { useCompanyContextListener } from '@/company-management/hooks/useCompanyContextListener';\n\n/**\n * Custom hook for fetching and managing customer company information\n * Listens to companyContext/changed events to refetch data when company context changes\n * @returns Object containing company info and loading state\n */\nexport const useCustomerCompanyInfo = () => {\n const [companyInfo, setCompanyInfo] = useState<CustomerCompanyInfo | null>(null);\n const [loading, setLoading] = useState<boolean>(true);\n\n const fetchCompanyInfo = async () => {\n try {\n setLoading(true);\n const data = await getCustomerCompany();\n setCompanyInfo(data);\n } catch (error) {\n setCompanyInfo(null);\n } finally {\n setLoading(false);\n }\n };\n\n useEffect(() => {\n fetchCompanyInfo();\n }, []);\n\n // Re-fetch customer company info when company context changes (e.g., user switches company)\n useCompanyContextListener(fetchCompanyInfo);\n\n return {\n companyInfo,\n loading,\n };\n};\n"],"names":["useCustomerCompanyInfo","companyInfo","setCompanyInfo","useState","loading","setLoading","fetchCompanyInfo","data","getCustomerCompany","useEffect","useCompanyContextListener"],"mappings":"mKA0BO,MAAMA,EAAyB,IAAM,CAC1C,KAAM,CAACC,EAAaC,CAAc,EAAIC,EAAqC,IAAI,EACzE,CAACC,EAASC,CAAU,EAAIF,EAAkB,EAAI,EAE9CG,EAAmB,SAAY,CACnC,GAAI,CACFD,EAAW,EAAI,EACf,MAAME,EAAO,MAAMC,EAAA,EACnBN,EAAeK,CAAI,CACrB,MAAgB,CACdL,EAAe,IAAI,CACrB,QAAA,CACEG,EAAW,EAAK,CAClB,CACF,EAEA,OAAAI,EAAU,IAAM,CACdH,EAAA,CACF,EAAG,CAAA,CAAE,EAGLI,EAA0BJ,CAAgB,EAEnC,CACL,YAAAL,EACA,QAAAG,CAAA,CAEJ"}
1
+ {"version":3,"file":"useCustomerCompanyInfo.js","sources":["/@dropins/storefront-company-management/src/hooks/containers/useCustomerCompanyInfo.ts"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\nimport { useState, useEffect } from 'preact/hooks';\nimport { getCustomerCompany } from '@/company-management/api/getCustomerCompany/getCustomerCompany';\nimport { CustomerCompanyInfo } from '@/company-management/data/models/customer-company-info';\nimport { useCompanyContextListener } from '@/company-management/hooks/useCompanyContextListener';\n\n/**\n * Custom hook for fetching and managing customer company information\n * Listens to companyContext/changed events to refetch data when company context changes\n * @returns Object containing company info and loading state\n */\nexport const useCustomerCompanyInfo = () => {\n const [companyInfo, setCompanyInfo] = useState<CustomerCompanyInfo | null>(null);\n const [loading, setLoading] = useState<boolean>(true);\n\n const fetchCompanyInfo = async () => {\n try {\n setLoading(true);\n const data = await getCustomerCompany();\n setCompanyInfo(data);\n } catch (error) {\n setCompanyInfo(null);\n } finally {\n setLoading(false);\n }\n };\n\n useEffect(() => {\n fetchCompanyInfo();\n }, []);\n\n // Re-fetch customer company info when company context changes (e.g., user switches company)\n useCompanyContextListener(fetchCompanyInfo);\n\n return {\n companyInfo,\n loading,\n };\n};\n"],"names":["useCustomerCompanyInfo","companyInfo","setCompanyInfo","useState","loading","setLoading","fetchCompanyInfo","data","getCustomerCompany","useEffect","useCompanyContextListener"],"mappings":"wKA0BO,MAAMA,EAAyB,IAAM,CAC1C,KAAM,CAACC,EAAaC,CAAc,EAAIC,EAAqC,IAAI,EACzE,CAACC,EAASC,CAAU,EAAIF,EAAkB,EAAI,EAE9CG,EAAmB,SAAY,CACnC,GAAI,CACFD,EAAW,EAAI,EACf,MAAME,EAAO,MAAMC,EAAA,EACnBN,EAAeK,CAAI,CACrB,MAAgB,CACdL,EAAe,IAAI,CACrB,QAAA,CACEG,EAAW,EAAK,CAClB,CACF,EAEA,OAAAI,EAAU,IAAM,CACdH,EAAA,CACF,EAAG,CAAA,CAAE,EAGLI,EAA0BJ,CAAgB,EAEnC,CACL,YAAAL,EACA,QAAAG,CAAA,CAEJ"}
@@ -1,6 +1,7 @@
1
1
  import { FunctionComponent } from 'preact';
2
2
  import { CompanyFormSlots } from '../../types/form.types';
3
3
  import { Company } from '../../data/models/company';
4
+ import { InLineAlertProps } from '../../types/companyProfile.types';
4
5
 
5
6
  export interface CompanyRegistrationFormProps {
6
7
  onSuccess?: (company: Company) => void;
@@ -8,6 +9,7 @@ export interface CompanyRegistrationFormProps {
8
9
  className?: string;
9
10
  slots?: CompanyFormSlots;
10
11
  hideActionFormButtons?: boolean;
12
+ inLineAlertProps?: InLineAlertProps;
11
13
  }
12
14
  export declare const CompanyRegistrationForm: FunctionComponent<CompanyRegistrationFormProps>;
13
15
  //# sourceMappingURL=CompanyRegistrationForm.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AcceptInvitation.js","sources":["/@dropins/storefront-company-management/src/lib/switchCompanyContext.ts","/@dropins/storefront-company-management/src/hooks/useAcceptInvitation.ts","/@dropins/storefront-company-management/src/components/AcceptInvitationForm/AcceptInvitationForm.tsx","/@dropins/storefront-company-management/src/containers/AcceptInvitation/AcceptInvitation.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { getCustomerCompany } from '@/company-management/api/getCustomerCompany';\n\n/**\n * Switches the company context to the specified company ID\n * Only switches if:\n * 1. The invited customer ID matches the logged-in customer ID\n * 2. There's no company ID already in session\n * \n * This replicates Luma's behavior in AcceptInvitation controller.\n * \n * @param companyId - The company ID to switch to (base64 encoded)\n * @param invitedCustomerId - The customer ID from the invitation (base64 encoded)\n */\nexport async function switchCompanyContext(companyId: string, invitedCustomerId: string): Promise<void> {\n const companySessionStorageKey = 'DROPIN__COMPANYSWITCHER__COMPANY__CONTEXT';\n const groupSessionStorageKey = 'DROPIN__COMPANYSWITCHER__GROUP__CONTEXT';\n\n // Check if there's already a company ID in session\n // Match Luma's behavior: only set company context if user doesn't have one yet\n const existingCompanyId = sessionStorage.getItem(companySessionStorageKey);\n if (existingCompanyId) {\n return; // Don't override existing company context\n }\n\n try {\n // Get logged-in customer info including customer ID\n const customerInfo = await getCustomerCompany();\n if (!customerInfo?.customerId) {\n return; // No customer ID available\n }\n\n // Compare base64-encoded IDs (GraphQL returns base64-encoded ID)\n if (customerInfo.customerId !== invitedCustomerId) {\n return; // Invitation is for a different customer\n }\n\n // Set company ID in session storage\n sessionStorage.setItem(companySessionStorageKey, companyId);\n \n // Remove customer group ID - company-switcher will refresh it on reload\n sessionStorage.removeItem(groupSessionStorageKey);\n } catch (error) {\n // Silently fail - don't set company context if we can't verify\n console.error('Failed to switch company context:', error);\n }\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { useEffect, useState, useRef } from 'preact/hooks';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { acceptCompanyInvitation, companyEnabled } from '@/company-management/api';\nimport { AcceptCompanyInvitationInput, InvitationStatus } from '@/company-management/types';\nimport { switchCompanyContext } from '@/company-management/lib';\n\n/**\n * Hook to handle company invitation acceptance from email link\n * Parses URL parameters, validates company is enabled, and calls the API\n * \n * @param isAuthenticated - Whether the user is currently authenticated\n */\nexport const useAcceptInvitation = (isAuthenticated: boolean = false): InvitationStatus => {\n // Check URL parameters synchronously to determine initial state\n const urlParams = new URLSearchParams(window.location.search);\n const code = urlParams.get('code');\n const customerId = urlParams.get('customer[customer_id]');\n const companyId = urlParams.get('customer[company_id]');\n const hasInvalidParams = !code || !customerId || !companyId;\n\n const translations = useText({\n companyDisabledError: 'Company.AcceptInvitation.companyDisabledError',\n invalidLinkError: 'Company.AcceptInvitation.invalidLinkError',\n expiredLinkError: 'Company.AcceptInvitation.expiredLinkError',\n genericError: 'Company.AcceptInvitation.genericError',\n });\n\n const [status, setStatus] = useState<InvitationStatus>({\n isLoading: false,\n isSuccess: false,\n isError: hasInvalidParams,\n errorMessage: '',\n isCompanyDisabled: false,\n });\n\n const hasProcessedRef = useRef(false);\n\n useEffect(() => {\n // Only process once\n if (hasProcessedRef.current) return;\n\n const processInvitation = async () => {\n // Validate required parameters - show error if missing\n if (hasInvalidParams) {\n hasProcessedRef.current = true;\n setStatus({\n isLoading: false,\n isSuccess: false,\n isError: true,\n errorMessage: translations.invalidLinkError,\n isCompanyDisabled: false,\n });\n return;\n }\n\n // Mark as processing IMMEDIATELY to prevent duplicate calls\n hasProcessedRef.current = true;\n\n // Valid invitation parameters - start processing\n setStatus({\n isLoading: true,\n isSuccess: false,\n isError: false,\n errorMessage: '',\n isCompanyDisabled: false,\n });\n\n // Check if B2B company features are enabled\n const isEnabled = await companyEnabled();\n if (!isEnabled) {\n setStatus({\n isLoading: false,\n isSuccess: false,\n isError: true,\n errorMessage: translations.companyDisabledError,\n isCompanyDisabled: true,\n });\n return;\n }\n\n // Get remaining URL parameters (code, customerId, companyId already extracted above)\n const jobTitle = urlParams.get('customer[job_title]');\n const telephone = urlParams.get('customer[telephone]');\n const statusParam = urlParams.get('customer[status]');\n\n // Prepare invitation input\n const invitationInput: AcceptCompanyInvitationInput = {\n code,\n user: {\n customerId,\n companyId,\n jobTitle: jobTitle || null,\n telephone: telephone || null,\n status: statusParam ? (statusParam === '1' ? 'ACTIVE' : 'INACTIVE') : null,\n },\n roleId: null,\n };\n\n try {\n // Call API to accept invitation\n const result = await acceptCompanyInvitation(invitationInput);\n\n if (result && result.success) {\n // Clear URL parameters\n const url = new URL(window.location.href);\n url.search = '';\n window.history.replaceState({}, '', url.toString());\n\n // Switch company context to the newly joined company (only if authenticated)\n // Only switches if logged-in customer matches invited customer\n // and there's no company ID already in session\n if (isAuthenticated) {\n await switchCompanyContext(companyId, customerId);\n }\n\n // Show success message with buttons for user to navigate\n // Company context will be applied when navigating to My Account\n setStatus({\n isLoading: false,\n isSuccess: true,\n isError: false,\n errorMessage: '',\n isCompanyDisabled: false,\n });\n } else {\n setStatus({\n isLoading: false,\n isSuccess: false,\n isError: true,\n errorMessage: translations.expiredLinkError,\n isCompanyDisabled: false,\n });\n }\n } catch (error) {\n // Extract error message from caught error (GraphQL errors are thrown by handleFetchError)\n const errorMessage = error instanceof Error ? error.message : translations.genericError;\n \n setStatus({\n isLoading: false,\n isSuccess: false,\n isError: true,\n errorMessage,\n isCompanyDisabled: false,\n });\n }\n };\n\n processInvitation();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [translations]);\n\n return status;\n};\n\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FunctionComponent } from 'preact';\nimport { Button, ProgressSpinner, InLineAlert } from '@adobe-commerce/elsie/components';\nimport { classes } from '@adobe-commerce/elsie/lib';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { useAcceptInvitation } from '@/company-management/hooks/useAcceptInvitation';\nimport { AcceptInvitationFormProps } from '@/company-management/types';\nimport '@adobe-commerce/storefront-design/dist/css/base.css';\nimport './AcceptInvitationForm.css';\n\nexport const AcceptInvitationForm: FunctionComponent<AcceptInvitationFormProps> = ({\n routeMyAccount,\n routeLogin,\n isAuthenticated = false,\n labels,\n className = '',\n}) => {\n const { isLoading, isSuccess, isError, errorMessage, isCompanyDisabled } = useAcceptInvitation(isAuthenticated);\n\n const translations = useText({\n title: 'Company.AcceptInvitation.title',\n loadingText: 'Company.AcceptInvitation.loadingText',\n successMessage: 'Company.AcceptInvitation.successMessage',\n myAccountButton: 'Company.AcceptInvitation.myAccountButton',\n loginButton: 'Company.AcceptInvitation.loginButton',\n });\n\n const finalLabels = { ...translations, ...labels };\n\n if (isLoading) {\n return (\n <div className={classes(['company-accept-invitation-wrapper', className])}>\n <h2>{finalLabels.title}</h2>\n <div className=\"company-accept-invitation-loading\">\n <ProgressSpinner />\n <p>{finalLabels.loadingText}</p>\n </div>\n </div>\n );\n }\n\n if (isSuccess || isError) {\n return (\n <div className={classes(['company-accept-invitation-wrapper', className])}>\n <h2>{finalLabels.title}</h2>\n <InLineAlert \n type={isSuccess ? 'success' : 'error'}\n variant=\"secondary\" \n heading={isSuccess ? finalLabels.successMessage || '' : errorMessage} \n />\n <div className=\"company-accept-invitation-wrapper__buttons\">\n {!isCompanyDisabled && !isAuthenticated && routeLogin && (\n <Button\n variant=\"primary\"\n onClick={() => {\n window.location.href = routeLogin();\n }}\n className=\"company-accept-invitation-wrapper__submit\"\n >\n {finalLabels.loginButton}\n </Button>\n )}\n {isAuthenticated && routeMyAccount && (\n <Button\n variant=\"primary\"\n onClick={() => {\n window.location.href = routeMyAccount();\n }}\n className=\"company-accept-invitation-wrapper__submit\"\n >\n {finalLabels.myAccountButton}\n </Button>\n )}\n </div>\n </div>\n );\n }\n\n return null;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { AcceptInvitationForm } from '@/company-management/components';\nimport { AcceptInvitationProps } from '@/company-management/types';\n\nexport const AcceptInvitation: Container<AcceptInvitationProps> = ({\n routeMyAccount,\n routeLogin,\n isAuthenticated,\n labels,\n className = '',\n}) => {\n return (\n <div className={`company-accept-invitation-container ${className}`}>\n <AcceptInvitationForm\n routeMyAccount={routeMyAccount}\n routeLogin={routeLogin}\n isAuthenticated={isAuthenticated}\n labels={labels}\n />\n </div>\n );\n};\n"],"names":["switchCompanyContext","companyId","invitedCustomerId","companySessionStorageKey","groupSessionStorageKey","customerInfo","getCustomerCompany","error","useAcceptInvitation","isAuthenticated","urlParams","code","customerId","hasInvalidParams","translations","useText","status","setStatus","useState","hasProcessedRef","useRef","useEffect","companyEnabled","jobTitle","telephone","statusParam","invitationInput","result","acceptCompanyInvitation","url","errorMessage","AcceptInvitationForm","routeMyAccount","routeLogin","labels","className","isLoading","isSuccess","isError","isCompanyDisabled","finalLabels","jsxs","classes","jsx","ProgressSpinner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ACZ,EAAA,CACC,eAAAC,EACA,WAAAC,EACA,gBAAAxB,EACA,OAAAyB,CAAA,CAAA,EAEJ"}
1
+ {"version":3,"file":"AcceptInvitation.js","sources":["/@dropins/storefront-company-management/src/lib/switchCompanyContext.ts","/@dropins/storefront-company-management/src/hooks/useAcceptInvitation.ts","/@dropins/storefront-company-management/src/components/AcceptInvitationForm/AcceptInvitationForm.tsx","/@dropins/storefront-company-management/src/containers/AcceptInvitation/AcceptInvitation.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { getCustomerCompany } from '@/company-management/api/getCustomerCompany/getCustomerCompany';\n\n/**\n * Switches the company context to the specified company ID\n * Only switches if:\n * 1. The invited customer ID matches the logged-in customer ID\n * 2. There's no company ID already in session\n * \n * This replicates Luma's behavior in AcceptInvitation controller.\n * \n * @param companyId - The company ID to switch to (base64 encoded)\n * @param invitedCustomerId - The customer ID from the invitation (base64 encoded)\n */\nexport async function switchCompanyContext(companyId: string, invitedCustomerId: string): Promise<void> {\n const companySessionStorageKey = 'DROPIN__COMPANYSWITCHER__COMPANY__CONTEXT';\n const groupSessionStorageKey = 'DROPIN__COMPANYSWITCHER__GROUP__CONTEXT';\n\n // Check if there's already a company ID in session\n // Match Luma's behavior: only set company context if user doesn't have one yet\n const existingCompanyId = sessionStorage.getItem(companySessionStorageKey);\n if (existingCompanyId) {\n return; // Don't override existing company context\n }\n\n try {\n // Get logged-in customer info including customer ID\n const customerInfo = await getCustomerCompany();\n if (!customerInfo?.customerId) {\n return; // No customer ID available\n }\n\n // Compare base64-encoded IDs (GraphQL returns base64-encoded ID)\n if (customerInfo.customerId !== invitedCustomerId) {\n return; // Invitation is for a different customer\n }\n\n // Set company ID in session storage\n sessionStorage.setItem(companySessionStorageKey, companyId);\n \n // Remove customer group ID - company-switcher will refresh it on reload\n sessionStorage.removeItem(groupSessionStorageKey);\n } catch (error) {\n // Silently fail - don't set company context if we can't verify\n console.error('Failed to switch company context:', error);\n }\n}\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { useEffect, useState, useRef } from 'preact/hooks';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { acceptCompanyInvitation, companyEnabled } from '@/company-management/api';\nimport { AcceptCompanyInvitationInput, InvitationStatus } from '@/company-management/types';\nimport { switchCompanyContext } from '@/company-management/lib';\n\n/**\n * Hook to handle company invitation acceptance from email link\n * Parses URL parameters, validates company is enabled, and calls the API\n * \n * @param isAuthenticated - Whether the user is currently authenticated\n */\nexport const useAcceptInvitation = (isAuthenticated: boolean = false): InvitationStatus => {\n // Check URL parameters synchronously to determine initial state\n const urlParams = new URLSearchParams(window.location.search);\n const code = urlParams.get('code');\n const customerId = urlParams.get('customer[customer_id]');\n const companyId = urlParams.get('customer[company_id]');\n const hasInvalidParams = !code || !customerId || !companyId;\n\n const translations = useText({\n companyDisabledError: 'Company.AcceptInvitation.companyDisabledError',\n invalidLinkError: 'Company.AcceptInvitation.invalidLinkError',\n expiredLinkError: 'Company.AcceptInvitation.expiredLinkError',\n genericError: 'Company.AcceptInvitation.genericError',\n });\n\n const [status, setStatus] = useState<InvitationStatus>({\n isLoading: false,\n isSuccess: false,\n isError: hasInvalidParams,\n errorMessage: '',\n isCompanyDisabled: false,\n });\n\n const hasProcessedRef = useRef(false);\n\n useEffect(() => {\n // Only process once\n if (hasProcessedRef.current) return;\n\n const processInvitation = async () => {\n // Validate required parameters - show error if missing\n if (hasInvalidParams) {\n hasProcessedRef.current = true;\n setStatus({\n isLoading: false,\n isSuccess: false,\n isError: true,\n errorMessage: translations.invalidLinkError,\n isCompanyDisabled: false,\n });\n return;\n }\n\n // Mark as processing IMMEDIATELY to prevent duplicate calls\n hasProcessedRef.current = true;\n\n // Valid invitation parameters - start processing\n setStatus({\n isLoading: true,\n isSuccess: false,\n isError: false,\n errorMessage: '',\n isCompanyDisabled: false,\n });\n\n // Check if B2B company features are enabled\n const isEnabled = await companyEnabled();\n if (!isEnabled) {\n setStatus({\n isLoading: false,\n isSuccess: false,\n isError: true,\n errorMessage: translations.companyDisabledError,\n isCompanyDisabled: true,\n });\n return;\n }\n\n // Get remaining URL parameters (code, customerId, companyId already extracted above)\n const jobTitle = urlParams.get('customer[job_title]');\n const telephone = urlParams.get('customer[telephone]');\n const statusParam = urlParams.get('customer[status]');\n\n // Prepare invitation input\n const invitationInput: AcceptCompanyInvitationInput = {\n code,\n user: {\n customerId,\n companyId,\n jobTitle: jobTitle || null,\n telephone: telephone || null,\n status: statusParam ? (statusParam === '1' ? 'ACTIVE' : 'INACTIVE') : null,\n },\n roleId: null,\n };\n\n try {\n // Call API to accept invitation\n const result = await acceptCompanyInvitation(invitationInput);\n\n if (result && result.success) {\n // Clear URL parameters\n const url = new URL(window.location.href);\n url.search = '';\n window.history.replaceState({}, '', url.toString());\n\n // Switch company context to the newly joined company (only if authenticated)\n // Only switches if logged-in customer matches invited customer\n // and there's no company ID already in session\n if (isAuthenticated) {\n await switchCompanyContext(companyId, customerId);\n }\n\n // Show success message with buttons for user to navigate\n // Company context will be applied when navigating to My Account\n setStatus({\n isLoading: false,\n isSuccess: true,\n isError: false,\n errorMessage: '',\n isCompanyDisabled: false,\n });\n } else {\n setStatus({\n isLoading: false,\n isSuccess: false,\n isError: true,\n errorMessage: translations.expiredLinkError,\n isCompanyDisabled: false,\n });\n }\n } catch (error) {\n // Extract error message from caught error (GraphQL errors are thrown by handleFetchError)\n const errorMessage = error instanceof Error ? error.message : translations.genericError;\n \n setStatus({\n isLoading: false,\n isSuccess: false,\n isError: true,\n errorMessage,\n isCompanyDisabled: false,\n });\n }\n };\n\n processInvitation();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [translations]);\n\n return status;\n};\n\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { FunctionComponent } from 'preact';\nimport { Button, ProgressSpinner, InLineAlert } from '@adobe-commerce/elsie/components';\nimport { classes } from '@adobe-commerce/elsie/lib';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { useAcceptInvitation } from '@/company-management/hooks/useAcceptInvitation';\nimport { AcceptInvitationFormProps } from '@/company-management/types';\nimport '@adobe-commerce/storefront-design/dist/css/base.css';\nimport './AcceptInvitationForm.css';\n\nexport const AcceptInvitationForm: FunctionComponent<AcceptInvitationFormProps> = ({\n routeMyAccount,\n routeLogin,\n isAuthenticated = false,\n labels,\n className = '',\n}) => {\n const { isLoading, isSuccess, isError, errorMessage, isCompanyDisabled } = useAcceptInvitation(isAuthenticated);\n\n const translations = useText({\n title: 'Company.AcceptInvitation.title',\n loadingText: 'Company.AcceptInvitation.loadingText',\n successMessage: 'Company.AcceptInvitation.successMessage',\n myAccountButton: 'Company.AcceptInvitation.myAccountButton',\n loginButton: 'Company.AcceptInvitation.loginButton',\n });\n\n const finalLabels = { ...translations, ...labels };\n\n if (isLoading) {\n return (\n <div className={classes(['company-accept-invitation-wrapper', className])}>\n <h2>{finalLabels.title}</h2>\n <div className=\"company-accept-invitation-loading\">\n <ProgressSpinner />\n <p>{finalLabels.loadingText}</p>\n </div>\n </div>\n );\n }\n\n if (isSuccess || isError) {\n return (\n <div className={classes(['company-accept-invitation-wrapper', className])}>\n <h2>{finalLabels.title}</h2>\n <InLineAlert \n type={isSuccess ? 'success' : 'error'}\n variant=\"secondary\" \n heading={isSuccess ? finalLabels.successMessage || '' : errorMessage} \n />\n <div className=\"company-accept-invitation-wrapper__buttons\">\n {!isCompanyDisabled && !isAuthenticated && routeLogin && (\n <Button\n variant=\"primary\"\n onClick={() => {\n window.location.href = routeLogin();\n }}\n className=\"company-accept-invitation-wrapper__submit\"\n >\n {finalLabels.loginButton}\n </Button>\n )}\n {isAuthenticated && routeMyAccount && (\n <Button\n variant=\"primary\"\n onClick={() => {\n window.location.href = routeMyAccount();\n }}\n className=\"company-accept-invitation-wrapper__submit\"\n >\n {finalLabels.myAccountButton}\n </Button>\n )}\n </div>\n </div>\n );\n }\n\n return null;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { AcceptInvitationForm } from '@/company-management/components';\nimport { AcceptInvitationProps } from '@/company-management/types';\n\nexport const AcceptInvitation: Container<AcceptInvitationProps> = ({\n routeMyAccount,\n routeLogin,\n isAuthenticated,\n labels,\n className = '',\n}) => {\n return (\n <div className={`company-accept-invitation-container ${className}`}>\n <AcceptInvitationForm\n routeMyAccount={routeMyAccount}\n routeLogin={routeLogin}\n isAuthenticated={isAuthenticated}\n labels={labels}\n />\n </div>\n );\n};\n"],"names":["switchCompanyContext","companyId","invitedCustomerId","companySessionStorageKey","groupSessionStorageKey","customerInfo","getCustomerCompany","error","useAcceptInvitation","isAuthenticated","urlParams","code","customerId","hasInvalidParams","translations","useText","status","setStatus","useState","hasProcessedRef","useRef","useEffect","companyEnabled","jobTitle","telephone","statusParam","invitationInput","result","acceptCompanyInvitation","url","errorMessage","AcceptInvitationForm","routeMyAccount","routeLogin","labels","className","isLoading","isSuccess","isError","isCompanyDisabled","finalLabels","jsxs","classes","jsx","ProgressSpinner","InLineAlert","Button","AcceptInvitation"],"mappings":"sqBA8BA,eAAsBA,EAAqBC,EAAmBC,EAA0C,CACtG,MAAMC,EAA2B,4CAC3BC,EAAyB,0CAK/B,GAD0B,gBAAe,QAAQD,CAAwB,EAKzE,GAAI,CAEF,MAAME,EAAe,MAAMC,EAAA,EAM3B,GALI,EAACD,GAAA,MAAAA,EAAc,aAKfA,EAAa,aAAeH,EAC9B,OAIF,eAAe,QAAQC,EAA0BF,CAAS,EAG1D,eAAe,WAAWG,CAAsB,CAClD,OAASG,EAAO,CAEd,QAAQ,MAAM,oCAAqCA,CAAK,CAC1D,CACF,CCjCO,MAAMC,EAAsB,CAACC,EAA2B,KAA4B,CAEzF,MAAMC,EAAY,IAAI,gBAAgB,OAAO,SAAS,MAAM,EACtDC,EAAOD,EAAU,IAAI,MAAM,EAC3BE,EAAaF,EAAU,IAAI,uBAAuB,EAClDT,EAAYS,EAAU,IAAI,sBAAsB,EAChDG,EAAmB,CAACF,GAAQ,CAACC,GAAc,CAACX,EAE5Ca,EAAeC,EAAQ,CAC3B,qBAAsB,gDACtB,iBAAkB,4CAClB,iBAAkB,4CAClB,aAAc,uCAAA,CACf,EAEK,CAACC,EAAQC,CAAS,EAAIC,EAA2B,CACrD,UAAW,GACX,UAAW,GACX,QAASL,EACT,aAAc,GACd,kBAAmB,EAAA,CAC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A,CACzB,EACA,UAAU,4CAET,SAAAO,EAAY,WAAA,CAAA,EAGhB/B,GAAmBuB,GAClBW,EAACG,EAAA,CACC,QAAQ,UACR,QAAS,IAAM,CACb,OAAO,SAAS,KAAOd,EAAA,CACzB,EACA,UAAU,4CAET,SAAAQ,EAAY,eAAA,CAAA,CACf,CAAA,CAEJ,CAAA,EACF,EAIG,IACT,EC1EaO,EAAqD,CAAC,CACjE,eAAAf,EACA,WAAAC,EACA,gBAAAxB,EACA,OAAAyB,EACA,UAAAC,EAAY,EACd,IAEIQ,EAAC,MAAA,CAAI,UAAW,uCAAuCR,CAAS,GAC9D,SAAAQ,EAACZ,EAAA,CACC,eAAAC,EACA,WAAAC,EACA,gBAAAxB,EACA,OAAAyB,CAAA,CAAA,EAEJ"}
@@ -1,4 +1,4 @@
1
1
  /*! Copyright 2025 Adobe
2
2
  All Rights Reserved. */
3
- import{jsx as t,jsxs as h,Fragment as K}from"@dropins/tools/preact-jsx-runtime.js";import{classes as me,Slot as ge}from"@dropins/tools/lib.js";import{Card as Q,IllustratedMessage as he,Button as X,Field as R,Input as V,Picker as ce,Header as ue,InLineAlert as fe,ProgressSpinner as ye}from"@dropins/tools/components.js";import{useState as L,useRef as J,useEffect as H,useCallback as U,useMemo as G}from"@dropins/tools/preact-hooks.js";import{events as ve}from"@dropins/tools/event-bus.js";import{p as Ce,E as Ae}from"../chunks/acdl.js";import{u as Ne}from"../chunks/useCompanyContextListener.js";import{g as Ie,u as _e}from"../chunks/updateCompany.js";import{g as pe,v as Ee}from"../chunks/validateCompanyEmail.js";import{useText as j}from"@dropins/tools/i18n.js";import{u as be}from"../chunks/useInLineAlert.js";import{c as xe}from"../chunks/CompanyLoaders.js";import"../chunks/fetchUserPermissions.js";import"../chunks/company-permissions.js";import"../chunks/fetch-error.js";import"../chunks/network-error.js";import"@dropins/tools/fetch-graphql.js";import"@dropins/tools/preact-compat.js";const Te=({company:a,slots:e,showEditForm:u,handleShowEditForm:y})=>{const o=j({editButton:"Company.shared.buttons.edit",noDataMessage:"Company.CompanyProfile.companyProfileCard.noDataMessage",companyName:"Company.shared.fields.companyName",email:"Company.shared.fields.email",legalName:"Company.shared.fields.legalName",vatTaxId:"Company.shared.fields.vatTaxId",resellerId:"Company.shared.fields.resellerId",legalAddress:"Company.shared.fields.legalAddress",contacts:"Company.CompanyProfile.companyProfileCard.contacts",companyAdministrator:"Company.CompanyProfile.companyProfileCard.companyAdministrator",salesRepresentative:"Company.CompanyProfile.companyProfileCard.salesRepresentative",paymentInformation:"Company.CompanyProfile.companyProfileCard.paymentInformation",shippingInformation:"Company.CompanyProfile.companyProfileCard.shippingInformation",availablePaymentMethods:"Company.CompanyProfile.companyProfileCard.availablePaymentMethods",availableShippingMethods:"Company.CompanyProfile.companyProfileCard.availableShippingMethods",noPaymentMethods:"Company.CompanyProfile.companyProfileCard.noPaymentMethods",noShippingMethods:"Company.CompanyProfile.companyProfileCard.noShippingMethods"});if(!a)return t(Q,{variant:"secondary",className:"account-company-profile-card",children:t("div",{className:"account-company-profile-card__wrapper",children:t("div",{className:"account-company-profile-card__content",children:t("div",{className:"account-company-profile-card__no-data",children:t(he,{message:t("p",{children:o.noDataMessage})})})})})});const i=a.permissionsFlags||{canViewAccount:!0,canViewAddress:!0,canViewContacts:!0,canViewPaymentInformation:!0,canViewShippingInformation:!0},r=[i.canViewAccount?{name:"name",label:o.companyName,value:a.name||"",legalName:a.legalName||""}:null,i.canViewAccount?{name:"email",label:o.email,value:a.email||""}:null,i.canViewAccount?{name:"vatTaxId",label:o.vatTaxId,value:a.vatTaxId||""}:null,i.canViewAccount?{name:"resellerId",label:o.resellerId,value:a.resellerId||""}:null].filter(Boolean);return t(Q,{variant:"secondary",className:me(["account-company-profile-card",["account-company-profile-card-short",u]]),children:h("div",{className:"account-company-profile-card__wrapper",children:[t("div",{className:"account-company-profile-card__actions",children:(a.canEditAccount||a.canEditAddress)&&t(X,{type:"button",variant:"tertiary",onClick:y,children:o.editButton})}),t("div",{className:"account-company-profile-card__content",children:(()=>{var v,p;const N=h(K,{children:[r.map((l,d)=>{if(!l.value)return null;let g;return l.name==="name"&&l.legalName?g=`${l.label}: ${l.value} (${l.legalName})`:g=l.label?`${l.label}: ${l.value}`:l.value,t("p",{"data-testid":`${l.name}_${d}`,children:g},`${l.name}_${d}`)}),i.canViewAddress&&a.legalAddress&&h("div",{className:"company-legal-address",children:[t("p",{children:h("strong",{children:[o.legalAddress,":"]})}),(v=a.legalAddress.street)==null?void 0:v.map((l,d)=>t("p",{children:l},d)),h("p",{children:[a.legalAddress.city,", ",(p=a.legalAddress.region)==null?void 0:p.region," ",a.legalAddress.postcode]}),t("p",{children:a.legalAddress.countryCode}),a.legalAddress.telephone&&h("p",{children:["Phone: ",a.legalAddress.telephone]})]}),i.canViewContacts&&(a.companyAdmin||a.salesRepresentative)&&h("div",{className:"company-contacts",children:[t("p",{children:h("strong",{children:[o.contacts,":"]})}),a.companyAdmin&&h("div",{className:"company-contact",children:[t("p",{children:h("strong",{children:[o.companyAdministrator,":"]})}),h("p",{children:[a.companyAdmin.firstname," ",a.companyAdmin.lastname]}),a.companyAdmin.jobTitle&&t("p",{children:a.companyAdmin.jobTitle}),t("p",{children:a.companyAdmin.email})]}),a.salesRepresentative&&h("div",{className:"company-contact",children:[t("p",{children:h("strong",{children:[o.salesRepresentative,":"]})}),h("p",{children:[a.salesRepresentative.firstname," ",a.salesRepresentative.lastname]}),t("p",{children:a.salesRepresentative.email})]})]}),i.canViewPaymentInformation&&h("div",{className:"company-payment-methods",children:[t("p",{children:h("strong",{children:[o.paymentInformation,":"]})}),a.availablePaymentMethods&&a.availablePaymentMethods.length>0?h(K,{children:[t("p",{children:h("strong",{children:[o.availablePaymentMethods,":"]})}),t("ul",{className:"payment-methods-list",children:a.availablePaymentMethods.map((l,d)=>t("li",{children:l.title},`payment_${d}`))})]}):t("div",{className:"message message-notice notice",children:t("div",{children:o.noPaymentMethods})})]}),i.canViewShippingInformation&&h("div",{className:"company-shipping-methods",children:[t("p",{children:h("strong",{children:[o.shippingInformation,":"]})}),a.availableShippingMethods&&a.availableShippingMethods.length>0?h(K,{children:[t("p",{children:h("strong",{children:[o.availableShippingMethods,":"]})}),t("ul",{className:"shipping-methods-list",children:a.availableShippingMethods.map((l,d)=>t("li",{children:l.title},`shipping_${d}`))})]}):t("div",{className:"message message-notice notice",children:t("div",{children:o.noShippingMethods})})]})]});return e!=null&&e.CompanyData?t(ge,{name:"CompanyData",slot:e.CompanyData,context:{companyData:r,Default:N}}):N})()})]})})},$e=({handleSetInLineAlert:a,editFormRef:e})=>{const u=j({companySuccess:"Company.CompanyProfile.editCompanyProfile.companySuccess",companyError:"Company.CompanyProfile.editCompanyProfile.companyError",loadError:"Company.CompanyProfile.messages.loadError",updateError:"Company.CompanyProfile.messages.updateError",noDataToUpdate:"Company.CompanyProfile.messages.noDataToUpdate"}),{companySuccess:y,companyError:o,loadError:i,updateError:r,noDataToUpdate:N}=u,[v,p]=L(null),[l,d]=L(!0),[g,C]=L(!1),[_,$]=L(!1),[m,k]=L([]),[D,A]=L({}),z=J(a),w=J(!1),P=J(!1);H(()=>{z.current=a},[a]);const O=U(f=>{A(f)},[]),F=U((f,B)=>{a&&(f==="success"?a({type:"success",text:B??y}):f==="error"?a({type:"error",text:B??o}):a(),C(!1))},[a,y,o]),S=U(async()=>{if(w.current)return null;w.current=!0,d(!0);try{const f=await Ie();return f&&p(f),d(!1),f}catch(f){return console.error("Failed to load company:",f),d(!1),z.current&&z.current({type:"error",text:i}),null}finally{w.current=!1}},[i]);H(()=>{P.current||(P.current=!0,S())},[S]),Ne(U(()=>{d(!0),$(!1),A({}),S()},[S])),H(()=>{pe().then(f=>{k(f.availableCountries)}).catch(f=>{console.error("Failed to load countries:",f)})},[]);const W=U(()=>{$(!0),F("success",""),A({})},[F]);H(()=>{_&&(e!=null&&e.current)&&setTimeout(()=>{var f;(f=e.current)==null||f.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},100)},[_,e]);const q=U(f=>{f==null||f(),$(!1),A({})},[]),Y=U(async f=>{try{if(C(!0),!f){F("error",N);return}const B=await _e(f);p(B),$(!1),A({}),F("success"),Ce(Ae.EDIT_COMPANY_EVENT,{...f,companyId:v==null?void 0:v.id}),ve.emit("company/updated",{company:B})}catch(B){console.error("Failed to update company:",B),F("error",B.message||r)}finally{C(!1)}},[v,F,r,N]);return{company:v,countries:m,loading:l,submitLoading:g,showEditForm:_,inputChange:D,handleShowEditForm:W,handleHideEditForm:q,handleUpdateCompany:Y,handleInputChange:O,renderAlertMessage:F,saving:g}},we=a=>{const[e,u]=L(null),[y,o]=L(!0);H(()=>{let p=!0;return pe().then(({availableCountries:l,countriesWithRequiredRegion:d,optionalZipCountries:g})=>{p&&(u({availableCountries:l,countriesWithRequiredRegion:d,optionalZipCountries:g}),o(!1))}).catch(()=>{p&&o(!1)}),()=>{p=!1}},[]);const i=G(()=>(e==null?void 0:e.availableCountries)||[],[e]),r=G(()=>{if(!a||!e)return[];const p=e.availableCountries.find(l=>l.value===a);return!(p!=null&&p.availableRegions)||p.availableRegions.length===0?[]:p.availableRegions.map(l=>({text:l.name,value:`${l.code},${l.id}`}))},[a,e]),N=G(()=>!a||!e?!1:e.countriesWithRequiredRegion.includes(a),[a,e]),v=G(()=>r.length>0,[r]);return{countryOptions:i,regionOptions:r,isRegionRequired:N,hasRegionOptions:v,loadingCountries:y}},Pe=({loading:a,value:e,errors:u,touched:y,onBlur:o,namePrefix:i="",fieldPathPrefix:r=""})=>{const N=j({companyName:"Company.shared.fields.companyName",email:"Company.shared.fields.email",legalName:"Company.shared.fields.legalName",vatTaxId:"Company.shared.fields.vatTaxId",resellerId:"Company.shared.fields.resellerId"}),v=i?`${i}_`:"",p=g=>r?`${r}.${g}`:g,l=g=>C=>{const _=C.target;o(p(g),_.value)},d={disabled:!!a,variant:"primary",size:"medium"};return h("div",{className:"account-edit-company-profile-form__group",children:[t(R,{label:N.companyName,required:!0,className:"account-edit-company-profile-form__field",error:y.name&&u.name?u.name:void 0,children:t(V,{name:`${v}name`,type:"text",value:e.name,onBlur:l("name"),...d,maxLength:40})}),t(R,{label:N.legalName,className:"account-edit-company-profile-form__field",children:t(V,{name:`${v}legalName`,type:"text",value:e.legalName,onBlur:l("legalName"),...d,maxLength:80})}),t(R,{label:N.email,required:!0,className:"account-edit-company-profile-form__field",error:y.email&&u.email?u.email:void 0,children:t(V,{name:`${v}email`,type:"email",value:e.email,onBlur:l("email"),...d})}),t(R,{label:N.vatTaxId,className:"account-edit-company-profile-form__field",children:t(V,{name:`${v}vatTaxId`,type:"text",value:e.vatTaxId,onBlur:l("vatTaxId"),...d,maxLength:40})}),t(R,{label:N.resellerId,className:"account-edit-company-profile-form__field",children:t(V,{name:`${v}resellerId`,type:"text",value:e.resellerId,onBlur:l("resellerId"),...d,maxLength:40})})]})},Fe=({loading:a,loadingCountries:e,value:u,errors:y,touched:o,onChange:i,onBlur:r,countryOptions:N,regionOptions:v,isRegionRequired:p,hasRegionOptions:l,namePrefix:d="legalAddress",fieldPathPrefix:g="legalAddress",requiredConfig:C})=>{var z;const _=j({legalAddress:"Company.shared.fields.legalAddress",streetAddress:"Company.shared.fields.streetAddress",city:"Company.shared.fields.city",country:"Company.shared.fields.country",stateProvince:"Company.shared.fields.stateProvince",zipPostalCode:"Company.shared.fields.zipPostalCode",phoneNumber:"Company.shared.fields.phoneNumber"}),$={street:`${d}_street`,street2:`${d}_street2`,city:`${d}_city`,countryCode:`${d}_countryCode`,region:`${d}_region`,postcode:`${d}_postcode`,telephone:`${d}_telephone`},m={street:`${g}.street`,street2:`${g}.street2`,city:`${g}.city`,countryCode:`${g}.countryCode`,region:`${g}.region`,regionCode:`${g}.regionCode`,postcode:`${g}.postcode`,telephone:`${g}.telephone`},k={street:(C==null?void 0:C.street)??!0,city:(C==null?void 0:C.city)??!0,postcode:(C==null?void 0:C.postcode)??!0,telephone:(C==null?void 0:C.telephone)??!0},D=w=>P=>{const O=P.target;r(w,O.value)},A={disabled:!!a,variant:"primary",size:"medium"};return h("div",{className:"account-edit-company-profile-form__section",children:[t("h3",{className:"account-edit-company-profile-form__section-title",children:_.legalAddress}),t(R,{label:_.streetAddress,required:k.street,className:"account-edit-company-profile-form__field",error:o[m.street]&&y[m.street]?y[m.street]:void 0,children:t(V,{name:$.street,type:"text",value:u.street,onBlur:D(m.street),...A})}),t(R,{label:`${_.streetAddress} 2`,className:"account-edit-company-profile-form__field",children:t(V,{name:$.street2,type:"text",value:u.street2,onBlur:D(m.street2),...A})}),t(R,{label:_.city,required:k.city,className:"account-edit-company-profile-form__field",error:o[m.city]&&y[m.city]?y[m.city]:void 0,children:t(V,{name:$.city,type:"text",value:u.city,onBlur:D(m.city),...A})}),t(R,{label:_.country,required:!0,className:"account-edit-company-profile-form__field",error:o[m.countryCode]&&y[m.countryCode]?y[m.countryCode]:void 0,children:t(ce,{name:$.countryCode,floatingLabel:`${_.country} *`,placeholder:_.country,options:N,value:u.countryCode,handleSelect:w=>{const P=w.target;i(m.countryCode)(P.value)},onBlur:()=>r(m.countryCode),disabled:!!a||e})}),t(R,{label:_.stateProvince,required:p,className:"account-edit-company-profile-form__field",error:o["legalAddress.region"]&&y["legalAddress.region"]?y["legalAddress.region"]:void 0,children:l?t(ce,{name:"legalAddress_region",floatingLabel:`${_.stateProvince} ${p?"*":""}`,placeholder:_.stateProvince,options:v,value:u.regionCode&&((z=v.find(w=>w.value.split(",")[0]===u.regionCode))==null?void 0:z.value)||"",handleSelect:w=>{var S;const P=w.target,[O]=P.value.split(","),F=((S=v.find(W=>W.value===P.value))==null?void 0:S.text)||"";i(m.region)(F),i(m.regionCode)(O)},onBlur:()=>r(m.region),disabled:!!a||e},`region_picker_${u.countryCode}`):t(V,{name:$.region,type:"text",value:u.region,onBlur:D(m.region),...A,disabled:!!a||e},`region_input_${u.countryCode}`)}),t(R,{label:_.zipPostalCode,required:k.postcode,className:"account-edit-company-profile-form__field",error:o[m.postcode]&&y[m.postcode]?y[m.postcode]:void 0,children:t(V,{name:$.postcode,type:"text",value:u.postcode,onBlur:D(m.postcode),...A})}),t(R,{label:_.phoneNumber,required:k.telephone,className:"account-edit-company-profile-form__field",error:o[m.telephone]&&y[m.telephone]?y[m.telephone]:void 0,children:t(V,{name:$.telephone,type:"tel",value:u.telephone,onBlur:D(m.telephone),...A})})]})},Me=({inLineAlertProps:a,company:e,loading:u=!1,onSubmit:y,onCancel:o})=>{var S,W,q,Y,f,B,Z,ee,te,ae,re,se,le,ne;const i=j({title:"Company.EditCompanyProfile.title",cancel:"Company.shared.buttons.cancel",save:"Company.shared.buttons.save",saving:"Company.shared.buttons.saving",required:"Company.shared.validation.required",invalidEmail:"Company.shared.validation.invalidEmail",companyNameRequired:"Company.shared.validation.companyNameRequired",emailRequired:"Company.shared.validation.emailRequired",emailNotAvailable:"Company.shared.validation.emailNotAvailable",companyNameLengthError:"Company.shared.validation.companyNameLengthError",legalNameLengthError:"Company.shared.validation.legalNameLengthError",vatTaxIdLengthError:"Company.shared.validation.vatTaxIdLengthError",resellerIdLengthError:"Company.shared.validation.resellerIdLengthError"}),[r,N]=L({name:(e==null?void 0:e.name)||"",email:(e==null?void 0:e.email)||"",legalName:(e==null?void 0:e.legalName)||"",vatTaxId:(e==null?void 0:e.vatTaxId)||"",resellerId:(e==null?void 0:e.resellerId)||"",legalAddress:{street:((W=(S=e==null?void 0:e.legalAddress)==null?void 0:S.street)==null?void 0:W[0])||"",street2:((Y=(q=e==null?void 0:e.legalAddress)==null?void 0:q.street)==null?void 0:Y[1])||"",city:((f=e==null?void 0:e.legalAddress)==null?void 0:f.city)||"",region:((Z=(B=e==null?void 0:e.legalAddress)==null?void 0:B.region)==null?void 0:Z.region)||"",regionCode:((te=(ee=e==null?void 0:e.legalAddress)==null?void 0:ee.region)==null?void 0:te.regionCode)||"",countryCode:((ae=e==null?void 0:e.legalAddress)==null?void 0:ae.countryCode)||"",postcode:((re=e==null?void 0:e.legalAddress)==null?void 0:re.postcode)||"",telephone:((se=e==null?void 0:e.legalAddress)==null?void 0:se.telephone)||""}}),[v,p]=L({}),[l,d]=L({}),g=((le=e==null?void 0:e.permissionsFlags)==null?void 0:le.canEditAccount)===!0,C=((ne=e==null?void 0:e.permissionsFlags)==null?void 0:ne.canEditAddress)===!0,{countryOptions:_,regionOptions:$,isRegionRequired:m,hasRegionOptions:k,loadingCountries:D}=we(r.legalAddress.countryCode),A=(s,n)=>s==="name"?n.trim()?n.length>40?i.companyNameLengthError:null:i.companyNameRequired:s==="email"?n.trim()?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(n)?null:i.invalidEmail:i.emailRequired:s==="legalName"?n.length>80?i.legalNameLengthError:null:s==="vatTaxId"?n.length>40?i.vatTaxIdLengthError:null:s==="resellerId"?n.length>40?i.resellerIdLengthError:null:s==="legalAddress.street"||s==="legalAddress.city"||s==="legalAddress.postcode"||s==="legalAddress.telephone"||s==="legalAddress.countryCode"?n.trim()?null:i.required:s==="legalAddress.region"&&m&&!n.trim()?i.required:null,z=()=>{var T,M;const s={};let n=!0;const x=((T=e==null?void 0:e.permissionsFlags)==null?void 0:T.canEditAccount)===!0,c=((M=e==null?void 0:e.permissionsFlags)==null?void 0:M.canEditAddress)===!0;if(x){const I=A("name",r.name);I&&(s.name=I,n=!1);const E=A("email",r.email);if(E&&(s.email=E,n=!1),r.legalName){const b=A("legalName",r.legalName);b&&(s.legalName=b,n=!1)}if(r.vatTaxId){const b=A("vatTaxId",r.vatTaxId);b&&(s.vatTaxId=b,n=!1)}if(r.resellerId){const b=A("resellerId",r.resellerId);b&&(s.resellerId=b,n=!1)}}if(c){const I=A("legalAddress.street",r.legalAddress.street);I&&(s["legalAddress.street"]=I,n=!1);const E=A("legalAddress.city",r.legalAddress.city);E&&(s["legalAddress.city"]=E,n=!1);const b=A("legalAddress.postcode",r.legalAddress.postcode);b&&(s["legalAddress.postcode"]=b,n=!1);const oe=A("legalAddress.telephone",r.legalAddress.telephone);oe&&(s["legalAddress.telephone"]=oe,n=!1);const ie=A("legalAddress.countryCode",r.legalAddress.countryCode);ie&&(s["legalAddress.countryCode"]=ie,n=!1);const de=A("legalAddress.region",r.legalAddress.region);de&&(s["legalAddress.region"]=de,n=!1)}return p(s),n},w=async s=>{var T,M;s.preventDefault();const n=((T=e==null?void 0:e.permissionsFlags)==null?void 0:T.canEditAccount)===!0,x=((M=e==null?void 0:e.permissionsFlags)==null?void 0:M.canEditAddress)===!0,c={};if(n&&(c.name=!0,c.email=!0,c.legalName=!0,c.vatTaxId=!0,c.resellerId=!0),x&&(c["legalAddress.street"]=!0,c["legalAddress.street2"]=!0,c["legalAddress.city"]=!0,c["legalAddress.region"]=!0,c["legalAddress.regionCode"]=!0,c["legalAddress.countryCode"]=!0,c["legalAddress.postcode"]=!0,c["legalAddress.telephone"]=!0),d(c),!!z()){if(n&&r.email!==(e==null?void 0:e.email)){const I=await Ee(r.email);if(!I.isValid){p(E=>({...E,email:I.error||i.emailNotAvailable}));return}}if(y){const I={};n&&(I.name=r.name,I.email=r.email,I.legalName=r.legalName,I.vatTaxId=r.vatTaxId,I.resellerId=r.resellerId),x&&(I.legalAddress={street:[r.legalAddress.street,r.legalAddress.street2].filter(Boolean),city:r.legalAddress.city,region:{region:r.legalAddress.region,regionCode:r.legalAddress.regionCode},countryCode:r.legalAddress.countryCode,postcode:r.legalAddress.postcode,telephone:r.legalAddress.telephone}),await y(I)}}},P=(s,n)=>{if(s.startsWith("legalAddress.")){const x=s.split(".")[1];x==="countryCode"?(N(c=>({...c,legalAddress:{...c.legalAddress,[x]:n,region:"",regionCode:""}})),p(c=>{const T={...c};return delete T["legalAddress.region"],delete T["legalAddress.regionCode"],T}),d(c=>{const T={...c};return delete T["legalAddress.region"],delete T["legalAddress.regionCode"],T})):N(x==="region"?c=>({...c,legalAddress:{...c.legalAddress,region:n,regionCode:k?c.legalAddress.regionCode:n}}):c=>({...c,legalAddress:{...c.legalAddress,[x]:n}}))}else N(x=>({...x,[s]:n}))},O=s=>n=>{const x=new Set(["name","email","legalName","vatTaxId","resellerId"]),c=s.startsWith("legalAddress.");x.has(s)&&!g||c&&!C||(P(s,n),v[s]&&p(M=>{const I={...M};return delete I[s],I}))},F=(s,n)=>{const x=new Set(["name","email","legalName","vatTaxId","resellerId"]),c=s.startsWith("legalAddress.");if(x.has(s)&&!g||c&&!C)return;n!==void 0&&P(s,n),d(E=>({...E,[s]:!0}));let M=n;if(M===void 0)if(s.startsWith("legalAddress.")){const E=s.split(".")[1],b=r.legalAddress[E];M=typeof b=="string"?b:""}else{const E=r[s];M=typeof E=="string"?E:""}const I=A(s,M);p(I?E=>({...E,[s]:I}):E=>{const b={...E};return delete b[s],b})};return h(Q,{variant:"secondary",className:"account-edit-company-profile",children:[t(ue,{title:i.title,divider:!1,className:"account-edit-company-profile__title"}),a!=null&&a.text?t(fe,{className:"account-edit-company-profile__notification",type:a.type,variant:"secondary",heading:a.text,icon:a.icon,"data-testid":"editCompanyInLineAlert"}):null,h("form",{className:"account-edit-company-profile-form",onSubmit:w,children:[g&&t(Pe,{loading:u,value:{name:r.name,email:r.email,legalName:r.legalName,vatTaxId:r.vatTaxId,resellerId:r.resellerId},errors:v,touched:l,onBlur:F}),C&&t(Fe,{loading:u,loadingCountries:D,value:r.legalAddress,errors:v,touched:l,onChange:O,onBlur:F,countryOptions:_,regionOptions:$,isRegionRequired:m,hasRegionOptions:k}),h("div",{className:"account-edit-company-profile__actions",children:[t(X,{disabled:u,type:"button",variant:"secondary",onClick:()=>o==null?void 0:o(),children:i.cancel}),t(X,{disabled:u||!g&&!C,type:"submit",variant:"primary",children:i.save})]})]}),u&&h("div",{className:"account-edit-company-profile__loading-overlay","data-testid":"editCompanyLoadingOverlay",children:[t(ye,{size:"large"}),t("div",{className:"account-edit-company-profile__loading-text",children:i.saving})]})]})},Qe=({className:a,withHeader:e=!0,slots:u})=>{const y=j({containerTitle:"Company.CompanyProfile.containerTitle"}),{inLineAlertProps:o,handleSetInLineAlert:i}=be(),r=J(null),{company:N,loading:v,saving:p,showEditForm:l,handleShowEditForm:d,handleHideEditForm:g,handleUpdateCompany:C}=$e({handleSetInLineAlert:i,editFormRef:r});return v?t("div",{"data-testid":"companyProfileLoader",children:t(xe,{withCard:!0})}):h("div",{className:me(["account-company-profile",a]),children:[e?t(ue,{title:y.containerTitle,divider:!1,className:"company-profile__title"}):null,t(Te,{company:N,slots:u,showEditForm:l,handleShowEditForm:d}),l?t("div",{ref:r,children:t(Me,{inLineAlertProps:o,company:N,loading:p,onSubmit:C,onCancel:g})}):null]})};export{Qe as CompanyProfile,Qe as default};
3
+ import{jsx as t,jsxs as g,Fragment as K}from"@dropins/tools/preact-jsx-runtime.js";import{classes as me,Slot as pe}from"@dropins/tools/lib.js";import{useState as V,useRef as J,useEffect as j,useCallback as U,useMemo as G}from"@dropins/tools/preact-hooks.js";import{events as ge}from"@dropins/tools/event-bus.js";import{p as he,E as fe}from"../chunks/acdl.js";import{u as ye}from"../chunks/useCompanyContextListener.js";import{g as ve,u as Ce}from"../chunks/updateCompany.js";import{g as ue,v as Ae}from"../chunks/validateCompanyEmail.js";import{useText as H}from"@dropins/tools/i18n.js";import{u as Ne}from"../chunks/useInLineAlert.js";import{c as Ie}from"../chunks/CompanyLoaders.js";import{Card as Q,IllustratedMessage as _e,Button as X,Field as R,Input as L,Picker as ce,Header as Ee,InLineAlert as be,ProgressSpinner as xe}from"@dropins/tools/components.js";import"../chunks/fetchUserPermissions.js";import"../chunks/company-permissions.js";import"../chunks/fetch-error.js";import"../chunks/network-error.js";import"@dropins/tools/fetch-graphql.js";import"@dropins/tools/preact-compat.js";const $e=({company:a,slots:e,showEditForm:u,handleShowEditForm:f})=>{const n=H({editButton:"Company.shared.buttons.edit",noDataMessage:"Company.CompanyProfile.companyProfileCard.noDataMessage",companyName:"Company.shared.fields.companyName",email:"Company.shared.fields.email",legalName:"Company.shared.fields.legalName",vatTaxId:"Company.shared.fields.vatTaxId",resellerId:"Company.shared.fields.resellerId",legalAddress:"Company.shared.fields.legalAddress",contacts:"Company.CompanyProfile.companyProfileCard.contacts",companyAdministrator:"Company.CompanyProfile.companyProfileCard.companyAdministrator",salesRepresentative:"Company.CompanyProfile.companyProfileCard.salesRepresentative",paymentInformation:"Company.CompanyProfile.companyProfileCard.paymentInformation",shippingInformation:"Company.CompanyProfile.companyProfileCard.shippingInformation",availablePaymentMethods:"Company.CompanyProfile.companyProfileCard.availablePaymentMethods",availableShippingMethods:"Company.CompanyProfile.companyProfileCard.availableShippingMethods",noPaymentMethods:"Company.CompanyProfile.companyProfileCard.noPaymentMethods",noShippingMethods:"Company.CompanyProfile.companyProfileCard.noShippingMethods"});if(!a)return t(Q,{variant:"secondary",className:"account-company-profile-card",children:t("div",{className:"account-company-profile-card__wrapper",children:t("div",{className:"account-company-profile-card__content",children:t("div",{className:"account-company-profile-card__no-data",children:t(_e,{message:t("p",{children:n.noDataMessage})})})})})});const o=a.permissionsFlags||{canViewAccount:!0,canViewAddress:!0,canViewContacts:!0,canViewPaymentInformation:!0,canViewShippingInformation:!0},r=[o.canViewAccount?{name:"name",label:n.companyName,value:a.name||"",legalName:a.legalName||""}:null,o.canViewAccount?{name:"email",label:n.email,value:a.email||""}:null,o.canViewAccount?{name:"vatTaxId",label:n.vatTaxId,value:a.vatTaxId||""}:null,o.canViewAccount?{name:"resellerId",label:n.resellerId,value:a.resellerId||""}:null].filter(Boolean);return t(Q,{variant:"secondary",className:me(["account-company-profile-card",["account-company-profile-card-short",u]]),children:g("div",{className:"account-company-profile-card__wrapper",children:[t("div",{className:"account-company-profile-card__actions",children:(a.canEditAccount||a.canEditAddress)&&t(X,{type:"button",variant:"tertiary",onClick:f,children:n.editButton})}),t("div",{className:"account-company-profile-card__content",children:(()=>{var y,p;const A=g(K,{children:[r.map((l,d)=>{if(!l.value)return null;let v;return l.name==="name"&&l.legalName?v=`${l.label}: ${l.value} (${l.legalName})`:v=l.label?`${l.label}: ${l.value}`:l.value,t("p",{"data-testid":`${l.name}_${d}`,children:v},`${l.name}_${d}`)}),o.canViewAddress&&a.legalAddress&&g("div",{className:"company-legal-address",children:[t("p",{children:g("strong",{children:[n.legalAddress,":"]})}),(y=a.legalAddress.street)==null?void 0:y.map((l,d)=>t("p",{children:l},d)),g("p",{children:[a.legalAddress.city,", ",(p=a.legalAddress.region)==null?void 0:p.region," ",a.legalAddress.postcode]}),t("p",{children:a.legalAddress.countryCode}),a.legalAddress.telephone&&g("p",{children:["Phone: ",a.legalAddress.telephone]})]}),o.canViewContacts&&(a.companyAdmin||a.salesRepresentative)&&g("div",{className:"company-contacts",children:[t("p",{children:g("strong",{children:[n.contacts,":"]})}),a.companyAdmin&&g("div",{className:"company-contact",children:[t("p",{children:g("strong",{children:[n.companyAdministrator,":"]})}),g("p",{children:[a.companyAdmin.firstname," ",a.companyAdmin.lastname]}),a.companyAdmin.jobTitle&&t("p",{children:a.companyAdmin.jobTitle}),t("p",{children:a.companyAdmin.email})]}),a.salesRepresentative&&g("div",{className:"company-contact",children:[t("p",{children:g("strong",{children:[n.salesRepresentative,":"]})}),g("p",{children:[a.salesRepresentative.firstname," ",a.salesRepresentative.lastname]}),t("p",{children:a.salesRepresentative.email})]})]}),o.canViewPaymentInformation&&g("div",{className:"company-payment-methods",children:[t("p",{children:g("strong",{children:[n.paymentInformation,":"]})}),a.availablePaymentMethods&&a.availablePaymentMethods.length>0?g(K,{children:[t("p",{children:g("strong",{children:[n.availablePaymentMethods,":"]})}),t("ul",{className:"payment-methods-list",children:a.availablePaymentMethods.map((l,d)=>t("li",{children:l.title},`payment_${d}`))})]}):t("div",{className:"message message-notice notice",children:t("div",{children:n.noPaymentMethods})})]}),o.canViewShippingInformation&&g("div",{className:"company-shipping-methods",children:[t("p",{children:g("strong",{children:[n.shippingInformation,":"]})}),a.availableShippingMethods&&a.availableShippingMethods.length>0?g(K,{children:[t("p",{children:g("strong",{children:[n.availableShippingMethods,":"]})}),t("ul",{className:"shipping-methods-list",children:a.availableShippingMethods.map((l,d)=>t("li",{children:l.title},`shipping_${d}`))})]}):t("div",{className:"message message-notice notice",children:t("div",{children:n.noShippingMethods})})]})]});return e!=null&&e.CompanyData?t(pe,{name:"CompanyData",slot:e.CompanyData,context:{companyData:r,Default:A}}):A})()})]})})},Te=({handleSetInLineAlert:a,editFormRef:e})=>{const u=H({companySuccess:"Company.CompanyProfile.editCompanyProfile.companySuccess",companyError:"Company.CompanyProfile.editCompanyProfile.companyError",loadError:"Company.CompanyProfile.messages.loadError",updateError:"Company.CompanyProfile.messages.updateError",noDataToUpdate:"Company.CompanyProfile.messages.noDataToUpdate"}),{companySuccess:f,companyError:n,loadError:o,updateError:r,noDataToUpdate:A}=u,[y,p]=V(null),[l,d]=V(!0),[v,N]=V(!1),[_,T]=V(!1),[m,k]=V([]),[D,C]=V({}),z=J(a),w=J(!1),P=J(!1);j(()=>{z.current=a},[a]);const O=U(h=>{C(h)},[]),F=U((h,B)=>{a&&(h==="success"?a({type:"success",text:B??f}):h==="error"?a({type:"error",text:B??n}):a(),N(!1))},[a,f,n]),S=U(async()=>{if(w.current)return null;w.current=!0,d(!0);try{const h=await ve();return h&&p(h),d(!1),h}catch(h){return console.error("Failed to load company:",h),d(!1),z.current&&z.current({type:"error",text:o}),null}finally{w.current=!1}},[o]);j(()=>{P.current||(P.current=!0,S())},[S]),ye(U(()=>{d(!0),T(!1),C({}),S()},[S])),j(()=>{ue().then(h=>{k(h.availableCountries)}).catch(h=>{console.error("Failed to load countries:",h)})},[]);const W=U(()=>{T(!0),F("success",""),C({})},[F]);j(()=>{_&&(e!=null&&e.current)&&setTimeout(()=>{var h;(h=e.current)==null||h.scrollIntoView({behavior:"smooth",block:"start",inline:"nearest"})},100)},[_,e]);const q=U(h=>{h==null||h(),T(!1),C({})},[]),Y=U(async h=>{try{if(N(!0),!h){F("error",A);return}const B=await Ce(h);p(B),T(!1),C({}),F("success"),he(fe.EDIT_COMPANY_EVENT,{...h,companyId:y==null?void 0:y.id}),ge.emit("company/updated",{company:B})}catch(B){console.error("Failed to update company:",B),F("error",B.message||r)}finally{N(!1)}},[y,F,r,A]);return{company:y,countries:m,loading:l,submitLoading:v,showEditForm:_,inputChange:D,handleShowEditForm:W,handleHideEditForm:q,handleUpdateCompany:Y,handleInputChange:O,renderAlertMessage:F,saving:v}},we=a=>{const[e,u]=V(null),[f,n]=V(!0);j(()=>{let p=!0;return ue().then(({availableCountries:l,countriesWithRequiredRegion:d,optionalZipCountries:v})=>{p&&(u({availableCountries:l,countriesWithRequiredRegion:d,optionalZipCountries:v}),n(!1))}).catch(()=>{p&&n(!1)}),()=>{p=!1}},[]);const o=G(()=>(e==null?void 0:e.availableCountries)||[],[e]),r=G(()=>{if(!a||!e)return[];const p=e.availableCountries.find(l=>l.value===a);return!(p!=null&&p.availableRegions)||p.availableRegions.length===0?[]:p.availableRegions.map(l=>({text:l.name,value:`${l.code},${l.id}`}))},[a,e]),A=G(()=>!a||!e?!1:e.countriesWithRequiredRegion.includes(a),[a,e]),y=G(()=>r.length>0,[r]);return{countryOptions:o,regionOptions:r,isRegionRequired:A,hasRegionOptions:y,loadingCountries:f}},Pe=({loading:a,value:e,errors:u,touched:f,onBlur:n,namePrefix:o="",fieldPathPrefix:r=""})=>{const A=H({accountInformation:"Company.shared.fields.accountInformation",companyName:"Company.shared.fields.companyName",email:"Company.shared.fields.email",legalName:"Company.shared.fields.legalName",vatTaxId:"Company.shared.fields.vatTaxId",resellerId:"Company.shared.fields.resellerId"}),y=o?`${o}_`:"",p=v=>r?`${r}.${v}`:v,l=v=>N=>{const _=N.target;n(p(v),_.value)},d={disabled:!!a,variant:"primary",size:"medium"};return g("div",{className:"account-edit-company-profile-form__group",children:[t("h3",{className:"account-edit-company-profile-form__section-title",children:A.accountInformation}),t(R,{label:A.companyName,required:!0,className:"account-edit-company-profile-form__field",error:f.name&&u.name?u.name:void 0,children:t(L,{name:`${y}name`,type:"text",value:e.name,onBlur:l("name"),...d,maxLength:40})}),t(R,{label:A.legalName,className:"account-edit-company-profile-form__field",children:t(L,{name:`${y}legalName`,type:"text",value:e.legalName,onBlur:l("legalName"),...d,maxLength:80})}),t(R,{label:A.email,required:!0,className:"account-edit-company-profile-form__field",error:f.email&&u.email?u.email:void 0,children:t(L,{name:`${y}email`,type:"email",value:e.email,onBlur:l("email"),...d})}),t(R,{label:A.vatTaxId,className:"account-edit-company-profile-form__field",children:t(L,{name:`${y}vatTaxId`,type:"text",value:e.vatTaxId,onBlur:l("vatTaxId"),...d,maxLength:40})}),t(R,{label:A.resellerId,className:"account-edit-company-profile-form__field",children:t(L,{name:`${y}resellerId`,type:"text",value:e.resellerId,onBlur:l("resellerId"),...d,maxLength:40})})]})},Fe=({loading:a,loadingCountries:e,value:u,errors:f,touched:n,onChange:o,onBlur:r,countryOptions:A,regionOptions:y,isRegionRequired:p,hasRegionOptions:l,namePrefix:d="legalAddress",fieldPathPrefix:v="legalAddress",requiredConfig:N})=>{var z;const _=H({legalAddress:"Company.shared.fields.legalAddress",streetAddress:"Company.shared.fields.streetAddress",city:"Company.shared.fields.city",country:"Company.shared.fields.country",stateProvince:"Company.shared.fields.stateProvince",zipPostalCode:"Company.shared.fields.zipPostalCode",phoneNumber:"Company.shared.fields.phoneNumber"}),T={street:`${d}_street`,street2:`${d}_street2`,city:`${d}_city`,countryCode:`${d}_countryCode`,region:`${d}_region`,postcode:`${d}_postcode`,telephone:`${d}_telephone`},m={street:`${v}.street`,street2:`${v}.street2`,city:`${v}.city`,countryCode:`${v}.countryCode`,region:`${v}.region`,regionCode:`${v}.regionCode`,postcode:`${v}.postcode`,telephone:`${v}.telephone`},k={street:(N==null?void 0:N.street)??!0,city:(N==null?void 0:N.city)??!0,postcode:(N==null?void 0:N.postcode)??!0,telephone:(N==null?void 0:N.telephone)??!0},D=w=>P=>{const O=P.target;r(w,O.value)},C={disabled:!!a,variant:"primary",size:"medium"};return g("div",{className:"account-edit-company-profile-form__section",children:[t("h3",{className:"account-edit-company-profile-form__section-title",children:_.legalAddress}),t(R,{label:_.streetAddress,required:k.street,className:"account-edit-company-profile-form__field",error:n[m.street]&&f[m.street]?f[m.street]:void 0,children:t(L,{name:T.street,type:"text",value:u.street,onBlur:D(m.street),...C})}),t(R,{label:`${_.streetAddress} 2`,className:"account-edit-company-profile-form__field",children:t(L,{name:T.street2,type:"text",value:u.street2,onBlur:D(m.street2),...C})}),t(R,{label:_.city,required:k.city,className:"account-edit-company-profile-form__field",error:n[m.city]&&f[m.city]?f[m.city]:void 0,children:t(L,{name:T.city,type:"text",value:u.city,onBlur:D(m.city),...C})}),t(R,{label:_.country,required:!0,className:"account-edit-company-profile-form__field",error:n[m.countryCode]&&f[m.countryCode]?f[m.countryCode]:void 0,children:t(ce,{name:T.countryCode,floatingLabel:`${_.country} *`,placeholder:_.country,options:A,value:u.countryCode,handleSelect:w=>{const P=w.target;o(m.countryCode)(P.value)},onBlur:()=>r(m.countryCode),disabled:!!a||e})}),t(R,{label:_.stateProvince,required:p,className:"account-edit-company-profile-form__field",error:n["legalAddress.region"]&&f["legalAddress.region"]?f["legalAddress.region"]:void 0,children:l?t(ce,{name:"legalAddress_region",floatingLabel:`${_.stateProvince} ${p?"*":""}`,placeholder:_.stateProvince,options:y,value:u.regionCode&&((z=y.find(w=>w.value.split(",")[0]===u.regionCode))==null?void 0:z.value)||"",handleSelect:w=>{var S;const P=w.target,[O]=P.value.split(","),F=((S=y.find(W=>W.value===P.value))==null?void 0:S.text)||"";o(m.region)(F),o(m.regionCode)(O)},onBlur:()=>r(m.region),disabled:!!a||e},`region_picker_${u.countryCode}`):t(L,{name:T.region,type:"text",value:u.region,onBlur:D(m.region),...C,disabled:!!a||e},`region_input_${u.countryCode}`)}),t(R,{label:_.zipPostalCode,required:k.postcode,className:"account-edit-company-profile-form__field",error:n[m.postcode]&&f[m.postcode]?f[m.postcode]:void 0,children:t(L,{name:T.postcode,type:"text",value:u.postcode,onBlur:D(m.postcode),...C})}),t(R,{label:_.phoneNumber,required:k.telephone,className:"account-edit-company-profile-form__field",error:n[m.telephone]&&f[m.telephone]?f[m.telephone]:void 0,children:t(L,{name:T.telephone,type:"tel",value:u.telephone,onBlur:D(m.telephone),...C})})]})},Me=({inLineAlertProps:a,company:e,loading:u=!1,onSubmit:f,onCancel:n})=>{var S,W,q,Y,h,B,Z,ee,te,ae,re,se,le,ne;const o=H({title:"Company.EditCompanyProfile.title",cancel:"Company.shared.buttons.cancel",save:"Company.shared.buttons.save",saving:"Company.shared.buttons.saving",required:"Company.shared.validation.required",invalidEmail:"Company.shared.validation.invalidEmail",companyNameRequired:"Company.shared.validation.companyNameRequired",emailRequired:"Company.shared.validation.emailRequired",emailNotAvailable:"Company.shared.validation.emailNotAvailable",companyNameLengthError:"Company.shared.validation.companyNameLengthError",legalNameLengthError:"Company.shared.validation.legalNameLengthError",vatTaxIdLengthError:"Company.shared.validation.vatTaxIdLengthError",resellerIdLengthError:"Company.shared.validation.resellerIdLengthError"}),[r,A]=V({name:(e==null?void 0:e.name)||"",email:(e==null?void 0:e.email)||"",legalName:(e==null?void 0:e.legalName)||"",vatTaxId:(e==null?void 0:e.vatTaxId)||"",resellerId:(e==null?void 0:e.resellerId)||"",legalAddress:{street:((W=(S=e==null?void 0:e.legalAddress)==null?void 0:S.street)==null?void 0:W[0])||"",street2:((Y=(q=e==null?void 0:e.legalAddress)==null?void 0:q.street)==null?void 0:Y[1])||"",city:((h=e==null?void 0:e.legalAddress)==null?void 0:h.city)||"",region:((Z=(B=e==null?void 0:e.legalAddress)==null?void 0:B.region)==null?void 0:Z.region)||"",regionCode:((te=(ee=e==null?void 0:e.legalAddress)==null?void 0:ee.region)==null?void 0:te.regionCode)||"",countryCode:((ae=e==null?void 0:e.legalAddress)==null?void 0:ae.countryCode)||"",postcode:((re=e==null?void 0:e.legalAddress)==null?void 0:re.postcode)||"",telephone:((se=e==null?void 0:e.legalAddress)==null?void 0:se.telephone)||""}}),[y,p]=V({}),[l,d]=V({}),v=((le=e==null?void 0:e.permissionsFlags)==null?void 0:le.canEditAccount)===!0,N=((ne=e==null?void 0:e.permissionsFlags)==null?void 0:ne.canEditAddress)===!0,{countryOptions:_,regionOptions:T,isRegionRequired:m,hasRegionOptions:k,loadingCountries:D}=we(r.legalAddress.countryCode),C=(s,i)=>s==="name"?i.trim()?i.length>40?o.companyNameLengthError:null:o.companyNameRequired:s==="email"?i.trim()?/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i)?null:o.invalidEmail:o.emailRequired:s==="legalName"?i.length>80?o.legalNameLengthError:null:s==="vatTaxId"?i.length>40?o.vatTaxIdLengthError:null:s==="resellerId"?i.length>40?o.resellerIdLengthError:null:s==="legalAddress.street"||s==="legalAddress.city"||s==="legalAddress.postcode"||s==="legalAddress.telephone"||s==="legalAddress.countryCode"?i.trim()?null:o.required:s==="legalAddress.region"&&m&&!i.trim()?o.required:null,z=()=>{var $,M;const s={};let i=!0;const x=(($=e==null?void 0:e.permissionsFlags)==null?void 0:$.canEditAccount)===!0,c=((M=e==null?void 0:e.permissionsFlags)==null?void 0:M.canEditAddress)===!0;if(x){const I=C("name",r.name);I&&(s.name=I,i=!1);const E=C("email",r.email);if(E&&(s.email=E,i=!1),r.legalName){const b=C("legalName",r.legalName);b&&(s.legalName=b,i=!1)}if(r.vatTaxId){const b=C("vatTaxId",r.vatTaxId);b&&(s.vatTaxId=b,i=!1)}if(r.resellerId){const b=C("resellerId",r.resellerId);b&&(s.resellerId=b,i=!1)}}if(c){const I=C("legalAddress.street",r.legalAddress.street);I&&(s["legalAddress.street"]=I,i=!1);const E=C("legalAddress.city",r.legalAddress.city);E&&(s["legalAddress.city"]=E,i=!1);const b=C("legalAddress.postcode",r.legalAddress.postcode);b&&(s["legalAddress.postcode"]=b,i=!1);const oe=C("legalAddress.telephone",r.legalAddress.telephone);oe&&(s["legalAddress.telephone"]=oe,i=!1);const ie=C("legalAddress.countryCode",r.legalAddress.countryCode);ie&&(s["legalAddress.countryCode"]=ie,i=!1);const de=C("legalAddress.region",r.legalAddress.region);de&&(s["legalAddress.region"]=de,i=!1)}return p(s),i},w=async s=>{var $,M;s.preventDefault();const i=(($=e==null?void 0:e.permissionsFlags)==null?void 0:$.canEditAccount)===!0,x=((M=e==null?void 0:e.permissionsFlags)==null?void 0:M.canEditAddress)===!0,c={};if(i&&(c.name=!0,c.email=!0,c.legalName=!0,c.vatTaxId=!0,c.resellerId=!0),x&&(c["legalAddress.street"]=!0,c["legalAddress.street2"]=!0,c["legalAddress.city"]=!0,c["legalAddress.region"]=!0,c["legalAddress.regionCode"]=!0,c["legalAddress.countryCode"]=!0,c["legalAddress.postcode"]=!0,c["legalAddress.telephone"]=!0),d(c),!!z()){if(i&&r.email!==(e==null?void 0:e.email)){const I=await Ae(r.email);if(!I.isValid){p(E=>({...E,email:I.error||o.emailNotAvailable}));return}}if(f){const I={};i&&(I.name=r.name,I.email=r.email,I.legalName=r.legalName,I.vatTaxId=r.vatTaxId,I.resellerId=r.resellerId),x&&(I.legalAddress={street:[r.legalAddress.street,r.legalAddress.street2].filter(Boolean),city:r.legalAddress.city,region:{region:r.legalAddress.region,regionCode:r.legalAddress.regionCode},countryCode:r.legalAddress.countryCode,postcode:r.legalAddress.postcode,telephone:r.legalAddress.telephone}),await f(I)}}},P=(s,i)=>{if(s.startsWith("legalAddress.")){const x=s.split(".")[1];x==="countryCode"?(A(c=>({...c,legalAddress:{...c.legalAddress,[x]:i,region:"",regionCode:""}})),p(c=>{const $={...c};return delete $["legalAddress.region"],delete $["legalAddress.regionCode"],$}),d(c=>{const $={...c};return delete $["legalAddress.region"],delete $["legalAddress.regionCode"],$})):A(x==="region"?c=>({...c,legalAddress:{...c.legalAddress,region:i,regionCode:k?c.legalAddress.regionCode:i}}):c=>({...c,legalAddress:{...c.legalAddress,[x]:i}}))}else A(x=>({...x,[s]:i}))},O=s=>i=>{const x=new Set(["name","email","legalName","vatTaxId","resellerId"]),c=s.startsWith("legalAddress.");x.has(s)&&!v||c&&!N||(P(s,i),y[s]&&p(M=>{const I={...M};return delete I[s],I}))},F=(s,i)=>{const x=new Set(["name","email","legalName","vatTaxId","resellerId"]),c=s.startsWith("legalAddress.");if(x.has(s)&&!v||c&&!N)return;i!==void 0&&P(s,i),d(E=>({...E,[s]:!0}));let M=i;if(M===void 0)if(s.startsWith("legalAddress.")){const E=s.split(".")[1],b=r.legalAddress[E];M=typeof b=="string"?b:""}else{const E=r[s];M=typeof E=="string"?E:""}const I=C(s,M);p(I?E=>({...E,[s]:I}):E=>{const b={...E};return delete b[s],b})};return g(Q,{variant:"secondary",className:"account-edit-company-profile",children:[t(Ee,{title:o.title,divider:!1,className:"account-edit-company-profile__title"}),a!=null&&a.text?t(be,{className:"account-edit-company-profile__notification",type:a.type,variant:"secondary",heading:a.text,icon:a.icon,"data-testid":"editCompanyInLineAlert"}):null,g("form",{className:"account-edit-company-profile-form",onSubmit:w,children:[v&&t(Pe,{loading:u,value:{name:r.name,email:r.email,legalName:r.legalName,vatTaxId:r.vatTaxId,resellerId:r.resellerId},errors:y,touched:l,onBlur:F}),N&&t(Fe,{loading:u,loadingCountries:D,value:r.legalAddress,errors:y,touched:l,onChange:O,onBlur:F,countryOptions:_,regionOptions:T,isRegionRequired:m,hasRegionOptions:k}),g("div",{className:"account-edit-company-profile__actions",children:[t(X,{disabled:u,type:"button",variant:"secondary",onClick:()=>n==null?void 0:n(),children:o.cancel}),t(X,{disabled:u||!v&&!N,type:"submit",variant:"primary",children:o.save})]})]}),u&&g("div",{className:"account-edit-company-profile__loading-overlay","data-testid":"editCompanyLoadingOverlay",children:[t(xe,{size:"large"}),t("div",{className:"account-edit-company-profile__loading-text",children:o.saving})]})]})},Qe=({className:a,slots:e})=>{const{inLineAlertProps:u,handleSetInLineAlert:f}=Ne(),n=J(null),{company:o,loading:r,saving:A,showEditForm:y,handleShowEditForm:p,handleHideEditForm:l,handleUpdateCompany:d}=Te({handleSetInLineAlert:f,editFormRef:n});return r?t("div",{"data-testid":"companyProfileLoader",children:t(Ie,{withCard:!0})}):g("div",{className:me(["account-company-profile",a]),children:[t($e,{company:o,slots:e,showEditForm:y,handleShowEditForm:p}),y?t("div",{ref:n,children:t(Me,{inLineAlertProps:u,company:o,loading:A,onSubmit:d,onCancel:l})}):null]})};export{Qe as CompanyProfile,Qe as default};
4
4
  //# sourceMappingURL=CompanyProfile.js.map