import { getDb, Plan, PlanDoc, PlanFilter, PlanQueryOptions, SimplePlanFilter, } from "../index"; import { Filter, ObjectId } from "mongodb"; import { applyQueryOptions } from "../utils/query.utils"; export const getPlansCollection = () => { return getDb().collection("plans"); }; /** * Converts a simple filter to MongoDB query format */ const buildSimpleQuery = (filter: SimplePlanFilter): Filter => { const query: Filter = {}; if (filter._id) { query._id = new ObjectId(filter._id); } if (filter.productKey !== undefined) { query.productKey = filter.productKey; } if (filter.isActive !== undefined) { query.isActive = filter.isActive; } if (filter.currency !== undefined) { query.currency = filter.currency; } if (filter.region !== undefined) { query.region = filter.region; } if (filter.countryCode !== undefined) { query.countryCode = filter.countryCode; } if (filter.originalPlanId !== undefined) { query.originalPlanId = filter.originalPlanId; } return query; }; /** * Generic function to find plans with flexible filtering */ export const findPlans = async ( filter?: PlanFilter, options?: PlanQueryOptions, ): Promise => { let query: Filter = {}; if (filter) { // Build the base query from simple filter properties const simpleFilter: SimplePlanFilter = { _id: filter._id, productKey: filter.productKey, isActive: filter.isActive, currency: filter.currency, region: filter.region, countryCode: filter.countryCode, originalPlanId: filter.originalPlanId, }; // Apply simple filters if any are present const baseQuery = buildSimpleQuery(simpleFilter); if (Object.keys(baseQuery).length > 0) { query = baseQuery; } // Add OR conditions if present if (filter.or && filter.or.length > 0) { query.$or = filter.or.map(buildSimpleQuery); } // Add AND conditions if present if (filter.and && filter.and.length > 0) { query.$and = filter.and.map(buildSimpleQuery); } } const cursor = getPlansCollection().find(query); return await applyQueryOptions(cursor, options).toArray(); }; export const findPlansByQuery = async ( query: Filter, options?: PlanQueryOptions, ): Promise => { const cursor = getPlansCollection().find(query); return await applyQueryOptions(cursor, options).toArray(); }; export const countPlans = async (query: Filter): Promise => { return getPlansCollection().countDocuments(query); }; export const createPlanDoc = async ( planData: Omit, ): Promise => { const now = new Date(); const result = await getPlansCollection().insertOne({ ...planData, createdAt: now, updatedAt: now, }); const plans = await findPlans({ _id: result.insertedId }); if (!plans[0]) throw new Error("Failed to retrieve created plan"); return plans[0]; }; export const updatePlanDoc = async ( planId: ObjectId, updates: Partial>, ): Promise => { return await getPlansCollection().findOneAndUpdate( { _id: planId }, { $set: { ...updates, updatedAt: new Date(), }, }, { returnDocument: "after", }, ); };