Add a purchase
Event params expected:
name: 'addPurchase'
id : string item id
date: DateTime date of purchase

@param Event $e
428475
public function preBuildListener(Event $e)
    {
        if ($e->getParam('name') == 'addPurchase') {
            $item = new ItemBuilder;
            $item->setId($e->getParam('id'))
                 ->setDate($e->getParam('date'));
            $this->addBuilder($item);
        }
    }
29424
def add(item, quantity: 1, unique: true)
      raise 'expecting an acts_as_purchasable object' unless item.kind_of?(ActsAsPurchasable)

      existing = (
        if unique.kind_of?(Proc)
          cart_items.find { |cart_item| instance_exec(item, cart_item.purchasable, &unique) }
        elsif unique.kind_of?(Symbol) || (unique.kind_of?(String) && unique != 'true')
          raise "expected item to respond to unique #{unique}" unless item.respond_to?(unique)
          cart_items.find { |cart_item| cart_item.purchasable.respond_to?(unique) && item.send(unique) == cart_item.purchasable.send(unique) }
        elsif unique.present?
          find(item)
        end
      )

      if existing
        if unique || (existing.unique.present?)
          existing.assign_attributes(purchasable: item, quantity: quantity, unique: existing.unique)
        else
          existing.quantity = existing.quantity + quantity
        end
      end

      if item.quantity_enabled? && (existing ? existing.quantity : quantity) > item.quantity_remaining
        raise EffectiveOrders::SoldOutException, "#{item.purchasable_name} is sold out"
      end

      existing ||= cart_items.build(purchasable: item, quantity: quantity, unique: (unique.to_s unless unique.kind_of?(Proc)))
      save!
    end
524636
def purchase!(payment: 'none', provider: 'none', card: 'none', email: true, skip_buyer_validations: false)
      return false if purchased?
      error = nil

      assign_attributes(
        state: EffectiveOrders::PURCHASED,
        purchased_at: Time.zone.now,
        payment: payment_to_h(payment),
        payment_provider: provider,
        payment_card: (card.presence || 'none'),
        skip_buyer_validations: skip_buyer_validations
      )

      Effective::Order.transaction do
        begin
          run_purchasable_callbacks(:before_purchase)
          save!
          update_purchasables_purchased_order!
        rescue => e
          self.state = state_was
          self.purchased_at = nil

          error = e.message
          raise ::ActiveRecord::Rollback
        end
      end

      raise "Failed to purchase order: #{error || errors.full_messages.to_sentence}" unless error.nil?

      send_order_receipts! if email

      run_purchasable_callbacks(:after_purchase)

      true
    end
1513
def add(self, cid, price, image, name, desc, major, market_time, property_alias, session, **kwargs):
        ''''''
        request = TOPRequest('taobao.product.add')
        request['cid'] = cid
        request['price'] = price
        request['image'] = image
        request['name'] = name
        request['desc'] = desc
        request['major'] = major
        request['market_time'] = market_time
        request['property_alias'] = property_alias
        for k, v in kwargs.iteritems():
            if k not in ('outer_id', 'props', 'binds', 'sale_props', 'customer_props', 'order_by', 'ww_status', 'post_free', 'location_state', 'location_city', 'is_3D', 'start_score', 'end_score', 'start_volume', 'end_volume', 'one_station', 'is_cod', 'is_mall', 'is_prepay', 'genuine_security', 'promoted_service', 'stuff_status', 'start_price', 'end_price', 'page_no', 'page_size', 'auction_flag', 'auto_post', 'has_discount', 'is_xinpin') and v==None: continue
            if k == 'location_state': k = 'location.state'
            if k == 'location_city': k = 'location.city'
            request[k] = v
        self.create(self.execute(request, session)['product'])
        return self
1370498
def onchange_partner_id(self):
        '''
        
        '''
        if self.partner_id:
            partner_rec = self.env['res.partner'].browse(self.partner_id.id)
            order_ids = [folio.order_id.id for folio in self]
            if not order_ids:
                self.partner_invoice_id = partner_rec.id
                self.partner_shipping_id = partner_rec.id
                self.pricelist_id = partner_rec.property_product_pricelist.id
                raise _('Not Any Order For  %s ' % (partner_rec.name))
            else:
                self.partner_invoice_id = partner_rec.id
                self.partner_shipping_id = partner_rec.id
                self.pricelist_id = partner_rec.property_product_pricelist.id
1015872
public function addCartItem($cartId, $cartItem)
    {
        $cartItem['id'] = count(session($this->itemsKey)) + 1;

        session()->push($this->itemsKey, $cartItem);
    }
339384
public function add($entity, $quantity)
    {
        if ($this->itemExists($entity)) {
            $cartItemIndex = $this->items->search($this->cartItemsCheck($entity));

            return $this->incrementQuantityAt($cartItemIndex, $quantity);
        }

        $this->items->push(CartItem::createFrom($entity, $quantity));

        event(new CartItemAdded($entity));

        return $this->cartUpdates($isNewItem = true);
    }
73510
function addToBasket( $objectID, $optionList, $quantity )
    {
        $object = eZContentObject::fetch( $objectID );
        $nodeID = $object->attribute( 'main_node_id' );
        $price = 0.0;
        $isVATIncluded = true;
        $attributes = $object->contentObjectAttributes();

        $priceFound = false;

        foreach ( $attributes as $attribute )
        {
            $dataType = $attribute->dataType();
            if ( eZShopFunctions::isProductDatatype( $dataType->isA() ) )
            {
                $priceObj = $attribute->content();
                $price += $priceObj->attribute( 'price' );
                $priceFound = true;
            }
        }

        if ( !$priceFound )
        {
            eZDebug::writeError( 'Attempted to add object without price to basket.' );
            return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED );
        }

        $currency = $priceObj->attribute( 'currency' );

        // Check for 'option sets' in option list.
        // If found each 'option set' will be added as a separate product purchase.
        $hasOptionSet = false;
        foreach ( array_keys( $optionList ) as $optionKey )
        {
            if ( substr( $optionKey, 0, 4 ) == 'set_' )
            {
                $returnStatus = eZShopOperationCollection::addToBasket( $objectID, $optionList[$optionKey] );
                // If adding one 'option set' fails we should stop immediately
                if ( $returnStatus['status'] == eZModuleOperationInfo::STATUS_CANCELLED )
                    return $returnStatus;
                $hasOptionSet = true;
            }
        }
        if ( $hasOptionSet )
            return $returnStatus;


        $unvalidatedAttributes = array();
        foreach ( $attributes as $attribute )
        {
            $dataType = $attribute->dataType();

            if ( $dataType->isAddToBasketValidationRequired() )
            {
                $errors = array();
                if ( $attribute->validateAddToBasket( $optionList[$attribute->attribute('id')], $errors ) !== eZInputValidator::STATE_ACCEPTED )
                {
                    $description = $errors;
                    $contentClassAttribute = $attribute->contentClassAttribute();
                    $attributeName = $contentClassAttribute->attribute( 'name' );
                    $unvalidatedAttributes[] = array( "name" => $attributeName,
                                                      "description" => $description );
                }
            }
        }
        if ( count( $unvalidatedAttributes ) > 0 )
        {
            return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED,
                          'reason' => 'validation',
                          'error_data' => $unvalidatedAttributes );
        }

        $basket = eZBasket::currentBasket();

        /* Check if the item with the same options is not already in the basket: */
        $itemID = false;
        $collection = $basket->attribute( 'productcollection' );
        if ( !$collection )
        {
            eZDebug::writeError( 'Unable to find product collection.' );
            return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED );
        }
        else
        {
            $collection->setAttribute( 'currency_code', $currency );
            $collection->store();

            $count = 0;
            /* Calculate number of options passed via the HTTP variable: */
            foreach ( array_keys( $optionList ) as $key )
            {
                if ( is_array( $optionList[$key] ) )
                    $count += count( $optionList[$key] );
                else
                    $count++;
            }
            $collectionItems = $collection->itemList( false );
            foreach ( $collectionItems as $item )
            {
                /* For all items in the basket which have the same object_id: */
                if ( $item['contentobject_id'] == $objectID )
                {
                    $options = eZProductCollectionItemOption::fetchList( $item['id'], false );
                    /* If the number of option for this item is not the same as in the HTTP variable: */
                    if ( count( $options ) != $count )
                    {
                        break;
                    }
                    $theSame = true;
                    foreach ( $options as $option )
                    {
                        /* If any option differs, go away: */
                        if ( ( is_array( $optionList[$option['object_attribute_id']] ) &&
                               !in_array( $option['option_item_id'], $optionList[$option['object_attribute_id']] ) )
                             || ( !is_array( $optionList[$option['object_attribute_id']] ) &&
                                  $option['option_item_id'] != $optionList[$option['object_attribute_id']] ) )
                        {
                            $theSame = false;
                            break;
                        }
                    }
                    if ( $theSame )
                    {
                        $itemID = $item['id'];
                        break;
                    }
                }
            }

            if ( $itemID )
            {
                /* If found in the basket, just increment number of that items: */
                $item = eZProductCollectionItem::fetch( $itemID );
                $item->setAttribute( 'item_count', $quantity + $item->attribute( 'item_count' ) );
                $item->store();
            }
            else
            {
                $item = eZProductCollectionItem::create( $basket->attribute( "productcollection_id" ) );

                $item->setAttribute( 'name', $object->attribute( 'name' ) );
                $item->setAttribute( "contentobject_id", $objectID );
                $item->setAttribute( "item_count", $quantity );
                $item->setAttribute( "price", $price );
                if ( $priceObj->attribute( 'is_vat_included' ) )
                {
                    $item->setAttribute( "is_vat_inc", '1' );
                }
                else
                {
                    $item->setAttribute( "is_vat_inc", '0' );
                }
                $item->setAttribute( "vat_value", $priceObj->attribute( 'vat_percent' ) );
                $item->setAttribute( "discount", $priceObj->attribute( 'discount_percent' ) );
                $item->store();
                $priceWithoutOptions = $price;

                $optionIDList = array();
                foreach ( array_keys( $optionList ) as $key )
                {
                    $attributeID = $key;
                    $optionString = $optionList[$key];
                    if ( is_array( $optionString ) )
                    {
                        foreach ( $optionString as $optionID )
                        {
                            $optionIDList[] = array( 'attribute_id' => $attributeID,
                                                     'option_string' => $optionID );
                        }
                    }
                    else
                    {
                        $optionIDList[] = array( 'attribute_id' => $attributeID,
                                                 'option_string' => $optionString );
                    }
                }

                $db = eZDB::instance();
                $db->begin();
                foreach ( $optionIDList as $optionIDItem )
                {
                    $attributeID = $optionIDItem['attribute_id'];
                    $optionString = $optionIDItem['option_string'];

                    $attribute = eZContentObjectAttribute::fetch( $attributeID, $object->attribute( 'current_version' ) );
                    $dataType = $attribute->dataType();
                    $optionData = $dataType->productOptionInformation( $attribute, $optionString, $item );
                    if ( $optionData )
                    {
                        $optionData['additional_price'] = eZShopFunctions::convertAdditionalPrice( $currency, $optionData['additional_price'] );
                        $optionItem = eZProductCollectionItemOption::create( $item->attribute( 'id' ), $optionData['id'], $optionData['name'],
                                                                             $optionData['value'], $optionData['additional_price'], $attributeID );
                        $optionItem->store();
                        $price += $optionData['additional_price'];
                    }
                }

                if ( $price != $priceWithoutOptions )
                {
                    $item->setAttribute( "price", $price );
                    $item->store();
                }
                $db->commit();
            }
        }

        return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE );
    }
1278686
public function addLogRecord($event) {
        /**
         * If logging is enabled
         */
        $module = \Yii::$app->getModule('cart');
        if ($module->enableLog) {

            $message = "UserId: $event->id";

            Yii::info($message, $event->name);
        }
    }
1170498
function enhancedEcommerceProductAction(track, action, data) {
  enhancedEcommerceTrackProduct(track);
  window.ga('ec:setAction', action, data || {});
}
854213
function addEvent (date, value) {
  date = this.toDate(date);
  if (!date) {
    return null;
  }
  var info = getDayInfo(this.dayInfo, date, true);
  if (!info) {
    return null;
  }
  var events = info.events;
  events.push(value);
  return events.length - 1;
}
1103303
public function addProductSaleElementAction()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
            return $response;
        }

        $event = new ProductSaleElementCreateEvent(
            $this->getExistingObject(),
            $this->getRequest()->get('combination_attributes', array()),
            $this->getCurrentEditionCurrency()->getId()
        );

        try {
            $this->dispatch(TheliaEvents::PRODUCT_ADD_PRODUCT_SALE_ELEMENT, $event);
        } catch (\Exception $ex) {
            // Any error
            return $this->errorPage($ex);
        }

        return $this->redirectToEditionTemplate();
    }
876864
@UiHandler("m_addButton")
    void addButtonClick(ClickEvent e) {

        if (null != m_newDate.getValue()) {
            m_dateList.addDate(m_newDate.getValue());
            m_newDate.setValue(null);
            if (handleChange()) {
                m_controller.setDates(m_dateList.getDates());
            }
        }
    }
594582
public function onPaymentDone(PaymentEvent $event)
    {
        $payment = $event->getPayment();
        if (!$payment instanceof OrderPayment) {
            return;
        }

        $order = $payment->getOrder();
        if ($order->getLocked()) {
            $order->setLocked(false);
            $this->updateOrder($order, $event);
        }

        $returnPath = null;
        $details = $payment->getDetails();
        if (array_key_exists('done_redirect_path', $details)) {
            $returnPath = $details['done_redirect_path'];
        } else {
            $type = $order->getType();
            if ($type === OrderTypes::TYPE_CART) {
                $returnPath = $this->urlGenerator->generate('ekyna_cart_payment');
            } elseif ($type === OrderTypes::TYPE_QUOTE) {
                throw new \BadMethodCallException('Not yet implemented');
            } elseif ($type === OrderTypes::TYPE_ORDER) {
                if ($this->authorization->isGranted('ROLE_ADMIN')) {
                    $returnPath = $this->urlGenerator->generate(
                        'ekyna_order_order_admin_show',
                        array('orderId' => $order->getId())
                    );
                } else {
                    $returnPath = $this->urlGenerator->generate(
                        'ekyna_cart_confirmation',
                        array(
                            'orderKey' => $order->getKey(),
                            'paymentId' => $payment->getId(),
                        )
                    );
                }
            }
        }

        if (null === $returnPath) {
            throw new LogicException('Unable to determine return path.');
        }

        $event->setResponse(new RedirectResponse($returnPath));
    }
21878
public static function paymentFailed(Purchase $purchase, $amount)
    {
        Log::info("Payment failed ({$purchase->purchaseId})");

        $purchase->buyer->sendEmail(
            'Your payment has failed',
            'emails.item.failed',
            [
                'total' => $amount,
                'item_name' => $purchase->item->name,
                'payment_id' => $purchase->purchaseId,
            ]
        );
    }
1269490
def track_purchase(self, user, items, total, purchase_id= None, campaign_id=None, 
					   template_id=None, created_at=None,
					   data_fields=None):
		

		call="/api/commerce/trackPurchase"

		payload ={}
	
		if isinstance(user, dict):
			payload["user"]= user
		else:
			raise TypeError('user key is not in Dictionary format')

		if isinstance(items, list):
			payload["items"]= items
		else:
			raise TypeError('items are not in Array format')

		if isinstance(total, float):
			payload["total"]= total
		else:
			raise TypeError('total is not in correct format')

		if purchase_id is not None:
			payload["id"]= str(purchase_id) 

		if campaign_id is not None:
			payload["campaignId"]= campaign_id

		if template_id is not None:
			payload["templateId"]= template_id		

		if created_at is not None:
			payload["createdAt"]= created_at

		if data_fields is not None:
			payload["data_fields"]= data_fields

		return self.api_call(call=call, method="POST", json=payload)
461251
public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('EcommerceBundle:Advert')->find($id);
        $purchase = $em->getRepository('EcommerceBundle:ProductPurchase')->findOneByAdvert($entity);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Advert entity.');
        }

        $form = $this->createEditForm($entity);
        
        return array(
            'entity'      => $entity,
            'purchase'   => $purchase,
            'form' => $form->createView(),
        );
    }