Your IP : 216.73.216.91


Current Path : /var/node/inatote/Inatote-Backend/users/
Upload File :
Current File : //var/node/inatote/Inatote-Backend/users/user-list.js

import makeUser from './user.js'
import { UniqueConstraintError } from '../helpers/errors.js'
import mongodb from 'mongodb'

export default function makeUserList({ database }) {
    return Object.freeze({
        add,
        findByEmailAndUserType,
        findById,
        getItems,
        remove,
        replace,
        update,
        findByMobile,
        changePassword,
        findByIdwithVendor,
        findByCode,
        findByEmail,
        getByCode,
        findByCardHolderId

    })

    async function changePassword({oldPassword , newPassword , userId}){

    }

    async function getItems({ max = 100, page = 1, userType = "", companyId , KYCStatus } = {}) {
        const db = await database
        var query = {}

        if (companyId) {
            query = { companyId: companyId }
        }

        if (userType) {
            query = { ...query, userType: userType }
        }
        if(KYCStatus){
            query = { ...query, KYCStatus: KYCStatus ,  userType: "Rider" }
        }

        return (await db
            .collection('users')
            .find(query)
            .limit(Number(max))
            .toArray())
            // .map(documentTouser)
    }

    async function getUserByCardholderId({cardHolderId}){
     try{
        let res = await db.collection('users').findOne({cardHolderId})
     }  
     catch(err){
       console.log("err" , err);
     } 

    }

    async function getByCode(query) {
        const db = await database
       
       

        let res = await db
            .collection('users')
            .findOne(query);

            if (res && res.address) {
                const address = await db
                    .collection('addresses')
                    .findOne({ _id: await db.makeId(res.address) });
                    res["address"] = address
    
            }
            return res
        
            // .map(documentTouser)
    }


    async function add({ userId, ...user }) {
        const db = await database
        // user._id = db.makeId(userId)
        var dateTime = new Date();

        user.createdDate = dateTime;
        user.lastUpdatedDate = dateTime;

        const { result, ops } = await db
            .collection('users')
            .insertOne(user)
            .catch(mongoError => {
                const [errorCode] = mongoError.message.split(' ')
                //console.log(errorCode)
                if (errorCode === 'E11000') {
                    const [_, mongoIndex] = mongoError.message.split(':')[2].split(' ')
                    throw new UniqueConstraintError(
                        mongoIndex === 'userEmailIndex' ? 'emailAddress' : 'userId'
                    )
                }
                throw mongoError
            })
        return {
            success: result.ok === 1,
            created: documentTouser(ops[0])
        }
    }

    async function findById({ userId }) {
        console.log("userId" , userId);
        try{
            const db = await database
        const found = await db
            .collection('users')
            .findOne({ _id:  db.makeId(userId) });
        if (found) {
            return documentTouser(found)
        }
        return null
        }catch(err){
            console.log("ERR" , err);
        }
        
    }

    async function findByCardHolderId(id) {
        console.log("userId" , id);
        try{
            const db = await database
        const found = await db
            .collection('users')
            .findOne({ berkleyCardHolderId: id });
        
            return found
        }catch(err){
            console.log("ERR" , err);
        }
        
    }

    async function findByCode({ forgotPasswordCode }) {
        try{
            const db = await database
        const found = await db
            .collection('users')
            .findOne({ forgotPasswordCode:  forgotPasswordCode });
        if (found) {
            return documentTouser(found)
        }
        return null
        }catch(err){
            //console.log("ERR" , err);
        }
        
    }


    async function findByIdwithVendor({userId}){
        const db = await database
        const found = await db
            .collection('users')
            .findOne({ _id: db.makeId(userId) })
        if (found) {
            if(found.userType == "Vendor"){
                var vendor = await db.collection("vendors").findOne({ _id : db.makeId(found.companyId) });
                //console.log("vendor" , vendor);
                found["Vendor"] = vendor;
            
            }
            return  documentTouser(found)
        }
        return null
    }

    async function findByEmailAndUserType(query) {
        const db = await database
        //console.log("email", query);
        if(query._id){
            query._id = await db.makeId(query._id)
        }
        const results = await db
            .collection('users')
            .findOne(query);

            console.log("ADDRESS", results);
                
        if (results && results.address) {
            const address = await db
                .collection('addresses')
                .findOne({ _id: await db.makeId(results.address) });
            results["address"] = address

        }



        //console.log("results", results);

        return results ? documentTouser(results) : null
    }

    async function findByEmail(query) {
        const db = await database
        const results = await db
            .collection('users')
            .findOne(query);

        
        return results ? documentTouser(results) : null
    }


    async function findByMobile(query) {
        const db = await database
        //console.log("email", query);
        const results = await db
            .collection('users')
            .findOne(query);

      

        return results ? documentTouser(results) : null
    }

    async function remove({ userId }) {
        console.log("USEWR", userId);
        const db = await database
       
        const { result } = await db.collection('users').remove({_id : db.makeId(userId) })
        return result.n
    }

    // todo:
    async function replace(user) { }

    // todo:
    async function update({ userId, user, image }) {
        const db = await database
        try{
            //console.log(userId)
            //console.log(image)
            user.lastUpdatedDate = new Date();
    
            var q = {};
                for (var item in user) {
                    //console.log(item)
                    q[item] = user[item]
                }
                if (image) {
                    q['imageURL'] = image.path;
                }
            
            const query = {
                $set: q
            }
    
            
            const result  = await db.collection('users').findOneAndUpdate({
                _id: db.makeId(userId)
            }, query, {returnNewDocument: true , returnDocument: "after"  , new: true})
    
            console.log("RES" ,result)
    
            if (result.ok != 1) {
                return {
                    success: false,
                    error: "Something went wrong when performing this operation."
                }
            }
    
            return {
                success: true,
                user: result.value,
            };
        }catch(err){
            console.log(err , "err");
        }
      
    }

    //     async function updateAddress({ userId, user }) {
    //         const db = await database
    //         // user.lastUpdatedDate = new Date();

    //         // var q = {};

    //         // for (var item in user) {
    //         //     //console.log(item)
    //         //     q[item] = user[item]
    //         // }

    //         // const query = {
    //         //     $push: q    
    //         // }

    //         // //console.log("query" , query)

    //         let result  = await db.collection('users').findOne({
    //             _id: db.makeId(userId)
    //         })
    //         if(result.address && result.address.length <= 5){
    //             let addressNames = []
    //             result.address.forEach(element => {
    //                 addressNames = [...addressNames, element.name]
    //             });
    //             //console.log("address" , addressNames);
    //             if(!addressNames.includes(user.name)){
    //             //console.log(`${user.name} is already exsits`);
    //             const final_result = await db.collection("users").updateOne({ _id: db.makeId(userId)}, {$push : {address : user}});
    //             if (final_result.result.nModified != 1) {
    //                 return {
    //                     success: false,
    //                     error: "Something went wrong when performing this operation."
    //                 }
    //             }

    //             return {
    //                 success: true,
    //                 user: "updated"
    //             };


    //         } else{
    //             //console.log("name majood hai");
    //             return {
    //                 success: false,
    //                 error: "Something went wrong when performing this operation."
    //             }

    //         }
    //         // result["address"] = [...result["address"] ,user ]

    //     }else{
    //         //console.log("address zada hai");
    //     }
    // }    


    function documentTouser({ _id: userId, ...doc }) {
        console.log("doc" , doc , userId);
        return makeUser({ userId, ...doc })
    }
}