增加库存

        :param product_id: 商品ID
        :param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格，则此处赋值为空字符串即可
        :param quantity: 增加的库存数量
        :return: 返回的 JSON 数据包
338429
def add_stock(self, product_id, sku_info, quantity):
        
        return self._post(
            'merchant/stock/add',
            data={
                "product_id": product_id,
                "sku_info": sku_info,
                "quantity": quantity
            }
        )
1095509
def add_to_cart(item_id):
    
    cart = Cart(session['cart'])
    if cart.change_item(item_id, 'add'):
        session['cart'] = cart.to_dict()
    return list_products()
895286
def assignproduct(self, category_id, product, position=None):
        
        return bool(self.call(
            'catalog_category.assignProduct', [category_id, product, position])
        )
881503
function (params, successCallback, failCallback) {
    var t$ = this;
    if (!t$._check(params.productIdentifier)) { return }

    // ////////////////////////////////////////////////////////////////////////////
    var _cb = function (obj) {
      try {
        $bc_$2.IAP.NoticeCenter().remove(_cb);
        if (lodash.isObject(obj)) {
          var info = obj.info;
          var notifyType = obj.notifyType;

          if (info.productIdentifier === params.productIdentifier) {
            if (notifyType === t$.MessageType['ProductPurchased']) {
              successCallback && successCallback(info.productIdentifier, obj);
            } else if (t$.MessageType['ProductPurchaseFailed']) {
              failCallback && failCallback(info.productIdentifier, obj);
            }
          }
        }
      } catch (e) {
        console.error(e);
      }
    };

    // 注册一个消息回调
    $bc_$2.IAP.NoticeCenter().add(_cb);

    if ($bc_$2.pN) {
      // 发送购买请求
      $bc_$2.pN.iap.buyProduct(JSON.stringify({
        identifier: params.productIdentifier,
        quantity: params.quantity || 1
      }));
    } else {
      console.log('Romanysoft SDK simulation environment....');
      var obj = window.localStorage.getItem($bc_$2.IAP_SE_KEY) || JSON.stringify({});

      $bc_$2.IAP_SE_OBJ = JSON.parse(obj);
      var orgQuantity = 0;
      var saveQuantity = 0;
      if ($bc_$2.IAP_SE_OBJ[params.productIdentifier]) {
        orgQuantity = $bc_$2.IAP_SE_OBJ[params.productIdentifier];
        saveQuantity = orgQuantity + params.quantity || 1;
      } else {
        saveQuantity = params.quantity || 1;
      }

      $bc_$2.IAP_SE_OBJ[params.productIdentifier] = saveQuantity;
      window.localStorage.setItem($bc_$2.IAP_SE_KEY, JSON.stringify($bc_$2.IAP_SE_OBJ));

      // 模拟发送成功购买信息
      $bc_$2.IAP_SE_Wrapper.caller().fire({
        notifyType: t$.MessageType['ProductPurchased'],
        info: {
          productIdentifier: params.productIdentifier,
          quantity: saveQuantity
        }
      });

      // 模拟发送购买完成信息
      $bc_$2.IAP_SE_Wrapper.caller().fire({
        notifyType: t$.MessageType['ProductCompletePurchased'],
        info: {
          productIdentifier: params.productIdentifier,
          transactionId: 'transactionId' + Math.round(999),
          receipt: 'receipt' + Math.round(999)
        }
      });
    }
  }
324355
def inventory(self, source_id):
        
        if self.n_sources==0:
            print('Please run group_sources() to create the catalog first.')
        
        else:
            
            if source_id>self.n_sources or source_id<1 or not isinstance(source_id, int):
                print('Please enter an integer between 1 and',self.n_sources)
            
            else:
            
                print('Source:')
                print(at.Table.from_pandas(self.catalog[self.catalog['id']==source_id]).pprint())
                for cat_name in self.catalogs:
                    cat = getattr(self, cat_name)
                    rows = cat[cat['source_id']==source_id]
                    if not rows.empty:
                        print('\n{}:'.format(cat_name))
                        at.Table.from_pandas(rows).pprint()
509306
def get_products(self, product_ids):
        
        if self.product_set_id is None:
            raise ValueError('product_set_id must be specified')
        data = {'ids': product_ids}
        return self.client.get(self.base_url + '/products', json=data)
336919
def _process_image_id(self):
        
        try:
            image_info = self.image_id.strip().split(':')
            self.image_publisher = image_info[0]
            self.image_offer = image_info[1]
            self.image_sku = image_info[2]
            self.image_version = image_info[3]
        except Exception:
            self.image_publisher = None
826946
public function payConfirm($card_id, $quantity, $order_id)
    {
        $data = ['card_id' => $card_id, 'quantity' => $quantity, 'order_id' => $order_id];
        $url = "https://api.weixin.qq.com/card/pay/confirm?access_token=ACCESS_TOKEN";
        $this->registerApi($url, __FUNCTION__, func_get_args());
        return $this->httpPostForJson($url, $data);
    }
382123
private function getItemBySku(string $sku, int $quantity): CartItem
    {
        $qb = $this->connection->createQueryBuilder();
        $qb->select('*')
            ->from('dumplie_inventory_product')
            ->where('sku = :sku')
            ->setParameter('sku', $sku);

        $itemData = $this->connection->fetchAssoc($qb->getSQL(), $qb->getParameters());

        if (empty($itemData)) {
            throw QueryException::cartItemNotFound($sku);
        }

        return new CartItem(
            $itemData['sku'],
            $quantity,
            $itemData['price_amount'] / $itemData['price_precision'],
            $itemData['price_currency'],
            $this->mao->getBy([Metadata::FIELD_SKU => $itemData['sku']])
        );
    }
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 );
    }
690436
def load_stock_quantity(self):
        
        info = StocksInfo(self.config)
        for stock in self.model.stocks:
            stock.quantity = info.load_stock_quantity(stock.symbol)
        info.gc_book.close()
353449
def post(self, request, *args, **kwargs):
        
        POST = json.loads(request.body.decode('utf-8'))

        if 'product_pk' in POST and 'quantity' in POST:
            cart = ShoppingCartProxy(request)
            cart.add(
                product_pk=int(POST['product_pk']),
                quantity=int(POST['quantity'])
            )
            return JsonResponse(cart.products)

        return HttpResponseBadRequest()
674309
def get_qrcode(self, product_id=1):
        
        if product_id == '1' or product_id == 1:
            params = None
        else:
            params = {'product_id': product_id}

        return self._get('getqrcode', params=params)
232511
def product_id_change(self):
        '''
         '''
        context = dict(self._context)
        if not context:
            context = {}
        if context.get('folio', False):
            if self.product_id and self.folio_id.partner_id:
                self.name = self.product_id.name
                self.price_unit = self.product_id.list_price
                self.product_uom = self.product_id.uom_id
                tax_obj = self.env['account.tax']
                pr = self.product_id
                self.price_unit = tax_obj._fix_tax_included_price(pr.price,
                                                                  pr.taxes_id,
                                                                  self.tax_id)
        else:
            if not self.product_id:
                return {'domain': {'product_uom': []}}
            val = {}
            pr = self.product_id.with_context(
                lang=self.folio_id.partner_id.lang,
                partner=self.folio_id.partner_id.id,
                quantity=val.get('product_uom_qty') or self.product_uom_qty,
                date=self.folio_id.date_order,
                pricelist=self.folio_id.pricelist_id.id,
                uom=self.product_uom.id
            )
            p = pr.with_context(pricelist=self.order_id.pricelist_id.id).price
            if self.folio_id.pricelist_id and self.folio_id.partner_id:
                obj = self.env['account.tax']
                val['price_unit'] = obj._fix_tax_included_price(p,
                                                                pr.taxes_id,
                                                                self.tax_id)
605052
public function getUnique($sku, $store_id)
    {
        $existing = $this->get(array('sku' => $sku, 'store_id' => $store_id));

        if (empty($existing)) {
            return $sku;
        }

        $counter = 1;

        do {
            $modified = $sku . '-' . $counter;
            $counter++;
        } while ($this->get(array('sku' => $modified, 'store_id' => $store_id)));

        return $modified;
    }
863690
public function store($product_sku)
    {
        $product = Subbly::api('subbly.product')->find($product_sku);

        if (!Input::hasFile('product_image')) {
            return $this->jsonErrorResponse('"product_image" is required.');
        }

        $productImage = Subbly::api('subbly.product_image')->create(array(
            'image' => Input::file('product_image'),
        ), $product);

        return $this->jsonResponse(array(
            'product_image' => $productImage,
        ),
        array(
            'status' => array(
                'code'    => 201,
                'message' => 'ProductImage created',
            ),
        ));
    }
907845
def addMov(self, product, quantity=None, mode="buy", stop_limit=None,
               auto_margin=None, name_counter=None):
        """"""
        # ~ ARGS ~
        if (not isinstance(product, type('')) or
                (not isinstance(name_counter, type('')) and
                 name_counter is not None)):
            raise ValueError('product and name_counter have to be a string')
        if not isinstance(stop_limit, type({})) and stop_limit is not None:
            raise ValueError('it has to be a dictionary')
        # exclusive args
        if quantity is not None and auto_margin is not None:
            raise ValueError("quantity and auto_margin are exclusive")
        elif quantity is None and auto_margin is None:
            raise ValueError("need at least one quantity")
        # ~ MAIN ~
        # open new window
        mov = self.new_mov(product)
        mov.open()
        mov.set_mode(mode)
        # set quantity
        if quantity is not None:
            mov.set_quantity(quantity)
            # for best performance in long times
            try:
                margin = mov.get_unit_value() * quantity
            except TimeoutError:
                mov.close()
                logger.warning("market closed for %s" % mov.product)
                return False
        # auto_margin calculate quantity (how simple!)
        elif auto_margin is not None:
            unit_value = mov.get_unit_value()
            mov.set_quantity(auto_margin * unit_value)
            margin = auto_margin
        # stop limit (how can be so simple!)
        if stop_limit is not None:
            mov.set_limit('gain', stop_limit['gain'][0], stop_limit['gain'][1])
            mov.set_limit('loss', stop_limit['loss'][0], stop_limit['loss'][1])
        # confirm
        try:
            mov.confirm()
        except (exceptions.MaxQuantLimit, exceptions.MinQuantLimit) as e:
            logger.warning(e.err)
            # resolve immediately
            mov.set_quantity(e.quant)
            mov.confirm()
        except Exception:
            logger.exception('undefined error in movement confirmation')
        mov_logger.info(f"added {mov.product} movement of {mov.quantity} " +
                        f"with margin of {margin}")
        mov_logger.debug(f"stop_limit: {stop_limit}")