| Current Path : /var/node/inatote/Inatote-Backend/payment/ |
| Current File : /var/node/inatote/Inatote-Backend/payment/payment-list.js |
import { UniqueConstraintError } from '../helpers/errors.js'
export default function makePaymentList({ database }) {
return Object.freeze({
// add,
// findByEmail,
// findById,
// getItems,
// remove,
// replace,
// update
})
async function calcCrow(lat1, lon1, lat2, lon2)
{
//console.log("lat" , lat1 , lon1 , lat2 , lon2);
var R = 6371; // km
var dLat = toRad(lat2-lat1);
var dLon = toRad(lon2-lon1);
var lat1 = toRad(lat1);
var lat2 = toRad(lat2);
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
// Converts numeric degrees to radians
function toRad(Value)
{
return Value * Math.PI / 180;
}
async function getItems({ max = 100, page = 1, _id , name, search_by } = {}) {
const db = await database
var query = { }
// "products.isEnabled" :true , "products.inStock" :true
if (_id) {
search_by == "vendor" ?
query = { ...query , "products.vendorId": db.makeId(_id) }:
query = {...query , _id: db.makeId(_id) };
}
if(name){
query= {...query , "products.productName" : {$regex : name , $options : "i"}}
}
try{
let configrations = (await db
.collection('configurations')
.findOne());
//console.log("query" , query);
var res = await db
.collection('categories')
.find(query)
.limit(Number(max))
.skip(max * (page - 1))
.toArray();
//console.log("res" , res);
let result = []
res.map(element => {
// let pp = element.products.filter(f => f.isEnabled && f.inStock)
// result = [...result , ...pp.map((p)=> p.isEnabled && p.inStock && documentToproduct(p , Number(configrations.productMarkup)))]
result = [...result , ...element.products.map((p)=>documentToproduct(p , Number(configrations.productMarkup)))]
});
return result
// [0].products.map(documentToproduct)
}catch(err){
//console.log("er" , err);
}
}
async function add({ productId, ...product }) {
const db = await database
product.productId = await db.makeId()
product.categoryId = await db.makeId(product.categoryId);
product.vendorId = await db.makeId(product.vendorId);
product.createdDate = new Date()
product.lastUpdatedDate = new Date()
const { result, ops } = await db.collection('categories').updateOne(
{
_id: db.makeId(product.categoryId)
},
{
$push: {
products: product
}
}
);
//console.log(result)
//console.log(ops)
// const { result, ops } = await db
// .collection('products')
// .insertOne(product)
// .catch(mongoError => {
// const [errorCode] = mongoError.message.split(' ')
// if (errorCode === 'E11000') {
// const [_, mongoIndex] = mongoError.message.split(':')[2].split(' ')
// throw new UniqueConstraintError(
// mongoIndex === 'productEmailIndex' ? 'emailAddress' : 'productId'
// )
// }
// throw mongoError
// })
return {
success: result.ok === 1,
created: product
}
}
async function findById({ productId , latitude , longitude }) {
const db = await database
let indexes =await db.collection("vendors").ensureIndex({ location: "2dsphere" })
const result = await db
.collection('categories')
.aggregate([
{ $match: { "products.productId": db.makeId(productId) } },
// { $match: { "products.productName":{$regex : , $options: 'i' } } },
{
$lookup:
{
from: "vendors",
localField: "vendorID" ,
foreignField: "_id",
as: "vendors"
}
},
{ $project: { products: { $filter: { input: "$products", as: "products", cond: { $eq: ["$$products.productId", db.makeId(productId)] } } }, vendors:1 } }
])
if( result && !latitude && !longitude){
var res = await result.toArray();
//console.log("res" , res[0]);
return res[0].products[0]
}
if (result) {
var res = await result.toArray();
//console.log("res" , res);
if (res.length < 1) {
return
}
let configrations = (await db
.collection('configurations')
.findOne());
let related_products = await db.collection("categories").aggregate([
{ $unwind :"$products"},
{ "$match": {
"products.productName": res[0].products[0]["productName"]
}},
]).toArray();
let dis = await db
.collection('vendors')
.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ Number(longitude), Number(latitude)] },
spherical: true,
distanceField: "distance",
key:"location"
},
},
// { "$match": {
// "_id": res[0]["vendors"][0]["_id"]
// }}
]).toArray()
//console.log("dis", dis);
var product = {
...res[0].products[0]
}
product["vendor"] = res[0].vendors[0];
product["relatedProducts"] = related_products;
product["distance"] = dis[0].distance;
// let distcnace = await calcCrow(latitude , longitude , product["vendor"]["location"]["coordinates"][1],product["vendor"]["location"]["coordinates"][0] )
// let distance = await calcCrow(24.88183632840989, 67.19647709243498 , 24.88407522025902, 67.19960982950711 )
// //console.log("distcnace" , distance);
return documentToproduct(product , configrations && configrations.productMarkup ? configrations.productMarkup : 0 )
}else{
//console.log("else");
}
return
}
async function findByEmail({ emailAddress }) {
return {
emailAddress: emailAddress
}
}
async function remove({ productId, product }) {
const db = await database
var q = {};
product.lastUpdatedDate = new Date();
for (var item in product) {
//console.log(item)
q[`products.$.${item}`] = product[item]
}
const query = {
$set: q
}
//console.log("qqqqqqqqqqqqq" , query);
const {result} = await db.collection('categories').updateOne({
"products.productId": db.makeId(productId)
}, query, {strict: false})
//console.log(result)
if (result.nModified != 1) {
return {
success: false,
error: "Something went wrong when performing this operation."
}
}
return {
success: true,
updated: product
};
}
// todo:
async function replace(product) {
}
// todo:
async function update({productId, categoryId, product }) {
const db = await database
var q = {};
product.lastUpdatedDate = new Date();
for (var item in product) {
//console.log(item)
q[`products.$.${item}`] = product[item]
}
const query = {
$set: q
}
const {result} = await db.collection('categories').updateOne({
_id: db.makeId(categoryId),
"products.productId": db.makeId(productId)
}, query, {strict: false})
//console.log(result)
if (result.nModified != 1) {
return {
success: false,
error: "Something went wrong when performing this operation."
}
}
return {
success: true,
updated: product
};
}
function documentToproduct({ _id: productId, ...doc } , markup) {
//console.log("doc" , doc);
doc["productMarkup"] = markup;
doc["totalPrice"] = parseInt(doc["productMarkup"]) + parseInt(doc["unitPrice"])
return makeproduct({ productId, ...doc })
}
}