I am making a report in which user can check due balance of them invoice day wise like between 1-30 days how many amount due. between 30-60 days how many amount due etc for that I have make below function.
I don't know how can I optimize this process time.
public function yajraAgingARSummaryByDueDate()
{
$customerData = GenerateInvoice::select('orders.customer_id','customers.first_name', 'customers.last_name','customers.terms','customers.account_id','customers.account_suffix','invoice.due_date','invoice.invoice_number')
->leftJoin('orders','orders.id','=','invoice.order_id')
->leftJoin('customers', 'customers.id', 'orders.customer_id')
->whereDate('invoice.due_date','<=',date('Y-m-d'))
->whereNotNull('orders.customer_id')
->where('invoice.is_invoice_paid','=','no')
->whereNull('invoice.deleted_at')
->groupBy('orders.customer_id')
->get();
$resultArr = [];
if(count($customerData))
{
foreach($customerData as $key => $row)
{
$current = 0;
$b_1_30 = 0;
$b_31_60 = 0;
$b_61_90 = 0;
$b_over_90 = 0;
$total_ar = 0;
$balance = 0;
$invoiceData = GenerateInvoice::select('invoice.id')
->leftJoin('orders','orders.id','=','invoice.order_id')
->where('orders.customer_id',$row['customer_id'])
->whereDate('invoice.due_date','<=',date('Y-m-d'))
->whereNotNull('orders.customer_id')
->whereNull('invoice.deleted_at')
->where('invoice.is_invoice_paid','=','no')
->get();
if(count($invoiceData))
{
foreach($invoiceData as $row1)
{
$data = GenerateInvoice::select(DB::raw("abs(DATEDIFF(STR_TO_DATE(due_date, '%Y-%m-%d'),CURDATE())) AS Days"),'orders.total_order_value','payments.payment_amount')
->selectRaw(' (select sum(auto_cash_distributions.payment_amount) from auto_cash_distributions where auto_cash_distributions.order_id = invoice.order_id and payment_amount is not null ) as acd_payament_amount ')
->leftJoin('orders','orders.id','=','invoice.order_id')
->leftJoin('payments','payments.order_id','=','orders.id')
->where('invoice.id',$row1['id'])
->whereNotNull('orders.customer_id')
->whereNull('invoice.deleted_at')
->whereNull('payments.deleted_at')
->where('invoice.is_invoice_paid','=','no')
// ->groupBy('payments.invoice_id')
->first();
$days = $data['Days'];
$acd_payament_amount = !(empty($data['acd_payament_amount'])) ? $data['acd_payament_amount'] : 0;
$payment_amount = $data['payment_amount'] + $acd_payament_amount;
$amount = $data['total_order_value'] - $payment_amount;
// H 30/12
$amount = $amount;
$balance =$balance + $amount;
$total_ar = $total_ar + $amount;
// $total_ar = $amount;
if($days>90)
{
$b_over_90 = $b_over_90 + $amount;
}
else if($days <=90 && $days>=61)
{
$b_61_90 = $b_61_90 + $amount;
}
else if($days <=60 && $days>=31)
{
$b_31_60 = $b_31_60 + $amount;
}
else if($days <=30 && $days>=1)
{
$b_1_30 = $b_1_30 + $amount;
}
else
{
$current = $current + $amount;
}
}
}
$resultArr[$key]['account_id'] = $row['account_id'];
$resultArr[$key]['account_suffix'] = $row['account_suffix'];
$resultArr[$key]['first_name'] = $row['first_name'];
$resultArr[$key]['terms'] = $row['terms'];
$resultArr[$key]['due_date'] = $row['due_date'];
$resultArr[$key]['invoice_number'] = $row['invoice_number'];
$resultArr[$key]['balance'] = number_format($balance,2,'.','');
$resultArr[$key]['current'] = number_format($current,2,'.','');
$resultArr[$key]['b_1_30'] = number_format($b_1_30,2,'.','');
$resultArr[$key]['b_31_60'] = number_format($b_31_60,2,'.','');
$resultArr[$key]['b_61_90'] = number_format($b_61_90,2,'.','');
$resultArr[$key]['b_over_90'] = number_format($b_over_90,2,'.','');
$resultArr[$key]['total_ar'] = number_format($total_ar,2,'.','');
}
}
return Datatables::of($resultArr)
->addColumn('due_date',function($sql){
return !empty($sql['due_date']) ? date(get_config('date_format'),strtotime($sql['due_date'])) : '';
})
->addIndexColumn()
->rawColumns(['due_date'])
->make(true);
}
but this code is taking to much time to open. can anybody help me to optimize this code?
Related
I have a problem in my controller, it doesn't get the value of what declare in getCMnumber, it needs to get the format of getCMNumber to cm_number and automatically save it to the database, but there was an error that says "Trying to get property 'cm_number' of non-object"
this my controller
public function store(Request $request)
{
try {
$userEmployment = UserEmployment::where('emp_xuser',Auth::user()->status_xuser)->first();
$stages = "UR,DH,SO,ITOPS,ITSA,ITSEC";
$cm = new ChangeManagement;
$cm->cm_user = Auth::user()->status_xuser;
$cm->cm_number = self::getCMNumber();
$cm->cm_company = $request->xcompany;
$cm->cm_projectname = $request->xproject;
$cm->cm_requesttype = $request->xcmtype;
$cm->cm_userdep = $request->xdepartment;
$cm->cm_depthead = $userEmployment->emp_xdepartment;
$cm->cm_remarks = $request->xremarks;
$cm->cm_status = "Open";
$cm->cm_priority = "Standard";
$cm->cm_stages = $stages;
$cm->cm_current = "UR";
$cm->cm_Requested = $request->xdateneeded;
$cm->save();
$dh_email = "";
$stgray = explode(',', $stages);
$stagecount = count($stgray);
$count = 0;
while($count<$stagecount) {
$cmstg_stage = $stgray[$count];
switch($cmstg_stage){
case "UR":
$cmstg_stageuser = Auth::user()->status_xuser;
break;
case "DH":
$cmstg_user = self::getdephead($userEmployment->emp_xdepartment);
$dh_email = $cmstg_user;
break;
case "SO":
$cmstg_user = self::getdephead('System Owner');
break;
case "ITOPS":
$cmstg_user = self::getdephead('IT-Operations');
break;
case "ITSA":
$cmstg_user = self::getdephead('System Administrator');
break;
case "ITSEC":
$cmstg_user = self::getdephead('IT-System Administrator');
break;
}
$cmstg = new ChangeManangementStages;
$cmstg->prstg_prnumber = $cm->cm_number;
$cmstg->prstg_stage = $cmstg_stage;
$cmstg->prstg_stageuser = $cmstg_stageuser;
$cmstg->save();
$count++;
}
$firewallcount = 0;
while ($firewallcount < count($request->pr_item)) {
$firewall = new FirewallRequest;
$firewall->cm_fw_number =$cm->cm_number;
$firewall->fw_number =self::getfirewallNumber($cm->cm_number);
$firewall->fw_user =Auth::user()->status_xuser;
$firewall->fw_stage =$stages;
$firewall->fw_purpose =$request->xpurpose[$firewallcount];
$firewall->fw_expected_result =$request->xresult[$firewallcount];
$firewall->fw_server_instance =$request->xinstance[$firewallcount];
$firewall->fw_src_servername =$request->xsrcname[$firewallcount];
$firewall->fw_src_ip =$request->xsrcip[$firewallcount];
$firewall->fw_dest_servename =$request->xdestname[$firewallcount];
$firewall->fw_dest_ip =$request->xdestip[$firewallcount];
$firewall->fw_port_services =$request->xprsr[$firewallcount];
$firewall->fw_remarks =$request->xremarks[$firewallcount];
$firewall->fw_date_requested =$request->xdatecr[$firewallcount];
$firewall->save();
$firewallcount++;
}
if($request->hasFile('filename'))
{
$path = storage_path('ChangeManagement/'.$cm->cm_number);
if(!File::exists($path)) {
Storage::disk('fw_upload')->makeDirectory($cm->cm_number);
}
$uploadcount = 0;
while ($uploadcount < count($request->filename)) {
$filename = $request->filename[$uploadcount];
$prupload = new ChangeManagementUploads;
$prupload->pr_number =$pr->pr_number;
$prupload->filename =$filename->getClientOriginalName();
$prupload->save();
Storage::disk('fw_upload')->put( '/'.$cm->cm_number.'/'.$filename->getClientOriginalName(),File::get($filename));
$uploadcount++;
}
}
alert()->success('Request submitted',$cm->cm_number.' has been submitted for review and approval')
->showConfirmButton(
$btnText = '<a class="add-padding" href="'.route('cm.show',$cm->cm_number).'">View Request</a>', // here is class for link
$btnColor = '#fa0031',
['className' => 'no-padding'],
)->autoClose(false);
return redirect()->back();
}
catch (\Throwable $th)
{
alert()->error($th->getMessage())->showConfirmButton('Return', '#fa0031');
return redirect()->back();
}
getcmNUmber
public static function getCMNumber() {
$cm = ChangeManagement::orderBy('cm_id','desc')->first();
$last_ticket = $cm->cm_number;
$tick_date = substr($last_ticket, 0, 10);
$tick_date_now = date('Y-m-d');
$tick_pre = "-CM-";
$tick_start = "000";
$tick_num = substr($last_ticket, 14, 17);
if ($tick_date == $tick_date_now) {
$tick_d1 = $tick_date;
$tick_d2 = $tick_pre;
$tick_dx = $tick_num + 1;
$tick_d3 = str_pad($tick_dx, 3, '0', STR_PAD_LEFT);
} else {
$tick_d1 = $tick_date_now;
$tick_d2 = $tick_pre;
$tick_d3 = $tick_start;
}
return $tick_dt = $tick_d1.$tick_d2.$tick_d3;
}
Just try this:
public static function getCMNumber()
{
$cm = ChangeManagement::whereNotNull('cm_number')->orderBy('cm_id', 'desc')->first();
if (!$cm) {
return null;
}
$last_ticket = $cm->cm_number;
$tick_date = substr($last_ticket, 0, 10);
$tick_date_now = date('Y-m-d');
$tick_pre = "-CM-";
$tick_start = "000";
$tick_num = substr($last_ticket, 14, 17);
if ($tick_date == $tick_date_now) {
$tick_d1 = $tick_date;
$tick_d2 = $tick_pre;
$tick_dx = $tick_num + 1;
$tick_d3 = str_pad($tick_dx, 3, '0', STR_PAD_LEFT);
} else {
$tick_d1 = $tick_date_now;
$tick_d2 = $tick_pre;
$tick_d3 = $tick_start;
}
return $tick_dt = $tick_d1 . $tick_d2 . $tick_d3;
}
i hope you are all doing ok.
I have a weird problem that i just can't find a way to solve and the worst part I don't even know how to start looking for this problem over the internet.
Here's the case:
I make a DB request with the code below in Laravel:
public function previsao(){
$dados = [];
$tempoEntrega = 0;
$tempoTroca = 0;
$sugestaoCompra = 0;
$frequencia = 0;
$qnt = 0;
$qntI = 0;
$qntR = 0;
$todosOsDados = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->get();
foreach ($todosOsDados as $todId) {
$toIds[] = $todId->pecaId;
}
$idsUnicos = array_unique($toIds);
foreach ($idsUnicos as $idu) {
$ids[] = $idu;
}
foreach ($ids as $id) {
$peca = $this->TecManutencaoPecasM
->select('peca')
->where('id', $id)
->first();
$entrega = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->where('pecaId', $id)
->where('mov', 'i')
->select('data', 'dataComp', 'qnt', 'est_min')
->get();
foreach ($entrega as $e) {
$tempoEntrega += (Carbon::parse($e->data)->diffInDays(Carbon::parse($e->dataComp)));
$estMin = $e->est_min;
$qntI += $e->qnt;
}
$qntRetirada = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('dataComp', '!=', null)
->where('pecaId', $id)
->where('mov', 'r')
->select('qnt')
->get();
foreach ($qntRetirada as $qr) {
$qntR += $qr->qnt;
}
$qnt = $qntI - $qntR;
$uso = $this->TecManutencaoEstoquePecaRegM
->where('pecaId', $id)
->where('mov', 'r')
->select('data')
->get();
foreach ($uso as $u) {
$ultimaEntrega = $this->TecManutencaoEstoquePecaRegM
->join('tec_manutencao_pecas', 'tec_manutencao_estoque_peca_regs.pecaId', 'tec_manutencao_pecas.id')
->where('pecaId', $id)
->where('mov', 'i')
->where('data', '<=', $u->data)
->select('data')
->orderBy('data', 'DESC')
->first();
$tempoTroca += (Carbon::parse($u->data)->diffInDays(Carbon::parse($ultimaEntrega->data)));
$ultimaTroca = $u->data;
}
$frequencia = count($entrega);
$sugestaoCompra = round(($tempoTroca * ($tempoEntrega + $frequencia)) - ($qnt - $estMin));
$tempoTrocaMedio = count($uso) == 0 ? $tempoTroca : round($tempoTroca / count($uso));
$tempoAteEstminAcabar = $qnt * $tempoTrocaMedio;
$dataProxComp = $tempoAteEstminAcabar - round($tempoEntrega / count($entrega));
$diasTroca = $tempoTroca <= 0 ? round($tempoEntrega / count($entrega)) : $dataProxComp;
$dados[] = [
'id' => $id,
'peca' => $peca->peca,
'tempoEntrega' => $tempoEntrega <= 0 ? $tempoEntrega : round($tempoEntrega / count($entrega)),
'tempoTroca' => $tempoTroca <= 0 ? $tempoTroca : round($tempoTroca / count($uso)),
'qntProxComp' => $sugestaoCompra,
//'dataProxComp' => date('d/m/Y', strtotime($ultimaTroca.'+'.$diasTroca.' days')),
'dataProxComp' => $ultimaTroca == 0 || $ultimaTroca == null ?
date('d/m/Y', strtotime($ultimaEntrega->data.'+'.$diasTroca.' days')) :
date('d/m/Y', strtotime($ultimaTroca.'+'.$diasTroca.' days')),
'qnt' => $qnt,
'estMin' => $estMin
];
$tempoEntrega = 0;
$tempoTroca = 0;
$sugestaoCompra = 0;
$frequencia = 0;
$qnt = 0;
$qntI = 0;
$qntR = 0;
}
//dd($dados);
return $dados;
}
This code returns what I've expected:
Then a get this return with Vue like this:
methods: {
getPredictions(){
axios.get(this.rotagetprevisoes, this.dadosIniciais).then(res => {
this.dadosIniciais = res.data
console.log(res.data)
})
},
rowClass(filtered, type){
if (!filtered) return
if (filtered.estMin < filtered.qnt) return 'table-success'
if (filtered.estMin = filtered.qnt) return 'table-warning'
if (filtered.estMin > filtered.qnt) return 'table-danger'
},
openRepModal(){
this.$root.$emit('bv::show::modal', 'gerRelPrev', '#btnShow')
},
sugModal(item){
if(item.qntProxComp >= 0){
this.qntSuges = item.qntProxComp
this.acimaEstMin = 'n'
} else {
this.qntSuges = Math.abs(item.qntProxComp)
this.acimaEstMin = 's'
}
this.dataSuges = item.dataProxComp
this.$root.$emit('bv::show::modal', 'adminSugestao', '#btnShow')
}
},
But what I got here is:
Note that the "estMin" has different values when is sent and when is received, the weirdest part is that it only goes from Laravel to Vue, nothing in the middle.
I already try changing a lot of parts of my code, doing it all over again but, ended up with the same result, try searching for something related over the internet but no succeed.
This field "estMin" is the only one affected and, it's not even a calculated field, it's only the data that I get from DB.
I simply don't understand why "estMin" comes from Laravel with the values that I expect and arrive in Vue with a different value.
One more thing, this is an array of objects, only pick one example to show you guys.
Can someone help me please?
thanks for trying to help me, i just figure what I was doing wrong and, it was stupid.
I've edited the question so you guys can have a better understand:
In the rowClass method, I have this line:
if (filtered.estMin = filtered.qnt) return 'table-warning'
I didn't notice the '=' sign, that's why the estMin was aways with a different value so, I change the '=' sign for '===' and the problems were solved:
if (filtered.estMin === filtered.qnt) return 'table-warning'
Honestly, I don't understand why exactly this method can be interfering with the other but, it is working.
Again, thank you all that have tried to help me.
Controller:
$next_id = $this->o->next_id();
$data['next_id']=$next_id;
Model:
public function next_id(){
$this->db->select_max('p_ori_id');
$max = $this->db->get('orientation_master');
if($max==0){
$next_id = 1;
}else{
$next_id = 1+$max;
}
return $next_id;
}
Return Error:
Object of class CI_DB_mysqli_result could not be converted to int
Please solve problem..
No offense to #pradeep but you may have some unexpected results if you don't have any rows. I suggest:
public function next_id()
{
$this->db->select_max('p_ori_id', 'max');
$query = $this->db->get('orientation_master');
if ($query->num_rows() == 0) {
return 1;
}
$max = $query->row()->max;
return $max == 0 ? 1 : $max + 1;
}
Hope this will help you:
public function next_id()
{
$this->db->select_max('p_ori_id', 'max');
$query = $this->db->get('orientation_master');
// Produces: SELECT MAX(p_ori_id) as max FROM orientation_master
$max = $query->row()->max;
if($max == 0){
$next_id = 1;
}else{
$next_id = $max+1;
}
return $next_id;
}
For more : https://www.codeigniter.com/user_guide/database/query_builder.html
You are getting that error becuase $max is a result set object and not an integer record value like you're trying to use it.
You can try this function to get the next id.
Modified function:
public function next_id(){
$this->db->select_max('p_ori_id', 'max');
$result = $this->db->get('orientation_master');
$row = $result->row_array();
$next_id = isset($row['max']) ? ($row['max']+1) : 1;
return $next_id;
}
If the column is auto increment, you can use the below code instead.
Alternative:
public function next_id() {
$sql_string = "SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = '".$this->db->dbprefix."orientation_master'";
$query = $this->db->query($sql_string);
$row = $query->row_array();
return $row['auto_increment'];
}
I have a problem when I execute controller method it process controller code but destroy all session including user.
So after process thus controller and I try to open home page, there is no logged in account.
I'm sure no destroy session code, nor logout code in my controller. and I can say this is not about session expired.
I don't know what wrong is this about code, yii2 configuration or logic, but is someone have similar problem in past?
Hope you can guide me to solve this problem.
If you need more information, please let me know.
This not related to code maybe, but here is my controller code.
<?php
namespace frontend\controllers;
use Yii;
use common\models\TbCustomer;
use yii\web\Controller;
use common\models\Model;
use common\models\VwProdukAgent;
use common\models\TbCart;
use yii\helpers\VarDumper;
use common\models\VwProduk;
use yii\data\ActiveDataProvider;
use common\models\VwProdukCustomer;
use common\models\TbCustomerShipment;
use common\component\BeoHelper;
use common\models\TbProdukEkspedisi;
use common\models\TbKota;
use yii\helpers\Url;
/**
* CustomerController implements the CRUD actions for TbCustomer model.
*/
class Pengiriman1Controller extends Controller
{
public function beforeAction($action)
{
Yii::$app->timeZone = 'Asia/Jakarta';
if(Yii::$app->user->isGuest)
{
//$url = Url::to([['home'],'message'=>'Anda Harus Login Terlebih Dahulu']);
\Yii::$app->getSession()->setFlash('message', \Yii::t('app', 'Anda Harus Login Terlebih Dahulu'));
$this->goHome();
return FALSE;
}
//if ($action->id == 'my-method') {
$this->enableCsrfValidation = false;
// }
return parent::beforeAction($action);
}
public function actionIndex()
{
//get alamat customer
//$lsalamat = array();
if(!\Yii::$app->user->isGuest)
{
BeoHelper::refreshCart();
//cek cart kosong atau tidak
if(isset(\Yii::$app->session['produkcart']))
{
$lsproduk = \Yii::$app->session['produkcart'];
if (count($lsproduk)<1)
{
\Yii::$app->getSession()->setFlash('message',"silahkan berbelanja terlebih dahulu");
return $this->redirect(Url::to(['cart/index']));
}
}
$customer_id = Yii::$app->user->id;
$message = '';
$model = null;
if(\Yii::$app->request->post('opsi_alamat',null)!=null)
{
$opsi_pengiriman = \Yii::$app->request->post('opsi_alamat',null);
//return $opsi_pengiriman;
if($opsi_pengiriman == 'new')
{
$model = new TbCustomerShipment();
$model->load(Yii::$app->request->post());
$model->customer_id = $customer_id;
if($model->save())
{
\Yii::$app->session['shipemenadd'] = $model;
//get kurir preselected
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where(['produk_id' => $produk->produk_id])->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $model->kota_id ")->one();
$berat_produk = $produk->kuantitas *$produk->berat_produk;
$berat_produk = round($berat_produk);
$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $berat_produk, $kode,$service,$produk->produk_id);
if(count($result)!=0)
{
$produk->harga_kurir = $result[0]['value'];
$produk->estimasi_sampai = $result[0]['etd'];
}
else
{
$message = "pilihan kurir untuk lokasi tersebut tidak tersedia";
}
//return VarDumper::dump($result);
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
if(isset(Yii::$app->session['shipemenadd'])){
return "exists";
}else{
return "doesn't exist";
}
//return $this->redirect(['pengiriman2/index','message'=>$message]);
//print_r(Yii::$app->session['shipemenadd']);
}
//else
//{
// VarDumper::dump($model);
//}
}
else
{
$pengiriman_selected = TbCustomerShipment::find()->where("customer_shipment_id = $opsi_pengiriman")->one();
\Yii::$app->session['shipemenadd'] = $pengiriman_selected;
if(isset(\Yii::$app->session['produkcart']))
{
$hargatotal = 0;
$lsproduk = \Yii::$app->session['produkcart'];
$i=0;
$lsprodukedit = array();
foreach ($lsproduk as $produk)
{
//pre selected
$pengiriman = TbProdukEkspedisi::find()->where("produk_id =$produk->produk_id")->one();
$kode = $pengiriman->idEkspedisi->kode_ekspedisi;
$service = $pengiriman->idEkspedisi->service;
$produk->kurir = $kode;
//get kota id rajaongkir
$kota_asal = TbKota::find()->where("kota_id = $produk->kota_id ")->one();
$kota_tujuan = TbKota::find()->where("kota_id = $pengiriman_selected->kota_id ")->one();
//$result = BeoHelper::getCostEkspedisi($kota_asal->api_id, $kota_tujuan->api_id, $produk->berat_produk, $kode,$service);
//return VarDumper::dump($result);
//if(count($result)!=0)
//{
//$produk->harga_kurir = $result[0]['value'];
//$produk->estimasi_sampai = $result[0]['etd'];
$produk->harga_kurir = 0;
$produk->estimasi_sampai = 0;
//}
//else
//{
// $message = "pilihan kuriri untuk lokasi tersebut tidak tersedia";
//}
$lsprodukedit[$i++] = $produk;
$hargatotal += $produk->kuantitas * $produk->harga_agen;
}
\Yii::$app->session['produkcart'] = $lsprodukedit;
}
return $this->redirect(['pengiriman2/index','message'=>$message]);
}
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
if(count($lsalamat)==0)
//insert to tb shipment
{
$datacustomer = TbCustomer::find()->where(['customer_id'=>$customer_id])->one();
$newalamat = new TbCustomerShipment();
$newalamat->customer_id = $customer_id;
$newalamat->kota_id = $datacustomer->kota_id;
$newalamat->kecamatan_id = $datacustomer->kecamatan_id;
$newalamat->negara_id = $datacustomer->negara_id;
$newalamat->propinsi_id = $datacustomer->propinsi_id;
$newalamat->alamat = $datacustomer->alamat;
$newalamat->shipment_name = "Alamat Rumah";
$newalamat->penerima = $datacustomer->nama;
$newalamat->hp_penerima = $datacustomer->hp;
$newalamat->save();
}
$lsalamat = TbCustomerShipment::find()->where(['customer_id'=>$customer_id])->all();
return $this->render('index',['lsalamat'=>$lsalamat,'newalamat'=> $model]);
}
else
{
return $this->goHome();
}
}
}
here is the problem
\Yii::$app->session['shipemenadd'] = $model;
it should
$currentTbCustomerShipment = TbCustomerShipment::find()->where(['customer_user_id' => $model->customer_user_id])->one(); //find latest object
Yii::$app->session['shipemenadd'] = $currentTbCustomerShipment;
Can anyone guide me how to generate pdf of wishlist items (products) in magento?
Wrap this code in your custom controller.
public function whishlistAction()
{
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));
if(!$session->isLoggedIn())
{
$this->_redirect(Mage::getUrl('customer/account'));
}
$customer = Mage::getModel('customer/customer')->load($session->getId());
$wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer);
$wishListItemCollection = $wishList->getItemCollection();
$pdf = new Zend_Pdf();
$pageCount = 0;
$collectionPreperedForPagesKey=0;
$collectionPreperedForPages = array();
foreach ($wishListItemCollection as $w)
{
$pageCount = $pageCount+1;
if($pageCount==4)
{
$collectionPreperedForPagesKey=$collectionPreperedForPagesKey+1;
$pageCount=0;
}
$collectionPreperedForPages[$collectionPreperedForPagesKey][]=$w;
}
foreach ($collectionPreperedForPages as $c)
{
$pdf->pages[] = $this->createWhishlistPage($c);
}
$pdfString = $pdf->render();
header("Content-Disposition: attachment; filename=whishlist.pdf");
header("Content-type: application/x-pdf");
echo $pdfString;
exit;
}
public function getImagePath($product)
{
$imageUrl = Mage::getModel('catalog/product_media_config')
->getMediaUrl( $product->getImage() );
$baseDir = Mage::getBaseDir() ;
$withoutIndex = str_replace('index.php/','', Mage::getBaseUrl());
$imageWithoutBase = str_replace($withoutIndex,'' , $imageUrl);
$imagePath = $baseDir.DIRECTORY_SEPARATOR.$imageWithoutBase ;
return $imagePath;
}
public function getImageSizesWithAspectRatio($widthImage,$heightImage,$widthBox,$heightBox)
{
if (($widthBox >= $widthImage) && ($heightBox >= $heightImage))
{
return array('width'=>$widthImage,'height'=>$heightImage);
}
$resizeRatio = 1;
if($widthBox < $widthImage)
{
$resizeRatio = $widthImage/$widthBox;
$widthImage = $widthBox;
}
if($heightBox < $heightImage)
{
if($resizeRatio!=1)
{
$heightImage = $heightImage/$resizeRatio;
}
if($heightImage>$heightBox)
{
$resizeRatio = $heightImage/$heightBox;
$heightImage = $heightBox;
$widthImage = $widthImage/$resizeRatio;
}
}
return array('width'=>$widthImage,'height'=>$heightImage);
}
public function createWhishlistPage($wishListItemCollection)
{
$lightFont = Zend_Pdf_Font::fontWithPath($this->getFont('light'));
$regularFont = Zend_Pdf_Font::fontWithPath($this->getFont('regular'));
$boldFont = Zend_Pdf_Font::fontWithPath($this->getFont('bold'));
$page1 = new Oxidian_Pdf_Helper_Page(Zend_Pdf_Page::SIZE_A4);
$page1->setFillColor(Zend_Pdf_Color_Html::color('#75645E'));
$page1->setLineColor(Zend_Pdf_Color_Html::color('#75645E'));
$page1->setLineWidth(1);
$headerFontSize = 40;
$headerLeft = 20;
$headerTop = $page1->getHeight()-$headerFont-50;
$page1->setFont($lightFont, $headerFontSize);
$contentTopFreeSpace = $headerTop-70;
$contentLeft = 20;
$contentRight = $page1->getWidth()-20;
$page1->drawText('JORDAN', $headerLeft,$headerTop);
$page1->setFont($regularFont, $headerFontSize/2);
$page1->drawText('My dreamboard', $page1->getWidth()/2+40,$headerTop);
$tableHeaderFont = 15;
$page1->setFont($boldFont, $tableHeaderFont);
$columnHeaderPadding = 5;
$productColumnSize = 100;
$previewColumnSize = 100;
$imagePreviewSize = 100;
$previewTableHeaderPosition = $columnHeaderPadding+$productColumnSize+$contentLeft;
$commentTableHeaderPosition = $previewTableHeaderPosition+$previewColumnSize+$columnHeaderPadding;
$productTableHeaderPosition = columnHeaderPadding+$contentLeft;
$commentColumnSize = $page1->getWidth()-$commentTableHeaderPosition ;
$page1->drawText('Product', $productTableHeaderPosition ,$contentTopFreeSpace);
$page1->drawText('Preview', $previewTableHeaderPosition,$contentTopFreeSpace);
$page1->drawText('Comments', $commentTableHeaderPosition,$contentTopFreeSpace);
$paddingRowHeaderFromLine = 5;
$contentTopFreeSpace = $contentTopFreeSpace-$paddingRowHeaderFromLine;
$tableStart = $contentTopFreeSpace;
$contentFont = 15;
$rowHeight= 125;
$page1->setFont($regularFont, $contentFont);
foreach($wishListItemCollection as $w)
{
$page1->drawLine($contentLeft,$contentTopFreeSpace ,$contentRight,$contentTopFreeSpace);
$contentTopFreeSpace =$contentTopFreeSpace- $contentFont-$paddingRowHeaderFromLine;
$product = $w->getProduct();
$product = Mage::getModel('catalog/product')->load($product->getId());
$page1->drawTextBlock($product->getName(), $productTableHeaderPosition,$contentTopFreeSpace,$productColumnSize);
$page1->drawTextBlock($w->getDescription(), $commentTableHeaderPosition,$contentTopFreeSpace,$commentColumnSize);
$imagePath = $this->getImagePath($product);
// Load image
$image = Zend_Pdf_Image::imageWithPath($imagePath);
$imageObj = new Varien_Image($imagePath);
$imageSizes = $this->getImageSizesWithAspectRatio($imageObj->getOriginalWidth(),$imageObj->getOriginalHeight(),$imagePreviewSize,$rowHeight);
$imageBottom = ($rowHeight-$imageSizes['height'])+$contentTopFreeSpace;
$imageLeft = $previewTableHeaderPosition;
$page1->drawImage($image,$imageLeft,$imageBottom-$imageSizes['height'],$previewTableHeaderPosition+$imageSizes['width'],$contentTopFreeSpace);
$contentTopFreeSpace = $contentTopFreeSpace-$rowHeight-$paddingRowHeaderFromLine;
$page1->drawLine($contentLeft,$contentTopFreeSpace ,$contentRight,$contentTopFreeSpace);
};
$tableLineProductsStartX = $previewTableHeaderPosition-$columnHeaderPadding;
$tableLineProductsStartY = $tableStart+$paddingRowHeaderFromLine+$tableHeaderFont;
$tableLineProductsStartX1 = $previewTableHeaderPosition-$columnHeaderPadding;
$tableLineProductsStartY1 = $contentTopFreeSpace;
$tableLinePreviewStartX = $commentTableHeaderPosition-$columnHeaderPadding;
$tableLinePreviewStartY = $tableStart+$paddingRowHeaderFromLine+$tableHeaderFont;
$tableLinePreviewStartX1 = $commentTableHeaderPosition-$columnHeaderPadding;
$tableLinePreviewStartY1 = $contentTopFreeSpace;
$page1->drawLine($tableLineProductsStartX ,$tableLineProductsStartY ,$tableLineProductsStartX1,$tableLineProductsStartY1);
$page1->drawLine($tableLinePreviewStartX ,$tableLinePreviewStartY ,$tableLinePreviewStartX1,$tableLinePreviewStartY1);
return $page1;
}
Source: http://gorrc.blogspot.in/2012/05/magento-print-whishlist-to-pdf.html