Exemplo n.º 1
0
/**
 * 2016-07-28
 * @see dfp_by_trans()
 * @param OP|int $payment
 * @param string $type
 * @return T|null
 */
function df_trans_by_payment($payment, $type)
{
    return dfcf(function ($paymentId, $type) {
        /** @var \Magento\Framework\DB\Select $select */
        $select = df_db_from('sales_payment_transaction', 'transaction_id');
        $select->where('? = payment_id', $paymentId);
        /**
         * 2016-08-17
         * Раньше здесь стояло условие
         * $select->where('parent_txn_id IS NULL');
         * потому что код использовался только для получения первой (родительской) транзакции.
         * Убрал это условие, потому что даже для первой транзакции оно не нужно:
         * ниже ведь используется операция order, и транзакция с минимальным идентификатором
         * и будет родительской.
         * Для функции же @used-by df_trans_by_payment_last() условие
         * $select->where('parent_txn_id IS NULL');
         * и вовсе ошибочно: оно отбраковывает все дочерние транзакции.
         */
        /**
         * 2016-07-28
         * Раньше стояла проверка: df_assert_eq(1, count($txnIds));
         * Однако при разработке платёжных модулей бывает,
         * что у первых транзакций данные не всегда корректны.
         * Негоже из-за этого падать, лучше вернуть просто первую транзакцию, как нас и просят.
         */
        $select->order('transaction_id ' . ('first' === $type ? 'asc' : 'desc'));
        /** @var int $id */
        $id = df_conn()->fetchOne($select, 'transaction_id');
        return !$id ? null : df_trans_r()->get($id);
    }, [df_idn($payment), $type]);
}
Exemplo n.º 2
0
 /**
  * @test
  * 2016-12-01
  */
 public function t01()
 {
     /** @var CR $r */
     $cr = df_customer_resource();
     /** @var \Magento\Framework\DB\Select $select */
     $select = df_db_from($cr, $cr->getEntityIdField());
     xdebug_break();
 }
Exemplo n.º 3
0
Arquivo: db.php Projeto: mage2pro/core
/**
 * 2015-11-03
 * @param $table
 * @param string $cSelect
 * @param array(string => string) $cCompare
 * @return string|null
 */
function df_fetch_one($table, $cSelect, $cCompare)
{
    /** @var Select $select */
    $select = df_db_from($table, $cSelect);
    foreach ($cCompare as $column => $value) {
        /** @var string $column */
        /** @var string $value */
        $select->where('? = ' . $column, $value);
    }
    /**
     * 2016-03-01
     * @uses \Zend_Db_Adapter_Abstract::fetchOne() возвращает false при пустом результате запроса.
     * https://mage2.pro/t/853
     */
    return df_ftn(df_conn()->fetchOne($select));
}
Exemplo n.º 4
0
/**
 * 2016-03-15
 * How to programmatically check whether a customer is new or returning? https://mage2.pro/t/1617
 * @param int|null $id
 * @return bool
 */
function df_customer_is_new($id)
{
    return dfcf(function ($id) {
        return !$id || !df_conn()->fetchOne(df_db_from('sales_order', 'COUNT(*)')->where('? = customer_id', $id)->where('state IN (?)', [O::STATE_COMPLETE, O::STATE_PROCESSING]));
    }, [$id]);
}
Exemplo n.º 5
0
 /**         
  * @used-by execute()
  * @return MC|null
  * 2016-12-01
  * Отныне метод может (и будет) возвращать null в том случае,
  * когда учётная запись покупателя отсутствует в Magento,
  * а метод @see canRegister() вернул false (случай Blackbaud NetCommunity).
  */
 private function mc()
 {
     return dfc($this, function () {
         /** @var MCR $resource */
         $resource = df_customer_resource();
         /** @var \Magento\Framework\DB\Select $select */
         $select = df_db_from($resource, $resource->getEntityIdField());
         /**
          * 2015-10-10
          * 1) Полученный нами от браузера идентификатор пользователя Facebook
          * не является глобальным: он разный для разных приложений.
          * 2) Я так понял, что нельзя использовать одно и то же приложение Facebook
          * сразу на нескольких доменах.
          * 3) Из пунктов 1 и 2 следует, что нам нельзя идентифицировать пользователя Facebook
          * по его идентификатору: ведь Magento — многодоменная система.
          *
          * Есть выход: token_for_business
          * https://developers.facebook.com/docs/apps/upgrading#upgrading_v2_0_user_ids
          * https://developers.facebook.com/docs/apps/for-business
          * https://business.facebook.com/
          */
         // 2016-11-21
         // Добавил возможность идентификации покупателей по email.
         // Вроде бы Discourse поступает аналогично.
         $select->where(df_db_or(df_db_quote_into("? = {$this->fId()}", $this->c()->id()), !$this->c()->email() ? null : ['? = email', $this->c()->email()]));
         /**
          * @see \Magento\Customer\Model\ResourceModel\Customer::loadByEmail()
          * https://github.com/magento/magento2/blob/2e2785cc6a78dc073a4d5bb5a88bd23161d3835c/app/code/Magento/Customer/Model/Resource/Customer.php#L215
          */
         if (!df_are_customers_global()) {
             /**
              * @see \Magento\Customer\Model\CustomerRegistry::retrieveByEmail()
              * https://github.com/magento/magento2/blob/2e2785cc6a78dc073a4d5bb5a88bd23161d3835c/app/code/Magento/Customer/Model/CustomerRegistry.php#L104
              * @see \Magento\Customer\Model\ResourceModel\Customer::loadByEmail()
              * https://github.com/magento/magento2/blob/2e2785cc6a78dc073a4d5bb5a88bd23161d3835c/app/code/Magento/Customer/Model/Resource/Customer.php#L222
              */
             $select->where('? = website_id', df_store_m()->getStore()->getWebsiteId());
         }
         /**
          * 2016-03-01
          * @uses \Zend_Db_Adapter_Abstract::fetchOne() возвращает false при пустом результате запроса.
          * https://mage2.pro/t/853
          * @var int|false $customerId
          */
         $customerId = df_conn()->fetchOne($select);
         /** @var MC|null $result */
         if ($result = !$customerId && !$this->canRegister() ? null : df_om()->create(MC::class)) {
             if (!$customerId) {
                 $this->register($result);
             } else {
                 $resource->load($result, $customerId);
                 // Обновляем в нашей БД полученую от сервиса авторизации информацию о покупателе.
                 $result->addData(dfa_select($this->customerData(), $this->customerFieldsToSync()));
                 $result->save();
             }
             /**
              * 2015-10-08
              * Ядро здесь делает так:
              * $customerModel = $this->customerFactory->create()->updateData($customer);
              * @see \Magento\Customer\Model\AccountManagement::authenticate()
              * https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Customer/Model/AccountManagement.php#L381
              * Я так понимаю, ядро так делает потому, что выше там код:
              * $customer = $this->customerRepository->get($username);
              * и этот код необязательно возвращает объект класса @see \Magento\Customer\Model\Customer
              * а может вернуть что-то другое, поддерживающее интерфейс
              * @see \Magento\Customer\Api\Data\CustomerInterface
              * @see \Magento\Customer\Api\CustomerRepositoryInterface::get()
              */
             /**
              * По аналогии с @see \Magento\Customer\Model\AccountManagement::authenticate()
              * https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Customer/Model/AccountManagement.php#L382-L385
              */
             df_dispatch('customer_customer_authenticated', ['model' => $result, 'password' => '']);
             /**
              * 2015-10-08
              * Не знаю, нужно ли это на самом деле.
              * Сделал по аналогии с @see \Magento\Customer\Model\CustomerRegistry::retrieveByEmail()
              * https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Customer/Model/CustomerRegistry.php#L133-L134
              *
              * 2016-12-01
              * Однозначно нужно.
              */
             df_customer_registry()->push($result);
             // 2015-12-10
             // Иначе новый покупатель не попадает в таблицу «customer_grid_flat».
             $result->reindex();
         }
         return $result;
     });
 }