diff --git a/src/services/pis.services.ts b/src/services/pis.services.ts index 57c4267..1ed0026 100644 --- a/src/services/pis.services.ts +++ b/src/services/pis.services.ts @@ -78,8 +78,12 @@ export async function findByTiplocArray( if (partialEnd) { return convertDocument(partialEnd, "first"); } else { - // Here, I should search for a partialStart match. For now return null. - return null; + const partialStart = await findPartialStartMatchByTiploc(tiplocArray); + if (partialStart) { + return convertDocument(partialEnd, "last"); + } else { + return null; + } } } } catch (err) { @@ -103,6 +107,13 @@ async function findPartialEndMatchByTiploc(array: string[]): Promise { return res[0]; } +// Uses a pipeline to find a partial match - supporting codes starting with the correct stops. +async function findPartialStartMatchByTiploc(array: string[]): Promise { + const pipeline = getPartialStartTiplocMatchPipeline(array); + const res = await queryAggregate("pis", pipeline); + return res[0]; +} + function convertDocument(doc: Document, skipType: string): OB_Pis_SimpleObject { return { code: doc.code.toString(), diff --git a/src/utils/pis.utils.ts b/src/utils/pis.utils.ts index 5d46ba9..f982bc8 100644 --- a/src/utils/pis.utils.ts +++ b/src/utils/pis.utils.ts @@ -75,6 +75,61 @@ export function getPartialEndTiplocMatchPipeline(query: string[]) { ]; } +export function getPartialStartTiplocMatchPipeline(query: string[]) { + return [ + { + '$match': { + 'tiplocs': { + '$all': query + } + } + }, { + '$addFields': { + 'query': query + } + }, { + '$match': { + '$expr': { + '$eq': [ + { + '$slice': [ + '$tiplocs', { + '$size': '$query' + } + ] + }, '$query' + ] + } + } + }, { + '$addFields': { + 'skipStops': { + '$subtract': [ + { + '$size': '$tiplocs' + }, { + '$size': '$query' + } + ] + } + } + }, { + '$sort': { + 'skipStops': 1 + } + }, { + '$limit': 1 + }, { + '$project': { + 'code': 1, + 'skipStops': 1, + 'toc': 1, + '_id': 0 + } + } + ] +} + export function getFullTiplocMatchPipeline(query: string[]) { return [ {