The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
v1.8.3 — Keep applied briefs visible after unlist (#25001)
Rashad Karanouh1c114559b872
diff --git a/packages/twenty-apps/internal/twenty-partners/package.json b/packages/twenty-apps/internal/twenty-partners/package.jsonindex 6e845bceeb2..004af8537a1 100644--- a/packages/twenty-apps/internal/twenty-partners/package.json+++ b/packages/twenty-apps/internal/twenty-partners/package.json@@ -1,6 +1,6 @@{"name": "twenty-partners",- "version": "1.8.1",+ "version": "1.8.3","license": "MIT","engines": {"node": "^24.5.0",diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/application/__tests__/on-application-created.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/application/__tests__/on-application-created.test.tsindex a1d5d20cdb7..e1e0d117c40 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/application/__tests__/on-application-created.test.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/application/__tests__/on-application-created.test.ts@@ -29,7 +29,7 @@ describe('on-application-created', () => {mutationMock.mockResolvedValue({ updateApplication: { id: APPLICATION_ID } });});- it('does nothing when the admin-created row already carries partnerUser', async () => {+ it('does not stamp when the admin-created row already carries partnerUser and has no opportunity', async () => {const result = await handler(event({id: APPLICATION_ID,@@ -42,6 +42,50 @@ describe('on-application-created', () => {expect(mutationMock).not.toHaveBeenCalled();});+ it('grants opportunity visibility on an apply row that already has partnerUser', async () => {+ queryMock+ .mockResolvedValueOnce({+ opportunities: {+ edges: [+ { node: { id: OPPORTUNITY_ID, applicantPartnerUserIds: null } },+ ],+ },+ })+ .mockResolvedValueOnce({+ opportunities: {+ edges: [+ {+ node: {+ id: OPPORTUNITY_ID,+ applicantPartnerUserIds: [MEMBER_ID],+ },+ },+ ],+ },+ });++ const result = await handler(+ event({+ id: APPLICATION_ID,+ partnerId: PARTNER_ID,+ partnerUserId: MEMBER_ID,+ opportunityId: OPPORTUNITY_ID,+ }),+ );++ expect(result).toEqual({});+ expect(mutationMock).toHaveBeenCalledTimes(1);+ expect(mutationMock).toHaveBeenCalledWith({+ updateOpportunity: {+ __args: {+ id: OPPORTUNITY_ID,+ data: { applicantPartnerUserIds: [MEMBER_ID] },+ },+ id: true,+ },+ });+ });+it('stamps partnerUser from the partner on an admin-created row', async () => {queryMock.mockResolvedValue({partners: { edges: [{ node: { id: PARTNER_ID, partnerUserId: MEMBER_ID } }] },@@ -58,6 +102,64 @@ describe('on-application-created', () => {expect(args.data).toEqual({ partnerUserId: MEMBER_ID });});+ it('stamps partnerUser and grants opportunity visibility on an invite with an opportunity', async () => {+ queryMock+ .mockResolvedValueOnce({+ partners: {+ edges: [{ node: { id: PARTNER_ID, partnerUserId: MEMBER_ID } }],+ },+ })+ .mockResolvedValueOnce({+ opportunities: {+ edges: [+ { node: { id: OPPORTUNITY_ID, applicantPartnerUserIds: null } },+ ],+ },+ })+ .mockResolvedValueOnce({+ opportunities: {+ edges: [+ {+ node: {+ id: OPPORTUNITY_ID,+ applicantPartnerUserIds: [MEMBER_ID],+ },+ },+ ],+ },+ });++ const result = await handler(+ event({+ id: APPLICATION_ID,+ partnerId: PARTNER_ID,+ opportunityId: OPPORTUNITY_ID,+ }),+ );++ expect(result).toEqual({ stamped: MEMBER_ID });++ const stampCall = mutationMock.mock.calls.find(+ (mutationCall) => mutationCall[0].updateApplication,+ )?.[0];+ expect(stampCall.updateApplication.__args.data).toEqual({+ partnerUserId: MEMBER_ID,+ });++ const grantCall = mutationMock.mock.calls.find(+ (mutationCall) => mutationCall[0].updateOpportunity,+ )?.[0];+ expect(grantCall).toEqual({+ updateOpportunity: {+ __args: {+ id: OPPORTUNITY_ID,+ data: { applicantPartnerUserIds: [MEMBER_ID] },+ },+ id: true,+ },+ });+ });+it('leaves an admin-created row alone when the partner has no member', async () => {queryMock.mockResolvedValue({partners: { edges: [{ node: { id: PARTNER_ID, partnerUserId: null } }] },@@ -150,7 +252,26 @@ describe('on-application-created', () => {.mockResolvedValueOnce({partners: { edges: [{ node: { id: PARTNER_ID } }] },})- .mockResolvedValueOnce({ applications: { edges: [] } });+ .mockResolvedValueOnce({ applications: { edges: [] } })+ .mockResolvedValueOnce({+ opportunities: {+ edges: [+ { node: { id: OPPORTUNITY_ID, applicantPartnerUserIds: null } },+ ],+ },+ })+ .mockResolvedValueOnce({+ opportunities: {+ edges: [+ {+ node: {+ id: OPPORTUNITY_ID,+ applicantPartnerUserIds: [MEMBER_ID],+ },+ },+ ],+ },+ });const result = await handler(event({@@ -161,13 +282,27 @@ describe('on-application-created', () => {);expect(result).toEqual({ applied: true, partnerId: PARTNER_ID });- expect(queryMock).toHaveBeenCalledTimes(2);- expect(mutationMock).toHaveBeenCalledTimes(1);- const call = mutationMock.mock.calls[0][0];++ const call = mutationMock.mock.calls.find(+ (mutationCall) => mutationCall[0].updateApplication,+ )?.[0];expect(call.updateApplication.__args.id).toBe(APPLICATION_ID);expect(call.updateApplication.__args.data.partnerId).toBe(PARTNER_ID);expect(call.updateApplication.__args.data.partnerUserId).toBe(MEMBER_ID);expect(call.updateApplication.__args.data.state).toBe('APPLIED');++ const grantCall = mutationMock.mock.calls.find(+ (mutationCall) => mutationCall[0].updateOpportunity,+ )?.[0];+ expect(grantCall).toEqual({+ updateOpportunity: {+ __args: {+ id: OPPORTUNITY_ID,+ data: { applicantPartnerUserIds: [MEMBER_ID] },+ },+ id: true,+ },+ });});it('soft-deletes a duplicate application and keeps the existing one', async () => {diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/application/services/resolve-candidacy.service.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/application/services/resolve-candidacy.service.tsindex c1edd880784..60444dba899 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/application/services/resolve-candidacy.service.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/application/services/resolve-candidacy.service.ts@@ -4,22 +4,23 @@ import type {ObjectRecordCreateEvent,} from 'twenty-sdk/define';-import { findPartnerByMember } from 'src/modules/shared/graphql/queries/find-partner-by-member';-import { getPartnerOwner } from 'src/modules/shared/graphql/queries/get-partner-owner';import { findDuplicateApplication } from 'src/modules/application/graphql/queries/find-duplicate-application';import { deleteApplication } from 'src/modules/application/graphql/mutations/delete-application';import { updateApplication } from 'src/modules/application/graphql/mutations/update-application';+import { findPartnerByMember } from 'src/modules/shared/graphql/queries/find-partner-by-member';+import { getPartnerOwner } from 'src/modules/shared/graphql/queries/get-partner-owner';+import { grantOpportunityVisibility } from 'src/modules/shared/services/grant-opportunity-visibility.service';type ApplicationCreatedProperties = DatabaseEventPayload<ObjectRecordCreateEvent<CoreSchema.Application>>['properties'];// The app route POST /apply-to-brief creates the Application with partnerId and-// partnerUserId already set, so this service returns at its first branch and does nothing.-// It still serves the admin path: an invite or an import sets partnerId but no-// partnerUserId, and this service stamps the partner's user so RLS doesn't hide the row-// from its own partner. The createdBy-based self-apply branch below is a fallback for rows-// created by a member without a partner set.+// partnerUserId already set, so this service skips the candidacy stamp and only grants+// opportunity read access. It still serves the admin path: an invite or an import sets+// partnerId but no partnerUserId, and this service stamps the partner's user so RLS+// doesn't hide the row from its own partner. The createdBy-based self-apply branch below+// is a fallback for rows created by a member without a partner set.export async function resolveCandidacy(client: CoreApiClient,after: ApplicationCreatedProperties['after'],@@ -27,15 +28,23 @@ export async function resolveCandidacy(const applicationId = after?.id;if (!applicationId) return {};+ const opportunityId = after.opportunityId;+// Admin path (invite/import): without partnerUser, RLS hides the row from its own partner.if (after.partnerId) {- if (after.partnerUserId) return {};+ if (after.partnerUserId) {+ await grantOpportunityVisibility(client, opportunityId, [+ after.partnerUserId,+ ]);+ return {};+ }const ownerRes = await getPartnerOwner(client, after.partnerId);const partnerUserId = ownerRes.partners?.edges?.[0]?.node?.partnerUserId;if (!partnerUserId) return { skipped: true, reason: 'partner_has_no_user' };await updateApplication(client, applicationId, { partnerUserId });+ await grantOpportunityVisibility(client, opportunityId, [partnerUserId]);return { stamped: partnerUserId };}@@ -46,23 +55,26 @@ export async function resolveCandidacy(const partnerId = partnerRes.partners?.edges?.[0]?.node?.id;if (!partnerId) return {}; // creator isn't a partner (e.g. admin) — leave it- const opportunityId = after.opportunityId;if (opportunityId) {const existingRes = await findDuplicateApplication(client, opportunityId, partnerId);const existingId = existingRes.applications?.edges?.find((edge) => edge.node?.id && edge.node.id !== applicationId,)?.node?.id;if (existingId) {+ // No grant here on purpose: the kept row's own member holds it. A second member of+ // the same partner never sees the first member's application either (partnerUser IS me).await deleteApplication(client, applicationId);return { duplicate: true, keptExisting: existingId };}}+ // ponytail: dedupe by (opportunity, partner) above; two near-simultaneous creates could still both pass before either stamps — acceptable.await updateApplication(client, applicationId, {partnerId,partnerUserId: memberId,state: 'APPLIED',});- // ponytail: dedupe by (opportunity, partner) above; two near-simultaneous creates could still both pass before either stamps — acceptable.+ await grantOpportunityVisibility(client, opportunityId, [memberId]);+return { applied: true, partnerId };}diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-on-partner-widget.view.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-on-partner-widget.view.test.tsnew file mode 100644index 00000000000..5a78e7917d2--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-on-partner-widget.view.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';+import { ViewFilterOperand, ViewType } from 'twenty-sdk/define';++import {+ APPLICATION_PARTNER_FIELD_ID,+ APPLICATION_STATE_FIELD_ID,+} from 'src/modules/application/objects/application.object';+import { APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER } from 'src/modules/application/views/applications-widget.view';++import applicationsOnPartnerWidgetView, {+ APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+} from './applications-on-partner-widget.view';++const parseFilterValue = (value: unknown) =>+ typeof value === 'string' ? JSON.parse(value) : value;++describe('applications-on-partner-widget.view', () => {+ it('uses a stable UUID distinct from the opportunity widget view', () => {+ expect(APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER).toBe(+ '22d162c7-404a-4f09-92c9-790d3c33a733',+ );+ expect(applicationsOnPartnerWidgetView.config.universalIdentifier).toBe(+ APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+ );+ expect(APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER).not.toBe(+ APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+ );+ });++ it('is a TABLE_WIDGET named for the partner parent', () => {+ expect(applicationsOnPartnerWidgetView.success).toBe(true);+ expect(applicationsOnPartnerWidgetView.config.type).toBe(+ ViewType.TABLE_WIDGET,+ );+ expect(applicationsOnPartnerWidgetView.config.name).toBe(+ 'Applications on Partner Widget',+ );+ });++ it('scopes rows with partner IS current record', () => {+ const filters = applicationsOnPartnerWidgetView.config.filters ?? [];++ expect(filters).toHaveLength(1);++ const partnerFilter = filters[0];++ expect(partnerFilter.fieldMetadataUniversalIdentifier).toBe(+ APPLICATION_PARTNER_FIELD_ID,+ );+ expect(partnerFilter.operand).toBe(ViewFilterOperand.IS);+ expect(parseFilterValue(partnerFilter.value)).toEqual({+ selectedRecordIds: [],+ isCurrentRecordSelected: true,+ });+ });++ it('does not filter by application state', () => {+ const filters = applicationsOnPartnerWidgetView.config.filters ?? [];++ expect(+ filters.some(+ (filter) =>+ filter.fieldMetadataUniversalIdentifier ===+ APPLICATION_STATE_FIELD_ID,+ ),+ ).toBe(false);+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-on-partner-widget.view.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-on-partner-widget.view.tsnew file mode 100644index 00000000000..75f0dcfbce6--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-on-partner-widget.view.ts@@ -0,0 +1,54 @@+import { ViewFilterOperand, ViewType, defineView } from 'twenty-sdk/define';++import {+ APPLICATION_OBJECT_UNIVERSAL_IDENTIFIER,+ APPLICATION_OPPORTUNITY_FIELD_ID,+ APPLICATION_PARTNER_FIELD_ID,+ APPLICATION_STATE_FIELD_ID,+} from 'src/modules/application/objects/application.object';++export const APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER =+ '22d162c7-404a-4f09-92c9-790d3c33a733';++// TABLE_WIDGET rather than TABLE so this view stays out of the record index view pickers.+export default defineView({+ universalIdentifier: APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+ name: 'Applications on Partner Widget',+ icon: 'IconSend',+ objectUniversalIdentifier: APPLICATION_OBJECT_UNIVERSAL_IDENTIFIER,+ type: ViewType.TABLE_WIDGET,+ fields: [+ {+ universalIdentifier: 'd9d4571b-5d73-4a84-ad82-e1e6fb730bc2',+ fieldMetadataUniversalIdentifier: APPLICATION_PARTNER_FIELD_ID,+ position: 0,+ isVisible: true,+ size: 220,+ },+ {+ universalIdentifier: '607be829-a697-41f8-8fe6-a2515ba20f91',+ fieldMetadataUniversalIdentifier: APPLICATION_OPPORTUNITY_FIELD_ID,+ position: 1,+ isVisible: true,+ size: 220,+ },+ {+ universalIdentifier: 'eb9a5b92-c697-41bf-83a9-bf0780eb4b51',+ fieldMetadataUniversalIdentifier: APPLICATION_STATE_FIELD_ID,+ position: 2,+ isVisible: true,+ size: 140,+ },+ ],+ filters: [+ {+ universalIdentifier: '1fc71ed2-319c-4267-b997-033056653d70',+ fieldMetadataUniversalIdentifier: APPLICATION_PARTNER_FIELD_ID,+ operand: ViewFilterOperand.IS,+ value: {+ selectedRecordIds: [],+ isCurrentRecordSelected: true,+ },+ },+ ],+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-widget.view.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-widget.view.test.tsnew file mode 100644index 00000000000..796b2a00ce3--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-widget.view.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest';+import { ViewFilterOperand, ViewType } from 'twenty-sdk/define';++import {+ APPLICATION_OPPORTUNITY_FIELD_ID,+ APPLICATION_STATE_FIELD_ID,+} from 'src/modules/application/objects/application.object';++import applicationsWidgetView, {+ APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+} from './applications-widget.view';++const parseFilterValue = (value: unknown) =>+ typeof value === 'string' ? JSON.parse(value) : value;++describe('applications-widget.view', () => {+ it('keeps the existing universal identifier so sync updates in place', () => {+ expect(APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER).toBe(+ 'cbaf92ec-c1a2-41c2-b471-cc131b060e4e',+ );+ expect(applicationsWidgetView.config.universalIdentifier).toBe(+ APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+ );+ });++ it('is a TABLE_WIDGET named for the opportunity parent', () => {+ expect(applicationsWidgetView.success).toBe(true);+ expect(applicationsWidgetView.config.type).toBe(ViewType.TABLE_WIDGET);+ expect(applicationsWidgetView.config.name).toBe(+ 'Applications on Opportunity Widget',+ );+ });++ it('scopes rows with opportunity IS current record', () => {+ const filters = applicationsWidgetView.config.filters ?? [];++ expect(filters).toHaveLength(1);++ const opportunityFilter = filters[0];++ expect(opportunityFilter.fieldMetadataUniversalIdentifier).toBe(+ APPLICATION_OPPORTUNITY_FIELD_ID,+ );+ expect(opportunityFilter.operand).toBe(ViewFilterOperand.IS);+ expect(parseFilterValue(opportunityFilter.value)).toEqual({+ selectedRecordIds: [],+ isCurrentRecordSelected: true,+ });+ });++ it('does not filter by application state', () => {+ const filters = applicationsWidgetView.config.filters ?? [];++ expect(+ filters.some(+ (filter) =>+ filter.fieldMetadataUniversalIdentifier ===+ APPLICATION_STATE_FIELD_ID,+ ),+ ).toBe(false);+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-widget.view.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-widget.view.tsindex 671698a6488..1243f3d2238 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-widget.view.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/application/views/applications-widget.view.ts@@ -1,4 +1,4 @@-import { ViewType, defineView } from 'twenty-sdk/define';+import { ViewFilterOperand, ViewType, defineView } from 'twenty-sdk/define';import {APPLICATION_OBJECT_UNIVERSAL_IDENTIFIER,@@ -13,7 +13,7 @@ export const APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER =// TABLE_WIDGET rather than TABLE so this view stays out of the record index view pickers.export default defineView({universalIdentifier: APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,- name: 'Applications Widget',+ name: 'Applications on Opportunity Widget',icon: 'IconSend',objectUniversalIdentifier: APPLICATION_OBJECT_UNIVERSAL_IDENTIFIER,type: ViewType.TABLE_WIDGET,@@ -40,4 +40,15 @@ export default defineView({size: 140,},],+ filters: [+ {+ universalIdentifier: 'df46abe6-a328-4a60-b658-e0866af03319',+ fieldMetadataUniversalIdentifier: APPLICATION_OPPORTUNITY_FIELD_ID,+ operand: ViewFilterOperand.IS,+ value: {+ selectedRecordIds: [],+ isCurrentRecordSelected: true,+ },+ },+ ],});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/fields/opportunity-applicant-partner-user-ids.field.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/fields/opportunity-applicant-partner-user-ids.field.tsnew file mode 100644index 00000000000..7fa6ad2bdd3--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/fields/opportunity-applicant-partner-user-ids.field.ts@@ -0,0 +1,27 @@+import {+ FieldType,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,+ defineField,+} from 'twenty-sdk/define';++export const OPPORTUNITY_APPLICANT_PARTNER_USER_IDS_FIELD_ID =+ '223ec774-6cd6-4c19-8f32-308faa6b80b1';++// RLS cannot join Opportunity → Application, so applicant member ids live on the+// opportunity. After unlist, (partnerUser IS me) OR (isListed) is not enough.+// The list is append-only and stamped from the Application create event: deleting an+// application does not revoke, and an opportunity linked after creation is not granted.+export default defineField({+ universalIdentifier: OPPORTUNITY_APPLICANT_PARTNER_USER_IDS_FIELD_ID,+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,+ type: FieldType.ARRAY,+ name: 'applicantPartnerUserIds',+ // Named as ids because that is what it renders. Applications is the readable list.+ label: 'Applicant Member IDs',+ description:+ 'Internal RLS allowlist of workspace member ids. Read Applications for the applicants themselves. The app maintains this list — editing it by hand grants or removes partner access to the brief.',+ icon: 'IconLock',+ isNullable: true,+ isUIEditable: false,+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/fields/opportunity-is-listed.field.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/fields/opportunity-is-listed.field.tsindex f34cef6c3f0..c48d3607d4c 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/fields/opportunity-is-listed.field.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/fields/opportunity-is-listed.field.ts@@ -7,8 +7,8 @@ import {export const OPPORTUNITY_IS_LISTED_FIELD_ID ='0384ac3e-7aaa-4f32-bc6c-a6de8ebdd6c3';-// Marketplace flag: a listed brief is visible to all partners. The RLS predicate that exposes-// listed opportunities is wired in a later block; here it is just the field.+// Marketplace flag: a listed brief is visible to all partners via RLS. Applicants stay+// visible after unlist through applicantPartnerUserIds (see partner.role.ts).export default defineField({universalIdentifier: OPPORTUNITY_IS_LISTED_FIELD_ID,objectUniversalIdentifier:diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/admin-copy.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/admin-copy.test.tsindex 270e3f5d359..0896e570f95 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/admin-copy.test.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/admin-copy.test.ts@@ -41,6 +41,7 @@ describe('HOW_TO_PROCESS_STEPS', () => {expect(text).toMatch(/daily digest/i);expect(text).toMatch(/Intro Sent At/i);expect(text).toMatch(/Listed.*off/i);+ expect(text).toMatch(/keep it in My Applications/i);expect(text).toMatch(/Won/i);expect(text).toMatch(/Declined/i);expect(text).toMatch(/Backup stays/i);diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/admin-copy.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/admin-copy.tsindex 12d2e8c024a..6960032dd18 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/admin-copy.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/admin-copy.ts@@ -58,8 +58,8 @@ export const HOW_TO_PROCESS_STEPS: PlaybookStep[] = [{num: '05',heading: 'Intro',- body: 'After you name the partners, /twenty-partner-intro creates Invited rows and sets Intro Sent At. The app then turns Listed off.',- note: 'Do not send a second wave unless you mean to.',+ body: 'After you name the partners, /twenty-partner-intro creates Invited rows and sets Intro Sent At. The app then turns Listed off. Turning Listed off removes the brief from Open Briefs, but applied and invited partners keep it in My Applications.',+ note: 'Do not send a second wave unless you mean to. Unlisting is not a way to hide the brief from the partners who already applied.',skills: [PLAYBOOK_SKILL_INTRO],},{diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/partner-copy.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/partner-copy.test.tsindex ae3b51d3483..3577021eef2 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/partner-copy.test.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/partner-copy.test.ts@@ -27,6 +27,7 @@ describe('HOW_TO_APPLY_STEPS', () => {expect(text).toMatch(/Won/);expect(text).toMatch(/Declined/);expect(text).toMatch(/do not set those/i);+ expect(text).toMatch(/My Applications still shows the brief/i);});it('names unpitchable states as the complement of PITCHABLE_STATES', () => {diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/partner-copy.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/partner-copy.tsindex 20dec854d1b..e0dae9a586b 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/partner-copy.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/how-to-process/constants/partner-copy.ts@@ -30,6 +30,6 @@ export const HOW_TO_APPLY_STEPS: PlaybookStep[] = [num: '03',heading: 'What happens next',body: 'Your row lands in My Applications as Applied. Twenty may also invite you. Then the row is Invited. After an intro, wait for Twenty. Do not chase the client unless Twenty asks. Won or Declined is set when Twenty picks the Partner. You do not set those yourself.',- note: 'A listed brief can still have a decided row. Listing and the winner field are not the same thing.',+ note: 'A listed brief can still have a decided row. Listing and the winner field are not the same thing. My Applications still shows the brief after it leaves Open Briefs.',},];diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/page-layouts/opportunity.page-layout.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/page-layouts/opportunity.page-layout.test.tsnew file mode 100644index 00000000000..345b83983f2--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/page-layouts/opportunity.page-layout.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { APPLICATIONS_ON_OPPORTUNITY_FIELD_ID } from 'src/modules/application/objects/application.object';+import { APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER } from 'src/modules/application/views/applications-widget.view';++import opportunityPageLayout from './opportunity.page-layout';++describe('opportunity.page-layout', () => {+ it('scopes the Partners FIELD TABLE to the opportunity widget view', () => {+ const partnersWidget = opportunityPageLayout.config.tabs+ .flatMap((tab) => tab.widgets ?? [])+ .find((widget) => widget.title === 'Partners');++ expect(partnersWidget).toBeDefined();+ expect(partnersWidget?.type).toBe('FIELD');+ expect(partnersWidget?.configuration).toMatchObject({+ configurationType: 'FIELD',+ fieldMetadataId: APPLICATIONS_ON_OPPORTUNITY_FIELD_ID,+ fieldDisplayMode: 'TABLE',+ viewId: APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+ });+ expect(+ 'nestedRelationFieldMetadataId' in (partnersWidget?.configuration ?? {})+ ? partnersWidget?.configuration.nestedRelationFieldMetadataId+ : undefined,+ ).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/page-layouts/opportunity.page-layout.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/page-layouts/opportunity.page-layout.tsindex 256f4657fed..b1d83fd97b9 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/page-layouts/opportunity.page-layout.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/opportunity/page-layouts/opportunity.page-layout.ts@@ -43,10 +43,11 @@ export default definePageLayout({type: 'FIELD',configuration: {configurationType: 'FIELD',- // A FIELD widget in TABLE mode is the only configuration scoped to the parent- // record; a RECORD_TABLE widget would list every Application in the workspace.- // Both ids below are typed `string` instead of being renamed to- // `...UniversalIdentifier`, but the sync resolves them as universal identifiers.+ // FIELD + TABLE is scoped only when the bound view filters the inverse+ // relation with isCurrentRecordSelected. A RECORD_TABLE widget has no+ // parent-record filter and lists every Application in the workspace.+ // fieldMetadataId and viewId are typed `string`; sync resolves them+ // as universal identifiers.fieldMetadataId: APPLICATIONS_ON_OPPORTUNITY_FIELD_ID,fieldDisplayMode: 'TABLE',viewId: APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/partner/directory/page-layouts/partner.page-layout.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/partner/directory/page-layouts/partner.page-layout.test.tsnew file mode 100644index 00000000000..0812c7c28a0--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/partner/directory/page-layouts/partner.page-layout.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { APPLICATIONS_ON_PARTNER_FIELD_ID } from 'src/modules/application/objects/application.object';+import { APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER } from 'src/modules/application/views/applications-on-partner-widget.view';+import { APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER } from 'src/modules/application/views/applications-widget.view';++import partnerPageLayout from './partner.page-layout';++describe('partner.page-layout', () => {+ it('scopes the Briefs FIELD TABLE to the partner widget view', () => {+ const briefsWidget = partnerPageLayout.config.tabs+ .flatMap((tab) => tab.widgets ?? [])+ .find((widget) => widget.title === 'Briefs');++ expect(briefsWidget).toBeDefined();+ expect(briefsWidget?.type).toBe('FIELD');+ expect(briefsWidget?.configuration).toMatchObject({+ configurationType: 'FIELD',+ fieldMetadataId: APPLICATIONS_ON_PARTNER_FIELD_ID,+ fieldDisplayMode: 'TABLE',+ viewId: APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+ });+ expect(+ 'nestedRelationFieldMetadataId' in (briefsWidget?.configuration ?? {})+ ? briefsWidget?.configuration.nestedRelationFieldMetadataId+ : undefined,+ ).toBeUndefined();+ });++ it('does not share a view UUID with the opportunity Partners widget', () => {+ expect(APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER).not.toBe(+ APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+ );+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/partner/directory/page-layouts/partner.page-layout.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/partner/directory/page-layouts/partner.page-layout.tsindex 08972d49338..a7525d5a010 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/partner/directory/page-layouts/partner.page-layout.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/partner/directory/page-layouts/partner.page-layout.ts@@ -2,7 +2,7 @@ import { PageLayoutTabLayoutMode, definePageLayout } from 'twenty-sdk/define';import { PARTNER_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { APPLICATIONS_ON_PARTNER_FIELD_ID } from 'src/modules/application/objects/application.object';-import { APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER } from 'src/modules/application/views/applications-widget.view';+import { APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER } from 'src/modules/application/views/applications-on-partner-widget.view';import { PARTNER_RECORD_PAGE_FIELDS_VIEW_ID } from 'src/modules/partner/directory/views/partner-record-page-fields.view';// Partner is a custom (app-owned) object, so we fully control its record page. The@@ -45,13 +45,14 @@ export default definePageLayout({type: 'FIELD',configuration: {configurationType: 'FIELD',- // A FIELD widget in TABLE mode is the only configuration scoped to the parent- // record; a RECORD_TABLE widget would list every Application in the workspace.- // Both ids below are typed `string` instead of being renamed to- // `...UniversalIdentifier`, but the sync resolves them as universal identifiers.+ // FIELD + TABLE is scoped only when the bound view filters the inverse+ // relation with isCurrentRecordSelected. A RECORD_TABLE widget has no+ // parent-record filter and lists every Application in the workspace.+ // fieldMetadataId and viewId are typed `string`; sync resolves them+ // as universal identifiers.fieldMetadataId: APPLICATIONS_ON_PARTNER_FIELD_ID,fieldDisplayMode: 'TABLE',- viewId: APPLICATIONS_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,+ viewId: APPLICATIONS_ON_PARTNER_WIDGET_VIEW_UNIVERSAL_IDENTIFIER,},},],diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/mutations/update-opportunity-applicant-partner-user-ids.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/mutations/update-opportunity-applicant-partner-user-ids.tsnew file mode 100644index 00000000000..c6657698b6c--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/mutations/update-opportunity-applicant-partner-user-ids.ts@@ -0,0 +1,14 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++export function updateOpportunityApplicantPartnerUserIds(+ client: CoreApiClient,+ opportunityId: string,+ applicantPartnerUserIds: string[],+) {+ return client.mutation({+ updateOpportunity: {+ __args: { id: opportunityId, data: { applicantPartnerUserIds } },+ id: true,+ },+ });+}diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/queries/get-opportunity-applicant-partner-user-ids.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/queries/get-opportunity-applicant-partner-user-ids.tsnew file mode 100644index 00000000000..ade24fe3013--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/queries/get-opportunity-applicant-partner-user-ids.ts@@ -0,0 +1,13 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++export function getOpportunityApplicantPartnerUserIds(+ client: CoreApiClient,+ opportunityId: string,+) {+ return client.query({+ opportunities: {+ __args: { filter: { id: { eq: opportunityId } }, first: 1 },+ edges: { node: { id: true, applicantPartnerUserIds: true } },+ },+ });+}diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/queries/list-applications-with-opportunity-partner-user.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/queries/list-applications-with-opportunity-partner-user.tsnew file mode 100644index 00000000000..29be782d24f--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/graphql/queries/list-applications-with-opportunity-partner-user.ts@@ -0,0 +1,21 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++const PAGE_SIZE = 200;++export function listApplicationsWithOpportunityPartnerUser(+ client: CoreApiClient,+ after?: string,+) {+ return client.query({+ applications: {+ __args: {+ first: PAGE_SIZE,+ ...(after ? { after } : {}),+ },+ edges: {+ node: { opportunityId: true, partnerUserId: true },+ },+ pageInfo: { hasNextPage: true, endCursor: true },+ },+ });+}diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/post-install.logic-function.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/post-install.logic-function.tsindex 9976ec30a45..b81d042c4b5 100644--- a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/post-install.logic-function.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/post-install.logic-function.ts@@ -1,37 +1,47 @@import { CoreApiClient } from 'twenty-client-sdk/core';import { type InstallPayload, definePostInstallLogicFunction } from 'twenty-sdk/define';+import { backfillApplicantOpportunityVisibility } from 'src/modules/shared/services/backfill-applicant-opportunity-visibility.service';import { backfillPartnerUserOnChildren } from 'src/modules/shared/services/backfill-partner-user-on-children.service';+import { planPostInstall } from 'src/modules/shared/utils/plan-post-install.util';-// The release that narrowed the Application RLS predicate to `partnerUser IS me`.-const STRICT_APPLICATION_RLS_VERSION = [1, 6, 1];+type PostInstallCounts = {+ stamped?: number;+ granted?: number;+};++type PostInstallResult = { skipped: true } | PostInstallCounts;-const isBefore = (version: string, target: number[]): boolean => {- const parts = version.split('.').map((part) => Number.parseInt(part, 10) || 0);+const handler = async ({+ previousVersion,+}: InstallPayload): Promise<PostInstallResult> => {+ const plan = planPostInstall(previousVersion);- for (let index = 0; index < target.length; index++) {- const part = parts[index] ?? 0;- if (part !== target[index]) return part < target[index];+ if (!plan.stampPartnerUser && !plan.grantApplicantVisibility) {+ return { skipped: true };}- return false;-};+ const client = new CoreApiClient();+ const result: PostInstallCounts = {};-const handler = async ({ previousVersion }: InstallPayload) => {- if (previousVersion && !isBefore(previousVersion, STRICT_APPLICATION_RLS_VERSION)) {- return { skipped: true };+ // Grant reads partnerUserId on Application. Stamp first so an upgrade from+ // before 1.6.1 does not skip those applicants.+ if (plan.stampPartnerUser) {+ result.stamped = await backfillPartnerUserOnChildren(client);}- const stamped = await backfillPartnerUserOnChildren(new CoreApiClient());+ if (plan.grantApplicantVisibility) {+ result.granted = await backfillApplicantOpportunityVisibility(client);+ }- return { stamped };+ return result;};export default definePostInstallLogicFunction({universalIdentifier: 'f92bad2e-5905-4757-96ee-af9869d4ca0c',name: 'post-install',description:- 'Stamps partnerUser on partner-owned records created before the Application RLS narrowing.',+ 'Stamps partnerUser on partner-owned records created before the Application RLS narrowing, and grants opportunity read access to existing applicants.',handler,shouldRunOnVersionUpgrade: true,shouldRunSynchronously: true,diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/backfill-applicant-opportunity-visibility.service.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/backfill-applicant-opportunity-visibility.service.test.tsnew file mode 100644index 00000000000..eda965840a1--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/backfill-applicant-opportunity-visibility.service.test.ts@@ -0,0 +1,267 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { backfillApplicantOpportunityVisibility } from './backfill-applicant-opportunity-visibility.service';++const OPPORTUNITY_A = 'opportunity-a';+const OPPORTUNITY_B = 'opportunity-b';+const MEMBER_1 = 'member-1';+const MEMBER_2 = 'member-2';++type GraphQlSelection = Record<string, unknown>;++const opportunityIdFromSelection = (selection: GraphQlSelection) =>+ (+ selection.opportunities as {+ __args?: { filter?: { id?: { eq?: string } } };+ }+ )?.__args?.filter?.id?.eq;++const createApplicantIdStore = (initial?: Iterable<[string, string[]]>) => {+ const applicantIdsByOpportunity = new Map<string, string[]>(initial);++ const readOpportunity = (opportunityId: string | undefined) => ({+ opportunities: {+ edges: opportunityId+ ? [+ {+ node: {+ id: opportunityId,+ applicantPartnerUserIds:+ applicantIdsByOpportunity.get(opportunityId) ?? [],+ },+ },+ ]+ : [],+ },+ });++ const writeOpportunity = (selection: GraphQlSelection) => {+ const args = (+ selection.updateOpportunity as {+ __args?: { id?: string; data?: { applicantPartnerUserIds?: string[] } };+ }+ )?.__args;++ if (args?.id && args.data?.applicantPartnerUserIds) {+ applicantIdsByOpportunity.set(args.id, args.data.applicantPartnerUserIds);+ }++ return {};+ };++ return { readOpportunity, writeOpportunity };+};++describe('backfillApplicantOpportunityVisibility', () => {+ const query = vi.fn();+ const mutation = vi.fn();+ const client = { query, mutation } as unknown as CoreApiClient;++ beforeEach(() => {+ query.mockReset();+ mutation.mockReset();+ mutation.mockResolvedValue({});+ });++ it('writes one merged list per opportunity and skips ids that are already present', async () => {+ const { readOpportunity, writeOpportunity } = createApplicantIdStore([+ [OPPORTUNITY_A, [MEMBER_1]],+ [OPPORTUNITY_B, [MEMBER_1]],+ ]);++ query.mockImplementation((selection: GraphQlSelection) => {+ if (selection.applications) {+ return Promise.resolve({+ applications: {+ edges: [+ {+ node: {+ id: 'app-1',+ opportunityId: OPPORTUNITY_A,+ partnerUserId: MEMBER_1,+ },+ },+ {+ node: {+ id: 'app-2',+ opportunityId: OPPORTUNITY_A,+ partnerUserId: MEMBER_2,+ },+ },+ {+ node: {+ id: 'app-3',+ opportunityId: OPPORTUNITY_B,+ partnerUserId: MEMBER_1,+ },+ },+ {+ node: {+ id: 'app-4',+ opportunityId: null,+ partnerUserId: MEMBER_1,+ },+ },+ ],+ pageInfo: { hasNextPage: false },+ },+ });+ }++ return Promise.resolve(+ readOpportunity(opportunityIdFromSelection(selection)),+ );+ });++ mutation.mockImplementation((selection: GraphQlSelection) =>+ Promise.resolve(writeOpportunity(selection)),+ );++ const updated = await backfillApplicantOpportunityVisibility(client);++ expect(updated).toBe(1);+ expect(mutation).toHaveBeenCalledTimes(1);+ expect(mutation).toHaveBeenCalledWith({+ updateOpportunity: {+ __args: {+ id: OPPORTUNITY_A,+ data: { applicantPartnerUserIds: [MEMBER_1, MEMBER_2] },+ },+ id: true,+ },+ });+ });++ it('returns 0 when no application has both an opportunity and a partner user', async () => {+ query.mockResolvedValue({+ applications: { edges: [], pageInfo: { hasNextPage: false } },+ });++ const updated = await backfillApplicantOpportunityVisibility(client);++ expect(updated).toBe(0);+ expect(mutation).not.toHaveBeenCalled();+ });++ it('follows the cursor across pages and merges rows from every page', async () => {+ const applicationPages: Record<string, unknown> = {+ first: {+ applications: {+ edges: [+ {+ node: { opportunityId: OPPORTUNITY_A, partnerUserId: MEMBER_1 },+ },+ ],+ pageInfo: { hasNextPage: true, endCursor: 'cursor-1' },+ },+ },+ second: {+ applications: {+ edges: [+ {+ node: { opportunityId: OPPORTUNITY_A, partnerUserId: MEMBER_2 },+ },+ ],+ pageInfo: { hasNextPage: false, endCursor: null },+ },+ },+ };+ const seenCursors: (string | undefined)[] = [];+ const { readOpportunity, writeOpportunity } = createApplicantIdStore();++ query.mockImplementation((selection: GraphQlSelection) => {+ if (selection.applications) {+ const after = (+ selection.applications as { __args?: { after?: string } }+ )?.__args?.after;++ seenCursors.push(after);++ return Promise.resolve(+ after === 'cursor-1'+ ? applicationPages.second+ : applicationPages.first,+ );+ }++ return Promise.resolve(+ readOpportunity(opportunityIdFromSelection(selection)),+ );+ });++ mutation.mockImplementation((selection: GraphQlSelection) =>+ Promise.resolve(writeOpportunity(selection)),+ );++ const updated = await backfillApplicantOpportunityVisibility(client);++ expect(seenCursors).toEqual([undefined, 'cursor-1']);+ expect(updated).toBe(1);+ expect(mutation).toHaveBeenCalledWith({+ updateOpportunity: {+ __args: {+ id: OPPORTUNITY_A,+ data: { applicantPartnerUserIds: [MEMBER_1, MEMBER_2] },+ },+ id: true,+ },+ });+ });++ it('grants the healthy opportunities, then fails loudly so the upgrade can be re-run', async () => {+ const { readOpportunity, writeOpportunity } = createApplicantIdStore();++ query.mockImplementation((selection: GraphQlSelection) => {+ if (selection.applications) {+ return Promise.resolve({+ applications: {+ edges: [+ {+ node: {+ id: 'app-1',+ opportunityId: OPPORTUNITY_A,+ partnerUserId: MEMBER_1,+ },+ },+ {+ node: {+ id: 'app-2',+ opportunityId: OPPORTUNITY_B,+ partnerUserId: MEMBER_2,+ },+ },+ ],+ pageInfo: { hasNextPage: false },+ },+ });+ }++ const requestedId = opportunityIdFromSelection(selection);++ if (requestedId === OPPORTUNITY_A) {+ return Promise.reject(new Error('boom'));+ }++ return Promise.resolve(readOpportunity(requestedId));+ });++ mutation.mockImplementation((selection: GraphQlSelection) =>+ Promise.resolve(writeOpportunity(selection)),+ );++ await expect(+ backfillApplicantOpportunityVisibility(client),+ ).rejects.toThrow(/failed for 1 of 2 opportunities/);++ expect(mutation).toHaveBeenCalledWith({+ updateOpportunity: {+ __args: {+ id: OPPORTUNITY_B,+ data: { applicantPartnerUserIds: [MEMBER_2] },+ },+ id: true,+ },+ });+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/backfill-applicant-opportunity-visibility.service.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/backfill-applicant-opportunity-visibility.service.tsnew file mode 100644index 00000000000..d44cf2e33c1--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/backfill-applicant-opportunity-visibility.service.ts@@ -0,0 +1,75 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { listApplicationsWithOpportunityPartnerUser } from 'src/modules/shared/graphql/queries/list-applications-with-opportunity-partner-user';+import { grantOpportunityVisibility } from 'src/modules/shared/services/grant-opportunity-visibility.service';+import { isNonEmptyString } from 'src/modules/shared/utils/is-non-empty-string.util';+import { collectAll } from 'src/modules/shared/utils/paginate.util';++type ApplicationRow = {+ opportunityId?: string | null;+ partnerUserId?: string | null;+};++export async function backfillApplicantOpportunityVisibility(+ client: CoreApiClient,+): Promise<number> {+ const applications = await collectAll<ApplicationRow>(async (after) => {+ const page = await listApplicationsWithOpportunityPartnerUser(client, after);++ return page.applications;+ });++ const idsByOpportunity = new Map<string, string[]>();++ for (const application of applications) {+ const opportunityId = application.opportunityId;+ const partnerUserId = application.partnerUserId;++ if (!isNonEmptyString(opportunityId) || !isNonEmptyString(partnerUserId)) {+ continue;+ }++ const current = idsByOpportunity.get(opportunityId) ?? [];++ if (!current.includes(partnerUserId)) {+ current.push(partnerUserId);+ idsByOpportunity.set(opportunityId, current);+ }+ }++ let updated = 0;+ const failedOpportunityIds: string[] = [];++ for (const [opportunityId, applicantIds] of idsByOpportunity) {+ // Collect failures rather than aborting on the first, so one bad opportunity cannot+ // strand the rest — then throw below. The version gate runs this once per upgrade, so+ // reporting a partial run as success would leave those applicants locked out for good.+ try {+ const result = await grantOpportunityVisibility(+ client,+ opportunityId,+ applicantIds,+ );++ if (result.granted) {+ updated += 1;+ }+ } catch (error) {+ failedOpportunityIds.push(opportunityId);+ console.error(+ `[backfill] applicant visibility failed for opportunity ${opportunityId}`,+ error,+ );+ }+ }++ if (failedOpportunityIds.length > 0) {+ throw new Error(+ `Applicant visibility backfill failed for ${failedOpportunityIds.length} of ` ++ `${idsByOpportunity.size} opportunities (${failedOpportunityIds.join(', ')}). ` ++ 'Re-run the upgrade — granting is idempotent, so the ones already done are skipped.',+ );+ }++ return updated;+}diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/grant-opportunity-visibility.service.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/grant-opportunity-visibility.service.test.tsnew file mode 100644index 00000000000..e58cd7bf433--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/grant-opportunity-visibility.service.test.ts@@ -0,0 +1,142 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { grantOpportunityVisibility } from './grant-opportunity-visibility.service';++const OPPORTUNITY_ID = 'opportunity-1';+const MEMBER_ID = 'member-1';+const OTHER_MEMBER_ID = 'member-2';++const oneOpportunity = (applicantPartnerUserIds: string[] | null) => ({+ opportunities: {+ edges: [{ node: { id: OPPORTUNITY_ID, applicantPartnerUserIds } }],+ },+});++const updateCall = (applicantPartnerUserIds: string[]) => ({+ updateOpportunity: {+ __args: {+ id: OPPORTUNITY_ID,+ data: { applicantPartnerUserIds },+ },+ id: true,+ },+});++describe('grantOpportunityVisibility', () => {+ const query = vi.fn();+ const mutation = vi.fn();+ const client = { query, mutation } as unknown as CoreApiClient;++ beforeEach(() => {+ query.mockReset();+ mutation.mockReset();+ mutation.mockResolvedValue({});+ });++ it('appends the member id when the opportunity has no list yet', async () => {+ query+ .mockResolvedValueOnce(oneOpportunity(null))+ .mockResolvedValueOnce(oneOpportunity([MEMBER_ID]));++ const result = await grantOpportunityVisibility(client, OPPORTUNITY_ID, [+ MEMBER_ID,+ ]);++ expect(result).toEqual({ granted: true });+ expect(mutation).toHaveBeenCalledTimes(1);+ expect(mutation).toHaveBeenCalledWith(updateCall([MEMBER_ID]));+ });++ it('keeps existing members and appends the new one', async () => {+ query+ .mockResolvedValueOnce(oneOpportunity([OTHER_MEMBER_ID]))+ .mockResolvedValueOnce(+ oneOpportunity([OTHER_MEMBER_ID, MEMBER_ID]),+ );++ const result = await grantOpportunityVisibility(client, OPPORTUNITY_ID, [+ MEMBER_ID,+ ]);++ expect(result).toEqual({ granted: true });+ expect(mutation).toHaveBeenCalledTimes(1);+ expect(mutation).toHaveBeenCalledWith(+ updateCall([OTHER_MEMBER_ID, MEMBER_ID]),+ );+ });++ it('does not write when every incoming member is already listed', async () => {+ query.mockResolvedValue(oneOpportunity([MEMBER_ID]));++ const result = await grantOpportunityVisibility(client, OPPORTUNITY_ID, [+ MEMBER_ID,+ ]);++ expect(result).toEqual({ granted: false, already: true });+ expect(mutation).not.toHaveBeenCalled();+ });++ it('does not write when the opportunity is missing', async () => {+ query.mockResolvedValue({ opportunities: { edges: [] } });++ const result = await grantOpportunityVisibility(client, OPPORTUNITY_ID, [+ MEMBER_ID,+ ]);++ expect(result).toEqual({ granted: false, reason: 'opportunity_missing' });+ expect(mutation).not.toHaveBeenCalled();+ });++ it('does not write when opportunity or member ids are missing', async () => {+ const result = await grantOpportunityVisibility(client, '', [MEMBER_ID]);++ expect(result).toEqual({ granted: false, reason: 'missing_ids' });+ expect(query).not.toHaveBeenCalled();+ expect(mutation).not.toHaveBeenCalled();+ });++ it('writes a second time when a concurrent grant dropped the member id', async () => {+ query+ .mockResolvedValueOnce(oneOpportunity(null))+ .mockResolvedValueOnce(oneOpportunity([OTHER_MEMBER_ID]))+ .mockResolvedValueOnce(+ oneOpportunity([OTHER_MEMBER_ID, MEMBER_ID]),+ );++ const result = await grantOpportunityVisibility(client, OPPORTUNITY_ID, [+ MEMBER_ID,+ ]);++ expect(result).toEqual({ granted: true });+ expect(mutation).toHaveBeenCalledTimes(2);+ expect(mutation).toHaveBeenNthCalledWith(1, updateCall([MEMBER_ID]));+ expect(mutation).toHaveBeenNthCalledWith(+ 2,+ updateCall([OTHER_MEMBER_ID, MEMBER_ID]),+ );+ });++ it('throws when the member id is still missing after concurrent writes', async () => {+ query.mockResolvedValue(oneOpportunity([OTHER_MEMBER_ID]));++ await expect(+ grantOpportunityVisibility(client, OPPORTUNITY_ID, [MEMBER_ID]),+ ).rejects.toThrow(/still missing member-1/);++ expect(mutation).toHaveBeenCalledTimes(2);+ });++ it('does not claim a grant when the opportunity disappears after the write', async () => {+ query+ .mockResolvedValueOnce(oneOpportunity(null))+ .mockResolvedValueOnce({ opportunities: { edges: [] } });++ const result = await grantOpportunityVisibility(client, OPPORTUNITY_ID, [+ MEMBER_ID,+ ]);++ expect(result).toEqual({ granted: false, reason: 'opportunity_missing' });+ expect(mutation).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/grant-opportunity-visibility.service.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/grant-opportunity-visibility.service.tsnew file mode 100644index 00000000000..fb04f386edc--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/services/grant-opportunity-visibility.service.ts@@ -0,0 +1,85 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { updateOpportunityApplicantPartnerUserIds } from 'src/modules/shared/graphql/mutations/update-opportunity-applicant-partner-user-ids';+import { getOpportunityApplicantPartnerUserIds } from 'src/modules/shared/graphql/queries/get-opportunity-applicant-partner-user-ids';+import { isNonEmptyString } from 'src/modules/shared/utils/is-non-empty-string.util';++const mergeApplicantPartnerUserIds = (+ current: readonly string[] | null | undefined,+ incoming: readonly string[],+): string[] => [...new Set([...(current ?? []), ...incoming])];++const GRANT_READ_ATTEMPTS = 3;++type GrantOpportunityVisibilityResult =+ | { granted: false; reason: 'missing_ids' | 'opportunity_missing' }+ | { granted: false; already: true }+ | { granted: true };++const readApplicantIds = async (+ client: CoreApiClient,+ opportunityId: string,+): Promise<string[] | null> => {+ const result = await getOpportunityApplicantPartnerUserIds(+ client,+ opportunityId,+ );+ const opportunity = result.opportunities?.edges?.[0]?.node;++ if (!opportunity?.id) {+ return null;+ }++ return opportunity.applicantPartnerUserIds ?? [];+};++export async function grantOpportunityVisibility(+ client: CoreApiClient,+ opportunityId: string | null | undefined,+ partnerUserIds: readonly string[],+): Promise<GrantOpportunityVisibilityResult> {+ const incoming = partnerUserIds.filter(isNonEmptyString);++ if (!isNonEmptyString(opportunityId) || incoming.length === 0) {+ return { granted: false, reason: 'missing_ids' };+ }++ // updateOpportunity replaces the array, so two applies can each merge from the same+ // stale read. Re-read after every write. Throw if the member id is still missing so the+ // create trigger retries and the upgrade backfill fails loud. The core API has no+ // atomic append; a lost id after this loop is a failed grant, not a silent success.+ let attempt = 0;++ while (true) {+ attempt += 1;+ const current = await readApplicantIds(client, opportunityId);++ if (current === null) {+ return { granted: false, reason: 'opportunity_missing' };+ }++ if (incoming.every((partnerUserId) => current.includes(partnerUserId))) {+ return attempt === 1+ ? { granted: false, already: true }+ : { granted: true };+ }++ if (attempt === GRANT_READ_ATTEMPTS) {+ const missingPartnerUserIds = incoming.filter(+ (partnerUserId) => !current.includes(partnerUserId),+ );++ throw new Error(+ `Could not grant opportunity visibility for ${opportunityId}: ` ++ `applicantPartnerUserIds still missing ${missingPartnerUserIds.join(', ')} ` ++ `after concurrent writes.`,+ );+ }++ await updateOpportunityApplicantPartnerUserIds(+ client,+ opportunityId,+ mergeApplicantPartnerUserIds(current, incoming),+ );+ }+}diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/utils/plan-post-install.util.test.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/utils/plan-post-install.util.test.tsnew file mode 100644index 00000000000..103dfd14642--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/utils/plan-post-install.util.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';++import { planPostInstall } from './plan-post-install.util';++describe('planPostInstall', () => {+ it('runs both backfills on a fresh install', () => {+ expect(planPostInstall(undefined)).toEqual({+ stampPartnerUser: true,+ grantApplicantVisibility: true,+ });+ });++ it('runs only the applicant grant when upgrading from 1.8.0', () => {+ expect(planPostInstall('1.8.0')).toEqual({+ stampPartnerUser: false,+ grantApplicantVisibility: true,+ });+ });++ // 1.8.1 is another PR; 1.8.2 never shipped on main. Both still need the grant.+ it('runs only the applicant grant when upgrading from a release below 1.8.3', () => {+ for (const previousVersion of ['1.8.1', '1.8.2']) {+ expect(planPostInstall(previousVersion)).toEqual({+ stampPartnerUser: false,+ grantApplicantVisibility: true,+ });+ }+ });++ it('skips both backfills when already on 1.8.3 or later', () => {+ expect(planPostInstall('1.8.3')).toEqual({+ stampPartnerUser: false,+ grantApplicantVisibility: false,+ });+ expect(planPostInstall('1.9.0')).toEqual({+ stampPartnerUser: false,+ grantApplicantVisibility: false,+ });+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/modules/shared/utils/plan-post-install.util.ts b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/utils/plan-post-install.util.tsnew file mode 100644index 00000000000..417fce930f6--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/modules/shared/utils/plan-post-install.util.ts@@ -0,0 +1,40 @@+// The release that narrowed the Application RLS predicate to `partnerUser IS me`.+const STRICT_APPLICATION_RLS_VERSION = [1, 6, 1] as const;+// The release that grants opportunity read access to applicants after unlist.+// Keep this equal to package.json for this feature. A gate below the shipping+// version skips the backfill for any workspace already on that lower number.+// 1.8.1 is #25010, so it still needs the grant.+const APPLICANT_OPPORTUNITY_VISIBILITY_VERSION = [1, 8, 3] as const;++const isBeforeAppVersion = (+ version: string,+ target: readonly number[],+): boolean => {+ const parts = version.split('.').map((part) => Number.parseInt(part, 10) || 0);++ for (let index = 0; index < target.length; index++) {+ const part = parts[index] ?? 0;+ if (part !== target[index]) return part < target[index];+ }++ return false;+};++export type PostInstallPlan = {+ stampPartnerUser: boolean;+ grantApplicantVisibility: boolean;+};++export const planPostInstall = (+ previousVersion: string | undefined,+): PostInstallPlan => ({+ stampPartnerUser:+ !previousVersion ||+ isBeforeAppVersion(previousVersion, STRICT_APPLICATION_RLS_VERSION),+ grantApplicantVisibility:+ !previousVersion ||+ isBeforeAppVersion(+ previousVersion,+ APPLICANT_OPPORTUNITY_VISIBILITY_VERSION,+ ),+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/roles/partner.role.test.ts b/packages/twenty-apps/internal/twenty-partners/src/roles/partner.role.test.tsnew file mode 100644index 00000000000..1de33d7b078--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/roles/partner.role.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it } from 'vitest';+import {+ RowLevelPermissionPredicateGroupLogicalOperator,+ RowLevelPermissionPredicateOperand,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,+} from 'twenty-sdk/define';++import {+ PARTNER_CONTENT_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_LINK_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_SERVICE_OBJECT_UNIVERSAL_IDENTIFIER,+} from 'src/constants/universal-identifiers';+import { APPLICATION_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/modules/application/objects/application.object';+import { OPPORTUNITY_APPLICANT_PARTNER_USER_IDS_FIELD_ID } from 'src/modules/opportunity/fields/opportunity-applicant-partner-user-ids.field';+import { OPPORTUNITY_IS_LISTED_FIELD_ID } from 'src/modules/opportunity/fields/opportunity-is-listed.field';++import partnerRole, { OPPORTUNITY_RLS_OR_GROUP_ID } from './partner.role';++const WORKSPACE_MEMBER_ID_FIELD =+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.workspaceMember.fields.id+ .universalIdentifier;+const OPPORTUNITY_OBJECT =+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier;++const predicates = partnerRole.config.rowLevelPermissionPredicates ?? [];+const groups = partnerRole.config.rowLevelPermissionPredicateGroups ?? [];++const opportunityPredicates = predicates.filter(+ (predicate) => predicate.objectUniversalIdentifier === OPPORTUNITY_OBJECT,+);++describe('partner.role row-level predicates', () => {+ it('is a valid role definition', () => {+ expect(partnerRole.errors).toEqual([]);+ expect(partnerRole.success).toBe(true);+ });++ // Every object the partner can read must be row-scoped. A missing entry here silently+ // widens the role to the whole workspace, so assert the exact set.+ it('row-scopes every object the partner can read', () => {+ const scopedObjects = predicates.map(+ (predicate) => predicate.objectUniversalIdentifier,+ );++ expect(new Set(scopedObjects)).toEqual(+ new Set([+ PARTNER_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_LINK_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_SERVICE_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_CONTENT_OBJECT_UNIVERSAL_IDENTIFIER,+ APPLICATION_OBJECT_UNIVERSAL_IDENTIFIER,+ OPPORTUNITY_OBJECT,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.workspaceMember+ .universalIdentifier,+ ]),+ );+ });++ it('gives every object outside the opportunity group a single owner check', () => {+ const ownershipPredicates = predicates.filter(+ (predicate) => predicate.objectUniversalIdentifier !== OPPORTUNITY_OBJECT,+ );++ expect(ownershipPredicates).toHaveLength(8);++ for (const predicate of ownershipPredicates) {+ // RELATION filters reject CONTAINS at query time, so ownership must use IS.+ expect(predicate.operand).toBe(RowLevelPermissionPredicateOperand.IS);+ expect(predicate.workspaceMemberFieldUniversalIdentifier).toBe(+ WORKSPACE_MEMBER_ID_FIELD,+ );+ expect(predicate.predicateGroupUniversalIdentifier).toBeUndefined();+ }+ });++ it('ORs the three opportunity predicates in one group', () => {+ expect(groups).toHaveLength(1);+ expect(groups[0].universalIdentifier).toBe(OPPORTUNITY_RLS_OR_GROUP_ID);+ expect(OPPORTUNITY_RLS_OR_GROUP_ID).toBe(+ '7a7fd85d-62c6-4cac-876f-3a67951e7b10',+ );+ expect(groups[0].logicalOperator).toBe(+ RowLevelPermissionPredicateGroupLogicalOperator.OR,+ );++ expect(opportunityPredicates).toHaveLength(3);++ for (const predicate of opportunityPredicates) {+ expect(predicate.predicateGroupUniversalIdentifier).toBe(+ groups[0].universalIdentifier,+ );+ }++ expect(+ opportunityPredicates.map((predicate) => predicate.position),+ ).toEqual([0, 1, 2]);+ });++ it('keeps a listed brief visible without naming a member', () => {+ const isListed = opportunityPredicates.find(+ (predicate) =>+ predicate.fieldUniversalIdentifier === OPPORTUNITY_IS_LISTED_FIELD_ID,+ );++ expect(isListed?.value).toBe(true);+ expect(isListed?.workspaceMemberFieldUniversalIdentifier).toBeUndefined();+ });++ it('matches an applicant against the array with CONTAINS', () => {+ const applicant = opportunityPredicates.find(+ (predicate) =>+ predicate.fieldUniversalIdentifier ===+ OPPORTUNITY_APPLICANT_PARTNER_USER_IDS_FIELD_ID,+ );++ expect(applicant?.operand).toBe(+ RowLevelPermissionPredicateOperand.CONTAINS,+ );+ expect(applicant?.workspaceMemberFieldUniversalIdentifier).toBe(+ WORKSPACE_MEMBER_ID_FIELD,+ );+ });++ it('hides applicantPartnerUserIds so one applicant cannot read the others', () => {+ const fieldPermission = partnerRole.config.fieldPermissions?.find(+ (permission) =>+ permission.fieldUniversalIdentifier ===+ OPPORTUNITY_APPLICANT_PARTNER_USER_IDS_FIELD_ID,+ );++ expect(fieldPermission?.canReadFieldValue).toBe(false);+ expect(fieldPermission?.canUpdateFieldValue).toBe(false);+ });++ it('keeps predicate identifiers unique and stable so sync updates in place', () => {+ const identifiers = [+ ...predicates.map((predicate) => predicate.universalIdentifier),+ ...groups.map((group) => group.universalIdentifier),+ ];++ expect(new Set(identifiers).size).toBe(identifiers.length);+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/roles/partner.role.ts b/packages/twenty-apps/internal/twenty-partners/src/roles/partner.role.tsindex 167b94aa66b..42c5eba7057 100644--- a/packages/twenty-apps/internal/twenty-partners/src/roles/partner.role.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/roles/partner.role.ts@@ -1,4 +1,6 @@import {+ RowLevelPermissionPredicateGroupLogicalOperator,+ RowLevelPermissionPredicateOperand,STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,SystemPermissionFlag,defineRole,@@ -29,6 +31,7 @@ import {PARTNER_CONTENT_TYPE_FIELD_ID,} from 'src/modules/partner/objects/partner-content.object';import { PARTNER_CONTENT_PARTNER_FIELD_ID } from 'src/modules/partner/fields/partner-content-partner.field';+import { OPPORTUNITY_APPLICANT_PARTNER_USER_IDS_FIELD_ID } from 'src/modules/opportunity/fields/opportunity-applicant-partner-user-ids.field';import { OPPORTUNITY_DESIGN_DOC_STATUS_FIELD_ID } from 'src/modules/opportunity/fields/opportunity-design-doc-status.field';import { OPPORTUNITY_DESIGN_DOC_URL_FIELD_ID } from 'src/modules/opportunity/fields/opportunity-design-doc-url.field';import { OPPORTUNITY_HOSTING_TYPE_FIELD_ID } from 'src/modules/opportunity/fields/opportunity-hosting-type.field';@@ -50,16 +53,56 @@ import { PARTNER_USER_ON_PARTNER_CONTENT_FIELD_ID } from 'src/modules/partner/fiimport { PARTNER_USER_ON_PARTNER_LINK_FIELD_ID } from 'src/modules/partner/fields/partner-user-on-partner-link.field';import { PARTNER_USER_ON_PARTNER_FIELD_ID } from 'src/modules/partner/fields/partner-user-on-partner.field';import { PARTNER_USER_ON_PARTNER_SERVICE_FIELD_ID } from 'src/modules/partner/fields/partner-user-on-partner-service.field';+import { PARTNER_USER_ON_COMPANY_FIELD_ID } from 'src/modules/partner/fields/partner-user-on-company.field';+import { PARTNER_USER_ON_PERSON_FIELD_ID } from 'src/modules/partner/fields/partner-user-on-person.field';import { REFERRED_BY_PARTNER_ON_OPPORTUNITY_FIELD_ID } from 'src/modules/opportunity/fields/referred-by-partner-on-opportunity.field';// Shared with configure-partner-rls.ts, which locates the role by this label.export const PARTNER_ROLE_LABEL = 'Partner';+export const OPPORTUNITY_RLS_OR_GROUP_ID =+ '7a7fd85d-62c6-4cac-876f-3a67951e7b10';++const RLS_PREDICATE_IDS = {+ partner: '501a50b0-9e57-4a5a-99c3-88c44dc46d4a',+ person: 'e22864f1-bf16-4645-a1be-2a7b496f9553',+ company: '5560449f-53a2-47e4-86a2-ac9d046d7f48',+ partnerLink: '12298a33-14b8-4400-a2a3-6808248f30ca',+ partnerService: '6b12da67-2e82-4a4a-950c-590dcccae147',+ partnerContent: 'a030e3a0-bcf5-4894-aa85-6f7ef346f540',+ application: '028e9c80-608f-4c19-883c-bea2978e957b',+ workspaceMemberSelf: 'cc793cb4-c57f-4b37-a16a-2d1077aaffee',+ opportunityPartnerUser: '05267679-8996-4787-aaf2-f9e2f7eb960f',+ opportunityIsListed: '06475b7d-5e56-4a9d-be5c-83a18c0c28ff',+ opportunityApplicant: '5278f25a-c5f9-4e77-bb38-4e28a1b01556',+} as const;++const WORKSPACE_MEMBER_ID_FIELD_UNIVERSAL_IDENTIFIER =+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.workspaceMember.fields.id+ .universalIdentifier;++// Operand must be IS, not CONTAINS: the upsert accepts CONTAINS but the RELATION query+// filter only allows IS / IS_NOT and throws at query time.+const ownedByCurrentMember = (+ universalIdentifier: string,+ objectUniversalIdentifier: string,+ fieldUniversalIdentifier: string,+) => ({+ universalIdentifier,+ objectUniversalIdentifier,+ fieldUniversalIdentifier,+ operand: RowLevelPermissionPredicateOperand.IS,+ workspaceMemberFieldUniversalIdentifier:+ WORKSPACE_MEMBER_ID_FIELD_UNIVERSAL_IDENTIFIER,+});+// External partner self-service role: a partner sees only its own records and can edit its// own Partner profile. Company, Person, Opportunity and Application are read-only — the// pitch is set once by the apply route (application role) at creation and is never editable// by the partner afterwards. Application rows are scoped to own partnerUser (RLS).-// Row-level predicates can't ship in the manifest, so run `yarn rls:configure` after install.+// Opportunity rows: listed briefs, assigned partnerUser, or applicantPartnerUserIds.+// Row-level predicates ship in this manifest (rowLevelPermissionPredicates below), so an+// install or upgrade configures them — no post-install script step.//// The Opportunity and Application field locks below are moot now that neither object is// writable at all. They stay because configure-partner-rls.ts asserts on them and exits@@ -75,7 +118,7 @@ export default defineRole({universalIdentifier: PARTNER_ROLE_UNIVERSAL_IDENTIFIER,label: PARTNER_ROLE_LABEL,description:- 'External partner self-service role. Sees only its own Partner/Person/Company/PartnerLink/PartnerService/PartnerContent/Opportunity/Application records (row-level). Can edit its own Partner profile; Application is read-only (the pitch is set once at apply time and cannot be edited afterwards); Opportunity stage/amount are read-only. Configure predicates with `yarn rls:configure` after install.',+ 'External partner self-service role. Sees only its own Partner/Person/Company/PartnerLink/PartnerService/PartnerContent/Opportunity/Application records (row-level). Can edit its own Partner profile; Application is read-only (the pitch is set once at apply time and cannot be edited afterwards); Opportunity stage/amount are read-only. Listed briefs are visible to all partners; after unlist, a partner still sees briefs it applied to or was invited to.',icon: 'IconBuildingStore',canBeAssignedToUsers: true,canUpdateAllSettings: false,@@ -279,6 +322,18 @@ export default defineRole({fieldUniversalIdentifier: OPPORTUNITY_IS_LISTED_FIELD_ID,canUpdateFieldValue: false,},+ {+ // RLS allowlist of applicant member ids — partners must not read or write it, or one+ // applicant would see the others. Hiding it costs realtime only: the server strips+ // restricted fields before matching an event against the RLS predicate, so live+ // updates for a brief matched solely by this field never reach the partner. The+ // initial query still returns the row, so it appears on reload.+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,+ fieldUniversalIdentifier: OPPORTUNITY_APPLICANT_PARTNER_USER_IDS_FIELD_ID,+ canReadFieldValue: false,+ canUpdateFieldValue: false,+ },{objectUniversalIdentifier:STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,@@ -512,8 +567,8 @@ export default defineRole({},{// Read-only so the UI can resolve member-typed relations (own partnerUser link,- // owner/createdBy). An RLS predicate scopes this to the partner's own member record- // (see scripts/configure-partner-rls.ts) so the internal roster stays hidden.+ // owner/createdBy). The workspaceMemberSelf predicate below scopes this to the+ // partner's own member record so the internal roster stays hidden.objectUniversalIdentifier:STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.workspaceMember.universalIdentifier,@@ -523,4 +578,90 @@ export default defineRole({canDestroyObjectRecords: false,},],+ rowLevelPermissionPredicateGroups: [+ {+ universalIdentifier: OPPORTUNITY_RLS_OR_GROUP_ID,+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,+ logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator.OR,+ },+ ],+ // RLS validates an insert against the row as submitted, so a row created without+ // partnerUser is rejected — which is why the apply route sets partnerUser at creation.+ rowLevelPermissionPredicates: [+ ownedByCurrentMember(+ RLS_PREDICATE_IDS.partner,+ PARTNER_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_USER_ON_PARTNER_FIELD_ID,+ ),+ ownedByCurrentMember(+ RLS_PREDICATE_IDS.person,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,+ PARTNER_USER_ON_PERSON_FIELD_ID,+ ),+ ownedByCurrentMember(+ RLS_PREDICATE_IDS.company,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,+ PARTNER_USER_ON_COMPANY_FIELD_ID,+ ),+ ownedByCurrentMember(+ RLS_PREDICATE_IDS.partnerLink,+ PARTNER_LINK_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_USER_ON_PARTNER_LINK_FIELD_ID,+ ),+ ownedByCurrentMember(+ RLS_PREDICATE_IDS.partnerService,+ PARTNER_SERVICE_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_USER_ON_PARTNER_SERVICE_FIELD_ID,+ ),+ ownedByCurrentMember(+ RLS_PREDICATE_IDS.partnerContent,+ PARTNER_CONTENT_OBJECT_UNIVERSAL_IDENTIFIER,+ PARTNER_USER_ON_PARTNER_CONTENT_FIELD_ID,+ ),+ ownedByCurrentMember(+ RLS_PREDICATE_IDS.application,+ APPLICATION_OBJECT_UNIVERSAL_IDENTIFIER,+ APPLICATION_PARTNER_USER_FIELD_ID,+ ),+ // Self-scope: a partner resolves member-typed relations to its own record only, so the+ // internal roster stays hidden. Other members resolve to null.+ ownedByCurrentMember(+ RLS_PREDICATE_IDS.workspaceMemberSelf,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.workspaceMember.universalIdentifier,+ WORKSPACE_MEMBER_ID_FIELD_UNIVERSAL_IDENTIFIER,+ ),+ // (partnerUser IS me) OR (isListed = true) OR (applicantPartnerUserIds CONTAINS me)+ {+ ...ownedByCurrentMember(+ RLS_PREDICATE_IDS.opportunityPartnerUser,+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,+ PARTNER_USER_ON_OPPORTUNITY_FIELD_ID,+ ),+ predicateGroupUniversalIdentifier: OPPORTUNITY_RLS_OR_GROUP_ID,+ position: 0,+ },+ {+ universalIdentifier: RLS_PREDICATE_IDS.opportunityIsListed,+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,+ fieldUniversalIdentifier: OPPORTUNITY_IS_LISTED_FIELD_ID,+ operand: RowLevelPermissionPredicateOperand.IS,+ value: true,+ predicateGroupUniversalIdentifier: OPPORTUNITY_RLS_OR_GROUP_ID,+ position: 1,+ },+ {+ universalIdentifier: RLS_PREDICATE_IDS.opportunityApplicant,+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.opportunity.universalIdentifier,+ fieldUniversalIdentifier:+ OPPORTUNITY_APPLICANT_PARTNER_USER_IDS_FIELD_ID,+ operand: RowLevelPermissionPredicateOperand.CONTAINS,+ workspaceMemberFieldUniversalIdentifier:+ WORKSPACE_MEMBER_ID_FIELD_UNIVERSAL_IDENTIFIER,+ predicateGroupUniversalIdentifier: OPPORTUNITY_RLS_OR_GROUP_ID,+ position: 2,+ },+ ],});diff --git a/packages/twenty-apps/internal/twenty-partners/src/scripts/configure-partner-rls.ts b/packages/twenty-apps/internal/twenty-partners/src/scripts/configure-partner-rls.tsindex 71dba20a45d..2330796f498 100644--- a/packages/twenty-apps/internal/twenty-partners/src/scripts/configure-partner-rls.ts+++ b/packages/twenty-apps/internal/twenty-partners/src/scripts/configure-partner-rls.ts@@ -1,34 +1,36 @@-// Idempotent. Re-run after every install/reinstall — the app manifest can't ship RLS-// predicates. Does three things:+// Read-only drift check. `partner.role.ts` declares every row-level predicate and the+// server ingests them from the manifest, so an install or upgrade configures them. This+// script no longer creates, updates or deletes any predicate.//-// 1. Upserts row-level-permission predicates on the Partner role:-// - "partnerUser IS the current member" on partner/person/company/partnerLink/partnerService/-// partnerContent/application. RLS validates an insert against the row as submitted, so a-// row created without partnerUser is rejected — which is why the apply route sets-// partnerUser when it creates the Application.-// - "(partnerUser IS me) OR (isListed = true)" on opportunity (marketplace briefs)-// - "id IS the current member" on workspaceMember (self-scope; internal roster hidden)+// Legacy predicates on an already-installed workspace: earlier versions created them+// through upsertRowLevelPermissionPredicates, which stamps them with the workspace's+// custom application rather than twenty-partners. The manifest sync diffs by application,+// so it cannot see those rows and will never remove them.//-// 2. Verifies (does NOT set) the Opportunity field permissions from `partner.role.ts`.-// upsertFieldPermissions rejects out-of-band changes to app-owned roles-// (ROLE_BELONGS_TO_ANOTHER_APPLICATION), so those must come from the manifest; if any-// expected lock is missing, the script exits non-zero and tells you to re-sync.+// Ungrouped leftovers AND to the same ownership check and are redundant. Two parentless+// Opportunity OR groups are not. The RLS compiler keeps only the first parentless group,+// so leftover (partnerUser IS me) OR (isListed) can drop applicantPartnerUserIds CONTAINS.+// This script fails when it finds more than one. Remove leftover groups with database+// access while the manifest predicates stay in place. Do NOT clear them through the+// upsert mutation: it deletes every predicate for a (role, object) pair, and a Partner+// role with no predicate has no row filter at all, so partners would read the whole+// workspace until the manifest predicates were restored.//-// 3. Verifies Application field permissions the same way. The Partner role cannot write-// Application at all (canUpdateObjectRecords: false); the field locks are kept as-// intent on top of that object-level block, not as the mechanism.+// Also verifies Opportunity and Application field permissions from `partner.role.ts`.+// upsertFieldPermissions rejects out-of-band changes to app-owned roles+// (ROLE_BELONGS_TO_ANOTHER_APPLICATION), so those must come from the manifest; if any+// expected lock is missing, the script exits non-zero and tells you to re-sync.//// Usage:// yarn rls:configure # against .env.local// yarn rls:configure:prod # against .env.prod-import { createHash } from 'node:crypto';-import { config } from 'dotenv';config({ path: process.env.ENV_FILE ?? '.env.local' });import { PARTNER_ROLE_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';import { PARTNER_ROLE_LABEL } from 'src/roles/partner.role';+import { findParentlessOpportunityRlsGroups } from 'src/scripts/find-parentless-opportunity-rls-groups.util';const requireEnv = (name: string): string => {const value = process.env[name];@@ -45,26 +47,7 @@ const SIMPLE_TARGET_OBJECTS = ['partnerContent','application',] as const;-type SimpleTargetObject = (typeof SIMPLE_TARGET_OBJECTS)[number];--// A UUIDv5-shaped id derived from a seed: stable across re-runs, distinct per workspace.-const deriveUuid = (seed: string): string => {- const hex = createHash('sha1').update(seed).digest('hex');- const version = `5${hex.slice(13, 16)}`;- const variant = ((parseInt(hex.slice(16, 18), 16) & 0x3f) | 0x80)- .toString(16)- .padStart(2, '0');-- return [- hex.slice(0, 8),- hex.slice(8, 12),- version,- variant + hex.slice(18, 20),- hex.slice(20, 32),- ].join('-');-};--// opportunity uses an OR group (handled separately), but still needs an existence check.+// Opportunity is in this list so leftover parentless OR groups can be resolved by id.const ALL_TARGET_OBJECTS = [...SIMPLE_TARGET_OBJECTS, 'opportunity'] as const;// Opportunity fields that must NOT be locked: system columns and updatedBy/position@@ -104,17 +87,6 @@ const APPLICATION_FIELD_LOCK_SKIP = new Set(['opportunity',]);-const APPLY_WORKFLOW_WARNING =- `[rls:configure] The apply path ships in the app manifest: a command menu item\n` +- ` opens a front component that calls POST /apply-to-brief. No workflow needs\n` +- ` building for it. That app route creates the Application under the\n` +- ` application role.\n`;--type ObjectInfo = {- objectMetadataId: string;- partnerUserFieldMetadataId: string;-};-type FieldEdge = {node: {id: string;@@ -164,65 +136,6 @@ async function metadataFetch<T>(return json.data;}-// Pages through an object's fields until it finds a field with the given name.-// Uses cursor-based pagination to avoid truncation on large objects (company/opportunity-// have >200 fields, so a single 200-cap request may miss partnerUser).-async function findFieldByName(- metadataUrl: string,- apiKey: string,- objectId: string,- objectName: string,- fieldName: string,-): Promise<string> {- let after: string | null = null;- let page = 0;-- // eslint-disable-next-line no-constant-condition- while (true) {- page++;- const pagingArg = after- ? `paging:{first:200, after:"${after}"}`- : `paging:{first:200}`;-- const query = `{- object(id: "${objectId}") {- fields(${pagingArg}) {- edges { node { id name type } }- pageInfo { hasNextPage endCursor }- }- }- }`;-- const data = await metadataFetch<{- object: { fields: FieldsPage };- }>(metadataUrl, apiKey, query);-- const match = data.object.fields.edges.find(- (e) => e.node.name === fieldName,- );-- if (match) {- console.log(- ` [rls:configure] ${objectName}.${fieldName} found on page ${page} ` +- `(type=${match.node.type}, id=${match.node.id})`,- );- return match.node.id;- }-- if (!data.object.fields.pageInfo.hasNextPage) {- // Print available fields to help diagnose a schema mismatch.- const names = data.object.fields.edges- .map((e) => e.node.name)- .join(', ');- throw new Error(- `Field "${fieldName}" not found on object "${objectName}" after ${page} page(s). ` +- `Last-page fields: ${names}`,- );- }-- after = data.object.fields.pageInfo.endCursor;- }-}// Collects every field on an object across all cursor pages.// Required for Opportunity which can grow; always paginate fully.@@ -272,34 +185,10 @@ type FieldPermissionResult = {canUpdateFieldValue: boolean | null;};-type PredicateResult = {+type PredicateGroupResult = {id: string;- fieldMetadataId: string;- objectMetadataId: string;- operand: string;- workspaceMemberFieldMetadataId: string | null;- roleId: string;- rowLevelPermissionPredicateGroupId: string | null;- positionInRowLevelPermissionPredicateGroup: number | null;-};--type UpsertPredicatesInput = {- roleId: string;objectMetadataId: string;- predicates: {- fieldMetadataId: string;- operand: string;- workspaceMemberFieldMetadataId?: string | null;- value?: boolean | null;- rowLevelPermissionPredicateGroupId?: string | null;- positionInRowLevelPermissionPredicateGroup?: number | null;- }[];- predicateGroups: {- id?: string;- objectMetadataId: string;- logicalOperator: string;- parentRowLevelPermissionPredicateGroupId?: string | null;- }[];+ parentRowLevelPermissionPredicateGroupId?: string | null;};async function main() {@@ -309,7 +198,7 @@ async function main() {console.log(`[rls:configure] target: ${metadataUrl}`);- // ── 1. Resolve all object metadata IDs and their partnerUser field IDs ──────+ // ── 1. Resolve the object metadata IDs ──────────────────────────────────────const objectsData = await metadataFetch<{objects: { edges: { node: { id: string; nameSingular: string } }[] };@@ -320,7 +209,10 @@ async function main() {);const objectIdByName = new Map<string, string>(- objectsData.objects.edges.map((e) => [e.node.nameSingular, e.node.id]),+ objectsData.objects.edges.map((edge) => [+ edge.node.nameSingular,+ edge.node.id,+ ]),);for (const name of ALL_TARGET_OBJECTS) {@@ -336,80 +228,31 @@ async function main() {throw new Error('workspaceMember object not found in workspace metadata.');}- const workspaceMemberId = objectIdByName.get('workspaceMember') as string;-- const objectInfoByName = new Map<SimpleTargetObject, ObjectInfo>();-- for (const name of SIMPLE_TARGET_OBJECTS) {- const objectId = objectIdByName.get(name) as string;- const partnerUserFieldMetadataId = await findFieldByName(- metadataUrl,- apiKey,- objectId,- name,- 'partnerUser',- );- objectInfoByName.set(name, {- objectMetadataId: objectId,- partnerUserFieldMetadataId,- });- }-const opportunityObjectId = objectIdByName.get('opportunity') as string;- const opportunityPartnerUserFieldId = await findFieldByName(- metadataUrl,- apiKey,- opportunityObjectId,- 'opportunity',- 'partnerUser',- );- const opportunityIsListedFieldId = await findFieldByName(- metadataUrl,- apiKey,- opportunityObjectId,- 'opportunity',- 'isListed',- );-- // ── 2. Resolve workspaceMember.id field metadata id ──────────────────────────- const workspaceMemberIdFieldId = await findFieldByName(- metadataUrl,- apiKey,- workspaceMemberId,- 'workspaceMember',- 'id',- );-- const workspaceData = await metadataFetch<{- currentWorkspace: { id: string };- }>(metadataUrl, apiKey, `{ currentWorkspace { id } }`);-- const workspaceId = workspaceData.currentWorkspace.id;-- // ── 3. Resolve Partner role id and fetch field permissions in one request ──────+ // ── 2. Resolve Partner role, field permissions, and predicate groups ────────//// getRoles returns a flat array (not a connection) and does NOT expose// universalIdentifier, so we match on the role label via the shared PARTNER_ROLE_LABEL// constant (exported from partner.role.ts) — a rename there can't desync this script.- // Fetching fieldPermissions here avoids a second getRoles call later in step 5.const rolesData = await metadataFetch<{getRoles: {id: string;label: string;fieldPermissions: FieldPermissionResult[];+ rowLevelPermissionPredicateGroups: PredicateGroupResult[];}[];}>(metadataUrl,apiKey,- `{ getRoles { id label fieldPermissions { id fieldMetadataId objectMetadataId canUpdateFieldValue canReadFieldValue } } }`,+ `{ getRoles { id label fieldPermissions { id fieldMetadataId objectMetadataId canUpdateFieldValue canReadFieldValue } rowLevelPermissionPredicateGroups { id objectMetadataId parentRowLevelPermissionPredicateGroupId } } }`,);const roles = rolesData.getRoles;- const partnerRole = roles.find((r) => r.label === PARTNER_ROLE_LABEL);+ const partnerRole = roles.find((role) => role.label === PARTNER_ROLE_LABEL);if (!partnerRole) {- const labels = roles.map((r) => r.label).join(', ');+ const labels = roles.map((role) => role.label).join(', ');throw new Error(`Partner role not found. Available roles: ${labels}. ` +`Ensure the app is installed (universalIdentifier=${PARTNER_ROLE_UNIVERSAL_IDENTIFIER}).`,@@ -421,232 +264,86 @@ async function main() {`(universalIdentifier in manifest: ${PARTNER_ROLE_UNIVERSAL_IDENTIFIER})`,);- // ── 4. Upsert one predicate per object ───────────────────────────────────────- //- // "the record's partnerUser relation IS the current workspace member". Operand must be IS,- // not CONTAINS: the upsert accepts CONTAINS but the RELATION query filter only allows- // IS / IS_NOT and throws "Unknown operand CONTAINS for RELATION filter" at query time.- // value stays null; workspaceMemberFieldMetadataId injects the current member at query time.-- const MUTATION = `- mutation UpsertRLSPredicates($input: UpsertRowLevelPermissionPredicatesInput!) {- upsertRowLevelPermissionPredicates(input: $input) {- predicates {- id- fieldMetadataId- objectMetadataId- operand- workspaceMemberFieldMetadataId- roleId- rowLevelPermissionPredicateGroupId- positionInRowLevelPermissionPredicateGroup- }- }- }- `;-- const upsertPredicates = async (- input: UpsertPredicatesInput,- label: string,- ): Promise<PredicateResult[]> => {- try {- const data = await metadataFetch<{- upsertRowLevelPermissionPredicates: { predicates: PredicateResult[] };- }>(metadataUrl, apiKey, MUTATION, { input });-- return data.upsertRowLevelPermissionPredicates.predicates;- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- const canRetryWithoutGroups =- input.predicateGroups.length > 0 &&- message.includes('rowLevelPermissionPredicateGroup');-- if (!canRetryWithoutGroups) {- throw error;- }-- console.log(- `[rls:configure] ${label}: predicate group upsert failed; ` +- 'retrying with predicates only (group already exists)',- );-- const data = await metadataFetch<{- upsertRowLevelPermissionPredicates: { predicates: PredicateResult[] };- }>(metadataUrl, apiKey, MUTATION, {- input: { ...input, predicateGroups: [] },- });-- return data.upsertRowLevelPermissionPredicates.predicates;- }- };-- console.log(`\n${APPLY_WORKFLOW_WARNING}`);-- const results: PredicateResult[] = [];+ const parentlessOpportunityGroups = findParentlessOpportunityRlsGroups(+ partnerRole.rowLevelPermissionPredicateGroups ?? [],+ opportunityObjectId,+ );- for (const name of SIMPLE_TARGET_OBJECTS) {- const info = objectInfoByName.get(name) as ObjectInfo;+ if (parentlessOpportunityGroups.length > 1) {+ const leftoverGroupIds = parentlessOpportunityGroups+ .map((group) => group.id)+ .join(', ');- const data = await metadataFetch<{- upsertRowLevelPermissionPredicates: {- predicates: PredicateResult[];- };- }>(metadataUrl, apiKey, MUTATION, {- input: {- roleId: partnerRole.id,- objectMetadataId: info.objectMetadataId,- predicates: [- {- fieldMetadataId: info.partnerUserFieldMetadataId,- operand: 'IS',- workspaceMemberFieldMetadataId: workspaceMemberIdFieldId,- },- ],- predicateGroups: [],- } satisfies UpsertPredicatesInput,- });-- const predicate =- data.upsertRowLevelPermissionPredicates.predicates[0];-- if (!predicate) {- throw new Error(- `upsertRowLevelPermissionPredicates returned no predicates for object "${name}"`,- );- }-- results.push(predicate);- console.log(- `[rls:configure] ✓ ${name}: predicate id=${predicate.id} ` +- `(fieldMetadataId=${predicate.fieldMetadataId}, operand=${predicate.operand})`,+ console.error(+ `\n[rls:configure] DRIFT DETECTED: Partner role has ` ++ `${parentlessOpportunityGroups.length} parentless Opportunity RLS groups ` ++ `(${leftoverGroupIds}).\n` ++ `The filter compiler keeps only the first parentless group, so leftover\n` ++ `(partnerUser IS me) OR (isListed) can drop applicantPartnerUserIds CONTAINS.\n\n` ++ `Keep the twenty-partners manifest group. Soft-delete the leftover custom-\n` ++ `application group (and its predicates) in core.rowLevelPermissionPredicateGroup\n` ++ `/ core.rowLevelPermissionPredicate. Inspect applicationId first:\n\n` ++ ` SELECT id, "universalIdentifier", "applicationId"\n` ++ ` FROM core."rowLevelPermissionPredicateGroup"\n` ++ ` WHERE id IN (${parentlessOpportunityGroups.map((group) => `'${group.id}'`).join(', ')});\n\n` ++ `Do NOT call upsertRowLevelPermissionPredicates for (Partner, opportunity):\n` ++ `it wipes every predicate for that pair and leaves partners unfiltered.\n`,);+ process.exitCode = 1;+ return;}- // Opportunity: (partnerUser IS me) OR (isListed = true) — listed briefs visible to all partners.- {- // Predicate-group ids are unique across the whole metadata schema, not per workspace,- // so a hardcoded id collides on a server that hosts more than one workspace.- const opportunityGroupId = deriveUuid(- `${workspaceId}:opportunity-rls-or-group`,- );-- const oppPredicates = await upsertPredicates(- {- roleId: partnerRole.id,- objectMetadataId: opportunityObjectId,- predicateGroups: [- {- id: opportunityGroupId,- objectMetadataId: opportunityObjectId,- logicalOperator: 'OR',- parentRowLevelPermissionPredicateGroupId: null,- },- ],- predicates: [- {- fieldMetadataId: opportunityPartnerUserFieldId,- operand: 'IS',- workspaceMemberFieldMetadataId: workspaceMemberIdFieldId,- rowLevelPermissionPredicateGroupId: opportunityGroupId,- positionInRowLevelPermissionPredicateGroup: 0,- },- {- fieldMetadataId: opportunityIsListedFieldId,- operand: 'IS',- value: true,- rowLevelPermissionPredicateGroupId: opportunityGroupId,- positionInRowLevelPermissionPredicateGroup: 1,- },- ],- } satisfies UpsertPredicatesInput,- 'opportunity',- );+ // ── 3. Verify Opportunity field permissions (set via manifest, not here — see header) ─- if (oppPredicates.length < 2) {- throw new Error(- 'upsertRowLevelPermissionPredicates returned fewer than 2 predicates for opportunity OR group',- );- }+ const oppObjectId = opportunityObjectId;- for (const predicate of oppPredicates) {- results.push(predicate);- }+ const allOppFields = await collectAllFields(metadataUrl, apiKey, oppObjectId);+ const oppFieldIdToName = new Map<string, string>(+ allOppFields.map((field) => [field.id, field.name]),+ );- console.log(- `[rls:configure] ✓ opportunity: OR group id=${opportunityGroupId} ` +- `(${oppPredicates.length} predicates: partnerUser IS me OR isListed = true)`,+ const applicantPartnerUserIdsField = allOppFields.find(+ (field) => field.name === 'applicantPartnerUserIds',+ );+ const applicantPartnerUserIdsPermission =+ applicantPartnerUserIdsField &&+ partnerRole.fieldPermissions.find(+ (fieldPermission) =>+ fieldPermission.fieldMetadataId === applicantPartnerUserIdsField.id,);- }- // workspaceMember predicate: "id IS the current member", scoping the role's read to the- // partner's own record. Other members (e.g. an opportunity's internal owner) resolve to null.- {- const wmData = await metadataFetch<{- upsertRowLevelPermissionPredicates: { predicates: PredicateResult[] };- }>(metadataUrl, apiKey, MUTATION, {- input: {- roleId: partnerRole.id,- objectMetadataId: workspaceMemberId,- predicates: [- {- fieldMetadataId: workspaceMemberIdFieldId,- operand: 'IS',- workspaceMemberFieldMetadataId: workspaceMemberIdFieldId,- },- ],- predicateGroups: [],- } satisfies UpsertPredicatesInput,- });-- const wmPredicate =- wmData.upsertRowLevelPermissionPredicates.predicates[0];-- if (!wmPredicate) {- throw new Error(- 'upsertRowLevelPermissionPredicates returned no predicate for workspaceMember',- );- }-- results.push(wmPredicate);- console.log(- `[rls:configure] ✓ workspaceMember: predicate id=${wmPredicate.id} ` +- `(fieldMetadataId=${wmPredicate.fieldMetadataId}, operand=${wmPredicate.operand})`,+ if (+ !applicantPartnerUserIdsField ||+ applicantPartnerUserIdsPermission?.canReadFieldValue !== false+ ) {+ console.error(+ `\n[rls:configure] DRIFT DETECTED: applicantPartnerUserIds must be ` ++ `read-locked on the Partner role (canReadFieldValue: false).\n` ++ `Without that lock one applicant can read the other applicants' member ids.\n` ++ `Deploy partner.role.ts via yarn twenty apply -r <remote>.\n`,);+ process.exitCode = 1;+ return;}- console.log(- `\n[rls:configure] Done — ${results.length} predicates upserted on Partner role ` +- `(${SIMPLE_TARGET_OBJECTS.length} simple objects + opportunity OR group + workspaceMember self-scope)`,- );- console.log(`\n${APPLY_WORKFLOW_WARNING}`);-- // ── 5. Verify Opportunity field permissions (set via manifest, not here — see header) ─-- const oppObjectId = opportunityObjectId;-- const allOppFields = await collectAllFields(metadataUrl, apiKey, oppObjectId);- const oppFieldIdToName = new Map<string, string>(- allOppFields.map((f) => [f.id, f.name]),- );-// Build the expected lock set: every non-system Opportunity field (incl. stage + amount).const expectedLockedNames = new Set<string>(allOppFields- .filter((f) => !OPPORTUNITY_FIELD_LOCK_SKIP.has(f.name))- .map((f) => f.name),+ .filter((field) => !OPPORTUNITY_FIELD_LOCK_SKIP.has(field.name))+ .map((field) => field.name),);- // Filter to Opportunity field permissions that lock update access.- // partnerRole was fetched with fieldPermissions in step 3 — no second getRoles needed.const oppLockedFps = partnerRole.fieldPermissions.filter(- (fp) =>- fp.objectMetadataId === oppObjectId && fp.canUpdateFieldValue === false,+ (fieldPermission) =>+ fieldPermission.objectMetadataId === oppObjectId &&+ fieldPermission.canUpdateFieldValue === false,);const missingLocks = [...expectedLockedNames].filter((name) =>!oppLockedFps.some(- (fp) => oppFieldIdToName.get(fp.fieldMetadataId) === name,+ (fieldPermission) =>+ oppFieldIdToName.get(fieldPermission.fieldMetadataId) === name,),);@@ -669,7 +366,7 @@ async function main() {`[rls:configure] ✓ ${oppLockedFps.length} Opportunity fields locked (Partner role cannot write Opportunity at all; locks kept as intent) — field permissions verified`,);- // ── 6. Verify Application field permissions (set via manifest, not here — see header) ─+ // ── 4. Verify Application field permissions (set via manifest, not here — see header) ─const applicationObjectId = objectIdByName.get('application') as string;diff --git a/packages/twenty-apps/internal/twenty-partners/src/scripts/find-parentless-opportunity-rls-groups.util.test.ts b/packages/twenty-apps/internal/twenty-partners/src/scripts/find-parentless-opportunity-rls-groups.util.test.tsnew file mode 100644index 00000000000..3b5147e5cff--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/scripts/find-parentless-opportunity-rls-groups.util.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { findParentlessOpportunityRlsGroups } from './find-parentless-opportunity-rls-groups.util';++const OPPORTUNITY_OBJECT_ID = 'opportunity-object';++describe('findParentlessOpportunityRlsGroups', () => {+ it('returns only parentless groups on the opportunity object', () => {+ const groups = findParentlessOpportunityRlsGroups(+ [+ {+ id: 'manifest',+ objectMetadataId: OPPORTUNITY_OBJECT_ID,+ parentRowLevelPermissionPredicateGroupId: null,+ },+ {+ id: 'leftover',+ objectMetadataId: OPPORTUNITY_OBJECT_ID,+ },+ {+ id: 'nested',+ objectMetadataId: OPPORTUNITY_OBJECT_ID,+ parentRowLevelPermissionPredicateGroupId: 'manifest',+ },+ {+ id: 'other-object',+ objectMetadataId: 'application-object',+ parentRowLevelPermissionPredicateGroupId: null,+ },+ ],+ OPPORTUNITY_OBJECT_ID,+ );++ expect(groups.map((group) => group.id)).toEqual(['manifest', 'leftover']);+ });+});diff --git a/packages/twenty-apps/internal/twenty-partners/src/scripts/find-parentless-opportunity-rls-groups.util.ts b/packages/twenty-apps/internal/twenty-partners/src/scripts/find-parentless-opportunity-rls-groups.util.tsnew file mode 100644index 00000000000..33fbb94c70a--- /dev/null+++ b/packages/twenty-apps/internal/twenty-partners/src/scripts/find-parentless-opportunity-rls-groups.util.ts@@ -0,0 +1,15 @@+export type RowLevelPermissionPredicateGroupRow = {+ id: string;+ objectMetadataId: string;+ parentRowLevelPermissionPredicateGroupId?: string | null;+};++export const findParentlessOpportunityRlsGroups = (+ groups: readonly RowLevelPermissionPredicateGroupRow[],+ opportunityObjectId: string,+): RowLevelPermissionPredicateGroupRow[] =>+ groups.filter(+ (group) =>+ group.objectMetadataId === opportunityObjectId &&+ !group.parentRowLevelPermissionPredicateGroupId,+ );