Compare commits
8
Commits
030e13d02e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccdf536763 | ||
|
|
e74ab26d6b | ||
|
|
19ce944518 | ||
|
|
9e947ecaae | ||
|
|
e863ce1729 | ||
|
|
302b336042 | ||
|
|
eff0c8b9fe | ||
|
|
221b66e0d3 |
+14
-11
@@ -1,6 +1,7 @@
|
|||||||
name: Build and deploy Docker image
|
name: Build and deploy Docker image
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
branches: [main]
|
||||||
|
|
||||||
@@ -12,19 +13,21 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Login to Gitea Registry
|
- name: Build and publish
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
registry: gitea.dsrptlab.com
|
|
||||||
username: ${{ gitea.actor }}
|
|
||||||
password: ${{ secrets.REGISTRY_TOKEN }}
|
|
||||||
|
|
||||||
- name: Build and push
|
|
||||||
run: |
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
docker build -t "$IMAGE:latest" -t "$IMAGE:${{ gitea.sha }}" .
|
docker build -t "$IMAGE:latest" -t "$IMAGE:${{ gitea.sha }}" .
|
||||||
docker push "$IMAGE:latest"
|
docker push "$IMAGE:latest"
|
||||||
docker push "$IMAGE:${{ gitea.sha }}"
|
docker push "$IMAGE:${{ gitea.sha }}"
|
||||||
docker image rm -f "$IMAGE:latest" "$IMAGE:${{ gitea.sha }}"
|
|
||||||
|
|
||||||
- name: Deploy to Dokploy
|
- name: Remove local image tags
|
||||||
run: curl -fsS -X POST "https://ind.dsrptlab.com/api/deploy/2Y2RjGRTm4HIkcO2UmyHL"
|
run: docker image rm -f "$IMAGE:latest" "$IMAGE:${{ gitea.sha }}"
|
||||||
|
|
||||||
|
- name: Deploy in Dokploy
|
||||||
|
env:
|
||||||
|
DOKPLOY_DEPLOY_WEBHOOK: ${{ secrets.DOKPLOY_DEPLOY_WEBHOOK }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
test -n "$DOKPLOY_DEPLOY_WEBHOOK"
|
||||||
|
curl -fsS -X POST "$DOKPLOY_DEPLOY_WEBHOOK"
|
||||||
|
|
||||||
|
|||||||
+5
-3
@@ -7,12 +7,13 @@ RUN npm ci
|
|||||||
|
|
||||||
FROM deps AS builder
|
FROM deps AS builder
|
||||||
|
|
||||||
|
COPY prisma.config.ts ./
|
||||||
COPY prisma ./prisma
|
COPY prisma ./prisma
|
||||||
RUN npx prisma generate
|
RUN TEAMS_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres npx prisma generate
|
||||||
|
|
||||||
COPY tsconfig.json ./
|
COPY tsconfig.json ./
|
||||||
COPY src ./src
|
COPY src ./src
|
||||||
RUN npm run build
|
RUN TEAMS_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/postgres npm run build
|
||||||
|
|
||||||
FROM deps AS runtime-deps
|
FROM deps AS runtime-deps
|
||||||
|
|
||||||
@@ -28,9 +29,10 @@ COPY --from=runtime-deps /app/node_modules ./node_modules
|
|||||||
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
|
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
|
||||||
COPY --from=builder /app/node_modules/@prisma/client ./node_modules/@prisma/client
|
COPY --from=builder /app/node_modules/@prisma/client ./node_modules/@prisma/client
|
||||||
COPY --from=builder /app/dist ./dist
|
COPY --from=builder /app/dist ./dist
|
||||||
|
COPY prisma.config.ts ./
|
||||||
COPY prisma ./prisma
|
COPY prisma ./prisma
|
||||||
COPY scripts ./scripts
|
COPY scripts ./scripts
|
||||||
|
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
|
|
||||||
CMD ["sh", "-c", ". /app/scripts/load-vault-env.sh && set +e && npx prisma migrate resolve --applied 0_init 2>/dev/null; set -e && npx prisma migrate deploy && node dist/index.js"]
|
CMD ["sh", "-c", ". /app/scripts/load-vault-env.sh && npx prisma migrate deploy && node dist/index.js"]
|
||||||
|
|||||||
+1
-1
Submodule graphql-contracts updated: c632d41e35...b1c5a3f885
Generated
+1182
-1076
File diff suppressed because it is too large
Load Diff
+14
-10
@@ -6,22 +6,26 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "tsx watch src/index.ts",
|
"dev": "tsx watch src/index.ts",
|
||||||
"build": "prisma generate && tsc",
|
"build": "prisma generate && tsc",
|
||||||
"start": "prisma migrate deploy && node dist/index.js"
|
"start": "prisma migrate deploy && node dist/index.js",
|
||||||
|
"seed:demo": "tsx scripts/seed-demo.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fastify/cors": "^11.2.0",
|
"@fastify/cors": "^11.2.0",
|
||||||
"@prisma/client": "^6.5.0",
|
"@prisma/adapter-pg": "^7.8.0",
|
||||||
"@sentry/node": "^9.5.0",
|
"@prisma/client": "^7.8.0",
|
||||||
|
"@sentry/node": "^10.56.0",
|
||||||
"fastify": "^5.8.5",
|
"fastify": "^5.8.5",
|
||||||
"graphql": "^16.10.0",
|
"graphql": "^16.14.1",
|
||||||
"graphql-tag": "^2.12.6",
|
"graphql-tag": "^2.12.6",
|
||||||
"jose": "^6.0.11",
|
"jose": "^6.2.3",
|
||||||
"mercurius": "^16.9.0"
|
"mercurius": "^16.9.0",
|
||||||
|
"pg": "^8.21.0",
|
||||||
|
"tsx": "^4.22.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^22.13.0",
|
"@types/node": "^25.9.2",
|
||||||
"prisma": "^6.5.0",
|
"@types/pg": "^8.20.0",
|
||||||
"tsx": "^4.19.0",
|
"prisma": "^7.8.0",
|
||||||
"typescript": "^5.7.0"
|
"typescript": "^6.0.3"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import 'dotenv/config'
|
||||||
|
import { defineConfig, env } from 'prisma/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: 'prisma/schema.prisma',
|
||||||
|
migrations: {
|
||||||
|
path: 'prisma/migrations',
|
||||||
|
},
|
||||||
|
datasource: {
|
||||||
|
url: env('TEAMS_DATABASE_URL'),
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -4,7 +4,6 @@ generator client {
|
|||||||
|
|
||||||
datasource db {
|
datasource db {
|
||||||
provider = "postgresql"
|
provider = "postgresql"
|
||||||
url = env("TEAMS_DATABASE_URL")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
model Team {
|
model Team {
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
import { prisma } from '../dist/db.js'
|
||||||
|
|
||||||
|
const DEMO_TEAM_UUID = process.env.DEMO_TEAM_UUID ?? '11111111-1111-4111-8111-111111111111'
|
||||||
|
const DEMO_TEAM_NAME = process.env.DEMO_TEAM_NAME ?? 'Optovia Demo Client'
|
||||||
|
const DEMO_ADDRESS_COUNT = Number(process.env.DEMO_ADDRESS_COUNT ?? '3')
|
||||||
|
|
||||||
|
function requiredEnv(name: string): string {
|
||||||
|
const value = process.env[name]?.trim()
|
||||||
|
if (!value) throw new Error(`${name} is required`)
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
function demoAddress(index: number) {
|
||||||
|
const row = Math.floor(index / 60)
|
||||||
|
const col = index % 60
|
||||||
|
const latitude = 43.238949 + row * 0.018 + (col % 5) * 0.002
|
||||||
|
const longitude = 76.889709 + col * 0.021 + (row % 5) * 0.002
|
||||||
|
|
||||||
|
return {
|
||||||
|
uuid: `11111111-2222-4${String(index).padStart(3, '0').slice(-3)}-8${String(index).padStart(3, '0').slice(-3)}-111111${String(index).padStart(6, '0')}`,
|
||||||
|
name: `Demo address ${index + 1}`,
|
||||||
|
address: `Warehouse ${index + 1}, Almaty logistics area`,
|
||||||
|
latitude,
|
||||||
|
longitude,
|
||||||
|
countryCode: 'KZ',
|
||||||
|
isDefault: index === 0,
|
||||||
|
status: 'processed',
|
||||||
|
processedAt: new Date(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const logtoId = requiredEnv('DEMO_LOGTO_USER_ID')
|
||||||
|
const email = process.env.DEMO_USER_EMAIL ?? 'demo@optovia.ru'
|
||||||
|
const phone = process.env.DEMO_USER_PHONE ?? '+79990000000'
|
||||||
|
const firstName = process.env.DEMO_USER_FIRST_NAME ?? 'Demo'
|
||||||
|
const lastName = process.env.DEMO_USER_LAST_NAME ?? 'Client'
|
||||||
|
|
||||||
|
let profile = await prisma.userProfile.findUnique({
|
||||||
|
where: { logtoId },
|
||||||
|
include: { user: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
if (profile === null) {
|
||||||
|
const user = await prisma.user.upsert({
|
||||||
|
where: { username: logtoId },
|
||||||
|
create: { username: logtoId, firstName, lastName, email },
|
||||||
|
update: { firstName, lastName, email, isActive: true },
|
||||||
|
})
|
||||||
|
profile = await prisma.userProfile.create({
|
||||||
|
data: { userId: user.id, logtoId, phone, avatarId: 'demo-client' },
|
||||||
|
include: { user: true },
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
await prisma.user.update({
|
||||||
|
where: { id: profile.userId },
|
||||||
|
data: { firstName, lastName, email, isActive: true },
|
||||||
|
})
|
||||||
|
profile = await prisma.userProfile.update({
|
||||||
|
where: { id: profile.id },
|
||||||
|
data: { phone, avatarId: 'demo-client' },
|
||||||
|
include: { user: true },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const team = await prisma.team.upsert({
|
||||||
|
where: { uuid: DEMO_TEAM_UUID },
|
||||||
|
create: {
|
||||||
|
uuid: DEMO_TEAM_UUID,
|
||||||
|
name: DEMO_TEAM_NAME,
|
||||||
|
teamType: 'BUYER',
|
||||||
|
ownerId: profile.userId,
|
||||||
|
selectedLocationType: 'ADDRESS',
|
||||||
|
selectedLocationUuid: '11111111-2222-4000-8000-111111000000',
|
||||||
|
selectedLocationName: 'Demo address 1',
|
||||||
|
selectedLocationLat: 43.238949,
|
||||||
|
selectedLocationLon: 76.889709,
|
||||||
|
},
|
||||||
|
update: {
|
||||||
|
name: DEMO_TEAM_NAME,
|
||||||
|
teamType: 'BUYER',
|
||||||
|
ownerId: profile.userId,
|
||||||
|
selectedLocationType: 'ADDRESS',
|
||||||
|
selectedLocationUuid: '11111111-2222-4000-8000-111111000000',
|
||||||
|
selectedLocationName: 'Demo address 1',
|
||||||
|
selectedLocationLat: 43.238949,
|
||||||
|
selectedLocationLon: 76.889709,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await prisma.teamMember.upsert({
|
||||||
|
where: {
|
||||||
|
teamId_userId: {
|
||||||
|
teamId: team.id,
|
||||||
|
userId: profile.userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create: { teamId: team.id, userId: profile.userId, role: 'OWNER' },
|
||||||
|
update: { role: 'OWNER' },
|
||||||
|
})
|
||||||
|
|
||||||
|
await prisma.userProfile.update({
|
||||||
|
where: { id: profile.id },
|
||||||
|
data: { activeTeamId: team.id },
|
||||||
|
})
|
||||||
|
|
||||||
|
const addresses = Array.from({ length: DEMO_ADDRESS_COUNT }, (_, index) => ({
|
||||||
|
...demoAddress(index),
|
||||||
|
teamId: team.id,
|
||||||
|
}))
|
||||||
|
const addressUuids = addresses.map((address) => address.uuid)
|
||||||
|
|
||||||
|
await prisma.teamAddress.deleteMany({
|
||||||
|
where: {
|
||||||
|
teamId: team.id,
|
||||||
|
name: { startsWith: 'Demo address ' },
|
||||||
|
uuid: { notIn: addressUuids },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await prisma.teamAddress.createMany({
|
||||||
|
data: addresses,
|
||||||
|
skipDuplicates: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
await prisma.teamAddress.updateMany({
|
||||||
|
where: { teamId: team.id },
|
||||||
|
data: { isDefault: false },
|
||||||
|
})
|
||||||
|
|
||||||
|
await prisma.teamAddress.update({
|
||||||
|
where: { uuid: '11111111-2222-4000-8000-111111000000' },
|
||||||
|
data: { isDefault: true },
|
||||||
|
})
|
||||||
|
|
||||||
|
console.log(`Seeded teams demo data for ${logtoId}: team ${DEMO_TEAM_UUID}, addresses ${DEMO_ADDRESS_COUNT}`)
|
||||||
|
|
||||||
|
await prisma.$disconnect()
|
||||||
+51
-11
@@ -13,6 +13,9 @@ const jwks = createRemoteJWKSet(new URL(LOGTO_JWKS_URL));
|
|||||||
export interface AuthContext {
|
export interface AuthContext {
|
||||||
userId?: string;
|
userId?: string;
|
||||||
teamUuid?: string;
|
teamUuid?: string;
|
||||||
|
teamName?: string;
|
||||||
|
teamType?: string;
|
||||||
|
logtoOrgId?: string;
|
||||||
scopes: string[];
|
scopes: string[];
|
||||||
isM2M?: boolean;
|
isM2M?: boolean;
|
||||||
}
|
}
|
||||||
@@ -47,6 +50,12 @@ function scopesFromPayload(payload: JWTPayload): string[] {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function clientScopes(payload: JWTPayload): string[] {
|
||||||
|
return [
|
||||||
|
...new Set([...scopesFromPayload(payload), "teams:user", "teams:member"]),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
export async function publicContext(): Promise<AuthContext> {
|
export async function publicContext(): Promise<AuthContext> {
|
||||||
return { scopes: [] };
|
return { scopes: [] };
|
||||||
}
|
}
|
||||||
@@ -59,6 +68,29 @@ function claimList(payload: JWTPayload, key: string): string[] {
|
|||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function claimString(payload: JWTPayload, key: string): string | undefined {
|
||||||
|
const value = (payload as Record<string, unknown>)[key];
|
||||||
|
return typeof value === "string" && value.length > 0 ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function teamClaims(payload: JWTPayload): Pick<
|
||||||
|
AuthContext,
|
||||||
|
"teamUuid" | "teamName" | "teamType" | "logtoOrgId"
|
||||||
|
> {
|
||||||
|
return {
|
||||||
|
teamUuid: claimString(payload, "team_uuid") ?? payload.sub,
|
||||||
|
teamName:
|
||||||
|
claimString(payload, "team_name") ??
|
||||||
|
claimString(payload, "organization_name") ??
|
||||||
|
claimString(payload, "org_name"),
|
||||||
|
teamType: claimString(payload, "team_type"),
|
||||||
|
logtoOrgId:
|
||||||
|
claimString(payload, "logto_org_id") ??
|
||||||
|
claimString(payload, "organization_id") ??
|
||||||
|
claimString(payload, "org_id"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function hasManagerClaim(payload: JWTPayload): boolean {
|
function hasManagerClaim(payload: JWTPayload): boolean {
|
||||||
const scopes = scopesFromPayload(payload);
|
const scopes = scopesFromPayload(payload);
|
||||||
return (
|
return (
|
||||||
@@ -71,8 +103,20 @@ function hasManagerClaim(payload: JWTPayload): boolean {
|
|||||||
export async function userContext(req: FastifyRequest): Promise<AuthContext> {
|
export async function userContext(req: FastifyRequest): Promise<AuthContext> {
|
||||||
const token = optionalBearerToken(req);
|
const token = optionalBearerToken(req);
|
||||||
if (token === null) return { scopes: [] };
|
if (token === null) return { scopes: [] };
|
||||||
const { payload } = await jwtVerify(token, jwks, { issuer: LOGTO_ISSUER });
|
const { payload } = await jwtVerify(token, jwks, {
|
||||||
return { userId: payload.sub, scopes: scopesFromPayload(payload) };
|
issuer: LOGTO_ISSUER,
|
||||||
|
audience: LOGTO_TEAMS_AUDIENCE,
|
||||||
|
});
|
||||||
|
if (!payload.sub) {
|
||||||
|
throw new GraphQLError("User subject is required", {
|
||||||
|
extensions: { code: "UNAUTHENTICATED" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
userId: payload.sub,
|
||||||
|
scopes: clientScopes(payload),
|
||||||
|
...teamClaims(payload),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function managerContext(
|
export async function managerContext(
|
||||||
@@ -90,9 +134,7 @@ export async function managerContext(
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
userId: payload.sub,
|
userId: payload.sub,
|
||||||
teamUuid: (payload as Record<string, unknown>).team_uuid as
|
...teamClaims(payload),
|
||||||
| string
|
|
||||||
| undefined,
|
|
||||||
scopes: [...new Set([...scopesFromPayload(payload), "manager"])],
|
scopes: [...new Set([...scopesFromPayload(payload), "manager"])],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -103,15 +145,13 @@ export async function teamContext(req: FastifyRequest): Promise<AuthContext> {
|
|||||||
issuer: LOGTO_ISSUER,
|
issuer: LOGTO_ISSUER,
|
||||||
audience: LOGTO_TEAMS_AUDIENCE,
|
audience: LOGTO_TEAMS_AUDIENCE,
|
||||||
});
|
});
|
||||||
const teamUuid = (payload as Record<string, unknown>).team_uuid as
|
const claims = teamClaims(payload);
|
||||||
| string
|
const scopes = clientScopes(payload);
|
||||||
| undefined;
|
if (!payload.sub || !claims.teamUuid)
|
||||||
const scopes = scopesFromPayload(payload);
|
|
||||||
if (!teamUuid || !scopes.includes("teams:member"))
|
|
||||||
throw new GraphQLError("Unauthorized", {
|
throw new GraphQLError("Unauthorized", {
|
||||||
extensions: { code: "UNAUTHENTICATED" },
|
extensions: { code: "UNAUTHENTICATED" },
|
||||||
});
|
});
|
||||||
return { userId: payload.sub, teamUuid, scopes };
|
return { userId: payload.sub, scopes, ...claims };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function m2mContext(): Promise<AuthContext> {
|
export async function m2mContext(): Promise<AuthContext> {
|
||||||
|
|||||||
@@ -1,3 +1,11 @@
|
|||||||
import { PrismaClient } from '@prisma/client'
|
import { PrismaClient } from '@prisma/client'
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg'
|
||||||
|
|
||||||
export const prisma = new PrismaClient()
|
const connectionString = process.env.TEAMS_DATABASE_URL
|
||||||
|
if (!connectionString) {
|
||||||
|
throw new Error('TEAMS_DATABASE_URL is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
const adapter = new PrismaPg({ connectionString })
|
||||||
|
|
||||||
|
export const prisma = new PrismaClient({ adapter })
|
||||||
|
|||||||
@@ -46,7 +46,6 @@ export const m2mTypeDefs = `#graphql
|
|||||||
}
|
}
|
||||||
|
|
||||||
type SetLogtoOrgIdResult { team: Team, success: Boolean! }
|
type SetLogtoOrgIdResult { team: Team, success: Boolean! }
|
||||||
type CreateTeamResult { success: Boolean!, teamId: String, teamUuid: String, message: String }
|
|
||||||
type CreateAddressResult { success: Boolean!, addressUuid: String, teamType: String, message: String }
|
type CreateAddressResult { success: Boolean!, addressUuid: String, teamType: String, message: String }
|
||||||
type UpdateAddressStatusResult { success: Boolean! }
|
type UpdateAddressStatusResult { success: Boolean! }
|
||||||
type CreateInvitationResult { success: Boolean!, message: String, invitationUuid: String, invitation: TeamInvitation }
|
type CreateInvitationResult { success: Boolean!, message: String, invitationUuid: String, invitation: TeamInvitation }
|
||||||
@@ -60,7 +59,6 @@ export const m2mTypeDefs = `#graphql
|
|||||||
|
|
||||||
type Mutation {
|
type Mutation {
|
||||||
setLogtoOrgId(teamId: String!, logtoOrgId: String!): SetLogtoOrgIdResult
|
setLogtoOrgId(teamId: String!, logtoOrgId: String!): SetLogtoOrgIdResult
|
||||||
createTeamFromWorkflow(teamName: String!, ownerId: String!, teamType: String, countryCode: String): CreateTeamResult
|
|
||||||
createAddressFromWorkflow(workflowId: String!, teamUuid: String!, name: String!, address: String!, latitude: Float, longitude: Float, countryCode: String, isDefault: Boolean): CreateAddressResult
|
createAddressFromWorkflow(workflowId: String!, teamUuid: String!, name: String!, address: String!, latitude: Float, longitude: Float, countryCode: String, isDefault: Boolean): CreateAddressResult
|
||||||
updateAddressStatus(addressUuid: String!, status: String!, errorMessage: String): UpdateAddressStatusResult
|
updateAddressStatus(addressUuid: String!, status: String!, errorMessage: String): UpdateAddressStatusResult
|
||||||
createInvitationFromWorkflow(input: CreateInvitationFromWorkflowInput!): CreateInvitationResult
|
createInvitationFromWorkflow(input: CreateInvitationFromWorkflowInput!): CreateInvitationResult
|
||||||
@@ -90,22 +88,6 @@ export const m2mResolvers = {
|
|||||||
return { team: { uuid: team.uuid, name: team.name, logtoOrgId: team.logtoOrgId, createdAt: team.createdAt.toISOString(), updatedAt: team.updatedAt.toISOString() }, success: true }
|
return { team: { uuid: team.uuid, name: team.name, logtoOrgId: team.logtoOrgId, createdAt: team.createdAt.toISOString(), updatedAt: team.updatedAt.toISOString() }, success: true }
|
||||||
},
|
},
|
||||||
|
|
||||||
createTeamFromWorkflow: async (_: unknown, args: { teamName: string; ownerId: string; teamType?: string; countryCode?: string }) => {
|
|
||||||
try {
|
|
||||||
let profile = await prisma.userProfile.findUnique({ where: { logtoId: args.ownerId }, include: { user: true } })
|
|
||||||
if (!profile) {
|
|
||||||
const user = await prisma.user.create({ data: { username: args.ownerId } })
|
|
||||||
profile = await prisma.userProfile.create({ data: { userId: user.id, logtoId: args.ownerId }, include: { user: true } })
|
|
||||||
}
|
|
||||||
const team = await prisma.team.create({ data: { name: args.teamName, teamType: args.teamType || 'BUYER', ownerId: profile.userId } })
|
|
||||||
await prisma.teamMember.create({ data: { teamId: team.id, userId: profile.userId, role: 'OWNER' } })
|
|
||||||
await prisma.userProfile.update({ where: { id: profile.id }, data: { activeTeamId: team.id } })
|
|
||||||
return { success: true, teamId: team.id.toString(), teamUuid: team.uuid, message: 'Team created' }
|
|
||||||
} catch (e) {
|
|
||||||
return { success: false, teamId: null, teamUuid: null, message: String(e) }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
|
|
||||||
createAddressFromWorkflow: async (_: unknown, args: { workflowId: string; teamUuid: string; name: string; address: string; latitude?: number; longitude?: number; countryCode?: string; isDefault?: boolean }) => {
|
createAddressFromWorkflow: async (_: unknown, args: { workflowId: string; teamUuid: string; name: string; address: string; latitude?: number; longitude?: number; countryCode?: string; isDefault?: boolean }) => {
|
||||||
const team = await prisma.team.findUnique({ where: { uuid: args.teamUuid } })
|
const team = await prisma.team.findUnique({ where: { uuid: args.teamUuid } })
|
||||||
if (!team) return { success: false, addressUuid: null, teamType: null, message: 'Team not found' }
|
if (!team) return { success: false, addressUuid: null, teamType: null, message: 'Team not found' }
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { GraphQLError } from 'graphql'
|
|||||||
import { randomUUID, createHash } from 'crypto'
|
import { randomUUID, createHash } from 'crypto'
|
||||||
import { prisma } from '../db.js'
|
import { prisma } from '../db.js'
|
||||||
import { requireScopes, type AuthContext } from '../auth.js'
|
import { requireScopes, type AuthContext } from '../auth.js'
|
||||||
|
import { materializeTeamFromContext } from '../team-materialization.js'
|
||||||
|
|
||||||
export const teamTypeDefs = `#graphql
|
export const teamTypeDefs = `#graphql
|
||||||
type TeamUser {
|
type TeamUser {
|
||||||
@@ -153,6 +154,7 @@ export const teamResolvers = {
|
|||||||
team: async (_: unknown, __: unknown, ctx: AuthContext) => {
|
team: async (_: unknown, __: unknown, ctx: AuthContext) => {
|
||||||
requireScopes(ctx, 'teams:member')
|
requireScopes(ctx, 'teams:member')
|
||||||
if (!ctx.teamUuid) throw new GraphQLError('Team UUID not found')
|
if (!ctx.teamUuid) throw new GraphQLError('Team UUID not found')
|
||||||
|
await materializeTeamFromContext(ctx)
|
||||||
const team = await getTeamByUuid(ctx.teamUuid)
|
const team = await getTeamByUuid(ctx.teamUuid)
|
||||||
return team ? mapTeam(team) : null
|
return team ? mapTeam(team) : null
|
||||||
},
|
},
|
||||||
@@ -166,6 +168,7 @@ export const teamResolvers = {
|
|||||||
teamMembers: async (_: unknown, __: unknown, ctx: AuthContext) => {
|
teamMembers: async (_: unknown, __: unknown, ctx: AuthContext) => {
|
||||||
requireScopes(ctx, 'teams:member')
|
requireScopes(ctx, 'teams:member')
|
||||||
if (!ctx.teamUuid) return []
|
if (!ctx.teamUuid) return []
|
||||||
|
await materializeTeamFromContext(ctx)
|
||||||
const team = await prisma.team.findUnique({ where: { uuid: ctx.teamUuid } })
|
const team = await prisma.team.findUnique({ where: { uuid: ctx.teamUuid } })
|
||||||
if (!team) return []
|
if (!team) return []
|
||||||
const members = await prisma.teamMember.findMany({
|
const members = await prisma.teamMember.findMany({
|
||||||
@@ -186,6 +189,7 @@ export const teamResolvers = {
|
|||||||
teamAddresses: async (_: unknown, __: unknown, ctx: AuthContext) => {
|
teamAddresses: async (_: unknown, __: unknown, ctx: AuthContext) => {
|
||||||
requireScopes(ctx, 'teams:member')
|
requireScopes(ctx, 'teams:member')
|
||||||
if (!ctx.teamUuid) return []
|
if (!ctx.teamUuid) return []
|
||||||
|
await materializeTeamFromContext(ctx)
|
||||||
const team = await prisma.team.findUnique({ where: { uuid: ctx.teamUuid } })
|
const team = await prisma.team.findUnique({ where: { uuid: ctx.teamUuid } })
|
||||||
if (!team) return []
|
if (!team) return []
|
||||||
const addrs = await prisma.teamAddress.findMany({ where: { teamId: team.id }, orderBy: { createdAt: 'desc' } })
|
const addrs = await prisma.teamAddress.findMany({ where: { teamId: team.id }, orderBy: { createdAt: 'desc' } })
|
||||||
@@ -204,6 +208,7 @@ export const teamResolvers = {
|
|||||||
inviteMember: async (_: unknown, args: { input: { email: string; role?: string } }, ctx: AuthContext) => {
|
inviteMember: async (_: unknown, args: { input: { email: string; role?: string } }, ctx: AuthContext) => {
|
||||||
requireScopes(ctx, 'teams:member')
|
requireScopes(ctx, 'teams:member')
|
||||||
if (!ctx.teamUuid || !ctx.userId) throw new GraphQLError('Not authenticated')
|
if (!ctx.teamUuid || !ctx.userId) throw new GraphQLError('Not authenticated')
|
||||||
|
await materializeTeamFromContext(ctx)
|
||||||
const team = await prisma.team.findUnique({ where: { uuid: ctx.teamUuid } })
|
const team = await prisma.team.findUnique({ where: { uuid: ctx.teamUuid } })
|
||||||
if (!team) throw new GraphQLError('Team not found')
|
if (!team) throw new GraphQLError('Team not found')
|
||||||
const invitation = await prisma.teamInvitation.create({
|
const invitation = await prisma.teamInvitation.create({
|
||||||
@@ -229,6 +234,7 @@ export const teamResolvers = {
|
|||||||
createTeamAddress: async (_: unknown, args: { input: { name: string; address: string; latitude?: number; longitude?: number; countryCode?: string; isDefault?: boolean } }, ctx: AuthContext) => {
|
createTeamAddress: async (_: unknown, args: { input: { name: string; address: string; latitude?: number; longitude?: number; countryCode?: string; isDefault?: boolean } }, ctx: AuthContext) => {
|
||||||
requireScopes(ctx, 'teams:member')
|
requireScopes(ctx, 'teams:member')
|
||||||
if (!ctx.teamUuid) throw new GraphQLError('Not authenticated')
|
if (!ctx.teamUuid) throw new GraphQLError('Not authenticated')
|
||||||
|
await materializeTeamFromContext(ctx)
|
||||||
const team = await prisma.team.findUnique({ where: { uuid: ctx.teamUuid } })
|
const team = await prisma.team.findUnique({ where: { uuid: ctx.teamUuid } })
|
||||||
if (!team) throw new GraphQLError('Team not found')
|
if (!team) throw new GraphQLError('Team not found')
|
||||||
const addr = await prisma.teamAddress.create({
|
const addr = await prisma.teamAddress.create({
|
||||||
@@ -275,6 +281,7 @@ export const teamResolvers = {
|
|||||||
setSelectedLocation: async (_: unknown, args: { input: { type: string; uuid: string; name: string; latitude: number; longitude: number } }, ctx: AuthContext) => {
|
setSelectedLocation: async (_: unknown, args: { input: { type: string; uuid: string; name: string; latitude: number; longitude: number } }, ctx: AuthContext) => {
|
||||||
requireScopes(ctx, 'teams:member')
|
requireScopes(ctx, 'teams:member')
|
||||||
if (!ctx.teamUuid) throw new GraphQLError('Not authenticated')
|
if (!ctx.teamUuid) throw new GraphQLError('Not authenticated')
|
||||||
|
await materializeTeamFromContext(ctx)
|
||||||
await prisma.team.update({
|
await prisma.team.update({
|
||||||
where: { uuid: ctx.teamUuid },
|
where: { uuid: ctx.teamUuid },
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
+7
-18
@@ -1,6 +1,10 @@
|
|||||||
import { GraphQLError } from "graphql";
|
import { GraphQLError } from "graphql";
|
||||||
import { prisma } from "../db.js";
|
import { prisma } from "../db.js";
|
||||||
import { type AuthContext } from "../auth.js";
|
import { type AuthContext } from "../auth.js";
|
||||||
|
import {
|
||||||
|
getOrCreateProfile,
|
||||||
|
materializeTeamFromContext,
|
||||||
|
} from "../team-materialization.js";
|
||||||
|
|
||||||
export const userTypeDefs = `#graphql
|
export const userTypeDefs = `#graphql
|
||||||
type UserTeam {
|
type UserTeam {
|
||||||
@@ -86,23 +90,6 @@ export const userTypeDefs = `#graphql
|
|||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
async function getOrCreateProfile(logtoId: string) {
|
|
||||||
let profile = await prisma.userProfile.findUnique({
|
|
||||||
where: { logtoId: logtoId },
|
|
||||||
include: { user: true, activeTeam: true },
|
|
||||||
});
|
|
||||||
if (!profile) {
|
|
||||||
const user = await prisma.user.create({
|
|
||||||
data: { username: logtoId, firstName: "", lastName: "" },
|
|
||||||
});
|
|
||||||
profile = await prisma.userProfile.create({
|
|
||||||
data: { userId: user.id, logtoId: logtoId },
|
|
||||||
include: { user: true, activeTeam: true },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return profile;
|
|
||||||
}
|
|
||||||
|
|
||||||
function displayName(
|
function displayName(
|
||||||
firstName: string,
|
firstName: string,
|
||||||
lastName: string,
|
lastName: string,
|
||||||
@@ -156,7 +143,9 @@ export const userResolvers = {
|
|||||||
Query: {
|
Query: {
|
||||||
me: async (_: unknown, __: unknown, ctx: AuthContext) => {
|
me: async (_: unknown, __: unknown, ctx: AuthContext) => {
|
||||||
if (!ctx.userId) throw new GraphQLError("Not authenticated");
|
if (!ctx.userId) throw new GraphQLError("Not authenticated");
|
||||||
const profile = await getOrCreateProfile(ctx.userId);
|
const profile = ctx.teamUuid
|
||||||
|
? (await materializeTeamFromContext(ctx)).profile
|
||||||
|
: await getOrCreateProfile(ctx.userId);
|
||||||
return mapProfileUser(profile, ctx);
|
return mapProfileUser(profile, ctx);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { GraphQLError } from "graphql";
|
||||||
|
import type { Prisma } from "@prisma/client";
|
||||||
|
import { prisma } from "./db.js";
|
||||||
|
import type { AuthContext } from "./auth.js";
|
||||||
|
|
||||||
|
export async function getOrCreateProfile(logtoId: string) {
|
||||||
|
let profile = await prisma.userProfile.findUnique({
|
||||||
|
where: { logtoId },
|
||||||
|
include: { user: true, activeTeam: true },
|
||||||
|
});
|
||||||
|
if (!profile) {
|
||||||
|
const user = await prisma.user.create({
|
||||||
|
data: { username: logtoId, firstName: "", lastName: "" },
|
||||||
|
});
|
||||||
|
profile = await prisma.userProfile.create({
|
||||||
|
data: { userId: user.id, logtoId },
|
||||||
|
include: { user: true, activeTeam: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return profile;
|
||||||
|
}
|
||||||
|
|
||||||
|
function teamName(ctx: AuthContext): string {
|
||||||
|
return ctx.teamName ?? ctx.logtoOrgId ?? ctx.teamUuid ?? "Team";
|
||||||
|
}
|
||||||
|
|
||||||
|
function teamUpdate(ctx: AuthContext): Prisma.TeamUpdateInput {
|
||||||
|
const data: Prisma.TeamUpdateInput = {};
|
||||||
|
if (ctx.teamName) data.name = ctx.teamName;
|
||||||
|
if (ctx.teamType) data.teamType = ctx.teamType;
|
||||||
|
if (ctx.logtoOrgId) data.logtoOrgId = ctx.logtoOrgId;
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function materializeTeamFromContext(ctx: AuthContext) {
|
||||||
|
if (!ctx.userId) throw new GraphQLError("Not authenticated");
|
||||||
|
if (!ctx.teamUuid) throw new GraphQLError("Team UUID not found in token");
|
||||||
|
|
||||||
|
const profile = await getOrCreateProfile(ctx.userId);
|
||||||
|
const team = await prisma.team.upsert({
|
||||||
|
where: { uuid: ctx.teamUuid },
|
||||||
|
create: {
|
||||||
|
uuid: ctx.teamUuid,
|
||||||
|
name: teamName(ctx),
|
||||||
|
teamType: ctx.teamType ?? "BUYER",
|
||||||
|
logtoOrgId: ctx.logtoOrgId,
|
||||||
|
ownerId: profile.userId,
|
||||||
|
},
|
||||||
|
update: teamUpdate(ctx),
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.teamMember.upsert({
|
||||||
|
where: {
|
||||||
|
teamId_userId: {
|
||||||
|
teamId: team.id,
|
||||||
|
userId: profile.userId,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
create: { teamId: team.id, userId: profile.userId, role: "OWNER" },
|
||||||
|
update: {},
|
||||||
|
});
|
||||||
|
const updatedProfile = await prisma.userProfile.update({
|
||||||
|
where: { id: profile.id },
|
||||||
|
data: { activeTeamId: team.id },
|
||||||
|
include: { user: true, activeTeam: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
return { profile: updatedProfile, team };
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user