feat(org): add organization and membership contract and storage

This commit is contained in:
shira committed 2026-10-06 15:55:29 +03:00
1 parent a0551a34b8
commit bdc5855001
90 files changed
+17545 -480

No files matched your search

@@ -0,0 +1,471 @@
/**
* Generated by orval 🍺
* Do not edit manually.
* Lincodex API
* OpenAPI spec version: 0.1.0
*/
import {
useMutation,
useQuery
} from '@tanstack/react-query';
import type {
DataTag,
DefinedInitialDataOptions,
DefinedUseQueryResult,
MutationFunction,
QueryClient,
QueryFunction,
QueryKey,
UndefinedInitialDataOptions,
UseMutationOptions,
UseMutationResult,
UseQueryOptions,
UseQueryResult
} from '@tanstack/react-query';
import type {
CreateOrganizationHeaders,
ListMyOrganizationsParams,
MyOrganizationList,
Organization,
OrganizationCreate,
OrganizationUpdate,
Problem
} from '../../schemas';
import { apiRequest } from '../../client';
import type { ErrorType } from '../../client';
type SecondParameter<T extends (...args: never) => unknown> = Parameters<T>[1];
const withQueryKey = <T extends object, K>(query: T, queryKey: K): T & { queryKey: K } => {
const result = { queryKey } as T & { queryKey: K };
for (const key of Object.keys(query)) {
// The explicit queryKey always wins, matching the previous
// `{ ...query, queryKey }` spread where it was set last.
if (key === 'queryKey') continue;
Object.defineProperty(result, key, {
enumerable: true,
configurable: true,
get: () => (query as Record<string, unknown>)[key],
});
}
return result;
};
export const getListMyOrganizationsUrl = (params?: ListMyOrganizationsParams,) => {
const normalizedParams = new URLSearchParams();
Object.entries(params || {}).forEach(([key, value]) => {
if (value !== undefined) {
normalizedParams.append(key, value === null ? 'null' : String(value))
}
});
const stringifiedParams = normalizedParams.toString();
return stringifiedParams.length > 0 ? `/api/v1/me/organizations?${stringifiedParams}` : `/api/v1/me/organizations`
}
/**
* Requires the session cookie of an employer account. The account comes from the session, never from a request parameter, so the response holds only the caller's own memberships and no request can name another account.
*
* Returns a page of the organizations in which the caller has an `active` membership, newest membership first with the organization identifier as the tie-breaker, with cursor pagination. Each item names the organization (`OrganizationSummary`) and holds the caller's role and state in it (`OrganizationMembership`). A membership in another state (`suspended`, `removed`, `left`) does not list its organization, so an organization the caller cannot enter is never named, and one that the caller was removed from disappears from the list at once.
*
* The list is the directory of the active organization context. The context is not stored on the server: every organization-scoped operation names its organization in the path `org_id`, and the server checks that identifier against the caller's active membership on every request, so a switch between organizations is a different `org_id` in the client's routes and cannot outlive a revoked membership. A client picks the context from this list, may remember the last choice in the browser as a convenience, and must read the list again after any answer 404 `not_found` from an organization path. An account with several memberships sees all of them here and works in one at a time; the rights and the data of the organizations stay separate.
*
* Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden. An employer account without an organization gets an empty page, which tells the client to offer CreateOrganization. A malformed `limit` or `cursor` answers 400 validation_failed.
* @summary List the organizations available to the current account.
*/
export const listMyOrganizations = async (params?: ListMyOrganizationsParams, options?: Parameters<typeof apiRequest>[1]): Promise<MyOrganizationList> => {
return apiRequest<MyOrganizationList>(getListMyOrganizationsUrl(params),
{
...options,
method: 'GET'
}
);}
export const getListMyOrganizationsQueryKey = (params?: ListMyOrganizationsParams,) => {
return [
`/api/v1/me/organizations`, ...(params ? [params] : [])
] as const;
}
export const getListMyOrganizationsQueryOptions = <TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(params?: ListMyOrganizationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getListMyOrganizationsQueryKey(params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof listMyOrganizations>>> = ({ signal }) => listMyOrganizations(params, { signal, ...requestOptions });
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type ListMyOrganizationsQueryResult = NonNullable<Awaited<ReturnType<typeof listMyOrganizations>>>
export type ListMyOrganizationsQueryError = ErrorType<Problem>
export function useListMyOrganizations<TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(
params: undefined | ListMyOrganizationsParams, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof listMyOrganizations>>,
TError,
Awaited<ReturnType<typeof listMyOrganizations>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useListMyOrganizations<TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(
params?: ListMyOrganizationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof listMyOrganizations>>,
TError,
Awaited<ReturnType<typeof listMyOrganizations>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useListMyOrganizations<TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(
params?: ListMyOrganizationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary List the organizations available to the current account.
*/
export function useListMyOrganizations<TData = Awaited<ReturnType<typeof listMyOrganizations>>, TError = ErrorType<Problem>>(
params?: ListMyOrganizationsParams, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof listMyOrganizations>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getListMyOrganizationsQueryOptions(params,options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getCreateOrganizationUrl = () => {
return `/api/v1/organizations`
}
/**
* Requires the session cookie of an employer account with a confirmed email, the CSRF token of that session in X-CSRF-Token, an allowed Origin, and an Idempotency-Key. The owner is the account of the session: the body has no owner, membership, role, verification, or version field, and unknown fields fail validation.
*
* The server creates the organization and the owner membership of the caller (role `owner`, state `active`) in one transaction, so an organization never exists without its owner. The organization starts at the verification level `e0` with the basis `confirmed_email`. The level cannot be requested: the creator of a company with a corporate domain, a long description, or many representatives still gets `e0`, and `e1`, `e2`, and `e3` come only from verification processes of the server that do not exist yet. Only `name` is required; the rest of the card can be completed with UpdateOrganization.
*
* Idempotency: a retry with the same key and body within 24 hours replays the stored 201 and creates nothing, so a lost response never creates a second organization. A different body with the same key answers 422 idempotency_key_reused. 400 is never stored, so a corrected retry is evaluated again. Two requests with different keys are two organizations; the product may limit the number of organizations per account (open question), which would answer 409 `state_conflict` without a change of the schema.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), the Idempotency-Key (422, 409 idempotency_in_progress, replay), domain rules (400 with a pointer such as `/contacts/website` for a website that is not an https URL of a host name, `/name` for a name with surrounding whitespace). The general rate limit can answer 429 with Retry-After before any check; 429 is never stored.
* @summary Create an organization; the caller becomes its owner.
*/
export const createOrganization = async (organizationCreate: OrganizationCreate,
headers: CreateOrganizationHeaders, options?: Parameters<typeof apiRequest>[1]): Promise<Organization> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<Organization>(getCreateOrganizationUrl(),
{
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json',...headers, ...getHeaders(options?.headers) },
body: JSON.stringify(organizationCreate)
}
);}
export const getCreateOrganizationMutationKey = () => ['createOrganization'] as const;
export const getCreateOrganizationMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createOrganization>>, TError,CreateOrganizationMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof createOrganization>>, TError,CreateOrganizationMutationVariables, TContext> => {
const mutationKey = getCreateOrganizationMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof createOrganization>>, CreateOrganizationMutationVariables> = (props) => {
const {data,headers} = props ?? {};
return createOrganization(data,headers,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type CreateOrganizationMutationResult = NonNullable<Awaited<ReturnType<typeof createOrganization>>>
export type CreateOrganizationMutationBody = OrganizationCreate
export type CreateOrganizationMutationError = ErrorType<Problem>
export type CreateOrganizationMutationVariables = {data: OrganizationCreate;headers: CreateOrganizationHeaders}
/**
* @summary Create an organization; the caller becomes its owner.
*/
export const useCreateOrganization = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof createOrganization>>, TError,CreateOrganizationMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof createOrganization>>,
TError,
CreateOrganizationMutationVariables,
TContext
> => {
return useMutation(getCreateOrganizationMutationOptions(options), queryClient);
}
export const getGetOrganizationUrl = (orgId: string,) => {
return `/api/v1/organizations/${orgId}`
}
/**
* Requires the session cookie of an employer account with an active membership in `org_id`. The organization comes from the path and is checked against the membership that the server holds for the session account on every request; the identifier itself grants nothing.
*
* Returns the profile with its current `version`, the verification level (`verification`), and the card as a candidate sees it (`candidate_card`). The verification level is always the one the server holds: it never rises because the profile is complete, because the organization has members, or because of an email domain. The role of the caller is not part of this resource; ListMyOrganizations returns it with the membership.
*
* In the MVP the profile is readable by any active member; every member is an owner, because the operations that add members are planned. The roles of PRD FR07 that read a company card without managing it change no field of this contract.
*
* Access: a missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account answers 403 forbidden; an account without an active membership in the organization, including a `suspended`, `removed`, or `left` one, and an unknown organization all answer 404 not_found, so organizations cannot be enumerated. A malformed `org_id` answers 400 validation_failed with the path pointer.
* @summary Read an organization of which the caller is a member.
*/
export const getOrganization = async (orgId: string, options?: Parameters<typeof apiRequest>[1]): Promise<Organization> => {
return apiRequest<Organization>(getGetOrganizationUrl(orgId),
{
...options,
method: 'GET'
}
);}
export const getGetOrganizationQueryKey = (orgId: string,) => {
return [
`/api/v1/organizations/${orgId}`
] as const;
}
export const getGetOrganizationQueryOptions = <TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(orgId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
) => {
const {query: queryOptions, request: requestOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getGetOrganizationQueryKey(orgId);
const queryFn: QueryFunction<Awaited<ReturnType<typeof getOrganization>>> = ({ signal }) => getOrganization(orgId, { signal, ...requestOptions });
return { queryKey, queryFn, enabled: orgId !== null && orgId !== undefined, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type GetOrganizationQueryResult = NonNullable<Awaited<ReturnType<typeof getOrganization>>>
export type GetOrganizationQueryError = ErrorType<Problem>
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
orgId: string, options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof getOrganization>>,
TError,
Awaited<ReturnType<typeof getOrganization>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
orgId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof getOrganization>>,
TError,
Awaited<ReturnType<typeof getOrganization>>
> , 'initialData'
>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
orgId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Read an organization of which the caller is a member.
*/
export function useGetOrganization<TData = Awaited<ReturnType<typeof getOrganization>>, TError = ErrorType<Problem>>(
orgId: string, options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof getOrganization>>, TError, TData>>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getGetOrganizationQueryOptions(orgId,options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
return withQueryKey(query, queryOptions.queryKey);
}
export const getUpdateOrganizationUrl = (orgId: string,) => {
return `/api/v1/organizations/${orgId}`
}
/**
* Requires the session cookie of an employer account with an active membership in `org_id`, the CSRF token of that session in X-CSRF-Token, and an allowed Origin. Only the owner manages the organization (the FR07 matrix gives this to no other role), so a member with another role answers 403 forbidden. The role comes from the server-side membership; the body has no organization, membership, role, owner, or verification field.
*
* Merge rules: the body is `application/json` with explicit field replacement, not JSON Merge Patch. Each field present replaces that field as a whole and an absent field stays unchanged; `contacts` and `representatives` are replaced entirely and never merged. `description` and `sphere` sent as null become unset; `name`, `contacts`, and `representatives` cannot be null.
*
* The body can change the profile only. The verification level, its basis, the card, the members, and every role are not fields of it, and unknown fields fail validation, so the owner can neither raise the trust level of the organization nor the rights of anyone by editing the profile; a longer description, a verified-looking website, or a new representative leaves the level unchanged. The level and the roles change only through processes of the server.
*
* Versions: every committed change creates version `expected_version + 1` and answers 200 with the organization. `expected_version` is the `version` the client read; when it is not current, the server answers 412 version_conflict and changes nothing, and the client reads the organization again and reapplies its edits. The version travels in the body rather than in If-Match because the generated client cannot read the ETag response header yet, as for needs. A body that changes nothing when applied to the current profile keeps the version and answers 200 with the current organization even when `expected_version` is older, so the operation needs no Idempotency-Key and a retry of a change that already succeeded is harmless.
*
* Order of checks: session (401), CSRF and Origin (403 csrf_check_failed), request validation (400), account scenario (403 forbidden for a candidate account), membership (404 not_found) and role (403 forbidden), a body that changes nothing (200), the version (412), domain rules (400 with a pointer such as `/contacts/website`, `/name`, or `/representatives/0/job_title`). The general rate limit can answer 429 with Retry-After before any check.
* @summary Change the profile of an organization.
*/
export const updateOrganization = async (orgId: string,
organizationUpdate: OrganizationUpdate, options?: Parameters<typeof apiRequest>[1]): Promise<Organization> => {
const getHeaders = (h?: NonNullable<RequestInit['headers']>): Record<string, string | readonly string[]> => {
if (!h) return {};
if (h instanceof Headers) return Object.fromEntries(h.entries());
if (Symbol.iterator in h) {
return Object.fromEntries(
Array.from(h as Iterable<Iterable<string>>, (entry) => Array.from(entry) as [string, string]),
);
}
const headers: Record<string, string | readonly string[]> = {};
for (const [name, value] of Object.entries<string | readonly string[] | undefined>(h)) {
if (value !== undefined) headers[name] = value;
}
return headers;
};
return apiRequest<Organization>(getUpdateOrganizationUrl(orgId),
{
...options,
method: 'PATCH',
headers: { 'Content-Type': 'application/json', ...getHeaders(options?.headers) },
body: JSON.stringify(organizationUpdate)
}
);}
export const getUpdateOrganizationMutationKey = () => ['updateOrganization'] as const;
export const getUpdateOrganizationMutationOptions = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof updateOrganization>>, TError,UpdateOrganizationMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
): UseMutationOptions<Awaited<ReturnType<typeof updateOrganization>>, TError,UpdateOrganizationMutationVariables, TContext> => {
const mutationKey = getUpdateOrganizationMutationKey();
const {mutation: mutationOptions, request: requestOptions} = options ?
options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ?
options
: {...options, mutation: {...options.mutation, mutationKey}}
: {mutation: { mutationKey, }, request: undefined};
const mutationFn: MutationFunction<Awaited<ReturnType<typeof updateOrganization>>, UpdateOrganizationMutationVariables> = (props) => {
const {orgId,data} = props ?? {};
return updateOrganization(orgId,data,requestOptions)
}
return { mutationFn, ...mutationOptions }}
export type UpdateOrganizationMutationResult = NonNullable<Awaited<ReturnType<typeof updateOrganization>>>
export type UpdateOrganizationMutationBody = OrganizationUpdate
export type UpdateOrganizationMutationError = ErrorType<Problem>
export type UpdateOrganizationMutationVariables = {orgId: string;data: OrganizationUpdate}
/**
* @summary Change the profile of an organization.
*/
export const useUpdateOrganization = <TError = ErrorType<Problem>,
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof updateOrganization>>, TError,UpdateOrganizationMutationVariables, TContext>, request?: SecondParameter<typeof apiRequest>}
, queryClient?: QueryClient): UseMutationResult<
Awaited<ReturnType<typeof updateOrganization>>,
TError,
UpdateOrganizationMutationVariables,
TContext
> => {
return useMutation(getUpdateOrganizationMutationOptions(options), queryClient);
}