import { firestore } from 'src/firebase' ; import { Offer , OfferFirestoreConverter , OfferStatus } from 'src/models/offers' ; import { ApplicationPreference } from 'src/models/users' ; import { IgetOffers , IgetRequestOffers } from './types' ; export const observeOffers = ( nextValue , payload ) : firebase . Unsubscribe => { if ( payload . userType === ApplicationPreference . cav ) { return firestore . collection ( 'offers' ) . where ( 'cavUserRef' , '==' , payload . userRef ) . withConverter ( OfferFirestoreConverter ) . onSnapshot ( snap => nextValue ( snap ) ) ; } return firestore . collection ( 'offers' ) . where ( 'pinUserRef' , '==' , payload . userRef ) . withConverter ( OfferFirestoreConverter ) . onSnapshot ( snap => nextValue ( snap ) ) ; } ; export const getRequestOffers = ( payload ) : Promise < firebase . firestore . QuerySnapshot < Offer > > => { const requestRef = firestore . collection ( 'requests' ) . doc ( payload . requestId ) ; let initialQuery = firestore . collection ( 'offers' ) . where ( 'requestRef' , '==' , requestRef ) ; if ( payload . userType === ApplicationPreference . cav ) { initialQuery = initialQuery . where ( 'cavUserRef' , '==' , payload . userRef ) ; } else { initialQuery = initialQuery . where ( 'pinUserRef' , '==' , payload . userRef ) ; } return initialQuery . withConverter ( OfferFirestoreConverter ) . get ( ) ; } ; export const createUserOffer = async ( { offerPayload , } ) => firestore . collection ( 'offers' ) . doc ( ) . withConverter ( OfferFirestoreConverter ) . set ( offerPayload ) . then ( ( ) => Promise . resolve ( offerPayload . status === OfferStatus . pending ? 1 : 2 ) ) ; export const setUserOffer = async ( { offerPayload , offerId , } ) => firestore . collection ( 'offers' ) . doc ( offerId ) . withConverter ( OfferFirestoreConverter ) . set ( offerPayload ) . then ( ( ) => Promise . resolve ( offerPayload . status === OfferStatus . pending ? 1 : offerPayload . status === OfferStatus . cavDeclined ? 2 : 3 ) ) ;