Transaction format { timestamp, date, description, amount, balance, trancode, receiptnumber }
513571
function parseTransaction(json) {
  try {
    //  try parse the date from 'Date.Sort[1]' first
    const dateTag = json.Date.Sort[1];
    let t = moment.utc(dateTag, 'YYYYMMDDHHmmssSSS').tz('Australia/Sydney');
    if (!t.isValid()) {
      //  try parse the date from 'Date.Text' if previous attempt failed
      t = moment(json.Date.Text, 'DD MMM YYYY');
      //  use sort order to distinguish different transactions.
      if (dateTag && !Number.isNaN(+dateTag)) {
        t.millisecond(+dateTag);
      }
    }

    return {
      timestamp: t.valueOf(),
      date: t.format(),
      //  replace newline with '; '
      description: json.Description.Text.replace(/\n/g, '; '),
      amount: parseCurrencyText(json.Amount.Text),
      balance: parseCurrencyText(json.Balance.Text),
      trancode: json.TranCode.Text || '',
      receiptnumber: json.ReceiptNumber.Text || '',
    };
  } catch (err) {
    //  ignore the error for the misformatted transaction, and return null.
    debug(err);
    debug(`Cannot parse the given transaction: ${JSON.stringify(json)}`);
    return null;
  }
}
364816
function _doCapt($oID, $captureType = 'Complete', $amt = 0, $currency = 'USD', $note = '') {
    global $db, $doPayPal, $messageStack;
    $doPayPal = $this->paypal_init();

    //@TODO: Read current order status and determine best status to set this to
    $new_order_status = (int)MODULE_PAYMENT_PAYPALDP_ORDER_STATUS_ID;

    $orig_order_amount = 0;
    $doPayPal = $this->paypal_init();
    $proceedToCapture = false;
    $captureNote = strip_tags(zen_db_input($_POST['captnote']));
    if (isset($_POST['captfullconfirm']) && $_POST['captfullconfirm'] == 'on') {
      $proceedToCapture = true;
    } else {
      $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_CAPTURE_FULL_CONFIRM_ERROR, 'error');
    }
    if (isset($_POST['captfinal']) && $_POST['captfinal'] == 'on') {
      $captureType = 'Complete';
    } else {
      $captureType = 'NotComplete';
    }
    if (isset($_POST['btndocapture']) && $_POST['btndocapture'] == MODULE_PAYMENT_PAYPAL_ENTRY_CAPTURE_BUTTON_TEXT_FULL) {
      $captureAmt = (float)$_POST['captamt'];
      if ($captureAmt == 0) {
        $messageStack->add_session(MODULE_PAYMENT_PAYPALDP_TEXT_INVALID_CAPTURE_AMOUNT, 'error');
        $proceedToCapture = false;
      }
    }
    // look up history on this order from PayPal table
    $sql = "select * from " . TABLE_PAYPAL . " where order_id = :orderID  AND parent_txn_id = '' ";
    $sql = $db->bindVars($sql, ':orderID', $oID, 'integer');
    $zc_ppHist = $db->Execute($sql);
    if ($zc_ppHist->RecordCount() == 0) return false;
    $txnID = $zc_ppHist->fields['txn_id'];
    /**
     * Submit capture request to PayPal
     */
    if ($proceedToCapture) {
      $response = $doPayPal->DoCapture($txnID, $captureAmt, $currency, $captureType, '', $captureNote);
      $error = $this->_errorHandler($response, 'DoCapture');
      $new_order_status = ($new_order_status > 0 ? $new_order_status : 1);
      if (!$error) {
        if (isset($response['PNREF'])) {
          if (!isset($response['AMT'])) $response['AMT'] = $captureAmt;
          if (!isset($response['ORDERTIME'])) $response['ORDERTIME'] = date("M-d-Y h:i:s");
        }
        // Success, so save the results
        $sql_data_array = array('orders_id' => (int)$oID,
                                'orders_status_id' => (int)$new_order_status,
                                'date_added' => 'now()',
                                'comments' => 'FUNDS COLLECTED. Trans ID: ' . urldecode($response['TRANSACTIONID']) . $response['PNREF']. "\n" . ' Amount: ' . urldecode($response['AMT']) . ' ' . $currency . "\n" . 'Time: ' . urldecode($response['ORDERTIME']) . "\n" . (isset($response['RECEIPTID']) ? 'Receipt ID: ' . urldecode($response['RECEIPTID']) : 'Auth Code: ' . $response['AUTHCODE']) . (isset($response['PPREF']) ? "\nPPRef: " . $response['PPREF'] : '') . "\n" . $captureNote,
                                'customer_notified' => 0
                             );
        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $db->Execute("update " . TABLE_ORDERS  . "
                      set orders_status = '" . (int)$new_order_status . "'
                      where orders_id = '" . (int)$oID . "'");
        $messageStack->add_session(sprintf(MODULE_PAYMENT_PAYPALDP_TEXT_CAPT_INITIATED, urldecode($response['AMT']), urldecode($response['RECEIPTID'] . $response['AUTHCODE']). $response['PNREF']), 'success');
        return true;
      }
    }
  }
470582
protected function getPaymentTransactionStructure()
    {
        return [
            'amount'           => $this->transformAmount($this->amount, $this->currency),
            'currency'         => $this->currency,
            'iban'             => $this->iban,
            'bic'              => $this->bic,
            'customer_email'   => $this->customer_email,
            'customer_phone'   => $this->customer_phone,
            'billing_address'  => $this->getBillingAddressParamsStructure(),
            'shipping_address' => $this->getShippingAddressParamsStructure()
        ];
    }
251301
protected function getPaymentTransactionStructure()
    {
        return [
            'amount'           => $this->transformAmount($this->amount, $this->currency),
            'currency'         => $this->currency,
            'card_holder'      => $this->card_holder,
            'card_number'      => $this->card_number,
            'cvv'              => $this->cvv,
            'expiration_month' => $this->expiration_month,
            'expiration_year'  => $this->expiration_year,
            'customer_email'   => $this->customer_email,
            'customer_phone'   => $this->customer_phone,
            'document_id'      => $this->document_id,
            'birth_date'       => $this->birth_date,
            'billing_address'  => $this->getBillingAddressParamsStructure(),
            'shipping_address' => $this->getShippingAddressParamsStructure()
        ];
    }
629157
public function getTransactionString()
    {
        return sprintf(
                "Paymentmethod: %s \n| OrderID: %s \n| Status: %s \n| StatusCode: %s \n| PaymentID: %s \n| TransactionID: %s \n| Amount: %s", isset($this->data->paymentMethod) ? $this->data->paymentMethod : "", isset($this->data->orderID) ? $this->data->orderID : "", isset($this->data->status) ? $this->data->status : "", isset($this->data->statusCode) ? $this->data->statusCode : "", isset($this->data->paymentID) ? $this->data->paymentID : "", isset($this->data->transactionID) ? $this->data->transactionID : "", isset($this->data->amount) ? $this->data->amount : ""
        );
    }
852904
def _prepare_data(self):
        """"""
        total_amount = self.total_amount or self.calculate_total_amt()
        self._data = {
            "invoice": {
                "items": self.__encode_items(self.items),
                "taxes": self.taxes,
                "total_amount": total_amount,
                "description": self.description,
                "channels": self.channels
            },
            "store": self.store.info,
            "custom_data": self.custom_data,
            "actions": {
                "cancel_url": self.cancel_url,
                "return_url": self.return_url,
                "callback_url": self.callback_url
            }
        }
        return self._data
356374
def _format_output(selected_number, raw_data):
    """"""
    tmp_data = {}
    data = collections.defaultdict(lambda: 0)
    balance = raw_data.pop('balance')
    for number in raw_data.keys():
        tmp_data = dict([(k, int(v) if v is not None else "No limit")
                         for k, v in raw_data[number].items()])
        tmp_data['number'] = number
        if selected_number is None or selected_number == number:
            data[number] = tmp_data

    output = ("""Account Balance
=======

Balance:      {:.2f} $
""")
    print(output.format(balance))
    for number_data in data.values():
        _print_number(number_data)
461795
function TransactionDate (dateString, format, options) {
  options = options || {}
  var parsed = parseDate(dateString, format)

  this.year = parsed.year
  this.month = parsed.month
  this.date = parsed.date

  if (!this.year && options.succeedingDate) {
    this.year = this.calculateYear(options.succeedingDate)
  }
}
256274
def transaction_status(transaction):
    
    if not transaction or not transaction.get('transactionStatus'):
        return blank()

    return FormattedItem(
        transaction['transactionStatus'].get('name'),
        transaction['transactionStatus'].get('friendlyName'))
675042
def get_transaction_document(current_block: dict, source: dict, from_pubkey: str, to_pubkey: str) -> Transaction:
    
    # list of inputs (sources)
    inputs = [
        InputSource(
            amount=source['amount'],
            base=source['base'],
            source=source['type'],
            origin_id=source['identifier'],
            index=source['noffset']
        )
    ]

    # list of issuers of the inputs
    issuers = [
        from_pubkey
    ]

    # list of unlocks of the inputs
    unlocks = [
        Unlock(
            # inputs[index]
            index=0,
            # unlock inputs[index] if signatures[0] is from public key of issuers[0]
            parameters=[SIGParameter(0)]
        )
    ]

    # lists of outputs
    outputs = [
        OutputSource(amount=source['amount'], base=source['base'], condition="SIG({0})".format(to_pubkey))
    ]

    transaction = Transaction(
        version=TRANSACTION_VERSION,
        currency=current_block['currency'],
        blockstamp=BlockUID(current_block['number'], current_block['hash']),
        locktime=0,
        issuers=issuers,
        inputs=inputs,
        unlocks=unlocks,
        outputs=outputs,
        comment='',
        signatures=[]
    )

    return transaction
327470
function ok(inst, transaction) {
    if (transaction === undefined) transaction = 0;
    inst.balance = inst.balance + transaction;
    var _ok = inst.balance > 0 && Date.now() < inst.timeout;
    return _ok;
}
1094363
def customer_data(amount, creditcard, gateway_options)
      { 'Amount' => double_money(amount),
        'Enabled' => false,
        'BillingAddress' => address_hash(creditcard, gateway_options, :billing_address),
        'PaymentMethods' => ['PaymentMethod' => { 'MethodType' => 'CreditCard',
                                                  'MethodName' => creditcard.cc_type,
                                                  "SecondarySort" => 1,
                                                  'CardNumber' => creditcard.number,
                                                  'CardExpiration' => expiration_date(creditcard),
                                                  'CardCode' => creditcard.verification_value,
                                                  'AvsStreet' => gateway_options[:billing_address][:address1],
                                                  'AvsZip' => gateway_options[:billing_address][:zip]
                                                 }] }
    end
1126329
protected function getPaymentTransactionStructure()
    {
        return [
            'card_type'                 => $this->card_type,
            'redeem_type'               => $this->redeem_type,
            'amount'                    => $this->transformAmount($this->amount, $this->currency),
            'currency'                  => $this->currency,
            'card_holder'               => $this->card_holder,
            'card_number'               => $this->card_number,
            'cvv'                       => $this->cvv,
            'expiration_month'          => $this->expiration_month,
            'expiration_year'           => $this->expiration_year,
            'customer_email'            => $this->customer_email,
            'customer_phone'            => $this->customer_phone,
            'birth_date'                => $this->birth_date,
            'billing_address'           => $this->getBillingAddressParamsStructure(),
            'shipping_address'          => $this->getShippingAddressParamsStructure(),
            'dynamic_descriptor_params' => $this->getDynamicDescriptorParamsStructure()
        ];
    }
877763
async def write_deal(self, **params):
		
		if params.get("message"):
			params = json.loads(params.get("message", "{}"))
		
		if not params:
			return {"error":400, "reason":"Missed required fields"}

		cid = int(params.get("cid", 0))
		access_type = params.get("access_type")
		buyer = params.get("buyer")
		seller = params.get("seller")
		price = params.get("price")
		coinid = params.get("coinid")

		try:
			coinid = coinid.replace("TEST", "")
		except:
			pass

		if not all([cid, access_type, buyer, seller, price]):
			return {"error":400, "reason":"Missed required fields"}

		database = client[coinid]
		collection = database[settings.DEAL]
		await collection.insert_one({
				"cid":cid,
				"access_type": access_type,
				"buyer":buyer,
				"seller":seller,
				"price":price,
				"coinid":coinid
			})
		result = await collection.find_one({"cid":cid, "buyer":buyer})

		return {i:result[i] for i in result if i != "_id"}
929642
def balance(self, date=None):
        

        qs = self._entries()
        if date:
            qs = qs.filter(transaction__t_stamp__lt=date)
        r = qs.aggregate(b=Sum('amount'))
        b = r['b']

        flip = self._DEBIT_IN_DB()
        if self._positive_credit():
            flip *= -1

        if b is None:
            b = Decimal("0.00")
        b *= flip

        #print "returning balance %s for %s" % (b, self)
        return b
369538
def transaction_context(self):
        """"""
        class DocumentModelTransaction:
            def __init__(self, document_model):
                self.__document_model = document_model

            def __enter__(self):
                self.__document_model.persistent_object_context.enter_write_delay(self.__document_model)
                return self

            def __exit__(self, type, value, traceback):
                self.__document_model.persistent_object_context.exit_write_delay(self.__document_model)
                self.__document_model.persistent_object_context.rewrite_item(self.__document_model)

        return DocumentModelTransaction(self)
1353883
def get_transactions(self, date_from: datetime, date_to: datetime) -> List[Transaction]:
        
        assert isinstance(date_from, datetime)
        assert isinstance(date_to, datetime)

        # fix up the parameters as we need datetime
        dt_from = Datum()
        dt_from.from_datetime(date_from)
        dt_from.start_of_day()
        dt_to = Datum()
        dt_to.from_datetime(date_to)
        dt_to.end_of_day()

        query = (
            self.book.session.query(Transaction)
            .join(Split)
            .filter(Split.account_guid == self.account.guid)
            .filter(Transaction.post_date >= dt_from.date, Transaction.post_date <= dt_to.date)
            .order_by(Transaction.post_date)
        )
        return query.all()