Please teach me how can I achieve this(Codeigniter framework)
Please see images that I want to achieve thank you.
and I'm also new to codeigniter and want to understand the answer.
enter image description here
Here is my database:
enter image description here
model
public function get_attendance_employees() {
$sql = 'SELECT * FROM tbl_employee';
//$binds = array(1);
$query = $this->db->query($sql);
return $query;
}
public function attendance_first_in_check($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timein' limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql,$binds);
return $query;
}
public function attendance_first_in($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timein'";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query->result();
}
public function attendance_first_out_check($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timeout' order by id desc limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query;
}
public function attendance_first_out($userid,$attendance_date) {
$sql = "SELECT * FROM tbl_employee_time_log as time_log WHERE userid = ? and substring(time_log.time,1,10) = ? and type = 'timeout' order by id desc limit 1";
$binds = array($userid,$attendance_date);
$query = $this->db->query($sql, $binds);
return $query->result();
}
controller
public function attendance_bio()
{
$session = $this->session->userdata('username');
if(!empty($session)){
$this->load->view("admin/timesheet/attendance_bio", $data);
} else {
redirect('admin/');
}
// Datatables Variables
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$attendance_date2 = $this->input->get("attendance_date"); //string
//$ref_location_id = $this->input->get("location_id");
//$convert_atten = strtotime($attendance_date2); //int value
//$attendance_date = $convert_atten->format('m-d-Y');
$attendance_date = date("m-d-Y",strtotime($attendance_date2));
//$timein = $this->Bio_model->get_attendance_date();
//$timein = $this->Bio_model->get_attendance_timein($get_day);
//$timein = $this->Bio_model->get_all();
$employee = $this->Bio_model->get_attendance_employees();
$data = array();
//var_dump($attendance_date);
foreach($employee->result() as $r){
$check = $this->Bio_model->attendance_first_in_check($r->userid,$attendance_date);
if($check->num_rows() > 0){
// check clock in time
$first_in = $this->Bio_model->attendance_first_in($r->userid,$attendance_date);
//$first_in2 = $first_in[0]->time->format('m-d-Y');
// clock in
$clock_in = new DateTime(strtotime($first_in[0]->time));
//$clock_in2 = $clock_in->format('H:i');
$clock_in2 = date_format($clock_in->time, 'H:i');
//$clock_in2 = var_dump($clock_in);
} else {
$clock_in2 = '-';
$clock_in = '-';
}
$check_out = $this->Bio_model->attendance_first_out_check($r->userid,$attendance_date);
if($check_out->num_rows() == 1){
$first_out = $this->Bio_model->attendance_first_out($r->userid,$attendance_date);
//$first_out2 = $firs
$clock_out = new DateTime(strtotime($first_out[0]->time));
if ($first_out[0]->time!='') {
//$clock_out2 = $clock_out->format('H:i');
//$clock_out2 = date('H:i',$clock_out);
$clock_out2 = date_format($clock_out->time, 'H:i');
} else {
$clock_out2 = '-';
}
}else {
$clock_out2 = '-';
$clock_out = '-';
}
$data[] = array(
$r->userid,
$attendance_date,
$clock_in2,
$clock_out2,
);
}
$output = array(
"draw" => $draw,
"recordsTotal" => $employee->num_rows(),
"recordsFiltered" => $employee->num_rows(),
"data" => $data
);
echo json_encode($output);
exit();
}
Thank you for providing more information on the topic and the code you have attempted so far. I have supplied an algorithm which I believe will work for you.
Contoller:
<?php namespace App\Controllers;
use App\Models\EmployeeTimeLog;
class Home extends BaseController
{
public function index($employeeId)
{
// get all between dates
$emplyeeModel = new EmployeeTimeLog();
// get one week before today - for example
$startDate = date("Y-m-d", strtotime("-1 week"));
$endDate = date("Y-m-d");
// get clock-in and clock-out for employee between dates
$timeIn = $emplyeeModel->getTimeIn($employeeId, $startDate, $endDate)->getResult();
$timeOut = $emplyeeModel->getTimeOut($employeeId, $startDate, $endDate)->getResult();
$timeInIndex = 0;
$timeOutIndex = 0;
$output = [];
$nextDate = $startDate;
// loop through all the days between start and end date
while($nextDate < $endDate){
// get the lowest "timein" datetime which is the same date as the search date $nextDate
$nextTimeIn = NULL;
while($timeInIndex < count($timeIn) && date("Y-m-d", strtotime($timeIn[$timeInIndex]->Time)) == $nextDate){
if(is_null($nextTimeIn)){
$nextTimeIn = $timeIn[$timeInIndex];
}
$timeInIndex ++;
}
// get the highest "timeout" datetime which is the same day as the search date $nextDate
$nextTimeOut = NULL;
while($timeOutIndex < count($timeOut) && date("Y-m-d", strtotime($timeOut[$timeOutIndex]->Time)) == $nextDate){
$nextTimeOut = $timeOut[$timeOutIndex];
$timeOutIndex ++;
}
// enter into a 2 dimentional array with
// index 0 = timein
// index 1 = timeout
$output[] = [$nextTimeIn, $nextTimeOut];
// get the next date
$nextDate = date('Y-m-d', strtotime($nextDate. ' + 1 days'));
}
// return view with data
return view('welcome_message', ["output" => $output]);
}
}
Model:
<?php
namespace App\Models;
use CodeIgniter\Model;
class EmployeeTimeLog extends Model{
private $tableName = "tbl_employee_time_log";
public function __construct(){
$db = \Config\Database::connect();
$this->builder = $db->table($this->tableName);
}
private function timeData($employeeId, $startDate, $endDate){
// builder function DRY
$this->builder->where("EmployeeId", $employeeId);
$this->builder->where("Time >", $startDate);
$this->builder->where("Time <", $endDate);
$this->builder->orderBy("Time", "ASC");
}
public function getTimeIn($employeeId, $startDate, $endDate){
// call builder function and add timeIn to only get clock in times
$this->timeData($employeeId, $startDate, $endDate);
$this->builder->where("Type", "timein");
return $this->builder->get();
}
public function getTimeOut($employeeId, $startDate, $endDate){
// call builder function and add timeout to only get clock out times
$this->timeData($employeeId, $startDate, $endDate);
$this->builder->where("Type", "timeout");
return $this->builder->get();
}
}
?>
View:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Timesheets</title>
</head>
<body>
<h1>Timesheets</h1>
<?php
echo "<h1>Times</h1>";
foreach ($output as $times) {
echo "Time in: ";
if(!is_null($times[0])){
echo $times[0]->Time;
}else{
echo "-";
}
echo " Time out: ";
if(!is_null($times[1])){
echo $times[1]->Time;
}else{
echo "-";
}
echo "<br>";
}
?>
</body>
</html>
Output:
Database:
The whole algorithm works by searching through the date between the start and end date of the dates provided. You can then check any timein and timeout values which have the same date as the loop date. If a date cannot be found, the default is NULL which is replaced by "-" in the view.
The algorithm specifically gets the earliest timein and the latest timeout value for the employee. This means that if the employee clocks-in twice in one day the earliest date will be used and the opposite for clock-out.
This algorithm specifically works for one employee, but just use your select * employees and loop through instead of the employeeId on the controller. You may want to look in the documentation for the Query Builder in CodeIgniter it makes querying the database much easier, and will escape data to protect from SQL Injections etc.
It could be better to redesign your database table and check on insert rather than manipulate on select. Where you have one row for each day and the timein and timeout which represent the time. Something like this:
You can check to see if the date already exists, if so override the current value if needed. If the current date doesn't exist for that employee create a new record.
If you need any clarification, let me know,
Thanks,
how can i call the id_product of the $itemsCart result line to be inserted in $ encomendas_detalhes-> id_produto?
where are the '----' is where I need help more
$itemsCart = cart::where('token_user', session()->get('_token') )->where('id_encomenda', 0)->get();
foreach ( $itemsCart as $items ) {
$encomendas_detalhes = new detalhes;
$encomendas_detalhes->id_encomenda = $encomendas->id;
$encomendas_detalhes->id_produto = ---$itemsCart->id_produto--- ;
$encomendas_detalhes->quantidade = 2;//$itemsCart->quantidade;
$encomendas_detalhes->total = $total;
$encomendas_detalhes->save();
$items->id_encomenda = $id_encomenda;
$items->save();
}
I created a store function on my controller. At the time I will enter data with just one submit, only indexed up to 40 data will be entered. While those 40 and above do not enter the database. Why did this happen? What's the solution? Please i need help.
Sorry for my bad English.
Thanks
I am use Laravel 5.6
public function store(Request $request)
{
//
foreach($request->quantity as $quantity){
if($quantity == NULL){
}
if($quantity != NULL){
$data = new KomponenOlahan;
$data->quantity = $quantity;
$harga_satuan_mu = Input::get('harga_satuan_mu');
$total = $quantity*$harga_satuan_mu;
$data->kode_proyek = Input::get('kode_proyek');
$data->nama_proyek = Input::get('nama_proyek');
$data->kode_panel = Input::get('kode_panel');
$data->nama_panel = Input::get('nama_panel');
$data->schedule_kirim = Input::get('schedule_kirim');
$data->nama_sales = Input::get('nama_sales');
$data->ukuran_panel = Input::get('ukuran_panel');
$data->ref = Input::get('ref');
$data->type = Input::get('type');
$data->komponen_bantu = Input::get('komponen_bantu');
$data->nama_komponen = Input::get('nama_komponen');
$data->spek = Input::get('spek');
$data->satuan = Input::get('satuan');
$data->diskon = Input::get('diskon');
$data->harga = Input::get('harga');
$data->pole = Input::get('pole');
$data->ka = Input::get('ka');
$data->ampere = Input::get('ampere');
$data->quantity = $quantity;
$data->harga_satuan_mu = $harga_satuan_mu;
$data->harga_satuan_mb = Input::get('harga_satuan_mb');
$data->harga_satuan_lb_oh = Input::get('harga_satuan_lb_oh');
$data->id_estimasi = Input::get('id_estimasi');
$data->nama_estimasi = Input::get('nama_estimasi');
$data->total = $total;
$data->trigger_bom = Input::get('trigger_bom');
$data->save();
}
}
My View
<td><input type="text" name="quantity[]" class="form-control"></td>
<td><input type="text" name="kode_proyek" hidden value="{{$panel->kode_projek}}">
etc....
My View
my view
You can save it first to array then use bulk insert.
Inserting data 1 by 1 will slow your application.
$insertArray = array();
foreach($request->quantity as $quantity){
if($quantity == NULL){
$insertArray[] = array(
'quantity' => $quantity,
'harga_satuan_mu ' => Input::get('harga_satuan_mu'),
.... // add other fields
)
}
}
KomponenOlahan::insert($insertArray);
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;
I am tring to do now is to make a many to many relation between "payments" table and "invoices" table ... but my problem is when i try to add a new payment and i select e list of invoices laravel gives me " Trying to get property of non-object " in line 217 ..
this is my code :
$selectedInvoices = $input['invoice'];
$invoices = collect([]);
foreach ($selectedInvoices as $invoice) {
$invoices = $invoices->merge([Invoice::find(Invoice::getPrivateId($invoice))]);
}
$invoices->all();
$invoices = $invoices->sortByDesc(function($invoice)
{
return $invoice->invoice_date;
});
$invoices->values()->all();
$totalAmount = 0;
foreach ($invoices as $invoice)
{
$totalAmount = $totalAmount + $invoice->balance;
}
if($payment->amount > $totalAmount){
foreach ($invoices as $invoice){
$adjustment = $invoice->balance * -1;
$partial = max(0, $invoice->partial - 0);
$invoice->updateBalances($adjustment, $partial);
$invoice->updatePaidStatus();
$payment->invoices()->attach($invoice->id) ;
}
$credit = Credit::createNew();
$credit->client_id = $clientId;
$credit->amount = $payment->amount - $totalAmount ;
$credit->balance = $payment->amount - $totalAmount ;
$credit->credit_date = $payment->payment_date;
$credit->private_notes = 'Crédit créé automatiquement suite au payement '.$payment->id.
' avec un montant de '.$payment->amount.' à la date de '.$payment->payment_date;
$credit->save();
}
if($payment->amount <= $totalAmount)
{
/*line 217*/ while ($payment->amount >= $invoices->last()->balance){
$payment->amount = $payment->amount - $invoices->last()->balance ;
$adjustment = $invoices->last()->balance * -1;
$partial = max(0, $invoices->last()->partial - 0);
$invoices->last()->updateBalances($adjustment, $partial);
$invoices->last()->updatePaidStatus();
$payment->invoices()->attach($invoices->last()->id) ;
$invoices->pop();
$invoices->all();
}
if ($payment->amount < $invoices->last()->balance){
$adjustment = $payment->amount * -1;
$partial = max(0, $invoices->last()->partial - $payment->amount);
$invoices->last()->updateBalances($adjustment, $partial);
$invoices->last()->updatePaidStatus();
$payment->invoices()->attach($invoices->last()->id) ;
}
}
p.s: when i give an amount > total amount of my invoices it works also when i give an amount < total amount it works too ..
Switch line 217
From:
while ($payment->amount >= $invoices->last()->balance){
To:
while (count($invoices) && $payment->amount >= $invoices->last()->balance) {
Explanation: $invoices->pop() is removing the last item in the collection. When all the items have been removed from the invoices collection, no invoice object will be found; Hence, the Trying to get property of non-object