delete from database error after expiration - php

In my database I have many products that have a datecreated attribute.
I want to delete any product after an amount of time, like 10 or 20 days, when I refresh my home page.
This is my controller:
public function indexAction()
{
$datenow = new \DateTimeImmutable();
$datenowStringType = $datenow->format('Y-m-d');
$em = $this->getDoctrine()->getManager();
$products = $em->getRepository('ProductBundle:Product')->findAll();
foreach ($products as $produit) {
$CreatedDate = $produit->getCreatedDate();
$CreatedDate_StringType = $CreatedDate->format('Y-m-d');
$duree = '+'.$produit->getDuree();
$date_fin_duree = date('Y-m-d', strtotime($CreatedDate_StringType.$duree));
if ( strtotime($datenowStringType)<strtotime($date_fin_duree) ) {
$em->remove($produit);
}
}
array_values($products);
return $this->render('product/index.html.twig', array(
'products' => $products,
));
}
There are no errors returned, but the product isn't deleted. It could be a simple error but I searched a lot and I think it's a lack of concentration.
Please help?

$date = ''; // calculate your date here, it should be DateTime object
$qb = $em->createQueryBuilder();
$qb->delete('Product', 'p');
$qb->where('p.duree < :date');
$qb->setParameter('date', $date);

Related

Minor tweak needed

I've a system that I need to get a minor tweak made to and hope someone can advise.I've a custom field from a modal called 'cancle_order_reason' that needs to be added to a transactions table when a internal refund is made. Currently the table says just 'internal', but I want it to give the info from the 'cancle_order_reason' field for greater info.
From what I can see the relevant controllers are
packages/catalyst/controllers/dashboard/catalyst/orders.php which is where the modal is.
public function add_refund_order(){
$valt = Loader::helper('validation/token');
if (!$valt->validate('add_refund_order', $this->post('token'))) {
throw new Exception($valt->getErrorMessage());
}
Loader::model('proforms_item','proforms');
$pfo = ProFormsItem::getByID($this->post('orderID'));
$orderID = $this->request('orderID');
$question_set = $pfo->asID;
$setAttribs = AttributeSet::getByID($question_set)->getAttributeKeys();
foreach ($setAttribs as $ak) {
if($ak->getAttributeType()->getAttributeTypeHandle() == 'price_total'){
$value = $pfo->getAttributeValueObject($ak);
$db = Loader::db();
$avID = $value->getAttributeValueID();
$amount = money_format('%(#4n',$this->post('credit_amount'));
$ak->getController()->savePayment($avID,$amount,2);
}
}
$desc = trim($amount . ' ' . $this->request('cancle_order_reason'));
$date = date('Y-m-d');
$u = new User();
$data = array(
'ProformsItemID'=> $this->request('orderID'),
'action'=> 'Refund (Internal)',
'amount'=> $amount,
'description'=> $desc,
'uID'=> $u->uID,
'date' => $date
);
Loader::model('order_history', 'catalyst');
$oh = new OrderHistory();
$oh->addOrderHistoryItem($data);
$this->redirect('/dashboard/catalyst/orders/refund_added_order/?view_order='.$orderID);
}
and then the model controller:
models/attribute/types/price_total/controller.php
public function savePayment($avID=null, $amount, $credit=null, $transID='internal', $type='internal', $status=1){
// $credit == 2 is refund
$this->load();
$db = Loader::db();
if($this->getAttributeValueID()){
$avID = $this->getAttributeValueID();
}
$db->Execute("INSERT INTO atPriceTotalPayments (avID,amount,payment_date,credit,transactionID,type,status) VALUES(?,?,?,?,?,?,?)", [$avID, $amount, date('Y-m-d'), $credit, $transID, $type, $status]);
$this->updatePaidAmount($avID);
}
What is needed is for the details contained in field name ‘cancle_order_reason’ on the modal to be used in place of the ‘internal’ on $transID=‘internal’ on the models/attribute/types/price_total/controller.php. I’ve tested replacing ‘internal’ with some other text, and it updates, so it is the correct one to update.
I’ve tried:
$amount = money_format('%(#4n',$this->post('credit_amount'));
$transID = $this->request('cancle_order_reason');
$ak->getController()->savePayment($avID,$amount,$transID);
And nothing changes.
Changing the other controller so
$transID='internal'
becomes
$transID
results in an error:
Too few arguments to function
PriceTotalAttributeTypeController::savePayment(), 3 passed in
/home/bookinme/web/test.book-in.me/public_html/packages/catalyst/controllers/dashboard/catalyst/orders.php
on line 842 and at least 4 expected.

Need reorder sort_column Yii2

I need to reorder the column sort_order.
It is, select the position where to allocate the category and
recalculate the table.
For example, if I select category 3, insert at next and reorder sort_order.
I tried this code but something is wrong:
public function actionUp($id) {
$model = $this->loadModel($id);
$prev = Category::find()
->andWhere(['<', 'sort_order', $model->sort_order])
->orderBy(['sort_order' => SORT_DESC])
->limit(1)->one();
$current = $model->sort_order;
$model->sort_order = $prev->sort_order;
$prev->sort_order = $current->sort_order;
$model->save();
$prev->save();
return $
this->redirect(['index']);
}
How I can reorder this column?
Thank you for any help.
public function actionUp($id, $newPosition=null) {
$model = Category::findOne($id);
if(!$model)
throw new UserException('We were unable to find a matching record');
$prev = Category::find()
->andWhere(['<', 'sort_order', $model->sort_order])
->orderBy(['sort_order' => SORT_DESC])
->limit(1)->one();
if($prev)
$prevOrder = $prev->sort_order;
else
$prevOrder = 0;
$currentOrder = $model->sort_order;
If($newPosition)
$model->sortOrder = $newPosition;
else
$model->sort_order = $prevOrder;
$prev->sort_order = $currentOrder;
$model->save();
$prev->save();
return $this->redirect(['index']);
}
actionUp and Down work well, thank you very much
And when I'm going to add a new category, how can I indicate the position, based o parent_id?
public function create(CategoryCreateForm $form): Category
{
$channel = Category::create(
$form->parentId,
$form->name,
$form->code,
$form->description
);
$category = $this->categories->get($form->parentId);
$next = Category::find()
->andWhere(['<', 'sort_order', $category->sort_order])
->orderBy(['sort_order' => SORT_DESC])
->limit(1)->one();
if ($next)
$nexOrder = $next->sort_order;
else
$nexOrder = 0;
$currentOrder = $category->parent_id;
if ($newPosition)
$category->parent_id =$newPosition;
else
$category->parent_id = $nexOrder;
$next->sort_order = $currentOrder;
$prev->save();
$this->categories->save($category);
return $category;
}
It does not work this way, what is wrong.
I have this, in the Categoryservice
public function moveUp($id){
$model = $this->categories->get($id);
$prev = Category::find()
->andWhere(['<', 'sort_order', $model->sort_order])
->orderBy(['sort_order' => SORT_DESC])
->limit(1)->one();
if($prev)
$prevOrder = $prev->sort_order;
else
$prevOrder = 0;
$currentOrder = $model->sort_order;
$model->sort_order = $prevOrder;
$prev->sort_order = $currentOrder;
$prev->save();
$this->categories->save($model);
}
You were right, one of the categories did not have sort_order, it was null, and it gave the error.
I have one more question, how can it do the same but, when creating to choose where to position it?

Is there a way to return one or many items without repeating yourself?

I seem to be stuck. I have a funtion that calculates the salary. I am trying to make it so that I can specify one or many users when I call the function. But I ran into 2 problems. One is how could I construct the output result if I specify multiple user ids. And second problem is how not to repeat my code twice (for one and many users). It works fine if I only need to get it for one user.
I would like to be able to call it like this:
// Get salary for user id: 10
$salary = Salary::getSalary([10], '2018-12-01', '2018-12-31');
echo $salary->user->fullname;
echo $salary->salary->total;
echo $salary->checked;
// Get salary for users - 10, 20, 30
$salaries = Salary::getSalary([10, 20, 30, '2018-12-01', '2018-12-31');
foreach ($salaries as $salary) {
echo $salary->user->fullname;
echo $salary->salary->total;
echo $salary->checked;
}
Here is my function
public function getSalary($user_id, $date_from, $date_to)
{
$salary = new stdClass;
if ( count($user_id) == 1 ) {
$salary->user = new stdClass;
$salary->user->fullname = self::getUserById($user_id)->fullname;
$salary->user->phone = self::getPhone($user_id);
$salary->user->email = self::getUserById($user_id)->e_mail;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
} else if ( count($user_id) > 1 ) {
foreach ($user_id as $employee)
{
$salary->employee = new stdClass;
$salary->employee->fullname = self::getUserById($user_id)->fullname;
$salary->employee->phone = self::getPhone($user_id);
$salary->employee->email = self::getUserById($user_id)->e_mail;
$salary->employee->siawork = self::getUserById($user_id)->siawork;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
}
}
return $salary;
}
I think if when you call the function and there is only 1 entry, then you can convert this to an array so that you always use the same code to process the data, and build an array of the salary data to send back...
public function getSalary($user_id, $date_from, $date_to)
{
$salaries = [];
if ( !is_array($user_id) ) {
$user_id = [$user_id];
}
foreach ($user_id as $employee)
{
$salary->employee = new stdClass;
$salary->employee->fullname = self::getUserById($user_id)->fullname;
$salary->employee->phone = self::getPhone($user_id);
$salary->employee->email = self::getUserById($user_id)->e_mail;
$salary->employee->siawork = self::getUserById($user_id)->siawork;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
$salaries[] = $salary;
}
return $salaries;
}
You could if you wish, return a single entry if you want to by amending the last part of the code...
if ( count($user_id) == 1 ) {
$salaries = $salaries[0];
}
return $salaries;
}
Here's my solution for your class function. It looks like you were trying to return a single object and overwriting employee every time. If you can accept an array of ID's, it makes sense to return an array of salaries. Does this make sense?
public function getSalary($user_id, $date_from, $date_to)
{
//Return an array of salary objects to match your array of id inputs
$salary = [];
if ( ! is_array($user_id) ) {
//In case a non-array is entered
$user_id = [$user_id];
}
// A foreach will work even if there's only one user ID given,
// as long as it's an array (which it should be by this point)
foreach ($user_id as $id)
{
//Get your salary object by id
$this_user = new stdClass;
$this_user->user = new stdClass;
$this_user->user->fullname = self::getUserById($id)->fullname;
$this_user->user->phone = self::getPhone($id);
$this_user->user->email = self::getUserById($id)->e_mail;
$this_user->salary = self::getSalary($id, $date_from, $date_to);
$this_user->checked = self::isChecked($id, $date_from, $date_to);
//Put it in the output array
$salary[] = $this_user;
}
return $salary;
}
Note, please validate all these inputs! Make sure that putting in something unexpected to $user_id or $date_from or $date_to will not break everything without at least showing an error.

Codeigniter: No error but it won't insert data to database

Model:
function insertMonths($dr){
$cus = $this->db->query("SELECT * FROM purchase WHERE status=1 AND dr_no='$dr'");
return $cus->row();
$start = (new DateTime($cus->date_sold))->modify('+1 month');
$end = (new DateTime($cust->due_date))->modify('+1 month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
$query = $this->db->query("SELECT * FROM duedate WHERE dr_no='$dr'");
if($query->num_rows() > 0){
return false;
}else{
foreach ($period as $dt) {
$datas = array(
'cust_id' => $cust->cust_id ,
'mi' => $dt->format("Y-m-d") ,
'amount' => $cust->monthly_instlmnt,
'dr_no' => $dr,
'payment' => $cust->monthly_instlmnt
);
$this->db->insert('duedate', $datas);
}
}
}
Controller:
function ledger($id, $dr){
$this->load->view('layout/header');
$data['cust_data'] = $this->m->getData($id);
$datar['mos'] = $this->m->insertMonths($dr);
$this->load->view('receivables/ledger', $data, $datar);
$this->load->view('layout/footer');
}
Botton js code that links to ledger:
'<td><button type="button" class="btn btn-success">View</button></td>'
I want it to add $datas into table duedate when I enter link ledger/id/dr with conditions if there is duplicate data it won't add.
But the problem is it won't add eventhough there is no duplicate data.
Why do you have a return statement on line 2 of your function?
$cus = $this->db->query("SELECT * FROM purchase WHERE status=1 AND dr_no='$dr'");
return $cus->row();
If you neglected that, it won't go to your insert query since you already commanded the function to return.
Remove this (On line 2 of your function)
return $cus->row();

Laravel 5 ORM update request, like date_add

I beg to excuse me for my poor english.
So, I have Laravel 5 ORM, and i need to make request that should add date to some rows, like MySQL DATE_ADD. Input is single date interval and array of id's, output is rows of database, that was changed by adding date interval. Ideally, it should be one ORM request. I know that it is possible to use "bad" way and get all rows, update it in a code, and insert to database, but imho it's not good.
I hope answer will be link to some help site or some code if it's does not complicate you. Thanks for your attention!
public function update($id)
{
$user_id = Auth::user()->id;
$rep_task = RepTask::find($id);
$cl_task = \Request::has('json') ? json_decode(\Request::input('json'),true) : \Request::all();
$ids = [];
$task_id = $rep_task->task_id;
$rep_tasks = RepTask::where('task_id', '=', $task_id)
->select('id')
->get();
$new_date = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['new_date']);
$selected_task_date = date_create_from_format(self::DATE_MYSQL_FORMAT, $rep_task->start_date);
$diff = date_diff($selected_task_date, $new_date);
if(\Request::has('json'))
{
$ids = [1,2,3]; //this for easy understanding
DB::table('rep_task')
->whereIn('id', $ids)
->update(['start_date' => DB::raw('DATE_ADD(start_date, INTERVAL ' . $diff->d . ' DAY)')]);
$out_json = ['updated' => $ids];
return json_encode($out_json, JSON_UNESCAPED_UNICODE);
}
else
{
$start_date = 0;
$end_date = 0;
if (!isset($cl_task['name']) || !isset($cl_task['text']))
return "{'error':'columns are not defined'}";
if (isset($cl_task['start_date']) && isset($cl_task['end_date']))
{
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT, $cl_task['start_date']);
$start_date = $dt->format(self::DATE_MYSQL_FORMAT);
$dt = date_create_from_format(self::DATE_FULLCALENDAR_FORMAT,$cl_task['end_date']);
$end_date = $dt->format(self::DATE_MYSQL_FORMAT);
}
$rep_task->name = $cl_task['name'];
$rep_task->text = $cl_task['text'];
$rep_task->start_date = $start_date;
$rep_task->end_date = $end_date;
$rep_task->users_id = $user_id;
$rep_task->save();
}
$user_id = Auth::user()->id;
$tasks = Task::getAllTasksByUserFullcalendar($user_id);
return view(
'task.index',
[
'tasks' => $tasks
]
);
}

Categories