Skip to content

Removes group_ids array from topic #12118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ export function CreateCommunity(): Command<typeof schemas.CreateCommunity> {
description: 'General discussions',
featured_in_sidebar: true,
featured_in_new_post: false,
group_ids: [],
allow_tokenized_threads: false,
},
{ transaction },
Expand Down
14 changes: 0 additions & 14 deletions libs/model/src/aggregates/community/CreateGroup.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,6 @@ export function CreateGroup(): Command<typeof schemas.CreateGroup> {
);
if (topics.length > 0) {
// add group to all specified topics
await models.Topic.update(
{
group_ids: sequelize.fn(
'array_append',
sequelize.col('group_ids'),
group.id,
),
},
{
where: { id: { [Op.in]: topics.map(({ id }) => id!) } },
transaction,
},
);

if (group.id) {
// add topic level interaction permissions for current group
const groupPermissions = (payload.topics || []).map((t) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ export function CreateTopic(): Command<typeof schemas.CreateTopic> {
featured_in_new_post,
default_offchain_template,
community_id: community_id!,
group_ids: [],
allow_tokenized_threads: allow_tokenized_threads ?? false,
};

Expand Down
16 changes: 1 addition & 15 deletions libs/model/src/aggregates/community/DeleteGroup.command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { InvalidInput, type Command } from '@hicommonwealth/core';
import * as schemas from '@hicommonwealth/schemas';
import { Op } from 'sequelize';
import { models, sequelize } from '../../database';
import { models } from '../../database';
import { authRoles } from '../../middleware';
import { mustExist } from '../../middleware/guards';

Expand All @@ -26,19 +25,6 @@ export function DeleteGroup(): Command<typeof schemas.DeleteGroup> {
throw new InvalidInput(DeleteGroupErrors.SystemManaged);

await models.sequelize.transaction(async (transaction) => {
await models.Topic.update(
{
group_ids: sequelize.fn(
'array_remove',
sequelize.col('group_ids'),
group_id,
),
},
{
where: { community_id, group_ids: { [Op.contains]: [group_id] } },
transaction,
},
);
await models.Membership.destroy({
where: { group_id },
transaction,
Expand Down
45 changes: 27 additions & 18 deletions libs/model/src/aggregates/community/GetGroups.query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as schemas from '@hicommonwealth/schemas';
import { Op } from 'sequelize';
import { z } from 'zod';
import { models } from '../../database';
import { buildTopicPermissionsMap } from './GetMemberships.query';

export function GetGroups(): Query<typeof schemas.GetGroups> {
return {
Expand All @@ -26,9 +27,10 @@ export function GetGroups(): Query<typeof schemas.GetGroups> {
],
});
const ids = groups.map((g) => g.id!);
const map = new Map<number, z.infer<typeof schemas.GroupView>>();

const output = new Map<number, z.infer<typeof schemas.GroupView>>();
groups.forEach((g) =>
map.set(g.id!, {
output.set(g.id!, {
...g.toJSON(),
id: g.id!,
name: g.metadata.name,
Expand All @@ -43,35 +45,42 @@ export function GetGroups(): Query<typeof schemas.GetGroups> {
include: [{ model: models.Address, as: 'address' }],
});
members.forEach((m) => {
const group = map.get(m.group_id);
const group = output.get(m.group_id);
group && group.memberships.concat(m);
});
}

if (include_topics) {
const topic_ids = groups
.map((g) => g.GroupPermissions || [])
.flat()
.map((p) => p.topic_id);
const topics = await models.Topic.findAll({
where: {
...(community_id && { community_id }),
group_ids: { [Op.overlap]: ids },
id: topic_ids,
},
});
groups.forEach((g) => {
const group = map.get(g.id!);
group &&
group.topics.concat(
topics
.filter((t) => t.group_ids.includes(group.id))
.map((t) => ({
...t.toJSON(),
permissions: (g.GroupPermissions || []).find(
(gtp) => gtp.topic_id === t.id,
)?.allowed_actions as schemas.PermissionEnum[],
})),
);

const topics_map = new Map<number, z.infer<typeof schemas.Topic>>();
topics.forEach((t) => topics_map.set(t.id!, t.toJSON()));

const topic_permissions = buildTopicPermissionsMap(groups);

output.forEach((g) => {
const perm = topic_permissions.get(g.id!);
perm &&
perm.forEach((p) => {
const topic = topics_map.get(p.id);
g.topics.push({
...topic!,
permissions: p.permissions,
});
});
});
}

return Array.from(map.values());
return Array.from(output.values());
},
};
}
50 changes: 31 additions & 19 deletions libs/model/src/aggregates/community/GetMemberships.query.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,37 @@
import { command, Query } from '@hicommonwealth/core';
import * as schemas from '@hicommonwealth/schemas';
import { Op } from 'sequelize';
import { z } from 'zod';
import { models } from '../../database';
import { systemActor } from '../../middleware';
import { mustExist } from '../../middleware/guards';
import { GroupAttributes } from '../../models';
import { RefreshCommunityMemberships } from './RefreshCommunityMemberships.command';

/**
* Builds a map of topic permissions indexed by group id
*/
export function buildTopicPermissionsMap(groups: GroupAttributes[]) {
const permissions = groups.map((g) => g.GroupPermissions || []).flat();
const map = new Map<number, z.infer<typeof schemas.TopicPermissionsView>[]>();
permissions.forEach((p) => {
const entry = map.get(p.group_id);
if (entry)
entry.push({
id: p.topic_id,
permissions: p.allowed_actions,
});
else
map.set(p.group_id, [
{
id: p.topic_id,
permissions: p.allowed_actions,
},
]);
});
return map;
}

export function GetMemberships(): Query<typeof schemas.GetMemberships> {
return {
...schemas.GetMemberships,
Expand All @@ -21,6 +47,7 @@ export function GetMemberships(): Query<typeof schemas.GetMemberships> {

const groups = await models.Group.findAll({
where: { community_id },
attributes: ['id'],
include: [
{
model: models.GroupPermission,
Expand All @@ -29,6 +56,7 @@ export function GetMemberships(): Query<typeof schemas.GetMemberships> {
},
],
});
const ids = groups.map((g) => g.id!);

// TODO: resolve stale community memberships in a separate job
await command(RefreshCommunityMemberships(), {
Expand All @@ -37,31 +65,15 @@ export function GetMemberships(): Query<typeof schemas.GetMemberships> {
});

const memberships = await models.Membership.findAll({
where: {
group_id: { [Op.in]: groups.map((g) => g.id!) },
address_id: addr.id!,
},
include: [{ model: models.Group, as: 'group' }],
where: { group_id: { [Op.in]: ids }, address_id: addr.id! },
});

const topics = await models.Topic.findAll({
where: { group_ids: { [Op.overlap]: groups.map((g) => g.id!) } },
attributes: ['id', 'group_ids'],
});
const topic_permissions = buildTopicPermissionsMap(groups);

// transform memberships to result shape
return memberships.map(({ group_id, reject_reason }) => ({
groupId: group_id,
topics: topics
.filter((t) => t.group_ids!.includes(group_id))
.map((t) => ({
id: t.id!,
permissions:
groups
.find((g) => g.id === group_id)
?.GroupPermissions?.find((gtp) => gtp.topic_id === t.id)
?.allowed_actions || [],
})),
topics: topic_permissions.get(group_id) || [],
isAllowed: !reject_reason,
rejectReason: reject_reason || undefined,
}));
Expand Down
1 change: 0 additions & 1 deletion libs/model/src/aggregates/community/GetTopics.query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ export function GetTopics(): Query<typeof schemas.GetTopics> {
t.default_offchain_template,
t."order",
t.channel_id,
t.group_ids,
t.weighted_voting,
t.token_symbol,
t.vote_weight_multiplier,
Expand Down
40 changes: 2 additions & 38 deletions libs/model/src/aggregates/community/UpdateGroup.command.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { InvalidInput, type Command } from '@hicommonwealth/core';
import * as schemas from '@hicommonwealth/schemas';
import { Op } from 'sequelize';
import { models, sequelize } from '../../database';
import { models } from '../../database';
import { authRoles } from '../../middleware';
import { mustExist } from '../../middleware/guards';
import { GroupAttributes } from '../../models';
Expand Down Expand Up @@ -51,42 +51,6 @@ export function UpdateGroup(): Command<typeof schemas.UpdateGroup> {
await group.update(updates, { transaction });

if (topics.length > 0) {
const ids = topics.map(({ id }) => id!);
await models.Topic.update(
{
group_ids: sequelize.fn(
'array_append',
sequelize.col('group_ids'),
group_id,
),
},
{
where: {
id: { [Op.in]: ids },
[Op.not]: { group_ids: { [Op.contains]: [group_id] } },
},
transaction,
},
);

// remove group from existing group topics
await models.Topic.update(
{
group_ids: sequelize.fn(
'array_remove',
sequelize.col('group_ids'),
group_id,
),
},
{
where: {
id: { [Op.notIn]: ids },
group_ids: { [Op.contains]: [group_id] },
},
transaction,
},
);

// update topic level interaction permissions for current group
await Promise.all(
(payload.topics || [])?.map(async (t) => {
Expand All @@ -101,7 +65,7 @@ export function UpdateGroup(): Command<typeof schemas.UpdateGroup> {
VALUES (:group_id, :topic_id, ${allowed_actions}, NOW(), NOW())
ON CONFLICT(group_id, topic_id) DO UPDATE
SET allowed_actions = EXCLUDED.allowed_actions,
updated_at = NOW();
updated_at = NOW();
`,
{
transaction,
Expand Down
4 changes: 0 additions & 4 deletions libs/model/src/aggregates/community/UpdateTopic.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ export function UpdateTopic(): Command<typeof schemas.UpdateTopic> {
name,
description,
telegram,
group_ids,
featured_in_sidebar,
featured_in_new_post,
allow_tokenized_threads,
Expand All @@ -55,9 +54,6 @@ export function UpdateTopic(): Command<typeof schemas.UpdateTopic> {
if (typeof telegram !== 'undefined') {
topic.telegram = telegram || '';
}
if (Array.isArray(group_ids)) {
topic.group_ids = group_ids;
}
if (typeof featured_in_sidebar !== 'undefined') {
topic.featured_in_sidebar = featured_in_sidebar || false;
}
Expand Down
18 changes: 11 additions & 7 deletions libs/model/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,6 @@ async function hasTopicPermissions(
const topic = await models.Topic.findOne({ where: { id: topic_id } });
if (!topic) throw new InvalidInput('Topic not found');

if (topic.group_ids?.length === 0) return;

// check if user has permission to perform "action" in 'topic_id'
// the 'topic_id' can belong to any group where user has membership
// the group with 'topic_id' having higher permissions will take precedence
Expand All @@ -262,11 +260,16 @@ async function hasTopicPermissions(
}
>(
`
SELECT g.*, gp.topic_id, gp.allowed_actions
FROM "Groups" as g
JOIN "GroupPermissions" gp ON g.id = gp.group_id
WHERE g.community_id = :community_id
AND gp.topic_id = :topic_id
SELECT
g.*,
gp.topic_id,
gp.allowed_actions
FROM
"Groups" as g
JOIN "GroupPermissions" gp ON g.id = gp.group_id
WHERE
g.community_id = :community_id
AND gp.topic_id = :topic_id
`,
{
type: QueryTypes.SELECT,
Expand All @@ -277,6 +280,7 @@ async function hasTopicPermissions(
},
},
);
if (!groups || groups.length === 0) return;

// There are 2 cases here. We either have the old group permission system where the group doesn't have
// any group_allowed_actions, or we have the new fine-grained permission system where the action must be in
Expand Down
5 changes: 0 additions & 5 deletions libs/model/src/models/topic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,6 @@ export default (
allowNull: true,
},
channel_id: { type: Sequelize.STRING, allowNull: true },
group_ids: {
type: Sequelize.ARRAY(Sequelize.INTEGER),
allowNull: false,
defaultValue: [],
},
telegram: { type: Sequelize.STRING, allowNull: true },
weighted_voting: { type: Sequelize.STRING, allowNull: true },
chain_node_id: { type: Sequelize.INTEGER, allowNull: true },
Expand Down
1 change: 0 additions & 1 deletion libs/model/test/contest/check-contests.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ describe.skip('Check Contests', () => {
id: topicId,
name: 'hello',
community_id: communityId,
group_ids: [],
},
],
contest_managers: [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ describe('Contest Worker Policy Lifecycle', () => {
id: topicId,
name: 'hello',
community_id: communityId,
group_ids: [],
},
],
contest_managers: [
Expand Down
Loading
Loading