WHEN tp is null or (tp->>''id'')::int = p.pipe_id THEN
CASE
WHEN ST_DWithin(ST_ClosestPoint(%3$L, coalesce(lp.geom, p.geom)), ST_StartPoint(%3$L), %5$s)
THEN st_lineinterpolatepoint(%3$L::geometry, 0.1/st_length(%3$L))
WHEN ST_DWithin(ST_ClosestPoint(%3$L, coalesce(lp.geom, p.geom)), ST_EndPoint(%3$L), %5$s)
THEN st_lineinterpolatepoint(%3$L::geometry, 1-(0.1/st_length(%3$L)))
ELSE ST_ClosestPoint(%3$L, coalesce(lp.geom, p.geom)) END
ELSE
CASE
WHEN ST_DWithin(ST_ClosestPoint(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154), coalesce(lp.geom, p.geom)), ST_StartPoint(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154)), %5$s)
THEN st_lineinterpolatepoint(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154), 0.1/st_length(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154)))
WHEN ST_DWithin(ST_ClosestPoint(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154), coalesce(lp.geom, p.geom)), ST_EndPoint(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154)), %5$s)
THEN st_lineinterpolatepoint(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154), 1-(0.1/st_length(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154))))
ELSE ST_ClosestPoint(ST_SetSRID(St_GeomFromGeoJSON((tp->>''geom'')), 2154), coalesce(lp.geom, p.geom)) END
END ugeom
FROM %1$I.%2$I p
LEFT OUTER JOIN %1$I.lpipe lp ON lp.end_node=p.id
AND NOT ST_DWithin(ST_ClosestPoint(%3$L, lp.geom), ST_StartPoint(%3$L), %5$s)
AND NOT ST_DWithin(ST_ClosestPoint(%3$L, lp.geom), ST_EndPoint(%3$L), %5$s)