Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
161 changes: 161 additions & 0 deletions api/src/repositories/userMaps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import pool from "../db";

export const USER_MAP_START_ID = 600;
export const USER_MAP_END_ID = 1999;
export const DEFAULT_MAX_USER_MAPS = 5;

export type UserMapStatus = "draft" | "proposed" | "published" | "archived";

export type UserMapRecord = {
id: number;
accountId: number;
name: string;
terrain: string;
zone: string;
status: UserMapStatus;
npcCount: number;
objectCount: number;
assetBytes: number;
createdAt: string;
updatedAt: string;
};

export type UserMapQuota = {
mapsUsed: number;
maxMaps: number;
assetBytesUsed: number;
maxAssetBytes: number;
npcCountUsed: number;
maxNpcCount: number;
objectCountUsed: number;
maxObjectCount: number;
};

export async function getUserMapQuota(accountId: number): Promise<UserMapQuota> {
const res = await pool.query(
`SELECT COUNT(*)::int AS "mapsCount",
COALESCE(SUM(asset_bytes), 0)::bigint AS "totalAssetBytes",
COALESCE(SUM(npc_count), 0)::int AS "totalNpcs",
COALESCE(SUM(object_count), 0)::int AS "totalObjects"
FROM user_maps
WHERE account_id = $1 AND status != 'archived'`,
[accountId]
);
const row = res.rows[0] || {};
return {
mapsUsed: row.mapsCount || 0,
maxMaps: DEFAULT_MAX_USER_MAPS,
assetBytesUsed: Number(row.totalAssetBytes || 0),
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Outdated

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Quality: Asset/NPC/object quotas computed but never enforced

getUserMapQuota reports maxAssetBytes, maxNpcCount, and maxObjectCount, and the PR description claims these limits are enforced, but createUserMap only checks mapsUsed >= maxMaps. The asset/NPC/object limits are never actually enforced on any write path. Either enforce them when maps/assets are added or remove the misleading claim.

Was this helpful? React with 👍 / 👎

maxAssetBytes: 10 * 1024 * 1024,
npcCountUsed: row.totalNpcs || 0,
maxNpcCount: 20,
objectCountUsed: row.totalObjects || 0,
maxObjectCount: 50,
};
}

export async function checkMapOwnership(mapId: number, accountId: number): Promise<boolean> {
const res = await pool.query(
`SELECT 1 FROM user_maps WHERE id = $1 AND account_id = $2`,
[mapId, accountId]
);
return (res.rowCount ?? 0) > 0;
}

export async function createUserMap(
accountId: number,
name: string,
terrain: string = "PRADERA",
zone: string = "CAMPO"
): Promise<UserMapRecord> {
const quota = await getUserMapQuota(accountId);
if (quota.mapsUsed >= quota.maxMaps) {
throw new Error(`Se ha alcanzado la cuota maxima de mapas (${quota.maxMaps})`);
}

const nextIdRes = await pool.query(
`SELECT COALESCE(MAX(id) + 1, $1) AS "nextId"
FROM user_maps
WHERE id >= $1 AND id <= $2`,
[USER_MAP_START_ID, USER_MAP_END_ID]
);
const nextId = Math.max(USER_MAP_START_ID, Number(nextIdRes.rows[0]?.nextId || USER_MAP_START_ID));
if (nextId > USER_MAP_END_ID) {
throw new Error("No hay identificadores de mapa disponibles en el rango de usuarios");
}
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Outdated

const res = await pool.query(
`INSERT INTO user_maps (id, account_id, name, terrain, zone, status)
VALUES ($1, $2, $3, $4, $5, 'draft')
RETURNING id, account_id AS "accountId", name, terrain, zone, status,
npc_count AS "npcCount", object_count AS "objectCount",
asset_bytes AS "assetBytes", created_at AS "createdAt", updated_at AS "updatedAt"`,
[nextId, accountId, name.trim(), terrain, zone]
);
return res.rows[0];
}

export async function getUserMap(mapId: number): Promise<UserMapRecord | null> {
const res = await pool.query(
`SELECT id, account_id AS "accountId", name, terrain, zone, status,
npc_count AS "npcCount", object_count AS "objectCount",
asset_bytes AS "assetBytes", created_at AS "createdAt", updated_at AS "updatedAt"
FROM user_maps
WHERE id = $1`,
[mapId]
);
return res.rows[0] || null;
}

export async function listUserMaps(accountId: number): Promise<UserMapRecord[]> {
const res = await pool.query(
`SELECT id, account_id AS "accountId", name, terrain, zone, status,
npc_count AS "npcCount", object_count AS "objectCount",
asset_bytes AS "assetBytes", created_at AS "createdAt", updated_at AS "updatedAt"
FROM user_maps
WHERE account_id = $1
ORDER BY id ASC`,
[accountId]
);
return res.rows;
}

export async function listPublishedUserMaps(page = 1, limit = 20): Promise<{ maps: UserMapRecord[]; total: number }> {
const offset = (Math.max(1, page) - 1) * limit;
const countRes = await pool.query(`SELECT COUNT(*)::int AS total FROM user_maps WHERE status = 'published'`);
const total = countRes.rows[0]?.total || 0;

const res = await pool.query(
`SELECT id, account_id AS "accountId", name, terrain, zone, status,
npc_count AS "npcCount", object_count AS "objectCount",
asset_bytes AS "assetBytes", created_at AS "createdAt", updated_at AS "updatedAt"
FROM user_maps
WHERE status = 'published'
ORDER BY id ASC
LIMIT $1 OFFSET $2`,
[limit, offset]
);
return { maps: res.rows, total };
}

export async function updateUserMapStatus(
mapId: number,
accountId: number,
newStatus: UserMapStatus
): Promise<UserMapRecord | null> {
const isOwner = await checkMapOwnership(mapId, accountId);
if (!isOwner) {
throw new Error("No tienes permiso para modificar este mapa");
}

const res = await pool.query(
`UPDATE user_maps
SET status = $1, updated_at = NOW()
WHERE id = $2 AND account_id = $3
RETURNING id, account_id AS "accountId", name, terrain, zone, status,
npc_count AS "npcCount", object_count AS "objectCount",
asset_bytes AS "assetBytes", created_at AS "createdAt", updated_at AS "updatedAt"`,
[newStatus, mapId, accountId]
);
return res.rows[0] || null;
}
88 changes: 88 additions & 0 deletions api/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2891,4 +2891,92 @@ app.get("/user-online-stats", async (request, response) => {
}
});

app.post("/internal/user-maps", requireAuth, async (request, response) => {
try {
const { name, terrain, zone } = request.body;
const accountId = (request as any).user?.accountId || 1;
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Outdated
const { createUserMap } = await import("./repositories/userMaps");
const result = await createUserMap(accountId, name, terrain, zone);
response.status(201).json(result);
} catch (error) {
response.status(400).json({
error: error instanceof Error ? error.message : "Unexpected error",
});
}
});

app.get("/internal/user-maps", requireAuth, async (request, response) => {
try {
const accountId = (request as any).user?.accountId || 1;
const { listUserMaps } = await import("./repositories/userMaps");
const result = await listUserMaps(accountId);
response.json(result);
} catch (error) {
response.status(500).json({
error: error instanceof Error ? error.message : "Unexpected error",
});
}
});

app.get("/internal/user-maps/quota", requireAuth, async (request, response) => {
try {
const accountId = (request as any).user?.accountId || 1;
const { getUserMapQuota } = await import("./repositories/userMaps");
const result = await getUserMapQuota(accountId);
response.json(result);
} catch (error) {
response.status(500).json({
error: error instanceof Error ? error.message : "Unexpected error",
});
}
});

app.get("/internal/user-maps/published", async (request, response) => {
try {
const page = Number(request.query.page || 1);
const limit = Number(request.query.limit || 20);
const { listPublishedUserMaps } = await import("./repositories/userMaps");
const result = await listPublishedUserMaps(page, limit);
response.json(result);
} catch (error) {
response.status(500).json({
error: error instanceof Error ? error.message : "Unexpected error",
});
}
});
Comment thread
gitar-bot[bot] marked this conversation as resolved.

app.get("/internal/user-maps/:id", requireAuth, async (request, response) => {
try {
const id = Number(request.params.id);
const { getUserMap } = await import("./repositories/userMaps");
const result = await getUserMap(id);
if (!result) {
return response.status(404).json({ error: "Mapa no encontrado" });
}
response.json(result);
} catch (error) {
response.status(500).json({
error: error instanceof Error ? error.message : "Unexpected error",
});
}
});
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Outdated

app.patch("/internal/user-maps/:id/status", requireAuth, async (request, response) => {
try {
const id = Number(request.params.id);
const { status } = request.body;
const accountId = (request as any).user?.accountId || 1;
const { updateUserMapStatus } = await import("./repositories/userMaps");
const result = await updateUserMapStatus(id, accountId, status);
if (!result) {
return response.status(404).json({ error: "Mapa no encontrado" });
}
response.json(result);
} catch (error) {
response.status(400).json({
error: error instanceof Error ? error.message : "Unexpected error",
});
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Outdated
}
});

void start();