BigCommerce Stencil - Product Variant Stock Levels - json

A client wants to set up A/B testing on the Product Detail Page related to the stock_level of a product's variants. Once the user selects their options, if the quantity is less than 5, I'd show something like "Hurry, only 3 more in stock"...
I believe I have the correct Inventory settings enabled, because I can retrieve the stock_level of a product without options.
Has anyone had success pulling variant SKU stock_levels in stencil?
Thanks

This can be done using javascript in the assets/js/theme/common/product-details.js file. On initial page load and each time a product option is changed, there is a function updateView(data) that is called. The data parameter contains all the info you need for the selected variation.
Starting on line 285, replace this:
updateView(data) {
const viewModel = this.getViewModel(this.$scope);
this.showMessageBox(data.stock_message || data.purchasing_message);
with this:
updateView(data) {
const viewModel = this.getViewModel(this.$scope);
if(data.stock < "5") {
data.stock_message = "Hurry, only " + data.stock + " left!";
}
this.showMessageBox(data.stock_message || data.purchasing_message);

Related

implementing users notification on the same table or on a seperated relationed table (laravel)

i have a user and invoice table which i want to make notifications for them that they will be able to turn them on/off .
now my question is that should i add 5 columns for example on users table and 3 on invoice table to make it on or off or make 2 tables as below :
notification_list and : notification_user to make user to be able to turn the notification from user model and invoice on or off .
the problem here is that notification_user will be a massive table as soon as the users table growth . for every user i need to add 5 records at least .
i am using laravel and the tables and relations of it .so i can use morph relations but i still dont know which one is better to implement it inside the table or on a seperated table . thanks
If this can be toggled globally for all invoices all at once
You definitely need notification_list, but instead of notification_user I'd add extra column to users table or create something like users_preferences to store multiple user preferences. Creating separate table for each of preferences doesn't seem like a good solution
If this should be done for each invoice separately
You actually can't add extra columns to invoices and users table as you would be required to have one column for each user.
You have to use your solution Nr 2. But bare in mind that you don't need to create any records in table unless they differ from default behavior. That means you only add record to table when user toggles button. Also you can delete these records once invoice is no longer active. So this new table doesn't really grow as fast.
You can also use only one field for your user notification preferences. but this solution require good structuring.
It's base on the fact that what you need to track is just the state of the preference (on or off).
so save it as an integer containing the prefrence of the user. here is an example:
$preference1 = 1;
$preference2 = 0;
$preference3 = 0;
$preference4 = 1;
$preference5 = 0;
//the value to save is the integer result of the binary 01001
$preference = 1 * $preference1 + 2 * $preference2 + 4 * $preference3 + 8 * $preference4 + 16 * $preference5;
//or simply
$preference = bindec($pref5.$pref4.$pref3.$pref2.$pref1);
Now to check if a specific preference is enabled, use the bitwise comparison
if ($preference & 4) { //preference 3 has value 4
//preference 3 is on.
}
//you can also check multiple prefrences at the same time
if ($preference & 5 == 5) { //this is preference 3 and preference 1
//user has both preference enabled
}
You can also use it in your database request
$users = User::whereRaw("BIT_COUNT('prefrence' & 4)")->get();
//this will give you all the users having preference 3 enabled
To add more structure to this solution, you should declare constants in your user model
class User extends Authenticatable
{
const PREFRENCE1 = 1;
const PREFRENCE2 = 2;
const PREFRENCE3 = 4;
const PREFRENCE4 = 8;
const PREFRENCE5 = 16;
//...
}
//This way everything will make more sense like:
$users = User::whereRaw("BIT_COUNT('prefrence' & ".User::PREFERENCE3.")")->get();
if ($preference & User::PREFERENCE3) {
//preference 3 is on.
}
PS: Make sure that the integer size in the database in not under your number of preference to save.

Update planned order - two committed modifications, only one saved

I need to update two information on one object: the quantity (PLAF-gsmng) and refresh the planned order via the module function 'MD_SET_ACTION_PLAF'.
I successfully find a way to update each data separately. But when I execute the both solutions the second modification is not saved on the database.
Do you know how I can change the quantity & set the action on PLAF (Planned order) table ?
Do you know other module function to update only the quantity ?
Maybe a parameter missing ?
It's like if the second object is locked (sm12 empty, no sy-subrc = locked) ... and the modification is not committed.
I tried to:
change the order of the algorithm (refresh and after, change PLAF)
add, remove, move the COMMIT WORK & COMMIT WORK AND WAIT
add DEQUEUE_ALL or DEQUEUE_EMPLAFE
This is the current code:
1) Read the data
lv_plannedorder = '00000000001'
"Read PLAF data
SELECT SINGLE * FROM PLAF INTO ls_plaf WHERE plnum = lv_plannedorder.
2) Update Quantity data
" Standard configuration for FM MD_PLANNED_ORDER_CHANGE
CLEAR ls_610.
ls_610-nodia = 'X'. " No dialog display
ls_610-bapco = space. " BAPI type. Do not use mode 2 -> Action PLAF-MDACC will be autmatically set up to APCH by the FM
ls_610-bapix = 'X'. " Run BAPI
ls_610-unlox = 'X'. " Update PLAF
" Customize values
MOVE p_gsmng TO ls_plaf-gsmng. " Change quantity value
MOVE sy-datlo TO ls_plaf-mdacd. " Change by/datetime, because ls_610-bapco <> 2.
MOVE sy-uzeit TO ls_plaf-mdact.
CALL FUNCTION 'MD_PLANNED_ORDER_CHANGE'
EXPORTING
ecm61o = ls_610
eplaf = ls_plaf
EXCEPTIONS
locked = 1
locking_error = 2
OTHERS = 3.
" Already committed on the module function
" sy-subrc = 0
If I go on the PLAF table, I can see that the quantity is edited. It's working :)
3) Refresh BOM & change Action (MDACC) and others fields
CLEAR ls_imdcd.
ls_imdcd-pafxl = 'X'.
CALL FUNCTION 'MD_SET_ACTION_PLAF'
EXPORTING
iplnum = lv_plannedorder
iaccto = 'BOME'
iaenkz = 'X'
imdcd = ls_imdcd
EXCEPTIONS
illegal_interface = 1
system_failure = 2
error_message = 3
OTHERS = 4.
IF sy-subrc = 0.
COMMIT WORK.
ENDIF.
If I go on the table, no modification (only the modif. of the part 2. can be found on it).
Any idea ?
Maybe because the ls_610-bapco = space ?
It should be possible to update planned order quantity with MD_SET_ACTION_PLAF too, at least SAP Help tells us so. Why don't you use it like that?
Its call for changing the quantity should possibly look like this:
DATA: lt_acct LIKE TABLE OF MDACCTO,
ls_acct LIKE LINE OF lt_acct.
ls_acct-accto = 'BOME'.
APPEND lt_acct.
ls_acct-accto = 'CPOD'.
APPEND lt_acct.
is_mdcd-GSMNG = 'value' "updated quantity value
CALL FUNCTION 'MD_SET_ACTION_PLAF'
EXPORTING
iplnum = iv_plnum
iaenkz = 'X'
IVBKZ = 'X'
imdcd = is_mdcd "filled with your BOME-related data + new quantity
TABLES
TMDACCTO = lt_accto
EXCEPTIONS
illegal_interface = 1
system_failure = 2
error_message = 3.
So there is no more need for separate call of MD_PLANNED_ORDER_CHANGE anymore and no more problems with update.
I used word possibly because I didn't find any example of this FM call in the Web (and SAP docu is quite ambiguous), so I propose this solution just as is, without verification.
P.S. Possible actions are listed in T46AS table, and possible impact of imdcd fields on order can be checked in MDAC transaction. It is somewhat GUI equivalent of this FM for single order.

Opencart + unique product with options + stock control

I make bracelets and place them in my opencart store. Each bracelet is unique, so I have 1 in stock. But customer has to let me know the size of his/her wrist so I can adapt it.
Options ask me for quantities. So, I can not use them because I must enter a number or the option does not become visible.
What I need is:
bracelet B ---> tell me your wrist´s size: (here a drop down or a text box to let the customer choose or write).
Order will reads: Bracelet B... Size: 18cm.... xx $
Then, when the customer pays, Bracelt B is out of stock.
Now, I can do all that, but any time a customer adds an option, the bracelet keeps available.
So Order reads:
Bracelet B ... Size: 18cm... xx$
Bracelet B ... Size: 19cm... xx$ etc
function addToCart(product_id, quantity) {
quantity = typeof(quantity) != 'undefined' ? quantity : 1;
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + quantity,
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, .information, .error').remove();
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
}
/*adding Shadyyx solution*/
if (json['error']) {
$('#notification').html('<div class="error" style="display: none;">' + json['error'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('.error').fadeIn('slow');
}
/*end adding*/
}
});
}
In default OC You have the ability to disable ordering of out of stock products.
Simply go to the administration -> System -> Settings, click edit on Your store and navigate to the Options tab. Then scroll down to the Stock section and notice the Stock Checkout: option. If You select No and save the users won't be able to order the products that are not in stock.
This means that if You create a bracelet product with 1 piece in stock, add an option to it with one piece in stock and somebody order this one, it's stock will be immediately set to Not in stock and nobody will be able to order it again.
If You'd like to hide all the products that are not in stock after they are ordered, You have two options - either do this manually by disabling the product or You'd need to implement few modifications in to the getProducts() method for the product model to load only those products that are still in stock.
UPDATE regarding the comment: You are misunderstaning the options in OpenCart. One option for which You have the stock 1 piece is the size option, which may have different values, e.g. 15cm, 16cm, 17cm, 18cm, etc. All these values contained in one single size option for one single stock item mean that if I select any of them, after ordering the bracelet there will no more pieces left.
What You are telling is creating one option for 15cm with 1pcs stock, another option for 16cm with 1pcs stock, etc., thus having 1 piece in stock for each size - this is incorrect (i.e. misuse of product options). Nevertheless, even in this case, when different sizes have all one piece but the product itself has only one piece, after ordering first it should be out of the stock even there are options with stock left...
Step by step walkthrough:
Go to Your OC administration and log in.
Hover the mouse over the Catalog menu point and click on the Options entry
On this Options overview screen notice the Insert in the top-right corner - click it
Enter the Option's name, e.g. Wrist Size
Choose the Option's type, either Select or Radio (depending on how many possible values You want to have, more than 4, use Select)
Sort Order may be a numeric value (or when blank, will be filled with 0)
Now there is empty table underneath with one row containing only a button Add Option Value - by clicking this it will add a row with empty form fields to enter the Option's value; let's say we want to add wrist sizes from 15cm to 22cm => 8 values => click that button 8 times (be careful, after each click it will be moved downward as a new row with form fields will appear above it)
into that 8 rows enter all the necessary values, e.g. 15cm, 16cm, ..., 22cm as value's name and sort order to match Your needs (leaving blank may lead to inappropriately ordered values when displayed)
Click on Save button located at top-right corner.
Now navigate Yourself to the products overview, select the product You want to add this option to and click Edit in that row. Move to the Data tab and make sure the bracelet has these settings:
Quantity: 1
Subtract Stock: Yes
Out of Stock Status: Out of Stock
Then move to the Option tab and add the new option by typing the Option's name (Wrist Size) in the left area - after the Option is found, click on that label and a new Option (new tab) will be added to the view. Now make sure the Option is required and add all possible values while setting these settings to all of them:
Quantity: 1
Subtract Stock: Yes
The other option values depends on Your business model. Now Save the product and try to order it with any of the wrist sizes value. If You have the settings set for the store that the customer isn't possible to order the products that are out of stock, this should work for You.
Let me know if there is something that I missed (or if it still doesn't work).
UPDATE:
Here is one possible solution (not tested but I believe it will work out of the box or maybe there is only simple bug You may fix Yourself):
Open up the catalog/controller/checkout/cart.php and find this line (should be at 543):
$this->cart->add($this->request->post['product_id'], $quantity, $option);
and before this line directly add this code (You may want to do this via vQmod extension):
if ($product_info['quantity'] == 1 && $product_info['subtract'] == 1) {
$products = $this->cart->getProducts();
$already_added = false;
foreach ($products as $product) {
if ($product['product_id'] == $this->request->post['product_id']) {
$already_added = true;
break;
}
}
if ($already_added) {
return $this->response->setOutput(json_encode(array(
'error' => $this->language->get('text_product_already_added')
)));
}
}
Then open up this file catalog/language/english/checkout/cart.php and add this to the end:
$_['text_product_already_added'] = 'This product has allowed quantity of 1 piece and is already added to a cart. Remove it from the cart to be able to add it (e.g. with different size).';
This is all only as an example, You may edit the error message to meet Your requirements.
Warning: this is only a simple solution not letting the same user (or within the same session) to add the same product twice or more times into the cart but it won't prevent the same product being added and ordered at the very same time by two different users (or one user using two browsers, for example). For this edge case You'd need to implement some kind of product locking - after it is added to cart this is saved to a DB and nobody else would be able to add the same product into the cart. In this case it would be nice to store also the datetime when it was locked and have a cron job that will unlock this product (also with removing from the cart) so that the product is not locked for ever and is orderable by other users again...
EDIT for JS part:
Open up this file catalog/view/javascript/common.js and search for method function addToCart(product_id, quantity) { - in this file find this part:
if (json['success']) {
...
}
and after this one add this code:
if (json['error']) {
$('#notification').html('<div class="error" style="display: none;">' + json['error'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('.error').fadeIn('slow');
}
This should be enough.
UPDATE XYZ:
In PHP find this code what have we added:
return $this->response->setOutput(json_encode(array(
'error' => $this->language->get('text_product_already_added')
)));
and change it to this (then try):
$this->response->setOutput(json_encode(array(
'error' => $this->language->get('text_product_already_added')
)));
return;
The point is to see in console where the request is done to index.php?route=checkout/cart/add the response with either success or error message in response. Try for both cases to make sure You are looking at the correct request (in success You can see the success message on the top of page so You may be sure it was done) and then try again to receive error (for the same product) message - it should be contained in the response the same way as the success message is. If still doesn't work, try to change return; to exit;...
Unfortunately I can't comment your post.
I had the problem with error message not showing up, when trying to add the product twice.
I needed to add the JS code to /catalog/view/theme/*/product/product.tpl
Just search for "url: 'index.php?route=checkout/cart/add'" and add the code shadyxx postet right after
if (json['success']) { ... }

Creating a user generated list in flash

I'm trying to create a flash application that will keep track of user generated values. The app should basically allow the user to input the name of the item and it's cost. The total costs should then be added up to show a total value to the user. I can probably figure out how to add the values together, but I'm not really sure how to allow the user to create a list and then allow the user to save it. Can anyone point me towards a tutorial or point me in the right direction?
I am using variables to add user inputed numbers to come up with a total. The first problem is that actionscript 3.0 does not allow variables for texts. I just converted it to 2.0 to fix this. The second problem, is when I test the app and put in my values and click submit, I get NaN in the total values field. Is there a reason why it wouldn't add the values?
Here is the code I used for the submit button:
on (release) {
total = Number(rent) + Number(food) + Number(travel) + Number(entertainment) + Number(bills);
}
Am I missing anything?
Can I give the input text instance names and then give them variables? How are some ways to go about this?
Thanks for the help!
Have an object array, say for example
var stack:Array = new Array();
Then push the item name and it's cost to that array when user inputs, like
stack.push({item:AAA, cost:xx});
So that you can generate the list whenever you want with that array.
You have to see how this works in code. A list in actionscript could be stored inside an array, vector, dictionary or even an Object.
Var myList:Array = [];
myList.push({name: "item 1", cost: 5 });
myList.push({name: "item 2", cost: 7.5 });
If you want to grab the 'product' of "item 1" from the list, you have to create a function for that, lets call it getProductByName
function getProductByName(name:String):Object
{
for each(var product:Object in myList)
{
if (product.name === name) return product;
}
return null; // no match found
}
You can call that function like this:
var product = getProductByName("item 1");
trace(product.cost); // 5
And you can alter the product, so lets make it more expensive
product.cost += 1;
trace(product.cost); // 6
Have fun! If you are using classes, you would create one for the product, with public name and cost, and in that case you'de better use a vector, to ensure working with the right type.
This is what fixed the issue for me in action script 3.0:
myButton.addEventListener(MouseEvent.CLICK, addThem);
function addThem(e:MouseEvent)
{
totalField.text = String ( Number(field1.text) + Number(field2.text) + ....);
}
I also had to name the instances appropriately.

AdvancedDataGrid total sum of branch nodes

Introduction:
I have an AdvancedDataGrid displaying hierarchical data illustrated by the image below:
The branch nodes "Prosjekt" and "Tiltak" display the sum of the leaf nodes below.
Problem: I want the root node "Tavle" to display the total sum of the branch nodes below. When i attempted to do this by adding the same SummaryRow the sum of the root node was not calculcated correctly(Every node's sum was calculated twice).
dg_Teknikktavles = new AutoSizingAdvancedDataGrid();
dg_Teknikktavles.sortExpertMode="true";
dg_Teknikktavles.headerHeight = 50;
dg_Teknikktavles.variableRowHeight = true;
dg_Teknikktavles.addEventListener(ListEvent.ITEM_CLICK,dg_TeknikktavlesItemClicked);
dg_Teknikktavles.editable="false";
dg_Teknikktavles.percentWidth=100;
dg_Teknikktavles.minColumnWidth =0.8;
dg_Teknikktavles.height = 1000;
var sumFieldArray:Array = new Array(context.brukerList.length);
for(var i:int = 0; i < context.brukerList.length; i++)
{
var sumField:SummaryField2 = new SummaryField2();
sumField.dataField = Ressurstavle.ressursKey + i;
sumField.summaryOperation = "SUM";
sumFieldArray[i] = sumField;
}
var summaryRow:SummaryRow = new SummaryRow();
summaryRow.summaryPlacement = "group";
summaryRow.fields = sumFieldArray;
var summaryRow2:SummaryRow = new SummaryRow();
summaryRow2.summaryPlacement = "group";
summaryRow2.fields = sumFieldArray;
var groupField1:GroupingField = new GroupingField();
groupField1.name = "tavle";
//groupField1.summaries = [summaryRow2];
var groupField2:GroupingField = new GroupingField();
groupField2.name = "kategori";
groupField2.summaries = [summaryRow];
var group:Grouping = new Grouping();
group.fields = [groupField1, groupField2];
var groupCol:GroupingCollection2 = new GroupingCollection2();
groupCol.source = ressursTavle;
groupCol.grouping = group;
groupCol.refresh();
Main Question: How do i get my AdvancedDataGrid's (dg_Teknikktavles) root node "Tavle" to correctly display the sum of the two branch nodes below?
Side Question: How do i add a red color to the numbers of the root node's summary row that exceed 5? E.g the column displaying 8 will exceed 5 in the root node's summary row, and should therefore be marked red
Thanks in advance!
This is a general answer, without code examples, but I had to do the same just couple of days ago, so my memory is still fresh :) Here's what I did:
Created a class A to represent an item renderer data, extended it from Proxy (I had field names defined at run time), and let it contain a collection of values as it's data member. Once accessed through flash_proxy::getPropery(fieldName) it would find a corresponding value in the data member containing the values and return it. Special note: implement IUID, just do it, it'll save you couple of days of frustration.
Extended A in B, added a children property containing ArrayCollection of A (don't try to experiment with other collection types, unless you want to find yourself examining tons of framework code, trust me, it's ugly and is impossible to identify as interesting). Let B override flash_proxy::getPropery - depending of your compiler this may, or may not be possible, if not possible - call some function from A.flash_proxy::getPropery() that you can override in B. Let this function query every instance of A, which is a child of B, asking the same thing, as DataGrid itself would, when building item renderers - this way you would get the total.
When creating a data provider. Create an ArrayCollection of B (again, don't try to experiment with other collections--unless you are ready for lots of frustration). Create Hierarchical data that uses this array collection as a source.
Colors - that's what you use item renderers for, just look up any tutorial on using item renderers, that must be pretty basic.
In case someone else has the same problem:
The initial problem that everything was summed twice, was the result of using the same Array of SummaryField2 (sumFieldArray in the code) for both grouping fields(GropingField2 tavle and kategori)
The Solution to the main question: was to create a new array of summaryfields for the root node(in my intial for loop):
//Summary fields for root node
var sumFieldRoot:SummaryField2 = new SummaryField2();
sumFieldRoot.dataField = Ressurstavle.ressursKey + i;
sumFieldRoot.summaryOperation = "SUM";
sumFieldArrayRoot[i] = sumFieldRoot;
Answer to the side question:
This was pretty much as easy as pointed out by wvxyw. Code for this solution below:
private function summary_styleFunction(data:Object, col:AdvancedDataGridColumn):Object
{
var output:Object;
var field:String = col.dataField;
if ( data.children != null )
{
if(data[field] >5){
output = {color:0xFF0000, fontWeight:"bold"}
}
else {
output = {color:0x006633, fontWeight:"bold"}
}
//output = {color:0x081EA6, fontWeight:"bold", fontSize:14}
}
return output;
}