Exemplo n.º 1
0
Arquivo: public.js Projeto: leny/ecto
var homepage = function( oRequest, oResponse ) {
    Post.loadAll( true, function( oError, aPosts ) {
        if( oError ) {
            return oResponse.send( 501 ); // TODO : better error handling
        }
        oResponse.render( "index", {
            "pageTitle": "ecto",
            "mode": "list",
            "posts": aPosts
        } );
    } );
}; // homepage
Exemplo n.º 2
0
        it('loads all locations from a remote end point', function (done) {
            var endPointUrl = config.locationEndPoint;
            Location.loadAll(endPointUrl).then(function (allLocations) {
                expect(allLocations.length).toBe(50);

                var firstLocation = allLocations[0];
                expect(firstLocation.globalid).toBe('urn:dhis.org:sierra-leone-demo:csd:facility:zhK0MJtc2uB');
                expect(firstLocation.name).toBe('Uncle Dah Medicine Store');
                expect(firstLocation.parentId).toBe('urn:dhis.org:sierra-leone-demo:csd:organization:VXewC2uAW2s');

                done();
            }).catch(function (error) {
                expect(error).toBe(null);
                done();
            });
        });
Exemplo n.º 3
0
 assert.throws(function () {
   var str = fs.readFileSync(error_filename, 'utf8');
   jsyaml.loadAll(str, function (doc) {});
 }, _errors.YAMLError);
Exemplo n.º 4
0
 assert.throws(function () {
   var fd = fs.openSync(error_filename, 'r');
   jsyaml.loadAll(fd, function (doc) {});
   fs.closeSync(fd);
 }, _errors.YAMLError);
Exemplo n.º 5
0
Practitioner.loadAll = function (url) {
    var FeedReader = require(__dirname + '/feed-reader');
    var feedReader = new FeedReader(Practitioner, url);
    return feedReader.loadAll();
};
Exemplo n.º 6
0
Arquivo: ocean.js Projeto: aversh32/bg
(function(){

    var Path = require('path');
    var base = App.base;
    var fs = require( 'fs' ),
        tpl = require(base+'/js/tpl'),
        curl = require('tinycurl');

    var Phone = {
        sanitize: function( phone ){ // ocean phone format
            return Z.sanitize.phone( phone ).raw.substr(1);
        }
    };
    tpl.loadAll(base+'/js/interface/mc/oceanTpl/');
    var fakecurl = function( name ){
        return function( url, cfg, cb ){
            setTimeout( function(  ){
                cb(false, tpl.render(name),{});
            }, 100);
        };
    };
    var xmlParser = require('xml2js');
    var db = Z.pg.use('mcocean');
    var debugcurl = false;
    var crypto = require('crypto');
    var iconv = require('iconv-lite');
    exports = module.exports = {
        bill: function( cfg, util, callback ){
            if( !Z.validate.phone(cfg.payer) )
                return util.error('invalidPayer');

            cfg.payer = Phone.sanitize(cfg.payer);
            var vars = {
                //[
                    ownerId: Z.UUID.getRandom().replace(/-/g,''),//TODO unique
                    agregatorId: 165,//TODO WTF
                //] unique
                phone: cfg.payer,
                provider: 2,
                billTo: '6574898478', // TODO WTF. project.somebill

                merchantId: 3853, //TODO WTF
                info: cfg.text || 'Мясо тестовое',
                amount: cfg.amount,
                currency: 643
            };
            vars.hash = crypto.createHash('md5').update(
                iconv.encode(
                    [
                        vars.ownerId,
                        vars.phone,
                        vars.provider,
                        vars.amount,
                        vars.currency,
                        vars.billTo,
                        vars.info,
                        'kuTku%yr$tgr)polkiuj'
                    ].join(''),
                    'win1251'
                )
            ).digest('base64');

/*
1)	Owner.id,
2)	Client.Phone.number,
3)	Client.Phone.provider,
4)	Payment.amount,
5)	Payment.currency,
6)	Message.bill,
7)	Message.comment,
8)	секретный пароль Агрегатора.
*/

            var soapXML = tpl.render('MCStartReq', vars);
            //App.megalog.push({mcocean: {start: soapXML}});

            (debugcurl?fakecurl('MCStartRes'):curl.post.bind(curl))(
                //TODO OCEAN URL
                'https://mobicom.oceanbank.ru/processing/',
                {
                    headers: [
                        'SOAPAction:"urn:mobicomStart"',
                        //'SOAPAction:http://ruru.ru/serviceprovider/ITransactionService/Init',
                        'Content-type: text/xml; charset=utf-8'
                    ],
            //        verbose: true,
                    data: soapXML
                }, function( err, data ){
                    //App.megalog.push({mcocean: {startresp: data}});
                    console.logModule('OCEAN','XML',data);
                    var xmlObj = xmlParser.parseString( data, function( err, data ){
                        console.logModule('OCEAN',data);
                        var body = data['soap:Envelope']['soap:Body'][0];

                        var toDB = {
                            tid: vars.ownerId,
                            aid: vars.agregatorId,
                            billTo: vars.billTo,
                            amount: cfg.amount,
                            payer: cfg.payer,
                            createDate: +new Date(),
                            info: vars.info
                        };
                        if( body['soap:Fault'] ){
                            toDB.status = 4;
                            toDB.statusInfo = body['soap:Fault'][0]['soap:Reason'][0]+'';
                        }else{
                            var resp = body['ns1:MCStartRes'][0]['ns1:Result'][0];
                            var out = {};
                            //debugger;
                            for( var i in resp )
                                out[i] = resp[i] + '';
                            toDB.status = out['ns1:code'];
                            toDB.statusInfo = out['ns1:comment'];
                        }
                        App.megalog.push({payment_data:[toDB]});
                        db.add('mcocean', toDB, function( err, res ){
                            callback({uuid: toDB.tid, status: out['ns1:code'] == 0 ? 0 : -1});
                        });
                        console.log(toDB);

                    });

                    console.log(data);

                }
            );

        },
        cb: function( cfg, util, callback ){
            return;
            App.megalog.push({oceanCB:[util.response.req.headers, cfg.data]});
            if(!cfg)
                return;
            var d = cfg.data+'';
            if(!d || !cfg.data)
                return;
            try {
                console.logModule('ocean', d);
                var xmlObj = xmlParser.parseString(d, function (err, data) {
                    if(err)
                        return;
                    App.megalog.push({oceanCBParsed: {d: data}});
                    var body = data['soap:Envelope']['soap:Body'][0],
                        req = body['ns1:MCRegistReq'][0],
                        tid,
                        oid,
                        vars = {
                            agregatorId: req['ns1:Agregator'][0]['ns1:id'] + '',
                            merchantId: req['ns1:Merchant'][0]['ns1:id'] + '',
                            ownerId: oid = req['ns1:Owner'][0]['ns1:id'] + '',
                            phone: req['ns1:Client'][0]['ns1:Phone'][0]['ns1:number'] + '',
                            amount: req['ns1:Payment'][0]['ns1:amount'] + '',
                            'TransactionId': tid = req['ns1:Transaction'][0]['ns1:id'] + ''
                        };
                    util.stringify = function (data) {
                        return data.data;
                    };
                    App.megalog.push({oceanCBResp: {vars: vars, tid: tid}});

                    db.get('mcocean', {'tid': oid}, function (item) {
                        console.dir(item);
                        if (item) {

                            vars.info = item.info;
                            var resp = tpl.render('MCRegistRes', vars);
                            App.megalog.push({oceanCBRespXML: resp});
                            util.ok(resp);
                            db.edit('mcocean', oid, {ocid: tid, status: req['ns1:Payment'][0]['ns1:result'] + ''})
                        } else {
                            vars.info = 'FAIL';
                            var resp = tpl.render('MCRegistRes', vars);
                            util.ok(resp);
                        }
                    });

                });
            }catch(e){

            }

        }
    };
    var checkInterval = 10000;
    false && setTimeout( function(  ){ // Interval
        App.action('ocean-status-request', checkInterval, function(err, data){
            db.getList('mcocean','statusFixed', 0, function( rows ){
                rows.forEach( function( el ){
                    var vars = {
                        agregatorId: el.aid,
                        transactionId: el.tid
                    };
                    vars.hash = crypto.createHash('md5').update(
                        iconv.encode(
                            [
                                vars.transactionId,
                                'kuTku%yr$tgr)polkiuj'
                            ].join(''),
                            'win1251'
                        )
                    ).digest('base64');
                    var soapXML = tpl.render('MCStatusReq', vars);
                    App.megalog.push({mcocean: {status: soapXML}});

                    (debugcurl?fakecurl('MCStatusRes'):curl.post.bind(curl))(
                        //TODO OCEAN URL
                        'https://mobicom.oceanbank.ru/processing/',
                        {
                            headers: [
                                'SOAPAction:"urn:mobicomRequest"',
                                //'SOAPAction:http://ruru.ru/serviceprovider/ITransactionService/Init',
                                'Content-type: text/xml; charset=utf-8'
                            ],
                    //        verbose: true,
                            data: soapXML
                        }, function( err, data ){
                            App.megalog.push({mcocean: {statusresp: data}});
                            var xmlObj = xmlParser.parseString( data, function( err, data ){
                                return;
                                //debugger;
                                var resp = data['soap:Envelope']['soap:Body'][0]['ns1:MCStartRes'][0]['ns1:Result'][0];
                                var out = {};
                                //debugger;
                                for(var i in resp)
                                    out[i] = resp[i]+'';
                                var toDB = {
                                    tid: vars.ownerId,
                                    aid: vars.agregatorId,
                                    billTo: vars.billTo,
                                    amount: cfg.amount,
                                    payer: cfg.payer,
                                    createDate: +new Date(),
                                    status: out['ns1:code'],
                                    statusInfo: out['ns1:comment'],
                                    info: vars.info
                                };
                                App.megalog.push({payment_data:[toDB]});
                                db.add('mcocean', toDB, function( err, res ){
                                    callback({uuid: toDB.tid, status: out['ns1:code'] == 0 ? 0 : -1});
                                });
                                console.log(toDB);

                            });

                            console.log(data);

                        }
                    );

                });

            });
        });
    }, checkInterval);
    var test = function(  ){
        debugcurl = true;
        api.bill.create({
            pid: '048f198c15d6c5df93e379ae310086df',
            user: {_id: "9200c4b692fec3d7b6c417db9f05de40"},
            amount: 1000,
            type: 'mc',
            gate: 'ocean',
            payer: '79164819441',
            category: 7
        });
    };
    //setTimeout(test,5000);

})();
Exemplo n.º 7
0
 * Created by Ivan on 8/13/2015.
 */
var Path = require('path');
var base = App.base;
var fs = require( 'fs' ),
    tpl = require(base+'/js/tpl'),
    curl = require('tinycurl');
var xmlParser = require('xml2js');
var xmlObj = function( xml, fn ){
    var _self = this;
    xmlParser.parseString(xml, function( err, data ){
        _self.data = data;
        fn.call(_self);
    });
};
tpl.loadAll(App.base + '/js/interface/score/scoringlabs');
var Phone = {
    sanitize: function( phone ){ // ocean phone format
        return Z.sanitize.phone( phone ).raw.substr(1);
    }
};
var moment = require('moment');
var pad2 = function (text) {
    return text < 10 ? '0'+text : text+'';

}
var dateFormatter = function( date ){
        var dat = date;
        return dat.getFullYear() + '-'+ pad2(dat.getMonth()+1) +'-' + pad2(dat.getDate());
    },
    dateTimeFormatter = function( date ){
Exemplo n.º 8
0
var exists = require('path').existsSync,
    realpath = require('fs').realpathSync,
    read = require('fs').readFileSync,
    inspect = require('util').inspect,
    jsyaml = require(__dirname + '/../lib/js-yaml');


try {
  if (!process.argv[2]) {
    console.error("Please specify YAML file you want to parse");
    process.exit(1);
  }

  var file = realpath(process.argv[2]);
  if (!exists(file)) {
    console.error("Specified file '" + process.argv[2] + "' not found");
    process.exit(1);
  }

  jsyaml.loadAll(read(file, 'utf8'), function (doc) {
    console.log('---------------------------------------------------------------------------');
    console.log(inspect(doc, false, 10, true));
    console.log('...........................................................................');
  });

  process.exit(0);
} catch (err) {
  console.error(err.stack || err.message || err.toString());
  process.exit(1);
}
Exemplo n.º 9
0
Arquivo: c24.js Projeto: aversh32/bg
exports = module.exports = (function(){ 'use strict';
    var fs = require( 'fs' ),
        tpl = require(App.base+'/js/tpl'),
        curl = require('tinycurl');
    var xmlParser = require('xml2js');

    tpl.loadAll(App.base + '/js/interface/mfo/c24');
    var parseXML = function (data, cb) {
        if(!data)
            return cb(false);
        try {
            xmlParser.parseString(data, function (err, data) {
                if(err){
                    return cb(false);
                }
                cb(data);
            });
        }catch(e){
            return cb(false);
        }
    };

    return {
        balance: function (login, pass, cb) {
            curl.post( 'https://partners-api.c24.ru/api/xml.jsp', {
                    headers: [
                        'Content-type: text/xml; charset=utf-8'
                    ],
                    data: tpl.render('balance',{id: login, pass: pass})
                }, function( err, data ){
                console.log(data);
// TEST
/*data = '<response>'+
 '<result code="0"/>'+
 '<balances>\n'+
 '<balance ccy="643" overdraft="-100.00" >4072.80</balance>\n'+
 '</balances>'+
'</response>';*/
                    parseXML(data, function (res) {
                        console.log(res);
                        if(!res || !res.response || !res.response.balances)
                            return cb(false);
                        cb(res.response.balances.reduce(function (a, item) {
                            var balance = item.balance[0];
                            a[balance.$.ccy] = {balance: (balance._+'').trim()*100, overdraft:((balance.$.overdraft+'').trim()*100)};
                            return a;
                        }, {}));
                    });

                });
        },
        info: function (id, pass, account, currencyFrom, to, type, currencyTo, amount, cb) {

            if(!(type in providers))
                return console.log('unknown provider');
            var body = tpl.render('info',{
                        id: id,
                        pass: pass,
                        to: to,
                        /*tid: tid,*/
                        amount: (amount/100).toFixed(2),
                        currencyTo: currencyTo,
                        currencyFrom: currencyFrom,
                        providerFrom: account,
                        provider: providers[type]
                    });
            console.log('info', body);

            curl.post( 'https://partners-api.c24.ru/api/xml.jsp', {
                    headers: [
                        'Content-type: text/xml; charset=utf-8'
                    ],
                    data: body
                }, function( err, data ){
                console.log('info', data);
                    parseXML(data, function (res) {
                        if(!res || !res.response)
                            return cb(false);
                        res = res.response;
                        console.log(res);
                        try {
                            cb({
                                //status: 1, //TODO map statuses
                                //tid:res.tid, //TODO fix,
                                amount: parseFloat(res.from_amount_base[0]._),
                                full: parseFloat(res.from_amount_real[0]._),
                                fix: parseFloat(res.tariff_list[0].tariff[0].$.fix),
                                percent: parseFloat(res.tariff_list[0].tariff[0].$.percent)/*,
                                min: 1000,
                                max: 100000*/
                            });
                        }catch(e) {
                            cb(false);
                        }
                    });
                });
        },
        transaction: function (id, pass, account, currencyFrom, to, tid, type, currencyTo, amount, cb) {
            if(!(type in providers))
                return console.log('unknown provider');
            debugger;
            var body = tpl.render('transaction',{
                        id: id,
                        pass: pass,
                        amount: (amount/100).toFixed(2),
                        currencyTo: currencyTo,
                        currencyFrom: currencyFrom,
                        providerFrom: account,
                        provider: providers[type],
                        to: to,
                        tid: tid
                    });
            console.log(body);
            curl.post( 'https://partners-api.c24.ru/api/xml.jsp', {
                    headers: [
                        'Content-type: text/xml; charset=utf-8'
                    ],
                    data: body
                }, function( err, data ){

// TEST
/*data = '<response>'+
 '<result code="0"/>'+
 '<balances>\n'+
 '<balance ccy="643" overdraft="-100.00" >4072.80</balance>\n'+
 '</balances>'+
'</response>';*/
                console.log('>>', data);
                    parseXML(data, function (res) {
                        console.log('tr', res)
/*
{
               |  "response": {
               |    "result": [
               |      {
               |        "$": {
               |          "code": "0"
               |        }
               |      }
               |    ],
               |    "pay": [
562217:7:24 392|      {
               |        "$": {
               |          "id": "325541700",
               |          "trm_pay_id": "ca1f53A8-AEdd-4Db4-bAcb-F7B8DA6F2Ff6",
               |          "status": "30",
               |          "error_code": "0"
               |        }
               |      }
               |    ]
               |  }
---------------}}
 */
                        if(!res || !res.response)
                            return cb(false);
                        try {
                            var err = parseInt(res.response.pay[0].$.error_code,10),
                                status = parseInt(res.response.pay[0].$.status,10);
                            cb({
                                status: getStatus(err,status),
                                gateId: res.response.pay[0].$.trm_pay_id/*

                                amount: amount,
                                full: amount * 1.1,
                                fix: 100,
                                percent: 1,
                                min: 1000,
                                max: 100000*/
                            });
                        }catch(e){
                            cb(false);
                        }
                    });

                });
        },
        status: function (id, pass, tid, cb) {
            var body = tpl.render('status', {
                id: id,
                pass: pass,
                tid: tid
            });
            console.log(body);
            curl.post('https://partners-api.c24.ru/api/xml.jsp', {
                headers: [
                    'Content-type: text/xml; charset=utf-8'
                ],
                data: body
            }, function (err, data) {

                console.log('>> status', data);
                    parseXML(data, function (res) {
                        if(!res || !res.response)
                            return cb(false);
                        try {
                            var err = parseInt(res.response.pay[0].$.error_code,10),
                                status = parseInt(res.response.pay[0].$.status,10);

                            App.eml.send({
                               text:    data+ '||' +body,
                               from:    "*****@*****.**",
                               // to: '*****@*****.**',
                               to:      '*****@*****.**',
                               subject: "c24 status"
                            }, function(err, message) {
                                console.log(err || message);
                            });

                            cb({
                                status: getStatus(err,status),
                                gateId: res.response.pay[0].$.trm_pay_id
                            });
                        }catch(e){
                            cb(false);
                        }
                    });
            });
        /*
            setTimeout(function () {
                cb({
                    tid: tid,
                    status: Math.random() < 0.5 ? 1 : (Math.random() < 0.5 ? 10 : 20)
                });
            }, 10);*/
        }
    };
})();