front controller of my module doesn't work neither shows any changes or validates order in prestashop1.7 - prestashop

I'm implementing external payment gateway. But Front controller does not show any changes in the frontoffice. Atleast it should throw some error(so it would be easy to understand) but instead it shows no changes.
I have tried deleting, again creating same file but i think there is something wrong with the code.
I'm a newbie in custom module development. Hopefully anybody can point me in right direction. A quick help would be really appreciated.
Please check my code below. Correct me if i missed something.
<?php
require_once dirname(__FILE__) . '/config/config.inc.php';
require_once dirname(__FILE__) . '/latpayredirect.php';
class LatpayRedirectValidationModuleFrontController extends ModuleFrontController
{
   
    public $warning = '';
    public $message = '';
    public function initContent()
    {  
      parent::initContent();
      $this->context->smarty->assign(array(
          'warning' => $this->warning,
          'message' => $this->message
          ));        
     
      $this->setTemplate('module:latpayredirect/views/templates/front/payment_return.tpl');    
    }
 
    public function postProcess()
    {
      ob_start();
    $context = Context::getContext();
    if (is_null($context->cart)) {
      $context->cart = new Cart($context->cookie->id_cart);
  }
  if (is_null($context->cart->id_currency)) {
      $context->cart->id_currency = $context->cookie->id_currency;
  }
      $cart = $this->context->cart;
      $this->abrir("http://davivienda.com");
       if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) {
           Tools::redirect('index.php?controller=order&step=1');
       }
       $customer = new Customer($cart->id_customer);
       if (!Validate::isLoadedObject($customer)) {
           Tools::redirect('index.php?controller=order&step=1');
       }
      // $currency = $this->context->currency;
      $currency = $cart->id_currency;
       $total = (float)$cart->getOrderTotal(true, Cart::BOTH);
       $object = new filemain();
       $order = $object->methodCreateInMain($cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $currency, $customer->secure_key);
       //The order passes directly on paid status
       $this->module->validateOrder((int)$cart->id, Configuration::get('PS_OS_PAYMENT'), $total, $this->module->displayName, null, array(), (int)$currency->id, false, $customer->secure_key);
       Tools::redirect('index.php?controller=order-confirmation&id_cart='.(int)$cart->id.'&id_module='.(int)$this->module->id.'&id_order='.$this->module->currentOrder.'&key='.$customer->secure_key);
   }
   public function abrir($param)
   {
       echo" <script> window.open(URL,'ventana1,'width=300,height=300,scrollbars=NO')</script> ";
   }  
}

I have created a simple module as yours and the controller works fine. Please find the below code.
I think, something wrong with your class name & file name (try file name in lowercases, and controller class name should be like class )
/modules/latpayredirect/latpayredirect.php
<?php
class Latpayredirect extends PaymentModule
{
public function __construct()
{
$this->name = 'latpayredirect';
$this->author = 'abdullacm';
$this->version = '1.0.0';
$this->need_instance = 0;
parent::__construct();
$this->displayName = 'payment module';
$this->description = 'payment module';
}
}
/modules/latpayredirect/controllers/front/validation.php
<?php
class LatpayredirectValidationModuleFrontController extends ModuleFrontController
{
public function initContent()
{
echo 'from latpay validation front controller';
exit;
}
}

I had the same problem, and it appears that you cannot override controllers or classes from a module with the method you are using (even though they say it works in the documentation!).
The way that worked for me is to copy your override class (for instance here the override of the Order class) directly in the main file of the module:
<?php
class MyModule extends Module
{
}
class MyCustomOrder extends Order
{
}
?>
Good luck!

Related

internalDelegator" is not a field of ChangeGroup even ifinternalDelegator appears as code suggestion

I am using the following code for a script listener in Jira  and here is the code below:
The problem is that I am receiving the exception MOUNA EXCEPTION ----java.lang.IllegalArgumentException: [GenericEntity.get] "internalDelegator" is not a field of ChangeGroup even though the field internalDelegator actually appears as code suggestion as shown in the screenshot below:
Anyone knows what the problem is?
package AutoDefaults
import com.atlassian.event.Event
import org.ofbiz.core.entity.GenericEntity
import com.atlassian.jira.event.issue.AbstractIssueEventListener
import com.atlassian.jira.event.issue.IssueEvent
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.util.IssueChangeHolder
import com.atlassian.jira.issue.Issue
import java.util.HashMap
import java.util.List
import org.ofbiz.core.entity.GenericValue
import org.ofbiz.core.entity.GenericDelegator
import com.atlassian.jira.issue.changehistory.ChangeHistoryManager
import com.atlassian.jira.issue.history.ChangeItemBean
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.comments.Comment
import org.apache.log4j.Logger
import com.atlassian.jira.issue.changehistory.ChangeHistoryItem
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.util.UserManager
import com.atlassian.jira.user.ApplicationUser
import AutoDefaults.Configuration_AutoDefaults
import com.atlassian.applinks.api.ApplicationLinkService;
import com.atlassian.applinks.host.spi.HostApplication;
import com.atlassian.core.util.map.EasyMap;
import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.event.type.EventType;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.comments.Comment;
import org.ofbiz.core.entity.GenericEntityException;
import org.ofbiz.core.entity.GenericValue;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
def log = Logger.getLogger('atlassian-jira.log')
log.warn('Start Auto Defaults Listener')
Issue issue = event.getIssue()
 def autoDefaultsMap = Configuration_AutoDefaults.getMap()
String impedimentIssueType = autoDefaultsMap['impedimentIssueType'] as String
if (issue.getIssueType().getName().equalsIgnoreCase(impedimentIssueType)) {
    event2 = (IssueEvent) event
    def warning = analyzeImpedimentChangeLog(event2)
    if (!warning.isEmpty()) {
        setWarning(issue, warning)
  } else {
    }
}
def analyzeImpedimentChangeLog(IssueEvent event) {
    def autoDefaultsMap = Configuration_AutoDefaults.getMap()
    String statusNew = autoDefaultsMap['statusNew'] as String
    String statusInspecting = autoDefaultsMap['statusInspecting'] as String
    String modifiedFieldSourceType = autoDefaultsMap['modifiedFieldSourceType'] as String
    String modifiedFieldClass = autoDefaultsMap['modifiedFieldClass'] as String
    String modifiedFieldPlanningRequired = autoDefaultsMap['modifiedFieldPlanningRequired'] as String
    String warningMessage = autoDefaultsMap['warning'] as String
    String noString = autoDefaultsMap['noString'] as String
    String warning = ''
    String warningMessage1 = ''
    String warningMessage2 = ''
    String warningMessage3 = ''
            List<GenericValue> changeItems = null;
    def impedimentStatus = event.getIssue().getStatus().getName()
    // status New and Inspecting are out of scope
            GenericValue changeLog = event.getChangeLog()
    if (!statusNew.equalsIgnoreCase(impedimentStatus) && !statusInspecting.equalsIgnoreCase(impedimentStatus)) {
        log.warn('MOUNA ------ hey')
       
            log.warn('MOUNA2 warning ----' + changeLog)
                HashMap<String, Object> fields = new HashMap<String,Object>();
                fields.put("group", changeLog.get("id"));
         log.warn('MOUNA3 AUTHOR ----' + fields)
                String author = changeLog.getString("author");
         log.warn('MOUNA4 AUTHOR ----' + author )
    try{
      //  changeItems = event.getChangeLog().entrySet()
            log.warn('MOUNA EXCEPTION hello ----' + event.getChangeLog().interna)
    //changeItems = event.getChangeLog().getRelatedByAnd("ChangeItem", fields)
   
    //findByAnd("ChangeItem", fields);
    }catch(Exception e){
            log.warn('MOUNA EXCEPTION ----' + e)
    }  
           
      //   if (modifiedField.equals(modifiedFieldSourceType) || modifiedField.equals(modifiedFieldClass) ||
      // modifiedField.equals(modifiedFieldPlanningRequired)) {
      //       log.warn('MOUNA ------ hey22')
      //       // GenericValue changeLog = event.getChangeLog()
      //       // log.warn('MOUNA ------' + changeLog)
      // }else{
      //               log.warn('MOUNA ------ hey33'+modie)
      // }
    }
    log.warn('MOUNA2 warning ----' + warning)
    return warning
}
void setWarning(Issue mutableIssue, String warning) {
    def autoDefaultsMap = Configuration_AutoDefaults.getMap()
    String customFieldwarningIDString = autoDefaultsMap['customFieldwarningID'] as String
    CustomField customField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(new Long(customFieldwarningIDString))
    IssueChangeHolder issueChangeHolder = new DefaultIssueChangeHolder()
    customField.updateValue(null, mutableIssue, new ModifiedValue(mutableIssue.getCustomFieldValue(customField), warning), issueChangeHolder)
}

unnamed parameter as argument in a called function

can a var that is not named in the param be used as an arg when a function is called in the main? like in the following codes:
fun main() {
    val firstNumber = 10
    val secondNumber = 5
    val thirdNumber = 8
   
    val result = add(firstNumber, secondNumber)
    val anotherResult = subtract(firstNumber, thirdNumber)
    println("$firstNumber + $secondNumber = $result")
    println("$firstNumber - $thirdNumber = $anotherResult")
}
fun add(firstNumber: Int, secondNumber: Int): Int {
    return firstNumber + secondNumber
}
fun subtract(firstNumber: Int, secondNumber: Int): Int {
    return firstNumber - secondNumber
}
thirdNumber is not a parameter in the two functions i.e add and subtract functions but was used as an argument in variable anotherResult().
i have run the code and i expect the code not to run but it runs
can a var that is not named in the param be used as an arg when a function is called in the main?
Yes, that is how variable and parameters work, at least in Kotlin.
Variables are just a way to give names to values, so you can refer to those values, reuse them, and understand their meaning better. They don't have to match the names of the parameters of the function you're calling.
You could make things even clearer by using named parameters, to show that you are using the value of an arbitrarily named variable as argument for a parameter of a different name:
val anotherResult = subtract(firstNumber = firstNumber, secondNumber = thirdNumber)
i have run the code and i expect the code not to run but it runs
Wouldn't you expect add(1, 2) to work? Those literal arguments don't have names, so they can't match the parameter names.

Why do I get the error "Unresolved reference: launch" when I test the code?

I'm learning Coroutines of Kotlin, I'm a beginner of running code online in https://try.kotlinlang.org/
I try to test Code A in the website, but I get many errors just like Image A, how can I fix it?
Code A
import kotlinx.coroutines.*
fun main(args: Array<String>) {
val job = launch {
    val child = launch {
        try {
            delay(Long.MAX_VALUE)
        } finally {
            println("Child is cancelled")
        }
    }
    yield()
    println("Cancelling child")
    child.cancel()
    child.join()
    yield()
    println("Parent is not cancelled")
}
job.join()
}
Image A
Try to run following code:
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
fun main() = runBlocking<Unit> { //here i made change
val job = launch {
val child = launch {
try {
delay(Long.MAX_VALUE)
} finally {
println("Child is cancelled")
}
}
yield()
println("Cancelling child")
child.cancel()
child.join()
yield()
println("Parent is not cancelled")
}
job.join()
}
Output would be :)
Cancelling child
Child is cancelled
Parent is not cancelled

Java lambda type inference not working as expected in Kotlin

Why does this piece of Java code not compile in Kotlin without the explicit type parameter in Collectors.toList<String>()? Is there a more idiomatic way to do this?
// works
List<String> folders = Files.walk(Paths.get(args[0]))
         .filter(it -> it.toFile().isDirectory())
           .map(it -> it.toAbsolutePath().toString())
           .collect(Collectors.toList());
// does not compile - resulting type is `MutableList<in String!>..List<Any?>?` which is not compatible to `List<String>`
val folders: List<String> = Files.walk(Paths.get(args[0]))
           .filter { it.toFile().isDirectory }
           .map { it.toAbsolutePath().toString() }
           .collect(Collectors.toList())
// compiles
val folders: List<String> = Files.walk(Paths.get(args[0]))
           .filter { it.toFile().isDirectory }
           .map { it.toAbsolutePath().toString() }
           .collect(Collectors.toList<String>())
Why does this piece of Java code not compile in Kotlin without the explicit type parameter in Collectors.toList<String>()?
This looks like a compiler bug to me. I recommend creating an issue in Kotlin (KT) | YouTrack.
Is there a more idiomatic way to do this?
Yes. As Kirill Rakhman comments, "Kotlin has its own File.walk extension method." e.g.:
val folders: List<String> = File(args[0]).walk()
.filter(File::isDirectory)
.map(File::getAbsolutePath)
.toList()
If you prefer using Java 8 streams then checkout Kotlin/kotlinx.support: Extension and top-level functions to use JDK7/JDK8 features in Kotlin 1.0. It defines a Stream<T>.toList() function:
val folders: List<String> = Files.walk(Paths.get(args[0]))
.filter { it.toFile().isDirectory }
.map { it.toAbsolutePath().toString() }
.toList()
I've found two ways to make it work without explicitly specifying generic type in both places.
Either you can specify full type of variable with generic covariance
val folders: MutableList<in String> = Files.walk(Paths.get(args[0]))
.filter { it.toFile().isDirectory }
.map { it.toAbsolutePath().toString() }
.collect(Collectors.toList())
or you can simply let Kotlin do its type inference for variable (not generic parameter of method)
val folders2 = Files.walk(Paths.get(args[0]))
.filter { it.toFile().isDirectory }
.map { it.toAbsolutePath().toString() }
.collect(Collectors.toList<String>())

Swift Array handling of Subclasses

If I have a variable declared like var gameBoard: [Piece] = [], is there any way to add a subclass of Piece, called Queen, to the array?
I am using Piece to represent all pieces. Queen, Pawn, Bishop and such are all subclasses of Piece, and should be included on the board.
I remember doing this frequently in Objective C, where subclasses were able to be used in place of the superclass. But in my first attempts, it I am getting an error saying
'#lvalue $T11' is not identical to 'Piece`
Is this not possible anymore? Or would there need to be some use of generics that I cannot think of right now?
Edit
Here is the implementation of my board, including only the relevant parts.
struct GameBoard{
var board: [[Piece]]
init() {
board = []
for _ in 0...7{
var collumn: [Piece] = []
for _ in 0...7{
var piece = Piece(player: .None, board: self)
collumn.append(piece)
}
board.append(collumn)
}
}
subscript(coords:(Int, Int) ) -> Piece {
return board[coords.1][coords.0]
}
}
The code that fails is
var board = GameBoard()
var q = Queen(player: .Black, board: board)
board[(4,5)] = q //Throws the error
board.board[5][4] = q //Works
It seems to me that these two should work the same way. It may be an issue with the subscripting, but I am not completely sure.
Just to followup on your edits, this works fine in Swift. For example:
class Piece {}
class Bishop : Piece {}
let pieces: [Piece] = [Bishop()]
Do you have an example that does not work?
As a note, when you see #lvalue $T## in your errors, it often means you're trying to modify a constant. An easy way to make that mistake is to try to modify an array that was passed to you and that you did not mark var. For example, see Swift function that takes in array giving error: '#lvalue $T24' is not identical to 'CGFloat'.
Here is how I would write it. Includes answer to the question about subscripting, and for bonus, uses a Coords struct in place of tuples (allows implementation of Printable for example) and uses optionals for each square (allows nil to be used as the representation of an empty square.)
class Piece : Printable {
var description: String { get { return "Piece" } }
}
class Queen : Piece {
override var description: String { get { return "Queen" } }
}
struct Coords : Printable {
let column: Int
let row: Int
init(_ column: Int, _ row: Int) {
self.column = column
self.row = row
}
var description: String { get { return "Coords(\(column), \(row))" } }
}
struct GameBoard {
var board: [[Piece?]]
init() {
board = []
for _ in 1...8 {
board.append(Array<Piece?>(count: 8, repeatedValue:nil))
}
}
subscript(c: Coords) -> Piece? {
get {
return board[c.column][c.row]
}
set (newValue) {
board[c.column][c.row] = newValue
}
}
}
func testGameBoard() {
var board = GameBoard()
board[Coords(4, 5)] = Queen()
func printSquare(coords: Coords) {
if let p = board[coords] {
println("At \(coords) is a \(p)")
} else {
println("At \(coords) is an empty square")
}
}
printSquare(Coords(4, 5)) // Prints: At Coords(4, 5) is a Queen
printSquare(Coords(4, 6)) // Prints: At Coords(4, 6) is an empty square
}
As long as Queen is a subclass of Piece then there would be no problem. As such:
class Piece {}
class Queen : Piece {}
class Board {
var board : [[Piece?]] =
{ var board : [[Piece?]] = []
for _ in 0..<8 { board.append (Array<Piece?>(count: 8, repeatedValue:nil)) }
return board } ()
subscript (row:Int, col:Int) -> Piece? {
get { return board[row][col] }
set { board[row][col] = newValue }}
}
and then use as:
23> let board = Board()
 24> b[0,4] = Queen()
 25> b[7,4] = Queen()
 26> b
$R0: Board = {
  board = 8 values {
    [0] = 8 values {
      [0] = nil
      [1] = nil
      [2] = nil
      [3] = nil
      [4] = Some
      [5] = nil
      [6] = nil
      [7] = nil
    } ...