Example #1
0
router.get('/remove-category-2', (req, res) => {
    
    let queryCategory2 = new AV.Query(ProductCategory2);
    let queryProduct = new AV.Query(Product);
    
    let category1Id = parseInt(req.query.category1Id);
    let category2Id = parseInt(req.query.category2Id);

    //查询product是否含有category2,否则无法删除
    queryProduct.equalTo('category2Id',category2Id);
    queryProduct.first().then(item => {
        
        if(item) {
            res.send({success:0,message:'已有产品引用该分类,无法删除'});
            return AV.Promise.error();
        }

        queryCategory2.equalTo('category2Id', category2Id);
        return queryCategory2.first();
        
    }).done(item => {

        item.destroy().done(() => {

            let query = new AV.Query(ProductCategory2);
            query.equalTo('category1Id',category1Id);
            query.ascending('index');

            return query.find();

        }).done(items => {
            //批量更新index
            let promises = [];
            items.forEach((item, i) => {
                item.set('index', i);
                promises.push(item.save());
            });
            return AV.Promise.when(promises);

        }).done(()=>res.send({success: 1}));
    });
    
});
Example #2
0
router.get('/getpointfirstimage/:id', function (req, res) {


    var args = url.parse(req.url, true).query;
    var queryimg = new AV.Query(Point_Image);
    queryimg.equalTo("PointId", req.params.id);
    queryimg.first({
        success: function (queryimg) {
            //console.log(point.id)

            if (queryimg != null) {
                //imgurl = queryimg.get('Image').url();

                if (args.w != null && args.h != null) {
                    //imgurl = queryimg.get('Image').thumbnailURL(args.w, args.h)+"?watermark/1/image/aHR0cDovL2FjLXdhYnBzYTZ5LmNsb3VkZG4uY29tL1RFd1RxV2Q2S0NyYmlVb0lnV0I0andNaTlmd1JDUnZhMXZyNXBNZncucG5n";
                    //imgurl = queryimg.get('Image').url()+"?imageView/1/w/"+args.w+"/h/"+args.h+"|watermark/1/image/aHR0cDovL2FjLXdhYnBzYTZ5LmNsb3VkZG4uY29tL0hjUThtaW1henM5aU83YUNPdmVZcFk4eGM2emduYkVLZ3lUazc2b0MucG5n/dissolve/70";
                    imgurl = queryimg.get('Image').thumbnailURL(args.w, args.h);
                }
                else {
                    imgurl = queryimg.get('Image').url();
                    //imgurl = queryimg.get('Image').url()+"?watermark/1/image/aHR0cDovL2FjLXdhYnBzYTZ5LmNsb3VkZG4uY29tL1RFd1RxV2Q2S0NyYmlVb0lnV0I0andNaTlmd1JDUnZhMXZyNXBNZncucG5n";
                    //imgurl = queryimg.get('Image').url()+"?watermark/1/image/aHR0cDovL2FjLXdhYnBzYTZ5LmNsb3VkZG4uY29tL0hjUThtaW1henM5aU83YUNPdmVZcFk4eGM2emduYkVLZ3lUazc2b0MucG5n/dissolve/70";
                }

            }
            else {
                imgurl = "/images/default.jpg";
            }

            res.redirect(imgurl);

            // Successfully retrieved the object.
            //var pointimage=queryimg.get('Image');
            //point.url= pointimage.url();


        },
        error: function (error) {
            //console.log("Error: " + error.code + " " + error.message);
        }
    });

});
Example #3
0
router.get('/:productBrandId', (req, res, next) => {

    base.isAdminUserLogin(req, res);  //判断是否登录

    var productBrandId = parseInt(req.params.productBrandId);

    data = extend(data, {
        user: req.AV.user
    });
    
    let query = new AV.Query(ProductBrand);
    query.equalTo('productBrandId',productBrandId);
    query.first().then( item => {
        data = extend(data,{
            productBrand:item
        });
        res.render('admin/product-brand/edit',data);
    });

});
Example #4
0
router.post('/set-update-stock-date/:productId',(req,res)=> {
    let productId = parseInt(req.params['productId']);
    let updateStockDate = req.body['updateStockDate'] === 'true' ? true : false;
    if (updateStockDate) {
        let query = new AV.Query(Product);
        query.equalTo('productId',productId);
        query.first().then(result => {
            result.set('updateStockDate', 1);
            return result.save();
        }).then(result => {
            res.send({
                success:1
            });
        });
    } else {
        res.send({
            success:1
        });
    }
});
Example #5
0
router.post('/set-update-stock/:productId',(req,res)=> {
    let productId = parseInt(req.params['productId']);
    let isUpdateStock = req.body['isUpdateStock'] === 'true' ? true : false;
    let updateTotaobaoImage = req.body['updateTotaobaoImage'] === 'true' ? 1 : 0;
    let updateTotaobaoTitle = req.body['updateTotaobaoTitle'] === 'true' ? 1 : 0;
    let updateTotaobaoContent = req.body['updateTotaobaoContent'] === 'true' ? 1 : 0;
    let updateTotaobaoPrice = req.body['updateTotaobaoPrice'] === 'true' ? 1 : 0;
    let updateTotaobaoCategory = req.body['updateTotaobaoCategory'] === 'true' ? 1 : 0;
    let query = new AV.Query(Product);
    query.equalTo('productId',productId);
    query.first().then(result => {
        result.set('isUpdateStock', isUpdateStock);
    result.set('offlineTag',{updateTotaobaoImage,updateTotaobaoTitle,updateTotaobaoContent,updateTotaobaoPrice, updateTotaobaoCategory});
    return result.save();
    }).then(result => {
        res.send({
            success:1
        });
    });
});
Example #6
0
router.post('/set-onsale/:productId',(req,res)=> {

    let productId = parseInt(req.params['productId']);
    let isOnsale = req.body['isOnsale'] === 'true' ? true : false;
    let query = new AV.Query(Product);
    query.equalTo('productId',productId);
    query.first().then(result => {
        
        result.set('isOnsale', isOnsale);
        if (isOnsale) {
            result.set('onsaleDate', new Date());
        }
        return result.save();
    }).then(result => {
        res.send({
            success:1
        });
    });
    
});
Example #7
0
router.get('/remove-category-1', (req, res) => {

    let query1 = new AV.Query(ProductCategory1);
    let query2 = new AV.Query(ProductCategory2);
    let category1Id = parseInt(req.query.id);
    let productMethodId = parseInt(req.query.productMethodId);
    
    //查询query2是否带有category1,否则无法删除
    query2.equalTo('category1Id',category1Id);
    query2.first().then(item => {
        
        if(item) {
            res.send({success: 0,message:'该分类含有子分类,请先删除所有子分类再进行删除'});
            return AV.Promise.error();
        }

        query1.equalTo('category1Id', category1Id);
        return query1.first();
        
    }).done(item => {

        item.destroy().done(()=> {

            let query = new AV.Query(ProductCategory1);
            query.equalTo('productMethodId',productMethodId);
            query.ascending('index');
            return query.find();

        }).done(items=> {
            //批量更新index
            let promises = [];
            items.forEach((item, i) => {
                item.set('index', i);
                promises.push(item.save());
            });
            return AV.Promise.when(promises);

        }).done(()=>res.send({success: 1}));
    });
    
});
AV.Cloud.beforeSave("People", function(request, response) {

  var peopleName = request.object.get("userName");
  var roomId = request.object.get("room");
  var newOutDate = request.object.get("outDate");
  var objectId = request.object.id;

  console.log('before save people' + objectId );

  var RoomClass = AV.Object.extend("Room");
  var room= new RoomClass();
  room.id = roomId ;

  request.object.set("roomRef", room);

  var People = AV.Object.extend("People");
  var querySameName = new AV.Query(People);
  querySameName.equalTo("userName", peopleName);
  querySameName.first({
    success: function(object) {
      //no same name or is update mode
      if(!object || !request.object.isNew())
      {
        //notthing happen for create
        response.success();
      }
      else {
        var errormsg = peopleName + ' 已經存在, 請使用其它名稱';
        response.error(errormsg);
      }
    },
    error: function(error) {
      response.error(error.message);
    }
  });

});
Example #9
0
 }).then(result => {
     let query = new AV.Query(Product);
     query.equalTo('objectId',result.id);
     return query.first();
 }).then(result => {
Example #10
0
 category2.save().done(data => {
     let query = new AV.Query(ProductCategory2);
     query.equalTo('objectId',data.id);
     return query.first();
 }).done(data => res.send({success:1,id:data.get('category2Id'),name:name}));
Example #11
0
router.get('/:productId', function (req, res, next) {

    base.isAdminUserLogin(req, res);  //判断是否登录

    res.cookie('x_lc_sign',data.x_lc_sign);
    res.cookie('x_lc_session',req.AV.user._sessionToken);

    var productId = parseInt(req.params.productId);

    data = extend(data, {
        user: req.AV.user
    });
    
    async.auto({
        
        getProduct(resolve) {
            let query = new AV.Query(Product);
            query.equalTo('productId', productId);
            query.first().done(product => {
                console.log(product);
                data = extend(data, {product});
                resolve();
            });
        },
        getBanner(resolve) {
            let query = new AV.Query(Banner);
            query.find().then(items => {
                data = extend(data, {
                    banner: items
                });
                resolve();
            });
        },
        getMethod(resolve) {
            let query = new AV.Query(ProductMethod);
            query.ascending('index');
            query.find().then(productMethod => {
                data = extend(data,{productMethod});
                resolve();
            });
        },
        
        //处理main images
        getMainImage:['getProduct',function(resolve) {
            
            if(data.product.get('mainImage')) {
                let mainImages = [];
                let images = data.product.get('mainImage');
                for(let i in images) {
                    mainImages.push({id:i, url:images[i].url , isMainImage: images[i].isMainImage });
                }
                data = extend(data, {
                    mainImage:mainImages
                });
            } else {
                data = extend(data, {mainImage:[]});
            }
            resolve();
        }],
        
        getCategory1:['getProduct',function(resolve) {
            
            let category1 = [];
            async.forEachSeries(data.product.get('productMethod'), function(productMethodId,cb) {
                let query = new AV.Query(ProductCategory1);
                query.equalTo('productMethodId',productMethodId);
                query.ascending('index');
                query.find().then(results => {
                    category1.push(results);
                    cb();
                });
            },err => {
                data = extend(data,{category1});
                resolve();
            });
        }],

        getCategory2:['getProduct',function(resolve) {
            let category2 = [];
            async.forEachSeries(data.product.get('category1'), function(category1Id,cb) {
                let query = new AV.Query(ProductCategory2);
                query.equalTo('category1Id',category1Id);
                query.ascending('index');
                query.find().then(results => {
                    category2.push(results);
                    cb();
                });
            },err => {
                data = extend(data,{category2});
                resolve();
            });
        }]
        
    },(err,results) => res.render('admin/product/edit', data));
    
   

});
//custom function!!!

//Pass all parameter to calculate a people rent fee in particular month
function rentFeeCalculator(people, rentFee, monthStart, monthEnd, freeHousingDay, isInsertMode, successCallBack, errorCallBack)
{
  var dateFormat = 'YYYY-MM-DD';
  //for calculator use
  var overridedMonthStart = monthStart;
  var overridedMonthEnd = monthEnd;

  var reference = overridedMonthStart.format('MMMM') + ' 租金';

  var numberOfDaysInMonth = monthEnd.date();

  //one person;
  var room = people.get('roomRef');

  var outDateStr = people.get('outDate');
  var inDateStr = people.get('inDate');

  var outDate = moment(outDateStr).utcOffset(8);
  var inDate = moment(inDateStr).utcOffset(8);

  //Special discount: 42days free housing
  inDate = inDate.add(freeHousingDay, 'days');

  var hasPartialDay =  false;

  console.log('calculateRentFee: people: ' + people.get('userName') + ' outDate: ' + outDateStr + ' inDate: ' + inDateStr + ' discountInDate: ' + inDate);

  //1. out date must be valid
  if(outDateStr === undefined)
  {
  }
  else {
    if(monthStart.isAfter(outDate))
    {
      console.log('calculateRentFee: exit home already.');
      //already exit home
      return;
    }

    if(outDate.isAfter(monthStart) &&
      monthEnd.isAfter(outDate) )
    {
      //partial case
      overridedMonthEnd = outDate;
      hasPartialDay = true;
    }
  }

  //2. in date must be valid
  if(inDate.isAfter(monthEnd))
  {
    //no need calc if inDate is future (still in discount period)
    console.log('calculateRentFee: inDate is future.');
    return;
  }else if(inDate.isAfter(monthStart)) {
    overridedMonthStart = inDate;
    hasPartialDay = true;
  }


  //3. calc ratio if the
  var ratio = 1.0;
  if(hasPartialDay)
  {
    var numberOfDiffDay = overridedMonthEnd.diff(overridedMonthStart, 'days') + 1;
    ratio = numberOfDiffDay / numberOfDaysInMonth;

    console.log('calculateRentFee: people: ' + people.get('userName') + ' overrideMonthStart: ' + overridedMonthStart.format(dateFormat) + ' overrideMonthEnd: ' + overridedMonthEnd.format(dateFormat) + ' dayDiff: ' + numberOfDiffDay);
  }

  //4. calc amount
  var amount;
  if(people.hasAssist)
  {
    //use assist price
    amount = ratio * room.get('assistPrice');
  }
  else {
    amount = ratio * room.get('nonAssistPrice');
  }

  //round to nearest dollar
  amount = Math.round(amount);
  console.log('calculateRentFee: room: ' + room.get('name') + ' assistPrice: ' + room.get('assistPrice') + ' nonAssistPrice: ' + room.get('nonAssistPrice') + ' ratio: ' + ratio + 'final amt: ' + amount);

  var FeeClass = AV.Object.extend("Fee");
  if(isInsertMode)
  {
    //month end mode
    var fee = new FeeClass();

    console.log('calculateRentFee ready for save fee: ' + rentFee.id + ' people id: ' + people.id);

    fee.set("amount", amount);
    fee.set("settledAmount", 0);
    fee.set("isSettled", false);
    fee.set("feeType", rentFee.id);
    fee.set("feeTypeRef", rentFee);
    fee.set("owner", people);
    fee.set("reference", reference);
    fee.set("creator", people.get('creator'));
    fee.save(null,{
      success: function(result) {
        console.log('calculateRentFee success');
        successCallBack();
      },
      error: function(results, error) {
        errorCallBack(error);
      }
    });
  }
  else {
    //stop in middle mode

    var queryFee = new AV.Query(FeeClass);
    queryFee.equalTo("owner", people);
    queryFee.equalTo("feeType", rentFee.id);
    queryFee.descending("createdAt");

    queryFee.first({
      success: function (targetedFee) {

        var settledAmount = targetedFee.get("settledAmount");
        if (settledAmount > amount) {
          //if new amount > settled amount, settle the fee (but not change the fee settled amount)
          targetedFee.set("isSettled", true);
        }

        targetedFee.set("amount", amount);
        targetedFee.save(null, {
          success: function (result) {
            console.log('update fee success. (For quit people)');
            successCallBack();
          },
          error: function (results, error) {
            errorCallBack(error);
          }
        });
      },
      error: function(error) {
        console.log('No update fee selected. (For quit people)');
      }
    });
  }

}
AV.Cloud.define("monthEndCalculation", function(request, status)
{
  //On 1st day of month, calculate last month's rent
  var dateFormat = 'YYYY-MM-DD';
  var currentDate = moment();
  var monthStart = moment().startOf('month');
  var monthEnd = moment().endOf('month');

  //var currentDay   = currentDate.date();
  //var currentMonth = currentDate.month();

  var numberOfDaysInMonth = monthEnd.date();

  console.log('monthEndCalculation: start: ' + monthStart.format(dateFormat) + ' end: ' + monthEnd.format(dateFormat) + ' # of days in month: ' + numberOfDaysInMonth);
  //****** important these task must be run in first day

  //if(day != 1)
  //{
  //
  //}

  var freeHousingDay = FREE_HOUSING_DAY;

  var FeeTypeClass= AV.Object.extend("FeeType");
  var queryFeeType = new AV.Query(FeeTypeClass);
  queryFeeType.equalTo("isRentFee", true);

  var PeopleClass = AV.Object.extend("People");
  var queryPeople = new AV.Query(PeopleClass);
  queryPeople.include("roomRef");
  queryPeople.equalTo("outDate", null);
  //not exit pls

  queryFeeType.first({
    success: function(rentFee)
    {
      queryPeople.find({
        success: function(results) {
          for (var i = 0; i < results.length; i++) {
            //call function
            //function rentFeeCalculator(people, rentFee, monthStart, monthEnd)
            var people = results[i];

            rentFeeCalculator(people, rentFee, monthStart, monthEnd, freeHousingDay, true, function()
            {

            }, function(error)
            {

            });
          }
        },
        error: function(error) {
          console.error('monthEndCalculation running query error!');
        }
      });
    },
    error: function(error)
    {
      console.error('monthEndCalculation running query error!');
    }
  });


});
AV.Cloud.beforeUpdate("People", function(request, response) {

  var peopleName = request.object.get("userName");
  var roomId = request.object.get("room");
  var newOutDate = request.object.get("outDate");
  var objectId = request.object.id;

  console.log('before update people' + objectId );

  var RoomClass = AV.Object.extend("Room");
  var room= new RoomClass();
  room.id = roomId ;

  request.object.set("roomRef", room);

  var People = AV.Object.extend("People");
  var querySameName = new AV.Query(People);
  querySameName.equalTo("userName", peopleName);
  querySameName.first({
    success: function(object) {
      //no same name or is update mode
      if(!object || !request.object.isNew())
      {
        //passed name validation
        if(objectId)
        {
          //update mode
          var queryPeople = new AV.Query(People);
          queryPeople.include("roomRef");
          queryPeople.get(objectId, {
            success: function (targetPeople) {

              console.log('before save people query success');
              var oldOutDate = targetPeople.get('outDate');

              console.log('before save out date: ' + newOutDate + ' object: '+ objectId );

              if (newOutDate && !oldOutDate) {
                console.log('need Calc Rent outdate: ' + newOutDate);
                //update mode && outDate is updated
                var newOutDateYear = moment(newOutDate).year();
                var newOutDateMonth = moment(newOutDate).month();
                var currentYear= moment().year();
                var currentMonth= moment().month();

                if(newOutDateYear != currentYear || currentMonth != newOutDateMonth)
                {
                  response.error('離開日期月份一定要在本月份內');
                }
                else {
                  AV.Cloud.run("memberExitCalculation", { objectId:objectId}).then(function(result) {
                    console.log('memberExitCalculation success');
                  }, function(error) {
                    console.log('memberExitCalculation failure');
                  });

                  response.success();
                }

              }
              else if(!newOutDate && oldOutDate)
              {
                response.error('不允許移除離開日期');
              }
              else {
                response.success();

              }

            },
            error: function(error) {
              response.error(error.message);
            }
          });
        }
        else {
          //create mode
          response.success();
        }

      }
      else {
        var errormsg = peopleName + ' 已經存在, 請使用其它名稱';
        response.error(errormsg);
      }
    },
    error: function(error) {
      response.error(error.message);
    }
  });

});
var createAIConnection = function(installation){
	if(!installation){
		return;
	}

	var deviceType = installation.get("deviceType");
	var installationId = installation.id;

	var uid = installation.get("user").id;
	userId_insatalltionId[uid] = installationId;

	installation_map[installationId] = installation;

	resetExpire(installationId);

	notification_cache[installationId].deviceType = deviceType;

	if(deviceType === "ios"){
		var token = installation.get("token");
		if(token){
			notification_cache[installationId].device = new apn.Device(token);
		}

		var appId = installation.get("application").id;
		var app_query = new AV.Query(application);
		app_query.equalTo("objectId", appId);
		return app_query.first().then(
			function(app){
				var cert_url = app.get('cert_url') || "";
				var key_url = app.get('key_url') || "";
				return AV.Promise.all([
					AV.Cloud.httpRequest({ url: cert_url }),
					AV.Cloud.httpRequest({ url: key_url }),
					app.get('passphrase')
				]);
			})
			.then(
				function(response){
					var cert = response[0].buffer;
					var key = response[1].buffer;
					var passpharse = response[2];
					if(cert && key){
						var apnConnection = new apn.Connection({cert: cert, key: key,
							production: true, passphrase: passpharse});
						var apnConnection_dev = new apn.Connection({cert: cert, key: key,
							production: false, passphrase: passpharse});
						notification_cache[installationId].apnConnection = apnConnection;
						notification_cache[installationId].apnConnection_dev = apnConnection_dev;
					}
					return AV.Promise.as(notification_cache[installationId]);
				})
			.catch(
				function(e){
					return AV.Promise.error(e);
				})
	}else{
		//var uid = installation.get("user").id;
		//userId_insatalltionId[uid] = installationId;
		var collect_data_ref = "https://notify.wilddogio.com/message/"+ uid + "/collect_data";
		var configuration_ref = "https://notify.wilddogio.com/configuration/"+ uid + "/content";
		var notify_ref = "https://notify.wilddogio.com/notification/"+ uid + "/content/";
		var updatedAt_ref = "https://notify.wilddogio.com/notification/"+ uid + "/updatedAt";
		notification_cache[installationId].collect_data_ref = collect_data_ref;
		notification_cache[installationId].configuration_ref = configuration_ref;
		notification_cache[installationId].notify_ref = notify_ref;
		notification_cache[installationId].updatedAt_ref = updatedAt_ref;
		return AV.Promise.as(notification_cache[installationId]);
	}

};