style: clean up code formatting and remove trailing whitespace
refactor: reorganize imports and fix type imports
This commit is contained in:
1 parent
d3704602fd
commit
47c04de6fe
232 files changed
+7140
-4798
No files matched your search
+115
-56
@@ -89,21 +89,26 @@ export interface ListingFilters {
|
||||
search?: string;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
sortBy?: "created_at" | "price_pix" | "price_tibia_coins" | "price_gold_coins" | "views_count";
|
||||
sortBy?:
|
||||
| "created_at"
|
||||
| "price_pix"
|
||||
| "price_tibia_coins"
|
||||
| "price_gold_coins"
|
||||
| "views_count";
|
||||
sortOrder?: "ASC" | "DESC";
|
||||
}
|
||||
|
||||
/**
|
||||
* Cria um novo anúncio
|
||||
*/
|
||||
export async function createListing(
|
||||
data: CreateListingData
|
||||
): Promise<Listing> {
|
||||
export async function createListing(data: CreateListingData): Promise<Listing> {
|
||||
// Validar item_id_unified se fornecido
|
||||
if (data.item_id_unified) {
|
||||
const exists = await itemExists(data.item_id_unified);
|
||||
if (!exists) {
|
||||
throw new Error(`Item com ID unificado ${data.item_id_unified} não encontrado na tabela items`);
|
||||
throw new Error(
|
||||
`Item com ID unificado ${data.item_id_unified} não encontrado na tabela items`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,11 +167,11 @@ export async function createListing(
|
||||
data.trade_item_id || null,
|
||||
data.trade_item_name || null,
|
||||
data.trade_item_quantity || null,
|
||||
data.is_auction ? (data.price_pix || null) : null, // initial_price_pix
|
||||
data.is_auction ? (data.price_tibia_coins || null) : null, // initial_price_tibia_coins
|
||||
data.is_auction ? (data.price_gold_coins || null) : null, // initial_price_gold_coins
|
||||
data.is_auction ? data.price_pix || null : null, // initial_price_pix
|
||||
data.is_auction ? data.price_tibia_coins || null : null, // initial_price_tibia_coins
|
||||
data.is_auction ? data.price_gold_coins || null : null, // initial_price_gold_coins
|
||||
minBidIncrement || null,
|
||||
]
|
||||
],
|
||||
);
|
||||
} catch (error) {
|
||||
// Se as colunas da migração 014 ou item_id_unified não existirem, usar INSERT sem elas
|
||||
@@ -210,11 +215,14 @@ export async function createListing(
|
||||
data.trade_item_id || null,
|
||||
data.trade_item_name || null,
|
||||
data.trade_item_quantity || null,
|
||||
]
|
||||
],
|
||||
);
|
||||
} catch (error2) {
|
||||
// Se item_id_unified também não existir, usar apenas item_id legado
|
||||
if (error2 instanceof Error && error2.message.includes("does not exist")) {
|
||||
if (
|
||||
error2 instanceof Error &&
|
||||
error2.message.includes("does not exist")
|
||||
) {
|
||||
result = await query<Listing>(
|
||||
`
|
||||
INSERT INTO listings (
|
||||
@@ -251,7 +259,7 @@ export async function createListing(
|
||||
data.trade_item_id || null,
|
||||
data.trade_item_name || null,
|
||||
data.trade_item_quantity || null,
|
||||
]
|
||||
],
|
||||
);
|
||||
} else {
|
||||
throw error2;
|
||||
@@ -268,7 +276,9 @@ export async function createListing(
|
||||
/**
|
||||
* Busca anúncio por ID
|
||||
*/
|
||||
export async function getListingById(listingId: number): Promise<Listing | null> {
|
||||
export async function getListingById(
|
||||
listingId: number,
|
||||
): Promise<Listing | null> {
|
||||
let result;
|
||||
try {
|
||||
// Tentar query com todas as colunas (se migração 014 foi executada)
|
||||
@@ -298,7 +308,7 @@ export async function getListingById(listingId: number): Promise<Listing | null>
|
||||
AND uc.is_main = TRUE
|
||||
WHERE l.listing_id = $1
|
||||
`,
|
||||
[listingId]
|
||||
[listingId],
|
||||
);
|
||||
} catch (error) {
|
||||
// Se as colunas da migração 014 não existirem, usar query sem elas
|
||||
@@ -332,7 +342,7 @@ export async function getListingById(listingId: number): Promise<Listing | null>
|
||||
AND uc.is_main = TRUE
|
||||
WHERE l.listing_id = $1
|
||||
`,
|
||||
[listingId]
|
||||
[listingId],
|
||||
);
|
||||
} else {
|
||||
throw error;
|
||||
@@ -354,7 +364,7 @@ export async function getListingById(listingId: number): Promise<Listing | null>
|
||||
* Lista anúncios com filtros e paginação
|
||||
*/
|
||||
export async function getListings(
|
||||
filters: ListingFilters = {}
|
||||
filters: ListingFilters = {},
|
||||
): Promise<{ listings: Listing[]; total: number }> {
|
||||
const {
|
||||
status,
|
||||
@@ -404,36 +414,45 @@ export async function getListings(
|
||||
}
|
||||
|
||||
if (search) {
|
||||
conditions.push(`(l.item_name ILIKE $${paramIndex} OR l.description ILIKE $${paramIndex})`);
|
||||
conditions.push(
|
||||
`(l.item_name ILIKE $${paramIndex} OR l.description ILIKE $${paramIndex})`,
|
||||
);
|
||||
params.push(`%${search}%`);
|
||||
paramIndex++;
|
||||
}
|
||||
|
||||
const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "WHERE 1=1";
|
||||
const whereClause =
|
||||
conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "WHERE 1=1";
|
||||
|
||||
// Contar total
|
||||
const countResult = await query<{ count: string }>(
|
||||
`SELECT COUNT(*) as count FROM listings l ${whereClause}`,
|
||||
params
|
||||
params,
|
||||
);
|
||||
const total = parseInt(countResult.rows[0].count, 10);
|
||||
|
||||
// Validar sortBy - garantir que seja uma coluna válida
|
||||
const validSortColumns = ["created_at", "price_pix", "price_tibia_coins", "price_gold_coins", "views_count"];
|
||||
const validSortColumns = [
|
||||
"created_at",
|
||||
"price_pix",
|
||||
"price_tibia_coins",
|
||||
"price_gold_coins",
|
||||
"views_count",
|
||||
];
|
||||
const sortColumn = validSortColumns.includes(sortBy) ? sortBy : "created_at";
|
||||
const sortDirection = sortOrder === "ASC" ? "ASC" : "DESC";
|
||||
|
||||
|
||||
// Mapear colunas para usar alias 'l.' quando necessário
|
||||
const sortColumnWithAlias = `l.${sortColumn}`;
|
||||
|
||||
// Buscar listings
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
|
||||
// Incrementar paramIndex para os parâmetros de LIMIT e OFFSET
|
||||
const limitParamIndex = paramIndex;
|
||||
const offsetParamIndex = paramIndex + 1;
|
||||
const finalParams = [...params, pageSize, offset];
|
||||
|
||||
|
||||
// Tentar query com todas as colunas (se migração 014 foi executada)
|
||||
// Se falhar, usar query sem as novas colunas
|
||||
let result;
|
||||
@@ -465,10 +484,10 @@ export async function getListings(
|
||||
ORDER BY ${sortColumnWithAlias} ${sortDirection}
|
||||
LIMIT $${limitParamIndex} OFFSET $${offsetParamIndex}
|
||||
`;
|
||||
|
||||
|
||||
result = await query<Listing & { seller_character_name: string }>(
|
||||
querySql,
|
||||
finalParams
|
||||
finalParams,
|
||||
);
|
||||
} catch (error) {
|
||||
// Se as colunas da migração 014 não existirem, usar query sem elas
|
||||
@@ -503,10 +522,10 @@ export async function getListings(
|
||||
ORDER BY ${sortColumnWithAlias} ${sortDirection}
|
||||
LIMIT $${limitParamIndex} OFFSET $${offsetParamIndex}
|
||||
`;
|
||||
|
||||
|
||||
result = await query<Listing & { seller_character_name: string }>(
|
||||
fallbackQuerySql,
|
||||
finalParams
|
||||
finalParams,
|
||||
);
|
||||
} else {
|
||||
throw error;
|
||||
@@ -514,7 +533,7 @@ export async function getListings(
|
||||
}
|
||||
|
||||
// Mapear resultados para garantir que seller_character_name seja null se não existir
|
||||
const listings = result.rows.map(row => ({
|
||||
const listings = result.rows.map((row) => ({
|
||||
...row,
|
||||
seller_character_name: row.seller_character_name || null,
|
||||
}));
|
||||
@@ -530,7 +549,7 @@ export async function getListings(
|
||||
*/
|
||||
export async function updateListing(
|
||||
listingId: number,
|
||||
data: UpdateListingData
|
||||
data: UpdateListingData,
|
||||
): Promise<Listing | null> {
|
||||
const updates: string[] = [];
|
||||
const params: any[] = [];
|
||||
@@ -589,7 +608,7 @@ export async function updateListing(
|
||||
}
|
||||
|
||||
params.push(listingId);
|
||||
|
||||
|
||||
let result;
|
||||
try {
|
||||
// Tentar query com todas as colunas (se migração 014 foi executada)
|
||||
@@ -611,13 +630,15 @@ export async function updateListing(
|
||||
l.trade_item_id, l.trade_item_name, l.trade_item_quantity,
|
||||
l.min_bid_increment, l.initial_price_pix, l.initial_price_tibia_coins, l.initial_price_gold_coins
|
||||
`,
|
||||
params
|
||||
params,
|
||||
);
|
||||
|
||||
|
||||
// Buscar dados do JOIN após o UPDATE
|
||||
if (result.rows.length > 0) {
|
||||
const listingId = result.rows[0].listing_id;
|
||||
const joinResult = await query<Listing & { seller_character_name: string }>(
|
||||
const joinResult = await query<
|
||||
Listing & { seller_character_name: string }
|
||||
>(
|
||||
`
|
||||
SELECT
|
||||
l.listing_id, l.seller_id, l.item_id, l.item_name, l.quantity, l.server_name,
|
||||
@@ -643,9 +664,9 @@ export async function updateListing(
|
||||
AND uc.is_main = TRUE
|
||||
WHERE l.listing_id = $1
|
||||
`,
|
||||
[listingId]
|
||||
[listingId],
|
||||
);
|
||||
|
||||
|
||||
if (joinResult.rows.length > 0) {
|
||||
result.rows[0] = joinResult.rows[0];
|
||||
}
|
||||
@@ -674,13 +695,15 @@ export async function updateListing(
|
||||
NULL::integer as initial_price_tibia_coins,
|
||||
NULL::bigint as initial_price_gold_coins
|
||||
`,
|
||||
params
|
||||
params,
|
||||
);
|
||||
|
||||
|
||||
// Buscar dados do JOIN após o UPDATE
|
||||
if (result.rows.length > 0) {
|
||||
const listingId = result.rows[0].listing_id;
|
||||
const joinResult = await query<Listing & { seller_character_name: string }>(
|
||||
const joinResult = await query<
|
||||
Listing & { seller_character_name: string }
|
||||
>(
|
||||
`
|
||||
SELECT
|
||||
l.listing_id, l.seller_id, l.item_id, l.item_name, l.quantity, l.server_name,
|
||||
@@ -709,9 +732,9 @@ export async function updateListing(
|
||||
AND uc.is_main = TRUE
|
||||
WHERE l.listing_id = $1
|
||||
`,
|
||||
[listingId]
|
||||
[listingId],
|
||||
);
|
||||
|
||||
|
||||
if (joinResult.rows.length > 0) {
|
||||
result.rows[0] = joinResult.rows[0];
|
||||
}
|
||||
@@ -742,7 +765,7 @@ export async function deleteListing(listingId: number): Promise<boolean> {
|
||||
SET listing_status = 'cancelled'
|
||||
WHERE listing_id = $1
|
||||
`,
|
||||
[listingId]
|
||||
[listingId],
|
||||
);
|
||||
|
||||
return (result.rowCount ?? 0) > 0;
|
||||
@@ -758,7 +781,7 @@ export async function incrementViews(listingId: number): Promise<void> {
|
||||
SET views_count = views_count + 1
|
||||
WHERE listing_id = $1
|
||||
`,
|
||||
[listingId]
|
||||
[listingId],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -767,7 +790,11 @@ export async function incrementViews(listingId: number): Promise<void> {
|
||||
*/
|
||||
export async function getListingsBySeller(
|
||||
sellerId: number,
|
||||
filters: { status?: Listing["listing_status"]; page?: number; pageSize?: number } = {}
|
||||
filters: {
|
||||
status?: Listing["listing_status"];
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
} = {},
|
||||
): Promise<{ listings: Listing[]; total: number }> {
|
||||
return getListings({
|
||||
seller_id: sellerId,
|
||||
@@ -779,7 +806,7 @@ export async function getListingsBySeller(
|
||||
* Busca apenas anúncios ativos
|
||||
*/
|
||||
export async function getActiveListings(
|
||||
filters: Omit<ListingFilters, "status"> = {}
|
||||
filters: Omit<ListingFilters, "status"> = {},
|
||||
): Promise<{ listings: Listing[]; total: number }> {
|
||||
return getListings({
|
||||
...filters,
|
||||
@@ -795,8 +822,13 @@ export async function placeBid(
|
||||
listingId: number,
|
||||
bidderId: number,
|
||||
bidAmount: number,
|
||||
paymentMethod: "pix" | "tc" | "gp"
|
||||
): Promise<{ success: boolean; listing: Listing | null; previousBidderId: number | null; error?: string }> {
|
||||
_paymentMethod: "pix" | "tc" | "gp",
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
listing: Listing | null;
|
||||
previousBidderId: number | null;
|
||||
error?: string;
|
||||
}> {
|
||||
const { getPool } = await import("../index");
|
||||
const pool = getPool();
|
||||
const client = await pool.connect();
|
||||
@@ -827,12 +859,17 @@ export async function placeBid(
|
||||
LEFT JOIN items i ON i.item_id = l.item_id_unified
|
||||
WHERE l.listing_id = $1
|
||||
`,
|
||||
[listingId]
|
||||
[listingId],
|
||||
);
|
||||
|
||||
if (listingResult.rows.length === 0) {
|
||||
await client.query("ROLLBACK");
|
||||
return { success: false, listing: null, previousBidderId: null, error: "Anúncio não encontrado" };
|
||||
return {
|
||||
success: false,
|
||||
listing: null,
|
||||
previousBidderId: null,
|
||||
error: "Anúncio não encontrado",
|
||||
};
|
||||
}
|
||||
|
||||
const listing = listingResult.rows[0];
|
||||
@@ -840,22 +877,45 @@ export async function placeBid(
|
||||
// Validações
|
||||
if (listing.listing_status !== "active") {
|
||||
await client.query("ROLLBACK");
|
||||
return { success: false, listing: null, previousBidderId: null, error: "Anúncio não está ativo" };
|
||||
return {
|
||||
success: false,
|
||||
listing: null,
|
||||
previousBidderId: null,
|
||||
error: "Anúncio não está ativo",
|
||||
};
|
||||
}
|
||||
|
||||
if (!listing.is_auction) {
|
||||
await client.query("ROLLBACK");
|
||||
return { success: false, listing: null, previousBidderId: null, error: "Este anúncio não é um leilão" };
|
||||
return {
|
||||
success: false,
|
||||
listing: null,
|
||||
previousBidderId: null,
|
||||
error: "Este anúncio não é um leilão",
|
||||
};
|
||||
}
|
||||
|
||||
if (listing.seller_id === bidderId) {
|
||||
await client.query("ROLLBACK");
|
||||
return { success: false, listing: null, previousBidderId: null, error: "Você não pode dar lance no seu próprio anúncio" };
|
||||
return {
|
||||
success: false,
|
||||
listing: null,
|
||||
previousBidderId: null,
|
||||
error: "Você não pode dar lance no seu próprio anúncio",
|
||||
};
|
||||
}
|
||||
|
||||
if (listing.auction_ends_at && new Date(listing.auction_ends_at) < new Date()) {
|
||||
if (
|
||||
listing.auction_ends_at &&
|
||||
new Date(listing.auction_ends_at) < new Date()
|
||||
) {
|
||||
await client.query("ROLLBACK");
|
||||
return { success: false, listing: null, previousBidderId: null, error: "Leilão expirou" };
|
||||
return {
|
||||
success: false,
|
||||
listing: null,
|
||||
previousBidderId: null,
|
||||
error: "Leilão expirou",
|
||||
};
|
||||
}
|
||||
|
||||
// Calcular lance mínimo
|
||||
@@ -886,7 +946,7 @@ export async function placeBid(
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE listing_id = $3
|
||||
`,
|
||||
[bidAmount, bidderId, listingId]
|
||||
[bidAmount, bidderId, listingId],
|
||||
);
|
||||
|
||||
// Buscar listing atualizado com JOIN
|
||||
@@ -912,7 +972,7 @@ export async function placeBid(
|
||||
LEFT JOIN items i ON i.item_id = l.item_id_unified
|
||||
WHERE l.listing_id = $1
|
||||
`,
|
||||
[listingId]
|
||||
[listingId],
|
||||
);
|
||||
|
||||
await client.query("COMMIT");
|
||||
@@ -929,4 +989,3 @@ export async function placeBid(
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user