Laravel pessimistic lock not working like supposed to - mysql

I'm developing a little shopping website for entertainment purpose but I'm intending to apply the same code to a possible real shop website in the future.
So I have these "slots" that are meant to be bought, like a reservation slot for saving seats with numbers.
So people will buy the slots and save the seats, but I'm facing a race condition problem, even though I'm using lockForUpdate method, I can buy more slots than I have balance for.
My piece of code for when the user clicks "buy":
foreach ($tSlots as $mSlot) {
DB::beginTransaction();
$slot = Slots::where('id', $mSlot)->lockForUpdate()->first();
$wallet = $user::getWallet();
$wallet->lockForUpdate();
if (($slot->user_id === null) && ($wallet->balance >= $slot->price)) {
$wallet->balance -= $slot->price;
$slot->user_id = $user->id;
if ($wallet->update() && $slot->update()) {
$counter++;
DB::commit();
} else {
DB::rollBack();
}
} else {
DB::rollBack();
}
}
I'm keeping track of the slots count as I will display how many slots the users has successfully bought on the view after redirection.
If i intercept the request and edit it to make, let's say, 4 requests, each buying 5 different slots, I can manage to buy more than I have balance for, and my balance turns negative. Where am I messing it up?

Related

Spoof JSON (or other resource) while loading realtime Web site

I'm trying to write a userscript for a friend. The Website I'm writing it for (app.patientaccess.com) tells you what doctors appointments you have, (among other things). However, in order to write my userscript, I need to know how the app handle appointments for the following year.
At the moment, the only way to know is to wait until the end of the year when my friend starts making appointments for the following year. Since it's an Angular app, I'd rather, if possible, point it to a fabricated JSON file of my creation when the app requests that particular data. In that file I can give it some data for this year and next year and then I can see what happens with appointments made for the following year.
I'm hoping this can be done with an addon for Chrome or Firefox or perhaps some kind of free/open source software.
Thanks in advance.
I came up with a function that will accurately guess there year, given the day name, date and month, if it's within a couple of years either side of the current year.
function calculateYear(dayName, dayOfMonth, monthNum, returnDateObj) {
monthNum -= 1;
maxIterations = 3;
var startYear = (new Date()).getFullYear();
var dateObj = new Date(startYear, monthNum, dayOfMonth);
for (var i = 0; i < maxIterations; i++) {
dateObj.setYear(startYear + (1 * i));
if (dayName == daysOfTheWeek[dateObj.getDay()]) {
return (returnDateObj) ? dateObj : dateObj.getFullYear();
}
dateObj.setYear(startYear - (i + 1));
if (dayName == daysOfTheWeek[dateObj.getDay()]) {
return (returnDateObj) ? dateObj : dateObj.getFullYear();
}
}
return 'No Match';
}
It works a treat, as you can see here.

How to wait, then do something, in the GameScene

SKAction has waiting for duration abilities, for a period of time on a node. And seems to perform actions on nodes. Like moveTo, etc.
If I don't want that, rather I'd prefer to call functions within GameScene after a period of time, how do I do that with SpriteKit in the GameScene, not on a Sprite or other Node?
Are SKActions the way to do this? The only way to do this?
Yes. This question IS that ridiculously simple. I lack the heuristics and terminology to find an answer. Just keep looping around on how SKAction waits are calls on SKSprites for things like scale, rotation, etc, after time. Which isn't want I want/need.
Update:
Desired outcome, inside GameScene
doSetupStuff() // does some stuff...
waitForAWhile() // somehow wait, perhaps do somethings in here, while waiting
doSomethingElse() // does this after the waitForAWhile has waited
UPDATE 2:
What I think happens, again, inside didMove(to view...)
func wait(){
let timeToPause = SKAction.wait(forDuration: 3)
run(timeToPause)
}
let wontwait = SKAction.wait(forDuration: 3)
run(wontwait)
thisFunction(willnot: WAIT"it starts immediately")
wait()
thisFunction(forcedToWait: "for wait()'s nested action to complete")
UPDATE 3:
Found a way to get the delay without using SKActions. It's a little crude and brutal, but makes more sense to me than SKActions, so far:
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
print("I waited ten seconds before printing this!")
}
An option, as you cited, is to manage this externally. The way I typically manage this sort of thing is to have an externally run update cycle. One that
To drive this updater, you could use either CADisplayLink (which is what I use right now with my OpenGL renderer) or a dispatch source timer (which I have used with my SpriteKit engine). When you use an updated, you want to calculate the delta time. The tick handler could look something like:
func tickHandler() {
let currTime = NSDate().timeIntervalSince1970
let dt = lastTime - currTime // lastTime is a data member of the class
// Call all updaters here, pretend "updater" is a known updater class
updater.update(dt)
}
And updater's update method would look something like:
func update(deltaTime:NSTimeInterval) {
// Do your magic
}
I typically have a main overall updater running independent of what people are calling scenes. Example usage would be something like having an attract mode like in old school arcade games. There they show title screen, sample game play, high scores, rinse and repeat. Scenes would be title, game play, high score. Here you can your main updater manage the time and coordinate the construction/destruction/switching of the scenes. Note this implies having an overall scene manager (which is actually quite handy to have).
For your case, you could use this updater to drive the GameScene updater. It's updater could look something like:
func update(deltaTime:NSTimeInterval) {
switch state {
case .SetupState:
// noop?
println("I'm in setup") // Shown just so you can see there is a setup state
case .WaitState:
waitTime += deltaTime
if waitTime >= kWaitTime {
// Do whats you gots to do
doSomethingElse()
state = .NextState
}
case .NextState:
// blah blah blah blah
}
}
So the flow to do this call path from your driver (CADisplayLink or dispatch source) would be something like:
tickHandler -> master updater -> game scene updater
Some will def find this is perhaps a little heavy handed. I, on the other hand, find this very helpful. While there is obviously some time management and the loss of being able to fire and forget, it can help provide more control for orchestrating pieces, as well as arbitrarily changing state without having to worry about killing already queued actions. There is also nothing that says you still cannot mix SKAction. When I did use SpriteKit, I did all my updating this way along with some dispatched items. I only used SKAction to update hierarchy. Keep in mind that I used my own animation and physics system. So at least for me I had a lot less dependency on SpriteKit (it effectively was just a renderer for me).
Note you have to have your own means to handle pause and coming to foreground where your timer will need to be resynced (you only need to worry about tickHandler). Breakpoints also will cause time jumps.
You can use below function
#define ANIM_TIME 2
SKAction *customACtion = [SKAction customActionWithDuration: ANIM_TIME actionBlock:^(SKNode *node, CGFloat elapsedTime) {
// Do Something Here
}];
Another way to make something happen after a certain period of time is to make use of the 'current time' parm passed to update(). The following code will spawn a boss at intervals ranging from 20 to 30 seconds.
In your property definitions:
var timeOfLastBoss: CFTimeInterval = -1 //Indicate no boss yet
var timePerBoss = CFTimeInterval()
.
.
.
didMoveToView() {
...
timePerBoss = CFTimeInterval(Int.random(20...30))
'''
}
.
.
.
func update(currentTime: CFTimeInterval) {
...
spawnBossForUpdate(currentTime)
...
}
'
'
'
func spawnBossForUpdate(currentTime : CFTimeInterval) {
if ( timeOfLastBoss == -1 ) {timeOfLastBoss = currentTime}
if (currentTime - timeOfLastBoss < timePerBoss) {return}
// Rest of 'spawnBoss code
self.timePerBoss = CFTimeInterval(Int.random(20...30))
self.timeOfLastBoss = currentTime
}
One way, using SKActions, in Swift 3.0, looks like this:
DEFINE: aPatientlyWaitingFunction() at the top level of
GameScene class.
To cause a delay to happen before calling the above function, inside
didMove(to view...)
three ways I've found to do this using Actions:
All three ways seem to accomplish the exact same thing:
let timeToWait: TimeInterval = 3 // is seconds in SKAction thinking time
let waitSomeTime = SKAction.wait(forDuration: timeToWait)
// 1st way __________________________________________
// with a completion handler, the function can be called after Action
run(waitSomeTime) {self.aPatientlyWaitingFunction()}
// 2nd way __________________________________________
// as a completion to be done after action, in the run invocation:
run(waitSomeTime, completion: aPatientlyWaitingFunction)
// 3rd way __________________________________________
// alternatively, as part of a sequence of actions...
// Create a sequence, by making a run action from waitSomeTime and...
let thenDoThis = SKAction.run(aPatientlyWaitingFunction)
// then activate sequence, which does one action, then the next
run(SKAction.sequence([waitSomeTime, thenDoThis]))
// OR... for something different ____________________
////////////////////////////////////////////////////////
DispatchQueue.main.asyncAfter(deadline: .now() + timeToWait) {
self.aPatientlyWaitingFunction()
print("DispatchQueue waited for 3 seconds")
}

BigCommerce Stencil - Product Variant Stock Levels

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);

How could *data inter-dependent* <select> dropdowns in rails be populated quickly?

Users need to select a car.
We have several dropdowns when picking a car in order to pick the year, make, model and submodel.
Initially we don't know what to use for the select options for make/model/submodel as they are interdependent.
Once we pick year we use ajax to make requests which query ActiveRecord to populate the make dropdown.
Then when we pick make we use ajax to query and populate the model dropdown.
Then when we pick model we ajax to query and populate the submodel dropdown.
The problem is that this is a lot of separate network requests and in real-world conditions of low bandwidth, network issues, etc. quite often there are pauses severely impacting the user experience and occasionally leading to failures.
What approaches could help avoid all these network requests. In there an approach would could store all of the several thousand makes-model combinations on the client browser?
Currently the data is stored in a sql database accessed via ActiveRecord in the Rails framework. Each dropdown selection results in another query because yuou can't show populate and show make until you know year and you can't populate and show model until you know make. Same for submodel (though I've omitted submodel from the rest of this post for simplicity!).
Would session (http://simonsmith.io/speeding-things-up-with-sessionstorage/) storage of the JSON data for 10,000 combinations be possible? I see that sessionStorage can generally be relied on to have at least 5MB(5,200,000 bytes) so that gives me 5200000/10000= 520 bytes per record. Probably enough? If this persists for the session and across pages then in many cases we could actually kick this off on the previous page and if that had time to finish we wouldn't need the external call at all on the relevant (next) page.
We would need to refresh that data either occasionally or on demand as new year-make-models are added periodically (several times a year).
Ultimately I think the solution here could be very useful to a large number of applications and companies. The example here of picking a vehicle itself it used by dozens of major car insurance websites (who all do the multiple calls right now). The general appraoch of storing client side data for relatioship dependent sdropdown could also mapply in many other situations such as online shopping for make-brand-year-model. The backend framework to populate sessionStorage could also be done via different backend frameworks.
Another options might be to try google's Lovefield - https://github.com/google/lovefield More at https://www.youtube.com/watch?v=S1AUIq8GA1k
It's open source and works in ff, chrome, IE, Safari, etc.
Seems like sessionStorage might be better for our (considerable) business than basing it on a google 100 day dev thing - though it is open source.
Hello you can create the JSON object
for all the detail and based on the Value selected you can loop the array and populate the value. Let me
var cardetail = [{
"name": "MARUTI",
"model": [{
"name": "SWIFT",
"year": ["2005", "2006", "2008"]
}, {
"name": "ALTO",
"year": ["2009", "2010", "2011"]
}]
}, {
"name": "Hundai",
"model": [{
"name": "I20",
"year": ["2011", "2012", "2013"]
}, {
"name": "I20",
"year": ["2013", "2014", "2015"]
}]
}];
var currentCumpany = null;
var currentModel = null;
$(document).ready(function() {
$("#company").append("<option value=''>Select Company</option>");
for (i = 0; i < cardetail.length; i++) {
$("#company").append("<option value='" + cardetail[i].name + "'>" + cardetail[i].name + "</option>");
};
$("#company").change(function() {
for (i = 0; i < cardetail.length; i++) {
if (cardetail[i].name == $("#company").val()) {
currentCumpany = cardetail[i];
}
};
$("#model").html("");
for (i = 0; i < currentCumpany.model.length; i++) {
$("#model").append("<option value='" + currentCumpany.model[i].name + "'>" + currentCumpany.model[i].name + "</option>");
};
});
$("#company").change(function() {
for (i = 0; i < cardetail.length; i++) {
if (cardetail[i].name == $("#company").val()) {
currentCumpany = cardetail[i];
}
};
$("#model").html("");
for (i = 0; i < currentCumpany.model.length; i++) {
$("#model").append("<option value='" + currentCumpany.model[i].name + "'>" + currentCumpany.model[i].name + "</option>");
};
});
$("#model").change(function() {
for (i = 0; i < currentCumpany.model.length; i++) {
if (currentCumpany.model[i].name == $("#model").val()) {
currentModel = currentCumpany.model[i];
}
};
$("#year").html("");
for (i = 0; i < currentModel.year.length; i++) {
$("#year").append("<option value='" + currentModel.year[i] + "'>" + currentModel.year[i] + "</option>");
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="company"></select>
<select id="model"></select>
<select id="year"></select>
First, unless the requisite bandwidth is too expensive you could conceivably check the cache and then start making requests for popular makes/models/submodels as soon as (or even before) the user picks a year and cache it. There's even a full RDBMS for the browser now (full disclosure: its new and I haven't played with it much) which sits atop indexDB.
In terms of picking which ones to preload, you could do it based on units produced, units sold, car and driver magazine rankings, data-mining your actual users' requests, whatever.
I'm of the opinion that from a UX perspective you should at least be caching the requests the user actually makes and offering an option on load to jump right back to the last year/make/model they searched for rather than having them enter it all fresh each visit. Having popular vehicles preloaded only makes things easier. How much you want to push the envelope with predictive analysis of what a given user is likely to search for is up to your team skills/budget/time constraints.
I realize that this isn't a full answer per se, I'm not sure as stated the question has one (e.g. 'use this strategy/framework/library and all your problems will magically disappear! it even makes julienned fries!'). But if faced with this kind of problem my first thought is how to get more (hopefully relevant) data to the client sooner, which hopefully translates to faster (in the UX sense of fast).
I would also recommend that you have that popular data in json files to request rather than have to hit Rails/ActiveRecord/Database server each time. That alone would shave valuable milliseconds off your response times (not to mention usage load on those machines).
Its not like that data really changes, a 2009 Toyota Rav 4 has the same specs it did in...2009.

Paypal Recurring Payment issue

My application allows subscription services and i am using paypal's recurring payment for this. There according to there manual, the order i used is
SetExperssCheckOut-->GetExppressCheckOut-->DoExpressCheckOut->CreateRecurringPayment Profile.
On DoExpressCheckOut event iteself my first payment is made and after that on creating the recurring payment profile the next payment is made, ie if I have a daily subscription , on the end of 3rd day, no of payments made =4 (3 from the recurring payment and 1 from the get express checkout). I want only 3 payments at the end of 3rdday. The code I used is:
GetExpressCheckout getExpressCheckout = new GetExpressCheckout();
GetExpressCheckoutDetailsResponseType getExpressCheckoutResponse = getExpressCheckout.ECGetExpressCheckoutCode(token);
if (getExpressCheckoutResponse.Ack == AckCodeType.Success)
{
ExpressCheckout expressCheckout = new ExpressCheckout();
DoExpressCheckoutPaymentResponseType doExpressCheckoutResponse = expressCheckout.DoExpressCheckoutPayment
(
token,
getExpressCheckoutResponse.GetExpressCheckoutDetailsResponseDetails.PayerInfo.PayerID,
PayPalSettings.OrderAmount,
PaymentActionCodeType.Sale,
CurrencyCodeType.USD
);
if (doExpressCheckoutResponse.Ack == AckCodeType.Success)
{
//create Recurring Payment Profile
CreateRecurringPaymentsProfile createRecurringPaymentsProfile = new CreateRecurringPaymentsProfile();
CreateRecurringPaymentsProfileResponseType recurringPaymentProfileResponse = createRecurringPaymentsProfile.CreateRecurringPaymentsProfileCode(
doExpressCheckoutResponse.DoExpressCheckoutPaymentResponseDetails.Token,
doExpressCheckoutResponse.Timestamp,
PayPalSettings.OrderAmount,
1,
BillingPeriodType.Day,//BillingPeriodType.Month
CurrencyCodeType.USD
);
if (recurringPaymentProfileResponse.Ack == AckCodeType.Success)
{
//Do something
}
How can I make all payments under the recurring payment section ?
When using Recurring Payments the DoExpressCheckoutPayment API call isn't required. When the customer is redirected to PayPal for authentication they submit their agreement to the scheduled payments.
Try skipping the DoExpressCheckoutPayment API call and this should take care of the extra payment.
Let me know if you run into any issues.