How to use TransactionResult method in devicefarmer-stf

Best JavaScript code snippet using devicefarmer-stf

Personas.model.js

Source:Personas.model.js Github

copy

Full Screen

1const database = require("../../config/database.async");2const db = require("../../config/conexion");3const GeneratorCode = require("../../helpers/GeneratorCode");4const fse = require("fs-extra");5const isUndefinedOrNull = require("validate.io-undefined-or-null/lib");6module.exports = {7 /**8 * @returns Si la persona se registra exitosamente devuelve el `id` de la persona registrada, en caso contrario devuelve `false`9 * @param {*} PersonaData - Recibe todos los datos de la persona nueva a registrarse.10 * @param {*} [callback]- Callback a ejecutarse cuando se registre usuario;11 */12 create: async (PersonaData, callback) => {13 console.log("----------------------------------------------------------------------");14 console.log(PersonaData);15 const { 16 nombre, 17 apellido, 18 telefono, 19 sexo, 20 nacionalidad, 21 fechaNacimiento, 22 departamentoNacimiento, 23 municipioNacimiento,24 cantonNacimiento,25 departamentoResidencia,26 municipioResidencia,27 cantonResidencia,28 tipoDocumento,29 numeroDocumento,30 estadoCivil,31 profesion,32 direccion,33 createUser,34 iglesia,35 correo_electronico,36 rol,37 alias38 } = PersonaData;39 let {avatar } = PersonaData;40 if(!avatar){41 avatar = "recursos/images/usuarios/profile_default.png";42 }43 try {44 let result;45 const transactionResult = await database.Transaction(46 db,47 async () =>{48 const newPersonaCode = GeneratorCode("P");49 const personaResult = await db.query(50 "INSERT INTO `personas`(`codigo`,`nombres`, `apellidos`, `telefono`, `sexo`, `avatar`, `nacionalidad`, `fecha_nacimiento`, `departemento_nacimiento`, `municipio_nacimiento`, `canton_nacimiento`, `departamento_residencia`, `municipio_residencia`, `canton_residencia`, `tipo_documento`, `numero_documento`, `estado_civil`, `profesion_oficio`, `direccion`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",51 [52 newPersonaCode,53 nombre, 54 apellido, 55 telefono, 56 sexo, 57 avatar, 58 nacionalidad, 59 fechaNacimiento, 60 departamentoNacimiento, 61 municipioNacimiento,62 cantonNacimiento,63 departamentoResidencia,64 municipioResidencia,65 cantonResidencia,66 tipoDocumento,67 numeroDocumento,68 estadoCivil,69 profesion,70 direccion71 ]72 );73 console.log(personaResult);74 if(personaResult.affectedRows > 0){75 console.log("-------------------ID OF PERSON");76 console.log(personaResult);77 if(createUser == true){78 const userResult = await callback({79 persona: newPersonaCode,80 iglesia,81 correo_electronico,82 rol,83 alias84 });85 if(userResult.affectedRows > 0){86 result = personaResult.insertId;87 }88 else{89 throw new Error("No se pudo crear el usuario");90 }91 }92 else{93 result = {id: personaResult.insertId, codigo: newPersonaCode};94 }95 }96 else{97 result = false;98 }99 100 }101 );102 if(transactionResult.errno){103 throw transactionResult;104 }105 return result;106 } catch (error) {107 console.log(error);108 return error;109 }110 111 },112 /**113 * @returns Si la persona es encontrada se devuelve un `object` de la persona, de lo contrario se devuelve `false`114 * @param {string} code - Es el id, codigo o numero de documento de la persona a buscar115 */116 findById: async (code) => {117 try {118 let personaFound;119 const transactionResult = await database.Transaction(120 db,121 async () => {122 const personaResult = await db.query(123 `SELECT id,avatar, codigo, nombres, apellidos, telefono, 124 (SELECT valor from miscelanea where grupo = "sexo_persona" AND code = personas.sexo ) as sexo,125 (SELECT code from miscelanea where grupo = "sexo_persona" AND code = personas.sexo ) as sexo_code,126 (SELECT nacionalidad from nacionalidades WHERE id = personas.nacionalidad) as nacionalidad, 127 (SELECT id from nacionalidades WHERE id = personas.nacionalidad) as nacionalidad_id,128 DATE_FORMAT(fecha_nacimiento,'%Y-%m-%d') AS fecha_nacimiento, 129 (SELECT nombre from departamentos where id = personas.departemento_nacimiento) as departemento_nacimiento,130 (SELECT id from departamentos where id = personas.departemento_nacimiento) as departemento_nacimiento_id, 131 (SELECT nombre from municipios where id = personas.municipio_nacimiento) as municipio_nacimiento,132 (SELECT id from municipios where id = personas.municipio_nacimiento) as municipio_nacimiento_id,133 (SELECT nombre from cantones where id = personas.canton_nacimiento) as canton_nacimiento, 134 (SELECT id from cantones where id = personas.canton_nacimiento) as canton_nacimiento_id,135 (SELECT nombre from departamentos where id = personas.departamento_residencia) as departamento_residencia,136 (SELECT id from departamentos where id = personas.departamento_residencia) as departamento_residencia_id, 137 (SELECT nombre from municipios where id = personas.municipio_residencia) as municipio_residencia,138 (SELECT id from municipios where id = personas.municipio_residencia) as municipio_residencia_id,139 (SELECT nombre from cantones where id = personas.canton_residencia) as canton_residencia, 140 (SELECT id from cantones where id = personas.canton_residencia) as canton_residencia_id, 141 (SELECT nombre from tipos_documentos where id = personas.tipo_documento) as tipo_documento, 142 (SELECT id from tipos_documentos where id = personas.tipo_documento) as tipo_documento_id, 143 numero_documento, 144 (SELECT nombre FROM estados_civiles WHERE id = personas.estado_civil) as estado_civil, 145 (SELECT id FROM estados_civiles WHERE id = personas.estado_civil) as estado_civil_id,146 (SELECT nombre from profesiones where id = personas.profesion_oficio) as profesion_oficio,147 (SELECT id from profesiones where id = personas.profesion_oficio)as profesion_oficio_id,148 direccion, estado, fecha_fallecimiento, condicion, fecha_cr, fecha_uac FROM personas WHERE (personas.id = ? OR personas.codigo = ? OR personas.numero_documento = ?)`,149 [code,code,code]150 );151 if(personaResult.length>0){152 personaFound = {153 "id": personaResult[0].id,154 "avatar": personaResult[0].avatar,155 "codigo": personaResult[0].codigo,156 "nombres":personaResult[0].nombres,157 "apellidos": personaResult[0].apellidos,158 "telefono": personaResult[0].telefono,159 "sexo": {160 label: personaResult[0].sexo,161 value: personaResult[0].sexo_code162 },163 "nacionalidad": {164 label: personaResult[0].nacionalidad,165 value: personaResult[0].nacionalidad_id166 },167 "fecha_nacimiento":personaResult[0].fecha_nacimiento,168 "departemento_nacimiento": {169 label: personaResult[0].departemento_nacimiento,170 value: personaResult[0].departemento_nacimiento_id171 },172 "municipio_nacimiento": {173 label:personaResult[0].municipio_nacimiento,174 value:personaResult[0].municipio_nacimiento_id175 },176 "canton_nacimiento": {177 label:personaResult[0].canton_nacimiento,178 value: personaResult[0].canton_nacimiento_id179 },180 "departamento_residencia": {181 label:personaResult[0].departamento_residencia,182 value: personaResult[0].departamento_residencia_id183 },184 "municipio_residencia": {185 label:personaResult[0].municipio_residencia,186 value: personaResult[0].municipio_residencia_id187 },188 "canton_residencia": {189 label:personaResult[0].canton_residencia,190 value: personaResult[0].canton_residencia_id191 },192 "tipo_documento": {193 label:personaResult[0].tipo_documento,194 value: personaResult[0].tipo_documento_id195 },196 "numero_documento": personaResult[0].numero_documento,197 "estado_civil": {198 label:personaResult[0].estado_civil,199 value: personaResult[0].estado_civil_id200 },201 "profesion_oficio": {202 label:personaResult[0].profesion_oficio,203 value: personaResult[0].profesion_oficio_id204 },205 "direccion": personaResult[0].direccion,206 "estado": personaResult[0].estado,207 "fecha_fallecimiento": personaResult[0].fechaNacimiento,208 "condicion": personaResult[0].condicion,209 "fecha_cr": personaResult[0].fecha_cr,210 "fecha_uac": personaResult[0].fecha_uac211 }212 }213 else{214 personaFound = false;215 }216 }217 );218 if(transactionResult.errno || transactionResult instanceof Error){219 throw transactionResult;220 }221 return personaFound;222 } catch (error) {223 return error;224 }225 },226 /**227 * @returns Devuelve un `booleano` indicando si se actualizo o no la foto de perfil.228 * @param {*} data - Datos sobre el usuario y el nuevo archivo guardado a actualizarse en el usuario.229 */230 updateProfilePicture: async(data)=>{231 const {user, avatar} = data;232 try {233 let result;234 if(!user.avatar.includes("profile_default.png"))235 await fse.remove(user.avatar)236 const transactionResult = await database.Transaction(237 db,238 async ()=>{239 const updateAvatarResult = await db.query(240 "UPDATE `personas` SET `avatar`= ? WHERE `id`=?",241 [avatar.filename, user.id]242 );243 console.log("-------------------aaa");244 console.log(updateAvatarResult);245 result = updateAvatarResult.affectedRows > 0;246 }247 );248 249 if(transactionResult.errno || transactionResult instanceof Error){250 throw Error;251 }252 console.log("--------------------result");253 console.log(result);254 return result;255 } catch (error) {256 return error;257 }258 },259 /**260 * @returns Devuelve la lista de personas que cumplan con `filter`. Cuando no se pasa `filter` se devuelven todos sin filtrar.261 * @param {string} filter - Opcional. Cadena a buscar en los campos de Personas. 262 */263 findAll: async (filter = "") => {264 let personas;265 try {266 const transactionResult = await database.Transaction(267 db, 268 async () => {269 if (filter != "" || !isUndefinedOrNull(filter)) {270 console.log("_-------------------------AKI");271 filter = filter.split(" ");272 let query = `SELECT id, codigo, nombres, apellidos, telefono, condicion, estado, (SELECT id from usuarios WHERE usuarios.persona = personas.codigo) as userId FROM personas WHERE `;273 for (let i = 0; i < filter.length; i++) {274 query += 275 `(nombres LIKE '%${filter[i]}%' OR apellidos LIKE '%${filter[i]}%' OR numero_documento LIKE '%${filter[i]}%' OR codigo LIKE '%${filter[i]}%' OR telefono LIKE '%${filter[i]}%') ${i + 1 - filter.length >= 0 ? "" : "AND"}`;276 }277 console.log(query);278 personas = await db.query(`${query} ORDER BY nombres ASC LIMIT 100`);279 console.log(personas);280 } else {281 console.log("todos");282 personas = await db.query(283 `SELECT * FROM personas ORDER BY nombres ASC LIMIT 100`284 );285 }286 287 });288 if(transactionResult.errno || transactionResult instanceof Error){289 throw transactionResult;290 }291 return personas;292 } catch (error) {293 return error;294 }295 },296 297 /**298 * @returns Devuelve un `boolean` indicando `true` si ya existe y `false` si no existe.299 * @param {string} phoneNumber - Número del telefono a saber si existe o no300 */301 findPhoneNumber: async(phoneNumber) =>{302 try {303 let result;304 const transactionResult = await database.Transaction(305 db,306 async ()=>{307 const queryResult = await db.query(308 "select telefono from personas where telefono = ?",309 [phoneNumber]310 );311 result = queryResult312 }313 );314 if(transactionResult.errno || transactionResult instanceof Error){315 throw transactionResult;316 }317 console.log("----------------");318 console.log(result);319 return result;320 } catch (error) {321 return error;322 }323 },324 /**325 * @returns Devuelve un `boolean` indicando `true` si ya existe y `false` si no existe.326 * @param {string} documentNumber - Número de documento a saber si existe o no327 */328 findDocumentNumber: async(documentNumber) =>{329 try {330 let result;331 const transactionResult = await database.Transaction(332 db,333 async ()=>{334 const queryResult = await db.query(335 "select numero_documento from personas where numero_documento = ?",336 [documentNumber]337 );338 result = queryResult;339 }340 );341 if(transactionResult.errno || transactionResult instanceof Error){342 throw transactionResult;343 }344 console.log("----------------");345 console.log(result);346 return result;347 } catch (error) {348 return error;349 }350 },351 /**352 * 353 * @param {Object} data - Datos para habilitar o deshabilitar el registro354 * @param {number} data.code - `id` de la persona a modificar355 * @param {number} data.status - 1 para habilitar, 0 para deshabilitar356 */357 disableOrEnable: async(data) =>{358 try {359 let result;360 const transactionResult = await database.Transaction(361 db,362 async ()=>{363 const queryResult = await db.query(364 "UPDATE personas SET condicion=? WHERE id=?",365 [data.status, data.code]366 );367 console.log(queryResult);368 result = queryResult.affectedRows >0;369 }370 );371 if(transactionResult.errno || transactionResult instanceof Error){372 throw transactionResult;373 }374 return result;375 } catch (error) {376 return error;377 }378 },379 /**380 * Función para buscar en las personas que están habilitadas y que están vivas.381 * @returns Devuelve la lista de personas que cumplan con `filter`. Cuando no se pasa `filter` se devuelven todos sin filtrar.382 * @param {string} filter - Opcional. Cadena a buscar en los campos de Personas. 383 */384 findAllInOk: async (filter = "") => {385 let personas;386 try {387 const transactionResult = await database.Transaction(388 db, 389 async () => {390 if (filter != "") {391 filter = filter.split(" ");392 let query = `SELECT * FROM personas WHERE (condicion = 1 AND estado = 1) AND `;393 for (let i = 0; i < filter.length; i++) {394 query += 395 `(nombres LIKE '%${filter[i]}%' OR apellidos LIKE '%${filter[i]}%' OR numero_documento LIKE '%${filter[i]}%' OR codigo LIKE '%${filter[i]}%' OR telefono LIKE '%${filter[i]}%') ${i + 1 - filter.length >= 0 ? "" : "AND"}`;396 }397 console.log(query);398 personas = await db.query(`${query} ORDER BY nombres ASC LIMIT 100`);399 console.log(personas);400 } else {401 console.log("todos");402 personas = await db.query(403 `SELECT id, codigo, apellidos, nombres, telefono, sexo, numero_documento, condicion, estado FROM personas WHERE condicion = 1 AND estado = 1 ORDER BY nombres ASC LIMIT 100`404 );405 }406 407 });408 if(transactionResult.errno || transactionResult instanceof Error){409 throw transactionResult;410 }411 return personas;412 } catch (error) {413 return error;414 }415 },416 417 /**418 * Función para buscar en las personas que están habilitadas, que están vivas y no son pastores.419 * @returns Devuelve la lista de personas que cumplan con `filter`. Cuando no se pasa `filter` se devuelven todos sin filtrar.420 * @param {string} filter - Opcional. Cadena a buscar en los campos de Personas. 421 */422 findAllInOkNotPastores: async (filter = "") => {423 let personas;424 try {425 const transactionResult = await database.Transaction(426 db, 427 async () => {428 if (filter != "") {429 filter = filter.split(" ");430 431 let query = `SELECT id, codigo, nombres, apellidos, telefono, sexo, numero_documento, condicion, estado FROM personas WHERE personas.codigo not in (Select pastores.persona from pastores) AND (condicion = 1 AND estado = 1) AND `;432 for (let i = 0; i < filter.length; i++) {433 query += 434 `(nombres LIKE '%${filter[i]}%' OR apellidos LIKE '%${filter[i]}%' OR numero_documento LIKE '%${filter[i]}%' OR codigo LIKE '%${filter[i]}%' OR telefono LIKE '%${filter[i]}%') ${i + 1 - filter.length >= 0 ? "" : "AND"}`;435 }436 console.log(query);437 personas = await db.query(`${query} ORDER BY nombres ASC LIMIT 100`);438 console.log(personas);439 } else {440 console.log("todos");441 personas = await db.query(442 `SELECT id, codigo, nombres, apellidos, telefono, sexo, numero_documento, condicion, estado FROM personas WHERE personas.codigo not in (Select pastores.persona from pastores) AND condicion = 1 AND estado = 1 ORDER BY nombres ASC LIMIT 100`443 );444 }445 446 447 });448 if(transactionResult.errno || transactionResult instanceof Error){449 throw transactionResult;450 }451 return personas;452 } catch (error) {453 return error;454 }455 456 },457 /**458 * 459 * @param {Object} data - Datos para habilitar o deshabilitar el registro460 * @param {number} data.code - `id` de la persona a modificar461 * @param {number} data.status - 1 para habilitar, 0 para deshabilitar462 */463 disableOrEnable: async(data) =>{464 try {465 let result;466 const transactionResult = await database.Transaction(467 db,468 async ()=>{469 const queryResult = await db.query(470 "UPDATE personas SET condicion=? WHERE id=?",471 [data.status, data.code]472 );473 console.log(queryResult);474 result = queryResult.affectedRows >0;475 }476 );477 if(transactionResult.errno || transactionResult instanceof Error){478 throw transactionResult;479 }480 return result;481 } catch (error) {482 return error;483 }484 },485 /**486 * Función para buscar en las personas que están habilitadas y que están vivas.487 * @returns Devuelve la lista de personas que cumplan con `filter`. Cuando no se pasa `filter` se devuelven todos sin filtrar.488 * @param {string} filter - Opcional. Cadena a buscar en los campos de Personas. 489 */490 findSelect: async (filter = "") => {491 let personas;492 try {493 const transactionResult = await database.Transaction(494 db, 495 async () => {496 if (filter != "") {497 filter = filter.split(" ");498 let query = "SELECT id, codigo, concat(nombres, ' ', apellidos) as nombre FROM `personas` WHERE condicion = 1 AND estado = 1 ";499 for (let i = 0; i < filter.length; i++) {500 query += 501 `AND (nombres LIKE '%${filter[i]}%'502 OR apellidos LIKE '%${filter[i]}%')`;503 }504 console.log(query);505 personas = await db.query(`${query} ORDER BY nombre ASC LIMIT 50`);506 console.log(personas);507 } else {508 console.log("todos");509 personas = await db.query(510 "SELECT id, codigo, concat(nombres, ' ', apellidos) as nombre FROM `personas` WHERE condicion = 1 AND estado = 1 ORDER BY nombre ASC LIMIT 50"511 );512 }513 514 });515 if(transactionResult.errno || transactionResult instanceof Error){516 throw transactionResult;517 }518 return personas;519 } catch (error) {520 return error;521 }522 },523 524 /**525 * 526 * @param {Object} data - Datos para habilitar o deshabilitar el registro527 * @param {number} data.code - `id` de la persona a modificar528 * @param {string} data.date - `Fecha` en la que falleció la persona529 */530 setDied: async(data) =>{531 try {532 let result;533 const transactionResult = await database.Transaction(534 db,535 async ()=>{536 const queryResult = await db.query(537 "UPDATE personas SET estado=2, condicion=0, fecha_fallecimiento = ? WHERE id=?",538 [data.date,data.code]539 );540 console.log(queryResult);541 result = queryResult.affectedRows >0;542 }543 );544 if(transactionResult.errno || transactionResult instanceof Error){545 throw transactionResult;546 }547 return result;548 } catch (error) {549 return error;550 }551 },552 553 /**554 * @returns Si la persona se registra exitosamente devuelve el `id` de la persona registrada, en caso contrario devuelve `false`555 * @param {*} PersonaData - Los datos a actualizar de la persona.556 * @param {*} [callback]- Callback a ejecutarse cuando se registre usuario;557 */558 update: async (PersonaData) => {559 const { 560 nombre, 561 apellido, 562 telefono, 563 sexo, 564 nacionalidad, 565 fechaNacimiento, 566 departamentoNacimiento, 567 municipioNacimiento,568 cantonNacimiento,569 departamentoResidencia,570 municipioResidencia,571 cantonResidencia,572 tipoDocumento,573 numeroDocumento,574 estadoCivil,575 profesion,576 direccion,577 id,578 } = PersonaData;579 try {580 let result;581 const transactionResult = await database.Transaction(582 db,583 async () =>{584 const personaResult = await db.query(585 "UPDATE `personas` SET `nombres`=?,`apellidos`=?,`telefono`=?,`sexo`=?,`nacionalidad`=?,`fecha_nacimiento`=?,`departemento_nacimiento`=?,`municipio_nacimiento`=?,`canton_nacimiento`=?,`departamento_residencia`=?,`municipio_residencia`=?,`canton_residencia`=?,`tipo_documento`=?,`numero_documento`=?,`estado_civil`=?,`profesion_oficio`=?,`direccion`=? WHERE id=?",586 [587 nombre, 588 apellido, 589 telefono, 590 sexo, 591 nacionalidad, 592 fechaNacimiento, 593 departamentoNacimiento, 594 municipioNacimiento,595 cantonNacimiento,596 departamentoResidencia,597 municipioResidencia,598 cantonResidencia,599 tipoDocumento,600 numeroDocumento,601 estadoCivil,602 profesion,603 direccion,604 id605 ]606 );607 console.log(personaResult);608 result = personaResult;609 610 }611 );612 if(transactionResult.errno){613 throw transactionResult;614 }615 return result;616 } catch (error) {617 console.log(error);618 return error;619 }620 621 },622 template: async(params) =>{623 try {624 let result;625 const transactionResult = await database.Transaction(626 db,627 async ()=>{628 //cosas629 const queryResult = await db.query(630 "",631 []632 );633 //result = queryResult.affectedRows > 0;634 /**635 * if(queryResult.length > 0){636 * 637 * }638 */639 }640 );641 if(transactionResult.errno || transactionResult instanceof Error){642 throw transactionResult;643 }644 return result;645 } catch (error) {646 return error;647 }648 }...

Full Screen

Full Screen

hodlings.d.ts

Source:hodlings.d.ts Github

copy

Full Screen

1declare module 'hodlings' {2 import { BigNumber } from 'bignumber.js';3 import {4 AnyContract,5 Contract,6 ContractBase,7 TransactionOptions,8 TransactionResult,9 TruffleArtifacts10 } from 'truffle';11 import { AnyNumber } from 'web3';12 namespace hodlings {13 interface Migrations extends ContractBase {14 setCompleted(15 completed: number,16 options?: TransactionOptions17 ): Promise<TransactionResult>;18 upgrade(19 address: Address,20 options?: TransactionOptions21 ): Promise<TransactionResult>;22 }23 interface Ownable extends ContractBase {24 owner(): Promise<Address>;25 transferOwnership(newOwner: Address): Promise<TransactionResult>;26 }27 interface ERC20Basic extends ContractBase {28 totalSupply(): Promise<BigNumber>;29 balanceOf(who: Address): Promise<BigNumber>;30 transfer(31 to: Address,32 amount: BigNumber,33 options?: TransactionOptions34 ): Promise<TransactionResult>;35 }36 interface MintableToken extends ERC20Basic, Ownable {37 mintingFinished(): Promise<boolean>;38 mint(39 to: Address,40 amount: AnyNumber,41 options?: TransactionOptions42 ): Promise<TransactionResult>;43 finishMinting(options?: TransactionOptions): Promise<TransactionResult>;44 }45 interface MintedEvent {46 to: Address;47 amount: BigNumber;48 }49 type MintingFinishedEvent = {};50 interface TestToken extends MintableToken {51 name(): Promise<string>;52 symbol(): Promise<string>;53 totalSupply(): Promise<BigNumber>;54 }55 interface PragmaticHodlings extends ContractBase, Ownable {56 addHodler(57 account: Address,58 joinDate: AnyNumber,59 options?: TransactionOptions60 ): Promise<TransactionResult>;61 removeHodler(62 account: Address,63 options?: TransactionOptions64 ): Promise<TransactionResult>;65 settleToken(66 token: Address,67 options?: TransactionOptions68 ): Promise<TransactionResult>;69 getHodlers(): Promise<[Address[], BigNumber[]]>;70 isHodler(account: Address): Promise<boolean>;71 }72 interface HodlerAddedEvent {73 account: Address;74 joinDate: BigNumber;75 }76 interface HodlerRemovedEvent {77 account: Address;78 }79 interface TokenSettledEvent {80 token: Address;81 amount: BigNumber;82 }83 interface MigrationsContract extends Contract<Migrations> {84 'new'(options?: TransactionOptions): Promise<Migrations>;85 }86 interface TestTokenContract extends Contract<TestToken> {87 'new'(88 name: string,89 symbol: string,90 totalSupply: AnyNumber,91 options?: TransactionOptions92 ): Promise<TestToken>;93 }94 interface PragmaticHodlingsContract extends Contract<PragmaticHodlings> {95 'new'(options?: TransactionOptions): Promise<PragmaticHodlings>;96 }97 interface HodlingsArtifacts extends TruffleArtifacts {98 require(name: string): AnyContract;99 require(name: './Migrations.sol'): MigrationsContract;100 require(name: './TestToken.sol'): TestTokenContract;101 require(name: './PragmaticHodlings.sol'): PragmaticHodlingsContract;102 }103 }104 export = hodlings;...

Full Screen

Full Screen

WithdrawlsHandler.ts

Source:WithdrawlsHandler.ts Github

copy

Full Screen

1import { ISecureDataRepository } from './../repository/ISecureDataRepository';2import { Payment } from './../../../poker.engine/src/model/Payment';3import { PaymentType } from '../../../poker.ui/src/shared/PaymentType';4import { TransactionResult } from '../services/BlockCypherService';5import { PaymentStatus } from '../../../poker.ui/src/shared/PaymentStatus';6import { IBlockCypherService } from '../services/IBlockCypherService';7import { Decimal } from '../../../poker.ui/src/shared/decimal';8import { IConnectionToGameServer } from '../services/ConnectionToGameServer';9import { GetPaymentsResult } from '../../../poker.engine/src/admin/model/incoming/GetPaymentsResult';10import { Logger, getLogger } from "log4js";11import { IAccountService } from '../services/AccountService';12var logger:Logger = getLogger();13export async function withdraw(payment:Payment, accountService:IAccountService, dataRepository:ISecureDataRepository, connectionToGameServer:IConnectionToGameServer, options:{allowFlagged:boolean}) : Promise<{errorMessage:string}> {14 15 let result:{errorMessage:string} = {errorMessage: null}16 if(payment.type !== PaymentType.outgoing){17 result.errorMessage = `invalid payment type: ${payment.type}`18 return result;19 }20 if(payment.status !== PaymentStatus.pending && !(payment.status === PaymentStatus.flagged && options.allowFlagged)){ 21 result.errorMessage = `payment has status of ${payment.status} but is required to have status pending`22 return result;23 }24 25 let waitingTxHash = await accountService.isWaitingOnPriorTransaction(payment.currency);26 if(waitingTxHash){ 27 result.errorMessage = `waiting for prior transaction (${waitingTxHash})`28 return result;29 }30 payment.error = null;31 let transactionResult: TransactionResult = await accountService.newTransaction(payment.currency, payment.address, new Decimal(payment.amount).toNumber(), payment.guid)32 logger.info(`TransactionResult: ${payment._id.toString()} success:${transactionResult.success} amount:${payment.amount}`)33 if (transactionResult.success) {34 payment.status = PaymentStatus.complete;35 payment.sentAmount = transactionResult.sentAmount;36 payment.fees = transactionResult.fees;37 payment.txId = transactionResult.txHash;38 payment.updated = new Date();39 }else{40 payment.error = transactionResult.errorMessage;41 }42 await dataRepository.savePayment(payment);43 44 45 if (transactionResult.success){46 let getPaymentsResult = new GetPaymentsResult();47 getPaymentsResult.payments = [ payment ]48 connectionToGameServer.send(getPaymentsResult)49 }50 return result;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var adb = require('adbkit');2var client = adb.createClient();3client.listDevices()4 .then(function(devices) {5 devices.forEach(function(device) {6 console.log(device.id);7 client.shell(device.id, 'cat /proc/cpuinfo')8 .then(adb.util.readAll)9 .then(function(output) {10 console.log('[%s] CPU info: %s', device.id, output.toString().trim());11 });12 });13 })14 .catch(function(err) {15 console.error('Something went wrong:', err.stack);16 });17client.listDevices()18 .then(function(devices) {19 devices.forEach(function(device) {20 console.log(device.id);21 client.shell(device.id, 'cat /proc/meminfo')22 .then(adb.util.readAll)23 .then(function(output) {24 console.log('[%s] Mem info: %s', device.id, output.toString().trim());25 });26 });27 })28 .catch(function(err) {29 console.error('Something went wrong:', err.stack);30 });31client.listDevices()32 .then(function(devices) {33 devices.forEach(function(device) {34 console.log(device.id);35 client.shell(device.id, 'cat /proc/diskstats')36 .then(adb.util.readAll)37 .then(function(output) {38 console.log('[%s] Disk info: %s', device.id, output.toString().trim());39 });40 });41 })42 .catch(function(err) {43 console.error('Something went wrong:', err.stack);44 });45client.listDevices()46 .then(function(devices) {47 devices.forEach(function(device) {48 console.log(device.id);49 client.shell(device.id, 'cat /proc/net/dev')50 .then(adb.util.readAll)51 .then(function(output) {52 console.log('[%s] Net info: %s', device.id, output.toString().trim());53 });54 });55 })56 .catch(function(err) {57 console.error('Something went wrong:', err.stack);58 });59client.listDevices()60 .then(function(devices) {61 devices.forEach(function(device) {62 console.log(device.id);63 client.shell(device.id, 'cat /proc/net/arp')64 .then(adb.util.readAll)65 .then(function(output) {66 console.log('[%s] ARP info: %s', device.id, output.toString().trim());

Full Screen

Using AI Code Generation

copy

Full Screen

1var stf = require('devicefarmer-stf');2var device = stf.use('device');3var path = require('path');4var fs = require('fs');5var util = require('util');6var exec = require('child_process').exec;7var child;8var deviceSerial = "HT4C3SK00075";9var filePath = "C:\\Users\\sneha\\Documents\\GitHub\\devicefarmer-stf\\test\\";10var fileName = "test.apk";11var filePathName = filePath + fileName;12var testStatus = "pass";13var testResult = "testResult";14var testLog = "testLog";15var testReport = "testReport";16var testDuration = "testDuration";17var testScreenshot = "testScreenshot";18function getDeviceStatus(deviceSerial) {19 return device.getStatus(deviceSerial).then(function(status) {20 return status;21 });22}23function installApk(deviceSerial, filePathName) {24 return device.installApk(deviceSerial, filePathName).then(function() {25 return true;26 });27}28function startTest(deviceSerial, testStatus, testResult, testLog, testReport, testDuration, testScreenshot) {29 return device.startTest(deviceSerial, testStatus, testResult, testLog, testReport, testDuration, testScreenshot).then(function() {30 return true;31 });32}33function getTestStatus(deviceSerial) {34 return device.getTestStatus(deviceSerial).then(function(status) {35 return status;36 });37}38function getTestResult(deviceSerial) {39 return device.getTestResult(deviceSerial).then(function(result) {40 return result;41 });42}43function getTestLog(deviceSerial) {44 return device.getTestLog(deviceSerial).then(function(log) {45 return log;46 });47}48function getTestReport(deviceSerial) {49 return device.getTestReport(deviceSerial).then(function(report) {50 return report;51 });52}53function getTestDuration(deviceSerial) {54 return device.getTestDuration(deviceSerial).then(function(duration) {55 return duration;56 });57}

Full Screen

Using AI Code Generation

copy

Full Screen

1var TransactionResult = require('devicefarmer-stf-provider').TransactionResult2var result = new TransactionResult()3result.setSuccess()4result.setFailure()5result.setRetry()6var result = new TransactionResult()7result.setSuccess()8result.setFailure()9result.setRetry()10result.setStatusCode(200)11result.setError('error message')12result.setResponse('response message')13var result = new TransactionResult()14result.setSuccess()15result.setFailure()16result.setRetry()17result.setStatusCode(200)18result.setError('error message')19result.setResponse('response message')20result.setResponseHeader('header name', 'header value')21var result = new TransactionResult()22result.setSuccess()23result.setFailure()24result.setRetry()25result.setStatusCode(200)26result.setError('error message')27result.setResponse('response message')28result.setResponseHeader('header name', 'header value')29result.setResponseHeaders({30})31var result = new TransactionResult()32result.setSuccess()33result.setFailure()34result.setRetry()35result.setStatusCode(200)36result.setError('error message')37result.setResponse('response message')38result.setResponseHeader('header name', 'header value')39result.setResponseHeaders({40})41result.setResponseHeaders({42})43var result = new TransactionResult()44result.setSuccess()45result.setFailure()46result.setRetry()47result.setStatusCode(200)48result.setError('error message')49result.setResponse('response message')50result.setResponseHeader('header name', 'header value')51result.setResponseHeaders({52})53result.setResponseHeaders({54})55result.setResponseHeaders({56})57var result = new TransactionResult()58result.setSuccess()59result.setFailure()60result.setRetry()61result.setStatusCode(

Full Screen

Using AI Code Generation

copy

Full Screen

1var stf = require('stf-client');2var device = stfClient.getDevice('7c2d4e4e');3device.use(function (device) {4 device.shell('input keyevent 82').then(function (result) {5 console.log(result);6 });7});8var stf = require('stf-client');9var device = stfClient.getDevice('7c2d4e4e');10device.use(function (device) {11 device.shell('input keyevent 82').then(function (result) {12 console.log(result);13 });14});15var stf = require('stf-client');16var device = stfClient.getDevice('7c2d4e4e');17device.use(function (device) {18 device.shell('input keyevent 82').then(function (result) {19 console.log(result);20 });21});22var stf = require('stf-client');23var device = stfClient.getDevice('7c2d4e4e');24device.use(function (device) {25 device.shell('input keyevent 82').then(function (result) {26 console.log(result);27 });28});29var stf = require('stf-client');30var device = stfClient.getDevice('7c2d4e4e');31device.use(function (device) {32 device.shell('input keyevent 82').then(function (result) {33 console.log(result);34 });35});36var stf = require('stf-client');37var device = stfClient.getDevice('7c2d4e4e');38device.use(function (device) {39 device.shell('input keyevent 82').then

Full Screen

Using AI Code Generation

copy

Full Screen

1var stf = require('devicefarmer-stf-client');2var serial = stf.TransactionResult().serial;3var result = stf.TransactionResult().result;4console.log("device serial number: " + serial);5console.log("result of the transaction: " + result);6console.log("result of the transaction: " + result);7console.log("device serial number: " + serial);8console.log("result of the transaction: " + result);9console.log("device serial number: " + serial);10console.log("result of the transaction: " + result);11console.log("device serial number: " + serial);12console.log("result of the transaction: " + result);13console.log("device serial number: " + serial);14console.log("result of the transaction: " + result);15console.log("device serial number: " + serial);16console.log("result of the transaction: " + result);17console.log("device serial number: " + serial);18console.log("result of the transaction: " + result);19console.log("device serial number: " + serial);20console.log("result of the transaction: " + result);21console.log("device serial number: " + serial);22console.log("result of the transaction: " + result);23console.log("device serial number: " + serial);24console.log("result of the transaction: " + result);25console.log("device serial number: " + serial);

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run devicefarmer-stf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful