Reset automatic code number every year on laravel - php

guys! i have automatic code number for invoice. the automatic code number is "xx/month/year". i want "xx" in my automatic code number reset to 1 when the year change or every 1 january. this is my code
function noinvoice()
{
$latest = Pengiriman::latest()->first();
$month = date('m');
$year = date('Y');
if (!$latest) {
return '1/' . $month . '/' . $year;
}
$string = preg_replace("/[^0-9\.]/", '', $latest->noinvoice);
return sprintf($string + 1) . '/' . $month . '/' . $year;
}

You need to inspect your $latest object. If $latest doesn't exist OR its year doesn't match this year, then the invoice number is 1. Otherwise, it's $latest->noinvoice + 1.
You never mentioned where you store your invoice creation date, so I'll assume you use the default created_at Laravel approach. For this task you should add one more condition to your if statement:
if (!$latest or date('Y', strtotime($latest->created_at)) != $year) {

Related

Adding days to current date only once

I want to add particular days to current date. where days are taking from database field. It adds to the present date properly but at next day, date is going to update to the present date again.so how to keep date unchanged. It should take only once in PHP
$day= $cur["Days"];
if(($cur["Days"]) == 0){
$new = '';
} else {
$Date = date('20y-m-d');
$new = date("20y-m-d", strtotime($Date . ' + ' . $day . ' days'));
}
input if $day=1,$day+$new
output= jan19,this is the output of one row and my problem is it should remain as it is for this row but now for next day it is going to change to jan20 that should not happen

How to set dynamically a dateperiod/daterange in function of a given date?

I'm searching the way to write a function to set a date period / date interval with a given date....
First, let me explain the context :
I have an application to manage wedding inscriptions.
I use for my archives page a system with "seasonnal dates" like
2017-2018
2018-2019
2019-2020 etc.
Each season (or date period) starts the 1st september and finishes the 31 august, so for example 2017-2018 correspond to 2017-09-01 to 2018-08-31, 2018-2019 correspond to 2018-09-01 to 2019-08-31 etc.
So if I have a wedding date like 2019-01-23 I want to save the season corresponding, right here 2018-2019.
Actually I write this code :
//for example (I have a date object in fact in this $evenement var)
$evenement = "2019-01-23";
$start = Carbon::createFromFormat('Y-m-d', $evenement->copy()->subYear()->year . '09-01');
$end = Carbon::createFromFormat('Y-m-d', $evenement->year . '08-31');
if($evenement->between($depart, $fin)){
$saison = $depart->year . '-' . $fin->year;
}
If the date is after 2019-01-01, it works but not for before and not for the future date, (and not a function at this time)...
Can you help me to achieve this ? It will be very nice.
Thanks
I found the solution during the last night !
This is my function to get the "season" in function of the given date.
public static function getSeason($date)
{
if($date->month >= 9 && $date->month <= 12){
$annee1 = $date->year;
$annee2 = $annee1 + 1;
$saison = $annee1 . '-' . $annee2;
}
elseif($date->month >= 1 && $date->month <= 8){
$annee2 = $date->year;
$annee1 = $annee2 - 1;
$saison = $annee1 . '-' . $annee2;
}
return $saison;
}
So for example, if the date is 2018-10-03,
$season = "2018-2019";
And if date = 2019-04-21,
$season = "2018-2019";
What do you think about this function, can I optimize it ?
Thank you

How to get an employee's attendance if it does not log out on a particular date

I am looking for some basic attendance logic. What I have done so far is that employees can click on two different kinds of buttons and mark themselves as Signed In, Signed Out (status 1 and 2) using one button and Break Start, Break Over (status 3 and 4) using the other button.
Now when I calculate employee's total Sign In hours and total Break hours for a particular date I do something like below.
First iterate over a loop of Starting date and Ending date for which I want to see the working hours.
Now first of all check if the employee logged in on a particular date, by finding a status 1 entry of that date.
If the employee logged in on that date, then I fetch all attendance records for that date.
Now I iterate over this date's attendance records add up the time differences starting from first status 1 (i.e. Login) to next status and from next status (which can be either a break start 3 or a log out 2) till the next status (which can be either break over 4 or log in 1).
This is working good and my working hours' calculations are coming fine.
There is however one logical part that I am not able to understand i.e. if the employee does not logout on the same date for which I have fetched out the records, then the time span from last login or break start till the logout are not getting calculated. Because the final logged out status does not fall on the same date for which I fetched the records.
So, I need some help in understanding any suggestions how this can be managed and how can I calculate the working hours if the employee's logout status falls on a different date than login date.
Thanks in advance.
Here is some code.
public function getEmployeeAttendance($company_uid , $emp_uid)
{
for($m=1; $m<=12; $m++)
{
$mon = strtotime(date('Y-' . $m . '-00'));
$first = date("Y-m-01", $mon); // First Date Of cuRRENT mONTH
$last = date("Y-m-t", $mon); // Last Date Of cuRRENT mONTH
$date[] = range_date($first, $last);
}
$atten = array();
//echo "<pre>";
foreach($date as $dt)
{
foreach($dt as $d)
{
// A function to check if there was a status 1 on this date
$myAttendance = $this->Attendance_Model->myAttendance($company_uid , $emp_uid, $d);
# If Employee Signed In on This Date (i.e. Status was 1)
if(count($myAttendance) >0)
{
# Calculate Working Hours
$attenRec = $this->Attendance_Model->getAttendanceRecords($company_uid , $emp_uid, $d);
$signInHrs = 0;
$breakHrs = 0;
$workingHrs = 0;
for($i=0; $i<count($attenRec); $i++)
{
// Get this record's status
$status = $attenRec[$i]['status'];
// Get next record's status
if(!empty($attenRec[$i + 1]))
{
if($status == '1' || $status == '4') // Sign In or Break Over
{
$thisTime = strtotime($attenRec[$i]['atten_time']);
$nextTime = strtotime($attenRec[$i + 1]['atten_time']);
$diff = round(($nextTime - $thisTime) / 3600, 2);
$signInHrs += $diff;
}
if($status == '3') // Break Start
{
$thisTime = strtotime($attenRec[$i]['atten_time']);
$nextTime = strtotime($attenRec[$i + 1]['atten_time']);
$diff = round(($nextTime - $thisTime) / 3600, 2);
$signInHrs += $diff;
$breakHrs += $diff;
}
}
}
$onlySignInHrs = floor($signInHrs);
$remainingSignInHrs = $signInHrs - $onlySignInHrs;
$signInMinutes = round($remainingSignInHrs * 60);
$myAttendance['signInHrs'] = $onlySignInHrs . " Hrs : " . $signInMinutes . " Min";
$onlyBreakHrs = floor($breakHrs);
$remainingBreakHrs = $breakHrs - $onlyBreakHrs;
$breakMinutes = round($remainingBreakHrs * 60);
$myAttendance['breakHrs'] = $onlyBreakHrs . " Hrs : " . $breakMinutes . " Min";
$workingHrs = $signInHrs - $breakHrs;
$onlyWorkingHrs = floor($workingHrs);
$remainingWorkingHrs = $workingHrs - $onlyWorkingHrs;
$workingMinutes = round($remainingWorkingHrs * 60);
$myAttendance['workingHrs'] = $onlyWorkingHrs . " Hrs : " . $workingMinutes . " Min";
}
# Save This Date's Attendance
$atten[] = $myAttendance;
}
}
return $atten;
}

Filter based on days of the week in a PHP foreach

I am getting from Facebook Graph API the last 3 months page views information from all the accounts that I am admin with the following method:
$since_date = date('Y-m-d', strtotime('-3 months'));
$until_date = date('Y-m-d');
$page_views = $facebook->api('/' . $account['id'] . '/insights/page_views?since=' . $since_date . '&until=' . $until_date . '','GET');
After that I am using a php foreach loop (actually two) to get the desired information (page views and the date) in a required format (an array) like this:
foreach ($page_views['data'] as $page_view) {
$i = 0;
$len = count($page_view['values']);
foreach($page_view['values'] as $key => $page_view_values) {
$end_time = strval($page_view_values['end_time']);
$value = intval($page_view_values['value']);
echo '[\'' . substr($end_time, 0, -14) . '\', ' . $value . ']';
if ($i == $len - 1) {
continue;
} else {
echo ', ';
}
$i++;
}
Which output for further needs the following array:
(.....],['2013-04-02', 21], ['2013-04-03', 7], ['2013-04-04', 2], ['2013-04-05', 0], ['2013-04-06', 2], ['2013-04-07', 3], ['2013-04-08', 1], ['2013-04-09', 2], ['2013-04-10', 5], ['2013-04-11', 1], ['2013-04-12', 11], ['2013-04-13', 0],[.....)
All is working like it should, with the above array. I render a very nice chart but I want to filter it if I could based on days of the week. For exemple: I want an array like the one above with only the dates from Monday or Tuesday and so on... I need to filter somewhere in the second php foreach to return only the days that I want but how? What condition is used for this kind of needs? Or I should use other method, for example, query something else from the Facebook Graph Api? Any guidance is more than welcomed.
You could do for example a switch case based on the 3-letter code of the week day, and do something like this for each day:
$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));
It will output: Tue
This will allow you to filter by the week day. For example, you would only add to the array if the weekday code is Tue. All others will be skipped.
Added #arraintxo note:
date('N', strtotime($tempDate))
would return a numeric value of the week day (1 to 7, 1 being Monday and 7 Sunday), easier to compare.
I'd suggest something similar to the current reply, with slight adjustments:
$first=false; $cache=array(); $conv=new \Date('2000-01-01T00:00:00Z');
foreach ($page_views['data'] as $page_view) {
foreach($page_view['values'] as $key => $page_view_values) {
$end_time = strval($page_view_values['end_time']);
$ds=substr($end_time, 0, -14);
$value = intval($page_view_values['value']);
if(!isset($cache[$ds])
$cache[$ds]=(int)$conv->modify($ds)->format('N');
if($first){ echo ', '; $first=false; }
echo '[\'' . $ds . '\', ' . $value . ', '.$cache[$ds].']';
}
}
The day indices are now present as the third items of the arrays. Notice 1: a cache is used so that you look up every date only once. Notice 2: using a bool to not add leading separators is much cheaper than counting down from a count which is in turn cheaper than counting up to a count (what you did in the first place). Notice 3: This modifies the $conv object again and again, because I don't like creating many objects, and this ought to perform at least as well as the procedural style (date() and strtotime()).
In the first place I want to thank you all for the prompt replies, it was a great help received and I am very grateful for it. Based on your guidelines I solve my "issue" in the following manner:
$since_date = date('Y-m-d', strtotime('-3 months'));
$until_date = date('Y-m-d');
$page_views = $facebook->api('/' . $account['id'] . '/insights/page_views?since=' . $since_date . '&until=' . $until_date . '','GET');
foreach ($page_views['data'] as $page_view) {
$i = 0;
foreach($page_view['values'] as $key => $page_view_values) {
$end_time = strval($page_view_values['end_time']);
$ds = substr($end_time, 0, -14);
$value = intval($page_view_values['value']);
if (date('N', strtotime($ds)) != 1) {
continue;
} else {
if ($i==1) {
echo ', ';
}
$i=1;
echo '[\'' . $ds . '\', ' . $value . ']';
}
}
}
I can do this for every day of the week by using date('N', strtotime($ds)) for the corresponding number of the day. I receive the array that I want but if I can, i want to know if is possible to sum the numbers in the variables called $page_view_values['value'] (i want to make a comparison between the days in the week).

Get previous week number from php week number

I currently need to get the previous week from a variable that passes a php week number so if it is week 13 I will get week 12.
The problem I am facing is that if I just minus 1 from the original number if I am in week 1 it will return week 0 unless I create an if statement ie:
if($week==1)
{
$prev_week=52;
$prev_year=$year-1;
}
This is assuming that php counts the weeks from 1 and not 0. This seems a bit clumsy and I was thinking there may be a better way of doing this utilizing PHP's many date and time functions.
Try this:
$currentWeek = date( 'W' );
$today = strtotime( date( 'Y-m-d' ) ) - 7*24*60*60; // last week this day
// change 7 to 30 to see last year's week numer
$lastWeek = date( 'W', $today );
echo $currentWeek . '--' . $lastWeek;
Hope this helps.
Update
$lastWeekNumber = date( 'W', strtotime( 'last week' ) );
$PreviousWeek = date("W",strtotime("-1 week"));
HamZa's and web-nomad's answers helped me to go a bit further and make sure, I get the right year. Using date ('Y') can lead to unexpected behavior since it can happen, that week 1 belongs to the next or the previous year according to ISO-8601 (which is what is used in Europe). Instead use date ('o'). Otherwise it can happen that you jump from week 52 to week 1 of the previous year (because the start of the week is in the previous year according to date ('Y').
$jahr = 2014; // jahr means year
$kw = 52; // kw contains week
Using date ('Y')returns:
previousWeek: 51-2014
currentWeek: 52-2014
nextWeek: 01-2014
Using date ('o')returns:
previousWeek: 51-2014
currentWeek: 52-2014
nextWeek: 01-2015
See all the code together, e. g. for building forward and backward-links:
$kwBack['kw'] = date ("W", strtotime ($jahr. 'W' . str_pad ($kw, 2, 0, STR_PAD_LEFT). ' -1 week'));
$kwBack['jahr'] = date ("o", strtotime ($jahr. 'W' . str_pad ($kw, 2, 0, STR_PAD_LEFT). ' -1 week'));
$kwNext['kw'] = date ("W", strtotime ($jahr. 'W' . str_pad ($kw, 2, 0, STR_PAD_LEFT). ' +1 week'));
$kwNext['jahr'] = date ("o", strtotime ($jahr. 'W' . str_pad ($kw, 2, 0, STR_PAD_LEFT). ' +1 week'));
echo "previousWeek: " . $kwBack['kw'] . "-" . $kwBack['jahr'];
echo "<br>currentWeek: " . $kw . "-" . $jahr;
echo "<br>nextWeek: " . $kwNext['kw'] . "-" . $kwNext['jahr'];
echo "<br>";
// Build the links
$urlBack = $_SERVER['PHP_SELF'] . "?" . http_build_query ($kwBack);
$urlNext = $_SERVER['PHP_SELF'] . "?" . http_build_query ($kwNext);
echo "Previous week: ". $urlBack . "<br>";
echo "Next week: ". $urlNext;
I think I could be over complicating the problem - basically I need to obtain results from the database that appear in the previous weeks from the selected week therefore if there is a possibility of 54 weeks in a year all I really need to do is:-
if($week==1)
{
$year_minsued=$year-1;
$week_minused=54;
}
else
{
$week_minused=$week-1;
$year_minused=$year;
}
My select statement can then read:
SELECT SUM(post_price), SUM(total_price) FROM
database_table
WHERE client_id='$account_no'
AND
(year<='$year_minused' AND week<='$week_minused')
I have not tested this as yet but thinks it should do the job.
We know that a year can be between 52 or 53 weeks. So, I created here a function that receives the current week and the current year. If this is true, it is obvious that the previous week will be the last week of the previous year, so through the variable year that I gave to this function, I subtract 1 to have the value or the previous year and I try to know how many weeks this year has, in this case that will be the week before week 1 for example. Otherwise, I subtract 1 in the value of the current week to have the value of the previous week.
i hope i have helped
function PreviusWeekNumber($ActualWeek, $Year){
if($ActualWeek === 1){
$TransformYearIntolastYear = $Year -1;
$date = new DateTime;
$date->setISODate($TransformYearIntolastYear, 53);
$Result = ($date->format("W") === "53" ? 53 : 52);
}else{
$Result = $ActualWeek -1;
}
return $Result;
}
Check this
$year = 2013; // Retrieved from the DB
$week = 1;
$prev_week = date("W",strtotime($year. 'W'.str_pad($week, 2, 0, STR_PAD_LEFT). ' -1 week'));
echo $prev_week; // returns 52
A demo which shows the year:
$year = 2013; // Retrieved from the DB
$week = 1;
$prev_week = date("W - Y",strtotime($year. 'W'.str_pad($week, 2, 0, STR_PAD_LEFT). ' -1 week'));
echo $prev_week; // returns 52 - 2012

Categories