@greatapps/common 1.1.357 → 1.1.358

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.
@@ -79,7 +79,7 @@ class ApiClient {
79
79
  });
80
80
  if (!response.ok) {
81
81
  const errBody = await response.text();
82
- let message = `HTTP error ${response.status} ${response.statusText} ${errBody}`;
82
+ let message = `HTTP error ${response.status}`;
83
83
  let code = "HTTP_ERROR";
84
84
  try {
85
85
  const errorData = JSON.parse(errBody);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/infra/api/client.ts"],"sourcesContent":["import { ApiError } from \"./types\";\r\nimport { findWhitelabel } from \"../../modules/whitelabel/actions/find-whitelabel.action\";\r\n\r\nexport interface ApiClientOptions {\r\n /**\r\n * Quando true, monta `{base}/{locale}/{wlId}{endpoint}` (ex.: r2-clone).\r\n * Padrão false: `{base}/v1/{locale}/{wlId}{endpoint}`.\r\n */\r\n omitApiVersion?: boolean;\r\n\r\n /** Habilita logs detalhados das requisições (útil para desenvolvimento) */\r\n emitLogs?: boolean;\r\n}\r\n\r\nexport interface RequestConfig extends RequestInit {\r\n timeout?: number;\r\n /** Padrão `json`. Use `text` quando a API devolve corpo não-JSON. */\r\n responseType?: \"json\" | \"text\";\r\n /** Força um whiteLabelId específico na URL, ignorando o findWhitelabel(). */\r\n whiteLabelId?: number;\r\n /** Força um token específico no header Authorization, ignorando o findWhitelabel(). */\r\n authToken?: string;\r\n}\r\n\r\nclass ApiClient {\r\n private readonly baseUrl: string;\r\n private readonly apiVersion = \"v1\";\r\n private readonly apiLocale = \"pt-br\";\r\n private readonly omitApiVersion: boolean;\r\n private readonly emitLogs: boolean = false;\r\n\r\n constructor(baseUrl: string, options?: ApiClientOptions) {\r\n this.baseUrl = baseUrl.replace(/\\/$/, \"\");\r\n this.omitApiVersion = options?.omitApiVersion ?? false;\r\n this.emitLogs = options?.emitLogs ?? false;\r\n }\r\n\r\n private async buildUrl(\r\n endpoint: string,\r\n whiteLabelId: number,\r\n ): Promise<string> {\r\n const wlPath = this.omitApiVersion\r\n ? `/${this.apiLocale}/${whiteLabelId}`\r\n : `/${this.apiVersion}/${this.apiLocale}/${whiteLabelId}`;\r\n const path = endpoint.startsWith(\"/\") ? endpoint : `/${endpoint}`;\r\n const url = `${this.baseUrl}${wlPath}${path}`;\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] buildUrl\", {\r\n baseURL: this.baseUrl,\r\n whiteLabelId,\r\n endpoint,\r\n fullUrl: url,\r\n });\r\n }\r\n return url;\r\n }\r\n\r\n private async getDefaultHeaders(\r\n token: string,\r\n isFormData = false,\r\n ): Promise<HeadersInit> {\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] getDefaultHeaders\", {\r\n token: token.substring(0, 20) + \"...\",\r\n });\r\n }\r\n\r\n const headers: HeadersInit = {\r\n authorization: token,\r\n };\r\n\r\n if (!isFormData) {\r\n headers[\"Content-Type\"] = \"application/json\";\r\n }\r\n\r\n return headers;\r\n }\r\n\r\n async request<T>(endpoint: string, config: RequestConfig = {}): Promise<T> {\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] request called\", {\r\n endpoint,\r\n method: config.method,\r\n });\r\n }\r\n\r\n const { timeout = 30000, responseType = \"json\", whiteLabelId: overrideWlId, authToken: overrideToken, ...fetchConfig } = config;\r\n\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), timeout);\r\n\r\n try {\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] Building URL and headers...\");\r\n }\r\n\r\n const { id, token } = await findWhitelabel();\r\n\r\n const [url, defaultHeaders] = await Promise.all([\r\n this.buildUrl(endpoint, overrideWlId ?? id),\r\n this.getDefaultHeaders(overrideToken ?? token, fetchConfig.body instanceof FormData),\r\n ]);\r\n\r\n if (this.emitLogs)\r\n console.log(\"[ApiClient] Fetching\", {\r\n url,\r\n method: fetchConfig.method,\r\n headers: defaultHeaders,\r\n });\r\n\r\n const response = await fetch(url, {\r\n ...fetchConfig,\r\n headers: {\r\n ...defaultHeaders,\r\n ...fetchConfig.headers,\r\n },\r\n signal: controller.signal,\r\n });\r\n\r\n if (this.emitLogs)\r\n console.log(\"[ApiClient] Response received\", {\r\n status: response.status,\r\n ok: response.ok,\r\n });\r\n\r\n if (!response.ok) {\r\n const errBody = await response.text();\r\n let message = `HTTP error ${response.status} ${response.statusText} ${errBody}`;\r\n let code = \"HTTP_ERROR\";\r\n try {\r\n const errorData = JSON.parse(errBody) as Record<string, unknown>;\r\n if (typeof errorData.message === \"string\")\r\n message = errorData.message;\r\n if (typeof errorData.code === \"string\") code = errorData.code;\r\n } catch {\r\n if (errBody.trim()) message = errBody.trim();\r\n }\r\n console.error(\"[ApiClient] Request failed\", {\r\n status: response.status,\r\n message,\r\n });\r\n throw new ApiError(message, code, response.status);\r\n }\r\n\r\n if (responseType === \"text\") {\r\n return (await response.text()) as T;\r\n }\r\n\r\n const data = (await response.json()) as T;\r\n if (this.emitLogs)\r\n console.log(\"[ApiClient] Request successful\", { hasData: !!data });\r\n return data;\r\n } catch (error) {\r\n if (this.emitLogs) console.error(\"[ApiClient] Request error\", { error });\r\n\r\n if (error instanceof ApiError) {\r\n throw error;\r\n }\r\n\r\n if (error instanceof Error) {\r\n if (error.name === \"AbortError\") {\r\n throw new ApiError(\"Tempo de requisição excedido\", \"TIMEOUT\", 408);\r\n }\r\n throw new ApiError(error.message, \"NETWORK_ERROR\", 0);\r\n }\r\n\r\n throw new ApiError(\"Erro desconhecido\", \"UNKNOWN_ERROR\", 500);\r\n } finally {\r\n clearTimeout(timeoutId);\r\n }\r\n }\r\n\r\n async get<T>(endpoint: string, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, { ...config, method: \"GET\" });\r\n }\r\n\r\n async post<T>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"POST\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : undefined,\r\n });\r\n }\r\n\r\n async put<T>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"PUT\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : undefined,\r\n });\r\n }\r\n\r\n async patch<T>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"PATCH\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : undefined,\r\n });\r\n }\r\n\r\n async delete<T>(endpoint: string, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, { ...config, method: \"DELETE\" });\r\n }\r\n}\r\n\r\nconst api = {\r\n apps: new ApiClient(\r\n process.env.GAPPS_R3_API_URL || \"https://r3-api.greatapps.dev.br\",\r\n ),\r\n pages: new ApiClient(\r\n process.env.GPAGES_R3_API_URL || \"https://r3-api.greatpages.dev.br\",\r\n ),\r\n};\r\n\r\n/** @deprecated use api.apps */\r\nexport const apiClient = api.apps;\r\n\r\nexport { api, ApiClient };\r\n"],"mappings":"AAAA,SAAS,gBAAgB;AACzB,SAAS,sBAAsB;AAuB/B,MAAM,UAAU;AAAA,EACG;AAAA,EACA,aAAa;AAAA,EACb,YAAY;AAAA,EACZ;AAAA,EACA,WAAoB;AAAA,EAErC,YAAY,SAAiB,SAA4B;AACvD,SAAK,UAAU,QAAQ,QAAQ,OAAO,EAAE;AACxC,SAAK,iBAAiB,SAAS,kBAAkB;AACjD,SAAK,WAAW,SAAS,YAAY;AAAA,EACvC;AAAA,EAEA,MAAc,SACZ,UACA,cACiB;AACjB,UAAM,SAAS,KAAK,iBAChB,IAAI,KAAK,SAAS,IAAI,YAAY,KAClC,IAAI,KAAK,UAAU,IAAI,KAAK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,IAAI,oBAAoB;AAAA,EAClC;AAAA,EACA,OAAO,IAAI;AAAA,IACT,QAAQ,IAAI,qBAAqB;AAAA,EACnC;AACF;AAGO,MAAM,YAAY,IAAI;","names":[]}
1
+ {"version":3,"sources":["../../../src/infra/api/client.ts"],"sourcesContent":["import { ApiError } from \"./types\";\r\nimport { findWhitelabel } from \"../../modules/whitelabel/actions/find-whitelabel.action\";\r\n\r\nexport interface ApiClientOptions {\r\n /**\r\n * Quando true, monta `{base}/{locale}/{wlId}{endpoint}` (ex.: r2-clone).\r\n * Padrão false: `{base}/v1/{locale}/{wlId}{endpoint}`.\r\n */\r\n omitApiVersion?: boolean;\r\n\r\n /** Habilita logs detalhados das requisições (útil para desenvolvimento) */\r\n emitLogs?: boolean;\r\n}\r\n\r\nexport interface RequestConfig extends RequestInit {\r\n timeout?: number;\r\n /** Padrão `json`. Use `text` quando a API devolve corpo não-JSON. */\r\n responseType?: \"json\" | \"text\";\r\n /** Força um whiteLabelId específico na URL, ignorando o findWhitelabel(). */\r\n whiteLabelId?: number;\r\n /** Força um token específico no header Authorization, ignorando o findWhitelabel(). */\r\n authToken?: string;\r\n}\r\n\r\nclass ApiClient {\r\n private readonly baseUrl: string;\r\n private readonly apiVersion = \"v1\";\r\n private readonly apiLocale = \"pt-br\";\r\n private readonly omitApiVersion: boolean;\r\n private readonly emitLogs: boolean = false;\r\n\r\n constructor(baseUrl: string, options?: ApiClientOptions) {\r\n this.baseUrl = baseUrl.replace(/\\/$/, \"\");\r\n this.omitApiVersion = options?.omitApiVersion ?? false;\r\n this.emitLogs = options?.emitLogs ?? false;\r\n }\r\n\r\n private async buildUrl(\r\n endpoint: string,\r\n whiteLabelId: number,\r\n ): Promise<string> {\r\n const wlPath = this.omitApiVersion\r\n ? `/${this.apiLocale}/${whiteLabelId}`\r\n : `/${this.apiVersion}/${this.apiLocale}/${whiteLabelId}`;\r\n const path = endpoint.startsWith(\"/\") ? endpoint : `/${endpoint}`;\r\n const url = `${this.baseUrl}${wlPath}${path}`;\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] buildUrl\", {\r\n baseURL: this.baseUrl,\r\n whiteLabelId,\r\n endpoint,\r\n fullUrl: url,\r\n });\r\n }\r\n return url;\r\n }\r\n\r\n private async getDefaultHeaders(\r\n token: string,\r\n isFormData = false,\r\n ): Promise<HeadersInit> {\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] getDefaultHeaders\", {\r\n token: token.substring(0, 20) + \"...\",\r\n });\r\n }\r\n\r\n const headers: HeadersInit = {\r\n authorization: token,\r\n };\r\n\r\n if (!isFormData) {\r\n headers[\"Content-Type\"] = \"application/json\";\r\n }\r\n\r\n return headers;\r\n }\r\n\r\n async request<T>(endpoint: string, config: RequestConfig = {}): Promise<T> {\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] request called\", {\r\n endpoint,\r\n method: config.method,\r\n });\r\n }\r\n\r\n const { timeout = 30000, responseType = \"json\", whiteLabelId: overrideWlId, authToken: overrideToken, ...fetchConfig } = config;\r\n\r\n const controller = new AbortController();\r\n const timeoutId = setTimeout(() => controller.abort(), timeout);\r\n\r\n try {\r\n if (this.emitLogs) {\r\n console.log(\"[ApiClient] Building URL and headers...\");\r\n }\r\n\r\n const { id, token } = await findWhitelabel();\r\n\r\n const [url, defaultHeaders] = await Promise.all([\r\n this.buildUrl(endpoint, overrideWlId ?? id),\r\n this.getDefaultHeaders(overrideToken ?? token, fetchConfig.body instanceof FormData),\r\n ]);\r\n\r\n if (this.emitLogs)\r\n console.log(\"[ApiClient] Fetching\", {\r\n url,\r\n method: fetchConfig.method,\r\n headers: defaultHeaders,\r\n });\r\n\r\n const response = await fetch(url, {\r\n ...fetchConfig,\r\n headers: {\r\n ...defaultHeaders,\r\n ...fetchConfig.headers,\r\n },\r\n signal: controller.signal,\r\n });\r\n\r\n if (this.emitLogs)\r\n console.log(\"[ApiClient] Response received\", {\r\n status: response.status,\r\n ok: response.ok,\r\n });\r\n\r\n if (!response.ok) {\r\n const errBody = await response.text();\r\n let message = `HTTP error ${response.status}`;\r\n let code = \"HTTP_ERROR\";\r\n try {\r\n const errorData = JSON.parse(errBody) as Record<string, unknown>;\r\n if (typeof errorData.message === \"string\")\r\n message = errorData.message;\r\n if (typeof errorData.code === \"string\") code = errorData.code;\r\n } catch {\r\n if (errBody.trim()) message = errBody.trim();\r\n }\r\n console.error(\"[ApiClient] Request failed\", {\r\n status: response.status,\r\n message,\r\n });\r\n throw new ApiError(message, code, response.status);\r\n }\r\n\r\n if (responseType === \"text\") {\r\n return (await response.text()) as T;\r\n }\r\n\r\n const data = (await response.json()) as T;\r\n if (this.emitLogs)\r\n console.log(\"[ApiClient] Request successful\", { hasData: !!data });\r\n return data;\r\n } catch (error) {\r\n if (this.emitLogs) console.error(\"[ApiClient] Request error\", { error });\r\n\r\n if (error instanceof ApiError) {\r\n throw error;\r\n }\r\n\r\n if (error instanceof Error) {\r\n if (error.name === \"AbortError\") {\r\n throw new ApiError(\"Tempo de requisição excedido\", \"TIMEOUT\", 408);\r\n }\r\n throw new ApiError(error.message, \"NETWORK_ERROR\", 0);\r\n }\r\n\r\n throw new ApiError(\"Erro desconhecido\", \"UNKNOWN_ERROR\", 500);\r\n } finally {\r\n clearTimeout(timeoutId);\r\n }\r\n }\r\n\r\n async get<T>(endpoint: string, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, { ...config, method: \"GET\" });\r\n }\r\n\r\n async post<T>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"POST\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : undefined,\r\n });\r\n }\r\n\r\n async put<T>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"PUT\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : undefined,\r\n });\r\n }\r\n\r\n async patch<T>(\r\n endpoint: string,\r\n data?: unknown,\r\n config?: RequestConfig,\r\n ): Promise<T> {\r\n return this.request<T>(endpoint, {\r\n ...config,\r\n method: \"PATCH\",\r\n body:\r\n data instanceof FormData\r\n ? data\r\n : data\r\n ? JSON.stringify(data)\r\n : undefined,\r\n });\r\n }\r\n\r\n async delete<T>(endpoint: string, config?: RequestConfig): Promise<T> {\r\n return this.request<T>(endpoint, { ...config, method: \"DELETE\" });\r\n }\r\n}\r\n\r\nconst api = {\r\n apps: new ApiClient(\r\n process.env.GAPPS_R3_API_URL || \"https://r3-api.greatapps.dev.br\",\r\n ),\r\n pages: new ApiClient(\r\n process.env.GPAGES_R3_API_URL || \"https://r3-api.greatpages.dev.br\",\r\n ),\r\n};\r\n\r\n/** @deprecated use api.apps */\r\nexport const apiClient = api.apps;\r\n\r\nexport { api, ApiClient };\r\n"],"mappings":"AAAA,SAAS,gBAAgB;AACzB,SAAS,sBAAsB;AAuB/B,MAAM,UAAU;AAAA,EACG;AAAA,EACA,aAAa;AAAA,EACb,YAAY;AAAA,EACZ;AAAA,EACA,WAAoB;AAAA,EAErC,YAAY,SAAiB,SAA4B;AACvD,SAAK,UAAU,QAAQ,QAAQ,OAAO,EAAE;AACxC,SAAK,iBAAiB,SAAS,kBAAkB;AACjD,SAAK,WAAW,SAAS,YAAY;AAAA,EACvC;AAAA,EAEA,MAAc,SACZ,UACA,cACiB;AACjB,UAAM,SAAS,KAAK,iBAChB,IAAI,KAAK,SAAS,IAAI,YAAY,KAClC,IAAI,KAAK,UAAU,IAAI,KAAK,SAAS,IAAI,YAAY;AACzD,UAAM,OAAO,SAAS,WAAW,GAAG,IAAI,WAAW,IAAI,QAAQ;AAC/D,UAAM,MAAM,GAAG,KAAK,OAAO,GAAG,MAAM,GAAG,IAAI;AAC3C,QAAI,KAAK,UAAU;AACjB,cAAQ,IAAI,wBAAwB;AAAA,QAClC,SA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AAM,IAAI,SAAS,qBAAqB,iBAAiB,GAAG;AAAA,IAC9D,UAAE;AACA,mBAAa,SAAS;AAAA,IACxB;AAAA,EACF;AAAA,EAEA,MAAM,IAAO,UAAkB,QAAoC;AACjE,WAAO,KAAK,QAAW,UAAU,EAAE,GAAG,QAAQ,QAAQ,MAAM,CAAC;AAAA,EAC/D;AAAA,EAEA,MAAM,KACJ,UACA,MACA,QACY;AACZ,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MACE,gBAAgB,WACZ,OACA,OACE,KAAK,UAAU,IAAI,IACnB;AAAA,IACV,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,IACJ,UACA,MACA,QACY;AACZ,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MACE,gBAAgB,WACZ,OACA,OACE,KAAK,UAAU,IAAI,IACnB;AAAA,IACV,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,MACJ,UACA,MACA,QACY;AACZ,WAAO,KAAK,QAAW,UAAU;AAAA,MAC/B,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,MACE,gBAAgB,WACZ,OACA,OACE,KAAK,UAAU,IAAI,IACnB;AAAA,IACV,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,OAAU,UAAkB,QAAoC;AACpE,WAAO,KAAK,QAAW,UAAU,EAAE,GAAG,QAAQ,QAAQ,SAAS,CAAC;AAAA,EAClE;AACF;AAEA,MAAM,MAAM;AAAA,EACV,MAAM,IAAI;AAAA,IACR,QAAQ,IAAI,oBAAoB;AAAA,EAClC;AAAA,EACA,OAAO,IAAI;AAAA,IACT,QAAQ,IAAI,qBAAqB;AAAA,EACnC;AACF;AAGO,MAAM,YAAY,IAAI;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greatapps/common",
3
- "version": "1.1.357",
3
+ "version": "1.1.358",
4
4
  "description": "Shared library for GreatApps frontend applications",
5
5
  "main": "./dist/index.mjs",
6
6
  "types": "./src/index.ts",
@@ -11,6 +11,8 @@ import { SecuritySection } from './sections/SecuritySection';
11
11
  import useConfigurationsModal from './hooks/useConfigurationsModal';
12
12
  import useIsMobile from '../../hooks/useIsMobile';
13
13
  import { useAccountModals } from '../../store/useAccountModals';
14
+ import { useAuth } from '../../providers/auth.provider';
15
+ import { UserProfile } from '../../modules/users/schema';
14
16
 
15
17
  export default function ConfigurationsMyAccountModal() {
16
18
  const {
@@ -24,6 +26,8 @@ export default function ConfigurationsMyAccountModal() {
24
26
  const open = activeModal === 'configurations';
25
27
  const { hasActiveSubscription } = config;
26
28
 
29
+ const { user } = useAuth();
30
+ const isOwnerOrAdmin = user?.profile === UserProfile.owner || user?.profile === UserProfile.admin;
27
31
  const isMobile = useIsMobile();
28
32
  const { activeSection, setActiveSection } = useConfigurationsModal({
29
33
  isOpen: open,
@@ -105,10 +109,12 @@ export default function ConfigurationsMyAccountModal() {
105
109
  <span className="paragraph-small-medium">Preferências</span>
106
110
  </TabsTrigger>
107
111
 
108
- <TabsTrigger value={AccountSectionType.SECURITY} className={tabTriggerClasses}>
109
- <IconLock size={20} className="shrink-0" />
110
- <span className="paragraph-small-medium">Segurança</span>
111
- </TabsTrigger>
112
+ {isOwnerOrAdmin && (
113
+ <TabsTrigger value={AccountSectionType.SECURITY} className={tabTriggerClasses}>
114
+ <IconLock size={20} className="shrink-0" />
115
+ <span className="paragraph-small-medium">Segurança</span>
116
+ </TabsTrigger>
117
+ )}
112
118
  </div>
113
119
  </TabsList>
114
120
 
@@ -117,17 +123,21 @@ export default function ConfigurationsMyAccountModal() {
117
123
  <PreferencesSection onClose={close} />
118
124
  </TabsContent>
119
125
 
120
- <TabsContent value={AccountSectionType.SECURITY} className="h-full! relative overflow-hidden">
121
- <SecuritySection
122
- setActiveSection={setActiveSection}
123
- onClose={close}
124
- onDeleteAccount={handleDeleteAccount}
125
- />
126
- </TabsContent>
127
-
128
- <TabsContent value={AccountSectionType.CHANGE_PASSWORD} className="h-full! relative overflow-hidden">
129
- <ChangePasswordSection onBack={() => setActiveSection(AccountSectionType.SECURITY)} />
130
- </TabsContent>
126
+ {isOwnerOrAdmin && (
127
+ <>
128
+ <TabsContent value={AccountSectionType.SECURITY} className="h-full! relative overflow-hidden">
129
+ <SecuritySection
130
+ setActiveSection={setActiveSection}
131
+ onClose={close}
132
+ onDeleteAccount={handleDeleteAccount}
133
+ />
134
+ </TabsContent>
135
+
136
+ <TabsContent value={AccountSectionType.CHANGE_PASSWORD} className="h-full! relative overflow-hidden">
137
+ <ChangePasswordSection onBack={() => setActiveSection(AccountSectionType.SECURITY)} />
138
+ </TabsContent>
139
+ </>
140
+ )}
131
141
  </div>
132
142
  </Tabs>
133
143
  </DialogContent>
@@ -4,6 +4,7 @@ import { useState, useEffect } from 'react';
4
4
  import { useForm } from 'react-hook-form';
5
5
  import { toast } from 'sonner';
6
6
  import { IconLock } from '@tabler/icons-react';
7
+ import { cn } from '../../../infra/utils/clsx';
7
8
  import { Button } from '../../ui/buttons/Button';
8
9
  import { Separator } from '../../ui/data-display/Separator';
9
10
  import { Toast } from '../../ui/feedback/Toast';
@@ -43,8 +44,8 @@ export function PreferencesSection({ onClose }: PreferencesSectionProps) {
43
44
  const { data: timezones = [] } = useTimezones();
44
45
  const { data: currencies = [] } = useCurrencies();
45
46
  const { user, account } = useAuth();
46
- const canEditPreferences =
47
- user?.profile === UserProfile.owner || user?.profile === UserProfile.admin;
47
+ const isOwner = user?.profile === UserProfile.owner;
48
+ const canEditPreferences = isOwner || user?.profile === UserProfile.admin;
48
49
  const updateAccountUser = useUpdateAccountUser();
49
50
  const updateAccount = useUpdateAccount();
50
51
  const [confirmGlobalOpen, setConfirmGlobalOpen] = useState(false);
@@ -116,7 +117,7 @@ export function PreferencesSection({ onClose }: PreferencesSectionProps) {
116
117
 
117
118
  const onSubmit = (data: PreferencesFormValues) => {
118
119
  const accountFields: UpdateAccountRequest = {
119
- ...(canEditPreferences && dirtyFields.companyName && { name: data.companyName }),
120
+ ...(isOwner && dirtyFields.companyName && { name: data.companyName }),
120
121
  ...(canEditPreferences && dirtyFields.currency && { currency: data.currency }),
121
122
  ...(canEditPreferences && dirtyFields.timezone && { timezone: data.timezone }),
122
123
  };
@@ -153,10 +154,10 @@ export function PreferencesSection({ onClose }: PreferencesSectionProps) {
153
154
  <FormField
154
155
  label="Nome da empresa"
155
156
  placeholder="Digite o nome da empresa"
156
- classnameContainer="w-full"
157
+ classnameContainer={cn('w-full', !isOwner && 'cursor-not-allowed opacity-50')}
157
158
  value={watch('companyName')}
158
159
  onChange={(e) => setValue('companyName', e.target.value, { shouldDirty: true })}
159
- disabled={!canEditPreferences}
160
+ disabled={!isOwner}
160
161
  />
161
162
  </div>
162
163
 
@@ -10,6 +10,9 @@ import type {
10
10
  UpdateAccountUserRequest,
11
11
  } from '../types';
12
12
  import { twoFactorService } from '../services/two-factor.service';
13
+ import { findUserById } from '../../users/action/find-user-by-id.action';
14
+ import { UserProfile } from '../../users/schema';
15
+ import { ApiError } from '../../../infra/api/types';
13
16
 
14
17
  export async function listAccountUsersAction(params?: AccountUsersPaginationParams) {
15
18
  return safeServerAction(async () => {
@@ -30,7 +33,20 @@ export async function updateAccountUserByIdAction(
30
33
  }
31
34
 
32
35
  export async function updateAccountAction(data: UpdateAccountRequest) {
33
- return safeServerAction(() => accountService.updateAccount(data));
36
+ return safeServerAction(async () => {
37
+ if (data.name !== undefined) {
38
+ const userResult = await findUserById();
39
+ if (!userResult.success || userResult.data?.profile !== UserProfile.owner) {
40
+ throw new ApiError(
41
+ 'Apenas o proprietário da conta pode alterar o nome da empresa',
42
+ 'FORBIDDEN',
43
+ 403
44
+ );
45
+ }
46
+ }
47
+
48
+ return accountService.updateAccount(data);
49
+ });
34
50
  }
35
51
 
36
52
  export async function deleteAccountUserAction(userId: number) {