Pass fees from one shipping method to another - magento

I have a tricky shipping issue that I'm trying to work out. I have a custom extension that calculates the table rates for all of the domestic shipping. But for international, one type of product(category A) is a flat $35/product shipping fee and the rest of the products (categories B and C) are calculated by UPS and USPS. The only way I've been able to figure out how to properly calculate shipping if a customer purchases both types of products is to create a table rate for Category A, then pass it along to UPS/USPS as a handling fee. Is there a variable/method I can use for this process? I haven't yet found one.
As requested, here's my function:
public function collectRates(Mage_Shipping_Model_Rate_Request $request)
{
// Cut out code where it adds up the categories and the number of items in each category
$rates = $this->getRates($request, $_categories);
if (!empty($rates))
{
$rateTypes = array();
foreach($rates as $rate)
{
$rateTypes[] = $rate['method_name'];
}
$rateTypes = array_unique($rateTypes);
$i=0;
// Create array to pass along to UPS/USPS, if needed
$tempCategories = $_categories;
foreach($rateTypes as $rateType)
{
$groupPrice = 0;
foreach($_categories as $category=>$catQty)
{
$rateExists = false;
$standardRate = 0;
foreach($rates as $rate)
{
$rateCats = explode(',',$rate['category_list']);
if(in_array($category,$rateCats) && $rate['method_name'] == $rateType )
{
$rateExists = true;
if($rate['condition_type'] == 'I'){
$ratePrice = $rate['price'] * $catQty;
}
else if ($rate['condition_type'] == 'O') {
$ratePrice = $rate['price'];
}
unset($tempCategories[$category]);
}
else if(in_array($category,$rateCats) && $rate['method_name'] == "Standard" && $rateType != "Standard")
{
if($rate['condition_type'] == 'I'){
$standardRate += $rate['price'] * $catQty;
}
else if ($rate['condition_type'] == 'O') {
$standardRate += $rate['price'];
}
unset($tempCategories[$category]);
}
}
if($rateExists == false)
{
$groupPrice += $standardRate;
}
else
$groupPrice += $ratePrice;
}
if(count($tempCategories) > 0)
{
// Figure out how to pass the $groupPrice to other shipping methods here
}
else {
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier('shippingcodes');
$method->setCarrierTitle($this->getConfigData('title'));
$method->setMethod('shippingcodes_'.$rateType);
$method->setMethodTitle($rateType);
$method->setPrice($groupPrice);
$result->append($method);
}
}
}
else
return false;
return $result;
}

Related

Sorting League Standings table

Am doing a league management system where the system generates fixtures and assign each match to an official who later enters results. Now when i have set everything possible for the log table but when i pass the results, am getting the some few errors : Too few arguments to function App\Models\Gamescores::updateStandings(), 0 passed in E:\Video\laraVids\laraProjects\HAM\app\Models\Gamescores.php on line 28 and exactly 1 expected
here is my code for the sorting of the league
class Gamescores extends Model
{
use HasFactory;
protected $table = 'gamescores';
protected $fillable = [
'games_id',
'away_score',
'home_score',
];
public function game()
{
return $this->belongsTo(Game::class, 'games_id');
}
public static function boot()
{
parent::boot();
static::created(function ($gamescore) {
$gamescore->updateStandings();
});
}
public function updateStandings($league_id)
{
// Get all gamescores for the specified league
$gameScores = Gamescores::whereHas('game', function ($query) use ($league_id) {
$query->where('league_id', $league_id);
})->get();
// Loop through each gamescore and update the log table for each team
foreach ($gameScores as $gameScore) {
$game = Games::find($gameScore->games_id);
$league_id = $game->league_id;
$home_team_id = $game->home_team;
$away_team_id = $game->away_team;
$home_team_log = Logtable::where('team_id', $home_team_id)->first();
if ($home_team_log !== null) {
$home_team_log->played += 1;
if ($gameScore->home_score > $gameScore->away_score) {
$home_team_log->won += 1;
$home_team_log->points += 3;
} else if ($gameScore->home_score == $gameScore->away_score) {
$home_team_log->drawn += 1;
$home_team_log->points += 1;
} else {
$home_team_log->lost += 1;
}
$home_team_log->goals_for += $gameScore->home_score;
$home_team_log->goals_against += $gameScore->away_score;
$home_team_log->goal_difference = $home_team_log->goals_for - $home_team_log->goals_against;
$home_team_log->save();
}
$away_team_log = Logtable::where('team_id', $away_team_id)->first();
if ($away_team_log !== null) {
$away_team_log->played += 1;
if ($gameScore->away_score > $gameScore->home_score) {
$away_team_log->won += 1;
$away_team_log->points += 3;
} else if ($gameScore->home_score == $gameScore->away_score) {
$away_team_log->drawn += 1;
$away_team_log->points += 1;
} else {
$away_team_log->lost += 1;
}
$away_team_log->goals_for += $gameScore->away_score;
$away_team_log->goals_against += $gameScore->home_score;
$away_team_log->goal_difference = $away_team_log->goals_for - $away_team_log->goals_against;
$away_team_log->save();
}
}
}
}
thats my model where am passing the method to genererate the results
public function fixtureToView($league)
{
// Fetch all rows from the games table, including the related official model
$games = Games::where('league_id', $league)->get();
// Extract the values for the role column as an array
$pluckedFixtures = $games->pluck('Fixture')->toArray();
// Count the number of occurrences of each value in the array
$counts = array_count_values($pluckedFixtures);
// Initialize an empty array to store the duplicate keys and values
$fixtures = collect([]);
// Iterate over the counts array
foreach ($counts as $key => $count) {
// If the count is greater than 1, add the key and value to the duplicates array
$fixtures->push($games->where('Fixture', $key));
}
// In your controller
$gamescores = Gamescores::all();
foreach ($gamescores as $gamescore) {
$game = Games::find($gamescore->games_id);
$league_id = $game->league_id;
$gamescore->updateStandings($league_id);
if($gamescore->games_id){
$game = Games::find($gamescore->games_id);
$league_id = $game->league_id;
$gamescore->updateStandings($league_id);
}
}
$standings = Logtable::all();
$standings = $standings->sortByDesc('points');
// return view('standings', compact('standings'));
return view(
'admin.league.fixtures.index',
compact('fixtures', 'standings')
);
thats my controller where am passing the method to retrieve it in the view, what i want is the log table to get the Id of the league where the games/matches belong to
the error am getting this error

How to add another array value in codeigniter using getRecords

The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .

checkbox controller in laravel

Hello this is my controller in laravel and I am not getting the problem here. It checks the file if I manually enter a dataset with the value of 1 but if I do it with the system it does not update the value and the box remains to 0 with unchecked box.
What I am trying to do is tick the box if the user tick it and keep the box ticked until he ticks it off plus update the database value too. Thank you in advance
public function tickoffUpload($id, $type, User $user) {
$uploads = $this->upload->get($id);
// if($this->request->isMethod('get')) {
// if($user->can('untick', $uploads)) {
// $uploads = $this->upload = 0;
// } else {
// return $uploads = $this->upload = 1;
// }
// }
if($this->request->isMethod('get')) {
if($type == 0) {
$uploads = $this->upload = 1;
} else if($type == 1){
$uploads = $this->upload = 0;
}
}
if(isset($_POST["uploaded"]) && !empty($_POST["uploaded"])) {
$uploads->uploaded = $this->request->uploaded;
$uploads->save();
}
return redirect('/home');
}
I have sorted this out. I was not getting the requesting value from the form as you can see here $uploads->uploaded = $this->upload = 1; so here is the updated code which I did and worked.
public function tickoffUpload($id, $type, User $user) {
$uploads = $this->upload->get($id); //gets upload id
// requesting uploaded value either 0 or 1
if($this->request->isMethod('get')) {
if($type == 0) {
$uploads->uploaded = $this->request->upload = 1;
} else if($type == 1) {
$uploads->uploaded = $this->request->upload = 0;
}
}
$uploads->save(); // saving the value in database
return redirect('/home');
}
Thank you d3r1ck for the help though ... :)

Flat Rate shipping for different customer groups?

Is it possible to set a flat rate shipping method with two different prices for two different customer groups?
Googled around, but couldn't find one, and why isn't this as easy as one would imagine it be to setup?
You can create this option by copy Flatrate file core/Mage/Shipping/Model/Carrier/Flatrate.php in local code pool local/Mage/Shipping/Model/Carrier/Flatrate.php.
you need to modify code in collectRates function.
$result = Mage::getModel('shipping/rate_result');
if ($this->getConfigData('type') == 'O') { // per order
$shippingPrice = $this->getConfigData('price');
} elseif ($this->getConfigData('type') == 'I') { // per item
$shippingPrice = ($request->getPackageQty() * $this->getConfigData('price')) - ($this->getFreeBoxes() * $this->getConfigData('price'));
} else {
$shippingPrice = false;
}
Replace the above code using the below code:
if(!Mage::getSingleton('customer/session')->isLoggedIn()){
//not logged in
$flatRatePrice = $this->getConfigData('price');
}else{
// logged in
$groupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
$group = Mage::getSingleton('customer/group')->load($groupId)->getData('customer_group_code');
$group = strtolower($group);
switch ($group) {
case 'general': //Set price for different customer group
$flatRatePrice = 10;
break;
case 'retailer':
$flatRatePrice = 20;
break;
case 'wholesale':
$flatRatePrice = 30;
break;
default:
$flatRatePrice = $this->getConfigData('price');
}
}
$result = Mage::getModel('shipping/rate_result');
if ($this->getConfigData('type') == 'O') { // per order
$shippingPrice = $flatRatePrice;
} elseif ($this->getConfigData('type') == 'I') { // per item
$shippingPrice = ($request->getPackageQty() * $flatRatePrice) - ($this->getFreeBoxes() * $flatRatePrice);
} else {
$shippingPrice = false;
}

Magento Core discount

I've been struggling with this for a while, should be pretty straight forward but...
I'm trying to apply coupon to order using magento cart.coupon.add api.
The product is Virtual
here is my code ( and I've tried everything i could find on google before I came here ):
protected function _applyCoupon($quoteId, $couponCode, $store = null)
{
$coupon = Mage::getModel('salesrule/coupon');
$coupon->loadByCode($couponCode);
Mage::log('_applyCoupon('.$couponCode.')');
$quote = $this->_getQuote($quoteId, $store);
if (!$quote->getItemsCount()) {
// $this->_fault('quote_is_empty');
}
$oldCouponCode = $quote->getCouponCode();
if (!strlen($couponCode) && !strlen($oldCouponCode)) {
return false;
}
try {
//$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->setCouponCode($couponCode);
$quote->setTotalsCollectedFlag(false)->collectTotals();
$quote->collectTotals();
$quote->save();
Mage::getModel("checkout/session")->setData("coupon_code",$couponCode);
Mage::getModel('checkout/cart')->getQuote()->setCouponCode($couponCode)->save();
Mage::getModel('checkout/cart')->getQuote()->collectTotals();
Mage::getModel('checkout/cart')->getQuote()->save();
Mage::log("_applyCoupon : Set coupon to quote:".$quote->getCouponCode());
} catch (Exception $e) {
$this->_fault("cannot_apply_coupon_code", $e->getMessage());
}
Mage::log('3');
if ($couponCode) {
Mage::log("Coupon applied");
if (!$couponCode == $quote->getCouponCode()) {
Mage::log('3.2');
$this->_fault('coupon_code_is_not_valid');
}
}
return true;
}
I've also tried applying coupon to address:
protected function applyDiscountToAddress($address,$quote)
{
Mage::log('applyDiscountToProduct ...');
$coupon = Mage::getModel('salesrule/coupon');
Mage::log("checkoutprocess: checkout/session:".Mage::getModel("checkout/session")->getData("coupon_code"));
$coupon->loadByCode(Mage::getModel("checkout/session")->getData("coupon_code"));
$rule = Mage::getModel('salesrule/rule');
$rule->load($coupon->getRuleId());
$discountamount = $rule->getDiscountAmount();
$dbldiscount = 0.00 + $discountamount;
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();
$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
Mage::log('applyDiscountToProduct $grandTotal:'.$grandTotal);
Mage::log('applyDiscountToProduct $subTotal:'.$subTotal);
$gTotal = $grandTotal - $dbldiscount;
$address->setDiscountAmount($dbldiscount)
->setBaseDiscountAmount($dbldiscount)
->setGrandTotal($gTotal)
->setBaseGrandTotal($gTotal);
$grandTotal = $address->getGrandTotal();
$baseGrandTotal = $address->getBaseGrandTotal();
Mage::log('applyDiscountToProduct Address:$grandTotal:'.$grandTotal);
Mage::log('applyDiscountToProduct Address:$baseGrandTotal:'.$baseGrandTotal);
$totals = array_sum($address->getAllTotalAmounts());
$baseTotals = array_sum($address->getAllBaseTotalAmounts());
$address->setGrandTotal($grandTotal+$totals);
$address->setBaseGrandTotal($baseGrandTotal+$baseTotals);
}
the coupon is valid but after the order being placed in the Magento admin I see that the discount amount = 0.0 and the user was charged full amount to his credit card.
Anyone....? Help...?
Finally found an answer
I needed to call setCouponCode() before adding any items to quote.
$quote= Mage::getModel('sales/quote')->setCouponCode($couponCode);

Resources