Magento using operators in where clauses - database

My products have date_created and expires_in attributes. date_created is Magento date backend format while expires_in is a select that contains options as 1 week, 1 month etc.
Using those two attributes I'm trying to determine the total number of expired products. My idea was to write a query that selects:
products where date created + 1 week < now() AND expires_in = 1 week
AND
products where date created + 1 month < now() AND expires_in = 1 month
...
But I don't seem to be able to make even the first part of the first step to work:
$currentTimestamp = Mage::getModel('core/date')->timestamp(time());
$oneWeekTimestamp = Mage::getModel('core/date')->timestamp(strtotime("+1 week"));
$products = Mage::getResourceModel('catalog/product_collection')
->setStoreId(Mage::app()->getStore()->getId())
->addAttributeToSelect('')
...
//these are what i have tried so far:
$products->addAttributeToFilter('date_updated + ' . $oneWeekTimestamp , array('gt' => $currentTimestamp));
$products->addAttributeToFilter(new Zend_Db_Expr('date_updated + ' . $oneWeekTimestamp), array('gt' => $currentTimestamp));
$products->addAttributeToFilter("DATEDIFF($currentTimestamp, 'date_updated')" , array('gt' => 7));
$countExpired = $products -> count();
None of them seem to work. If possible I'd like the cross RDBMS solution.

You can do this in following way:
$currentTimestamp = Mage::getModel('core/date')->timestamp(time());
$oneWeekTimestamp = Mage::getModel('core/date')->timestamp(strtotime("+1 week"));
$oneweekDate=date("Y-m-d H:i:s",$oneWeekTimestamp);
$products->addAttributeToFilter('date_updated',array('date'=>true,'gt',$oneweekDate);

Related

React - read dates from excel file

I am having a weird issue when I was reading dates from excel files in a react application. When I read it, it comes out as some form of float but what's weird is that it only does this for 1th to 12th date of the month from 13th till 31th is fine.
What I mean is that a date like 01-01-81 gets converted to 29587.00013888889
but 13-01-81 remains in its original.
I found this one solution from here How to read date from an excel file in JavaScript. But it does not give back the original value.
Really appreciate any kind of help. Cheers.
The problem was that excel has its own way for dates and we need to convert it, into the format we need.
This is the method I used
const ExcelDateToJSDate = (date) => {
let converted_date = new Date(Math.round((date - 25569) * 864e5));
converted_date = String(converted_date).slice(4, 15)
date = converted_date.split(" ")
let day = date[1];
let month = date[0];
month = "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(month) / 3 + 1
if (month.toString().length <= 1)
month = '0' + month
let year = date[2];
return String(day + '-' + month + '-' + year.slice(2, 4))
}
You can simply pass the excel date and change the function according to the date format you need.

POWER BI - workaround possible for recursive calculation of my dax measure?

I have 2 tables on orders with the order validity date and in transit stock (stock reaching where the order will be serviced).
(using sample data to simplify for understanding)
I am looking for a final calculation like this in my final table -
have done the calculation till column 4 in power BI
if this was in excel i could have simply done
used_stock(2) = serviced(1) + used_stock(1)
avail_stock(2) = total_qty(2) - used_stock(2)
serviced(2) = min(order(2),avail_stock(2))
My base tables look like this - 
order table -
intransit table -
I have done the total_qty measure calculation by finding the cumulative sum of shipment quantity for the dates before selected value of order validity date.
I am trying to do the rest of the measures but ending up in circular references. Is there a way I can do it?
edit -
Clarifying it a bit more for the logic needed -
let's say the 2nd order is 15 and the 2nd shipment reaches on 24th, then the base data and output table should look like this -
With present proposed solution the table will erroneously look like -
Try with these below measures-
total_qty =
VAR current_row_date = MIN('order'[order valid till date])
RETURN
CALCULATE(
SUM(intrasit[quantity in shipment]),
FILTER(
ALL(intrasit),
intrasit[expected date of reaching] < current_row_date
)
)
used_stock =
VAR current_row_date = MIN('order'[order valid till date])
RETURN
CALCULATE(
SUM('order'[order quantity]),
FILTER(
ALL('order'),
'order'[order valid till date] < current_row_date
)
) + 0
avail_stock = [total_qty] - [used_stock]
serviced =
IF(
MIN('order'[order quantity]) <= [avail_stock],
MIN('order'[order quantity]),
[avail_stock]
)
Here is your final output-

How to get last month row sum in cakephp 3

I need to get last month transactions amount sum , I wrote query but getting error Error: Call to undefined function App\Controller\YEAR()
// sum of total received amount
$conditions['transaction_type']=1;
$conditions['AND']['YEAR(Transactions.created) >='] = YEAR('CURRENT_DATE - INTERVAL 1 MONTH');
$conditions['AND']['MONTH(Transactions.created) <='] = MONTH('CURRENT_DATE - INTERVAL 1 MONTH');
$query = $this->Transactions->find('all',['conditions'=>$conditions]);
$collection = new Collection($query);
$sumOfReceivedAmount = $collection->sumOf('amount');
$this->set('sumOfReceivedAmount',$sumOfReceivedAmount);
I have also tried using query builder
$query = $this->Transactions->find()
->where(function ($exp, $q) {
$year = $q->func()->year([
'created' => 'identifier'
]);
$month = $q->func()->month([
'created' => 'identifier'
]);
return $exp
->eq($year, $q->func()->year(['CURRENT_DATE - INTERVAL 1 MONTH']))
->eq($month, $q->func()->month(['CURRENT_DATE - INTERVAL 1 MONTH']));
});
For this code I am getting query like
SELECT
*
FROM
transactions Transactions
WHERE
(
year(created) = (
year(
'CURRENT_DATE - INTERVAL 1 MONTH'
)
)
AND month(created) = (
month(
'CURRENT_DATE - INTERVAL 1 MONTH'
)
)
)
Problem is this single quote 'CURRENT_DATE - INTERVAL 1 MONTH'
How can I remove this single quote ?
Similar to your other year() usage where you decalare the passed value to be an identifier, you'd have to declare your other values as literal values (or pass expression objects) so that they are inserted into the query as is, instead of being bound.
['CURRENT_DATE - INTERVAL 1 MONTH' => 'literal']
CakePHP also ships with methods to express similar functionality, specifically the FunctionsBuilder::dateAdd() method. Also when expressing CURRENT_DATE as a function the query builder will be able to convert the SQL for other DBMS like SqlServer, which has no CURRENT_DATE:
$q->func()->year(
[$q->func()->dateAdd($q->func()->CURRENT_DATE(), -1, 'MONTH')]
)
NOW() should work too:
$q->func()->dateAdd($q->func()->now(), -1, 'MONTH')
See also
Cookbook > Database Access & ORM > Query Builder > Using SQL Functions

Converting day, weeknr and year to date

I've been given an excel document in which worktime information is noted, this document contains certain columns which are being read by using SSIS in visual studio, after that the information is writen to a Database.
The week and year column contain the week number and the year, the columns Monday up to Friday contain information about how many working hours have been spent on a certain task on that day of the week.
What I'd like to do is take the WeekNr, Year and Day and convert these into a date. I've been trying to accomplish this by using a script component that converts a day number, week number and year to a date but so far I haven't been able to get the day number from the columns. In my opinion it would work best if used with a start and end date taking the first and last date of that week.
So my question is if someone knows how to accomplish this, or if I should try a different approach.
The script component:
public override void Input0_ProcessInputRow(Input0Buffer Row, CultureInfo cultureInfo, int day )
{
DateTime firstDayOfYear = new DateTime(Int32.Parse(Row.Jaar), 1, 1);
int firstWeek = cultureInfo.Calendar.GetWeekOfYear(firstDayOfYear, cultureInfo.DateTimeFormat.CalendarWeekRule, cultureInfo.DateTimeFormat.FirstDayOfWeek);
int dayOffSet = day - (int)cultureInfo.DateTimeFormat.FirstDayOfWeek + 1;
Row.TaskDates = firstDayOfYear.AddDays((Int32.Parse(Row.Week) - (firstWeek + 1)) * 7 + dayOffSet + 1);
}
Based on this answer, I think you want something like the following. This result gives you Monday's date, so you can just AddDays based on the column day of the week.
DateTime jan1 = new DateTime(Int32.Parse(Row.Jaar), 1, 1);
int daysOffset = DayOfWeek.Monday - jan1.DayOfWeek;
DateTime firstMonday = jan1.AddDays(daysOffset);
var cal = CultureInfo.CurrentCulture.Calendar;
int firstWeek = cal.GetWeekOfYear(firstMonday, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
var weekNum = Int32.Parse(Row.Week);
if (firstWeek <= 1)
{
weekNum -= 1;
}
var mondaysDate = firstMonday.AddDays(weekNum * 7);
var tuesdaysDate = mondaysDate.AddDays(1);

filter by last 13 months

I have controller that is using a standardSetController to implement pagination. I want to filter by the trade date for the last 13 months. The date literals don't have a filter by Last_N_Months:N
Is there a way I can filter by the last 13 months?
Here is my current query:
setCtrl = new ApexPages.StandardSetController(Database.getQueryLocator([select TransactionType__c, TradeDate__c, ShareClass__c,
SettlementDate__c, Name, Fund__r.Name, Fund__r.Id, FirstTransaction__c, DCPosition__c, DBR__r.Name, DBR__r.Id, DBR__c,
Amount__c from Transaction__c where DBRPrimaryContact__r.Contact__c =: con.Id ORDER BY TradeDate__c ASC]));
If I can't filter by 13 months, what is the total number of records that can be returned in a query? Is it 2000? There can be a significant number of records for this object and I want to limit the results by 13 months of data. Once I have that result set, I want to add filtering by options.
Thanks for any help.
Try the code below for filtering Date range - you can programatically calculate exact date ranges
DATE d1 = date.today();
Date d2 = d1.addMonths(-13);
Integer d3 = d2.daysBetween(d1);
System.debug('*************' + [SELECT Id FROM Account WHERE CreatedDate >= :d2 AND CreatedDate <=:d1]);
For filtering by date you have LAST_90_DAYS or LAST_N_DAYS:90 like this
SELECT Id FROM Account WHERE CreatedDate = LAST_N_DAYS:90
More info in this link
And yes the total number retrieved in one query is 2000

Resources