The life time sales total is not changing on updating the status of the order - magento-1.9

I want to update the status of quite a few orders in bulk from pending to complete, and hence I am trying to do it in a programmatic way as there is no option in magento backend, for updating the status in bulk by using the method below.
require_once('app/Mage.php');
Mage::app();
Mage::init();
$order = Mage::getModel('sales/order')->loadByIncrementId('100010175');
//$order->setState(Mage_Sales_Model_Order::STATE_COMPLETE, true);
$order->setData('state', "complete");
$order->setStatus("complete");
$history = $order->addStatusHistoryComment('Order was set to Complete by our automation tool.', false);
$history->setIsCustomerNotified(false);
$order->save();
But when I update the status using the above method, only the status is getting updated to complete. But the order amount is not getting added up to the lifetime sales, that shows up on the dashboard main page.
Can anyone let me know, how the order amount also can be updated to the lifetime sales total, with the updating of the status of the order too?

The the order amount will be added to life time sales only if the invoice of the order is generated. So you need to create the invoice of the order also.
You can programmatically generate invoice of order by using the code given below.
$invoice = $order->prepareInvoice();
$invoice->register()->capture();
Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder())
->save();
$order->addStatusToHistory(Mage_Sales_Model_Order::STATE_PROCESSING,'Invoice generated successfully.');
$order->save();

Related

SSRS Subscription Schedule Started/Completed Events

I am pretty new to SSRS and I am trying to find a way to know when scheduled report is actually started on the server, when it has completed with success of failure and if it was canceled. As of now, I am using the ReportingService2010 class API to talk to the Report Server and the only way that it seems possible to me is to make something custom that checks the schedules and fire events at these times for the started events and to scan the folder where I'm going to save the report and when a new file is added, I know that the report has been successfully created, and maybe add a Timeout event after x time.
I don't think this is a really clean approach and I'm sure that you guys might have an easier answer because I'm sure that there must be a way to do it without manually scanning everything.
I used the ListJobs() method to access all the jobs that are currently running on the server but it doesn't seem to consider when a subscription is done, because, I only get results in the ListJobs() method when I manually click on "Run Now" for a specific report on the server.
Do you guys have any idea?
Thanks a lot,
Claude
There are few tables in 'ReportServer' database to provide you most of your information. e.g Subscriptions table has column as LastStatus, it gives how many subscriptions were processed and status of reports last run. e.g 'Done: 2 processed of 2 total; 0 errors' , 'Pending' ,
sample query would be like below, this is for getting a schedule but you can check and modify as you need.
Setup a new report with this query and schedule it as per your need to give you the status.
SELECT CAT.Name
,CAT.[Path] AS ReportPath
,SUB.LastRunTime
,SCH.NextRunTime
,CONVERT(VARCHAR(10), CONVERT(datetime, SCH.NextRunTime, 1), 101) As RunDate
,right(convert(varchar(32),SCH.NextRunTime,100),8) As RunTime
,SUB.[Description]
,SUB.EventType
,SUB.LastStatus
,SUB.ModifiedDate
,SCH.Name AS ScheduleName
FROM reportserver.dbo.Subscriptions AS SUB
INNER JOIN reportserver.dbo.Users AS USR
ON SUB.OwnerID = USR.UserID
INNER JOIN reportserver.dbo.[Catalog] AS CAT
ON SUB.Report_OID = CAT.ItemID
INNER JOIN reportserver.dbo.ReportSchedule AS RS
ON SUB.Report_OID = RS.ReportID
AND SUB.SubscriptionID = RS.SubscriptionID
INNER JOIN reportserver.dbo.Schedule AS SCH
ON RS.ScheduleID = SCH.ScheduleID
--Where CONVERT(VARCHAR(10), CONVERT(datetime, SCH.NextRunTime, 1), 101)
= CONVERT(VARCHAR(10), CONVERT(datetime, getDate()+1, 1), 101)
ORDER BY USR.UserName
,CAT.[Path];

How to immediately get timestamp value after update?

I've got some client code that is committing some data across some tables, in simple terms like so:
Client [Id, Balance, Timestamp]
ClientAssets [Id, AssetId, Quantity]
ClientLog [Id, ClientId, BalanceBefore, BalanceAfter]
When the customer buys an asset, I do the following pseudo code:
BEGIN TRANSACTION
GetClientRow Where ID = 1
Has enough balance for new asset cost? Yes...
Insert Into ClientAssets...
UpdateClient -> UPDATE Client SET Balance = f_SumAssetsForClient(1) WHERE ID = 1 and Timestamp = TS From Step 1;
GetClientRow Where ID = 1
Insert Into ClientLog BalanceBefore = Balance at Step 1, BalanceAfter = Balance at Step 5.
COMMIT
On step 4, the client row is updated in 1 update statement using a function 'f_SumAssetsForClient' that just sums the assets for the client and returns the balance of those assets. Also on Step 4, the timestamp is automatically updated.
My problem is, when I call GetClientRow again on Step 5, someone could have updated the clients balance, so when I go to write the log in Step 6, its not truly the balance after this set of steps. It would be the balance after a different write outside of this transaction.
If I could get the newly updated timestamp from the client row when I call UPDATE in Step 4, I could pass this to step to only grab the client row where the TS = the new updated TS. Is this possible at all? Or is my design flawed. I can't see a way out of the problem of stale data between step 5 and 6. I sense there is a problem in the table design but can't quite see it.
Step 1 needs to be SELECT ... FOR UPDATE. Any other data that needs to change also need to be "locked" FOR UPDATE.
That way, another thread cannot sneak in and modify those rows. They will probably be delayed until after you have COMMITted, or there might be a Deadlock. Either way, the thing you are worried about cannot happen. No timestamp games.
Copied from comment
Sounds like you need a step 3.5 that is SELECT f_SumAssetsForClient(1) then
store that value, then do the update, then write the log with the values - you
shouldnt have to deal with the timestamp at all -- or do the whole procedure as
a stored proc

What is the best way to update another table based on a certain condition ON UPDATE?

I'm having two tables subscription and subscription_event. A subscription_event can be one of the following types:
public enum SubscriptionEventType {
CREATED,
CANCELED,
CHARGED_SUCCESSFULLY,
CHARGED_UNSUCCESSFULLY,
EXPIRED,
TRIAL_STARTED,
TRIAL_ENDED,
WENT_ACTIVE, // Subscription went active and can be charged from now on.
WENT_PAST_DUE;
public Long getValue() {
return this.ordinal() + 1L;
}
}
What I want to do is to keep the state of subscription to the most recent event. The problem: Those events do not come in correct order. E.g. it is possible to get a CHARGED_SUCCESSFULLY event before a WENT_ACTIVE event.
So there are several way how I can accomplish what I need. First of all I can check the condition in my application layer and always set that "most recent" state based on the timestamp of the event.
Long subscriptionId = lastRecordedEvent.getSubscriptionId();
if(event.getTimestamp() > lastRecordedEvent.getTimestamp()) {
// Since the current event is more recent than all other events
// we also have to update the subscription state
subscriptionRepository.updateState(subscriptionId, event.getTimestamp());
}
However, I do not want to do this in my application layer. Another solution would be to use a TRIGGER on the subscription_event table and let that on decide whether to update the relevant subscription or not. The reason why I do not go for that just yet is because I know that triggers can be easily forgotten and also be a pain to maintain. Also I know one should take every other option into account before using a TRIGGER but since I am not a SQL/MySQL expert I'm not aware of all my options here.
So what would be the most practicable way to keep subscription up-to-date in this situation?
Insert your event as usual into the table and then execute the following
UPDATE subscriptions set state=events.state
FROM subscriptions inner join events on subscriptions.id = events.subscriptionID
Where events.SubscriptionId = ? and events.Timestamp =
(select max(timestamp) from events where events.SubscriptionId = ?)
You will need to pass parameters for the two ?s to be the subscription id of the event you just inserted
EDIT
An alternative approach is rather than have a status field in the database, create a view for your subscriptions and always query the view instead.
CREATE VIEW vw_subscriptions as
Select s.id, otherfields from subscription, coalesce(e.Status, 1) as status
from subscriptions s left outer join events e on s.id=e.subscriptionId
AND e.timestamp =
(select max(timestamp) from events where subscriptionId=s.id)
If you are worried about forgetting/maintaining the SQL or triggers, document them as comments in your repository functions and maintain all changes to the database as a change script that you store with your source code. That way your changes are all in your source control.

How to insert some processed data into another table automatically by ruby on rails?

example:
I have a Deposit Table => deposit = $100, date_added = Time.now, profit_percent = 0.01. user_id
The process => profit = deposit * profit_percent, date = Time.now
earning_history Table => profit , date, user_id
I want to do the process each month automatically and insert into earning history for all members. a month is based on date_added.1.month so it's differ for any member. The rake is not for infrequently jobs. Corn jobs maybe okay but how can I use it for all members with different date and time!
Can anyone help me, please guide me in details... any plugin suggestion, any workflow?
Edited:
Look I have an accounts table > Member chooses an account
I have a deposits table > Member deposits an amount
I have a profits table > it seeks in deposits and grab the amount and date_added, process it and add the profit and date (Time.now) to profits table
how can I say the server to do this automatically for profits table, to grab amount, process it and add it to profits table for all members! I know SQL code also ruby's, I just don't know how to communicate with server to do this! Model, Controller?!
As I know in MVC, browser sends command controller and controller connect model and model connect to database then it returns to controller then view then browser.
I want only model and database do this for my application, not browser command. :-s
"whenever"(https://github.com/javan/whenever) gem should solve your issue. Take a look at this Rails cast by Ryan Bates again: http://railscasts.com/episodes/164-cron-in-ruby
Use https://github.com/javan/whenever
whenever schedule.rb
set :output, "somewhere/logs/cron.log"
#This will be executed everyday after midnight.
every :day, :at => '0:1am' do
rake "process_monthly_earning"
end
process_monthly_earning.rake
implement your logic here
Or you can implement a after_save hook in Deposit model.
after_save :process_monthly_earning
private:
def process_monthly_earning
if new_record? #use it if then earnings are editable
#check if any monthly earnings are there, if any then update else create
else
#adjust the earning
end
end

Check for a date/time conflict MySQL

OK... So I have a calendar, in a custom PHP application built using CodeIgniter, which pulls its entries from a MySQL database. In the table containing the entry data, there are 3 fields that govern the date (start_date), time (start_time) and duration (duration) of the entry. Now, as the end-user moves an entry to a new date and/or time, the system needs to check against these 3 fields for any schedule conflicts.
Following are some vars used in the query:
$request_entry_id // the id of the entry being moved
$request_start_date // the requested new date
$request_start_time // the requested new time
$request_duration // the duration of the entry being moved (will remain the same)
$end_time = ($request_start_time + $request_duration); // the new end time of the entry being moved
My query used to check for a schedule conflict is:
SELECT t.id
FROM TABLE t
WHERE t.start_date = '$request_start_date'
AND (j.start_time BETWEEN '$request_start_time' AND '$end_time'))
AND t.id <> $request_entry_id
The above query will check for any entry that starts on the same date and time as the request. However, I also want to check to make sure that the new request does not fall within the duration of an existing entry, in the most efficient way (there's the trick). Any suggestions? Thanks in advance!
It's easier to figure out the logic if you first think about the condition for when there is no conflict:
The new event ends before the existing one starts, or starts after the existing event ends.
For there to be a conflict we take the negative of the above:
The new event ends after the existing one starts, and starts before the existing event ends.
In SQL:
SELECT t.id
FROM TABLE t
WHERE t.start_date = '$request_start_date'
AND ('$end_time' > t.start_time AND '$request_start_time' < addtime(t.start_time, t.duration))
AND t.id <> $request_entry_id