diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
deleted file mode 100644
index c26b9540..00000000
--- a/.github/CONTRIBUTING.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# Contributing
-
-First off, thanks for taking the time to contribute!
-
-### How can I contribute?
-
-* Fork this project;
-* Make your changes / new implementatios;
-* Use the pattern for git commts;
-* Make sure that the acceptance criteria are met (tests, docs, etc);
-* Create a pull request;
-
-### Pull Requests
-
-Template [PULLREQUEST-TEMPLATE](.github/PULLREQUEST-TEMPLATE.md)
-
-### Git Commit Messages
-
-* Use the present tense ("Adds feature" not "Added feature")
-* Limit the first line to 72 characters or less
-* Reference issues and pull requests liberally
-* Consider starting the commit message with an applicable emoji:
- * :art: `:art:` when improving the format/structure of the code
- * :racehorse: `:racehorse:` when improving performance
- * :non-potable_water: `:non-potable_water:` when plugging memory leaks
- * :memo: `:memo:` when writing docs
- * :penguin: `:penguin:` when fixing something on Linux
- * :apple: `:apple:` when fixing something on Mac OS
- * :checkered_flag: `:checkered_flag:` when fixing something on Windows
- * :bug: `:bug:` when fixing a bug
- * :fire: `:fire:` when removing code or files
- * :green_heart: `:green_heart:` when fixing the CI build
- * :white_check_mark: `:white_check_mark:` when adding tests
- * :lock: `:lock:` when dealing with security
- * :arrow_up: `:arrow_up:` when upgrading dependencies
- * :arrow_down: `:arrow_down:` when downgrading dependencies
- * :shirt: `:shirt:` when removing linter warnings
- * :bulb: `:bulb:` new idea
- * :construction: `:construction:` work in progress
- * :heavy_plus_sign: `:heavy_plus_sign:` when adding features
- * :heavy_minus_sign: `:heavy_minus_sign:` when removing features
- * :speaker: `:mute:` when adding logging
- * :mute: `:mute:` when reducing logging
- * :facepunch: `:facepunch:` when resolve conflict
- * :wrench: `:wrench:` when modify Web.config
-
diff --git a/.github/ISSUE-TEMPLATE.md b/.github/ISSUE-TEMPLATE.md
deleted file mode 100644
index 69d1ee6b..00000000
--- a/.github/ISSUE-TEMPLATE.md
+++ /dev/null
@@ -1,43 +0,0 @@
-```
-Please use the following template to submit your issue.
-Following this template will allow us to quickly investigate and help you with your issue.
-Please be aware that issues which do not conform to this template may be closed.
-
-DO NOT FORGET TO REMOVE THIS BLOCK
-```
-
-### Status
-
-BUG REPORT / TASK
-
-### Checklist
-
-Add checklist if this is a task
-
-- [x] Add slack integration
-- [_] Support xyz
-
-### Steps
-
-1. First step
-2. Second step
-3. Third step
-
-### Expected behaviour
-
-How do you think the program should work? Add screenshots and code blocks if necessary.
-
-### Actual behaviour
-
-How does the program work in its current state?
-
-### Environment
-
-You may write here the specifications like the version of the project, services, operating system, or hardware if applicable.
-
-### Logs / Stack trace
-
-```
-Insert your log/stack trace here
-```
-
diff --git a/.github/PULLREQUEST-TEMPLATE.md b/.github/PULLREQUEST-TEMPLATE.md
deleted file mode 100644
index 956d4d30..00000000
--- a/.github/PULLREQUEST-TEMPLATE.md
+++ /dev/null
@@ -1,44 +0,0 @@
-```
-This is a guide to use this Pull Request Template.
-
-# Title
-[feature] Implements the crazy powerful transaction search
-[hotfix] Fixes login with e-mail address
-
-Add a gif that expresses your reaction to the implemented code, make it fun
-
-DO NOT FORGET TO REMOVE THIS BLOCK
-```
-![Git Merge](https://media.giphy.com/media/cFkiFMDg3iFoI/giphy.gif)
-
-### Status
-
-READY / IN DEVELOPMENT
-
-### Whats?
-
-Describe in an objective way what has been done.
-
-### Why?
-
-Why do you need this implementation/fix?
-
-### How?
-
-How did you solve the problem? What are the main flows? Any technical information regarding infrastructure or architecture?
-
-### Attachments (if appropriate)
-
-Add additional informations like screenshots, issue link, zendesk ticket link, jira task link, etc
-
-### Definition of Done:
-- [ ] Increases API documentation
-- [ ] Implements integration tests
-- [ ] Implements unit tests
-- [ ] Is there appropriate logging included?
-- [ ] Does this add new dependencies?
-- [ ] Does need add new version in changelog?
-- [ ] Does need update readme, contributing, etc?
-- [ ] Does need change in CI server?
-- [ ] Will this feature require a new piece of infrastructure be implemented?
-- [ ] Does this PR require a blog post? If so, ensure marketing has signed off on content.
diff --git a/.github/bug_report.md b/.github/bug_report.md
new file mode 100644
index 00000000..0e03cc45
--- /dev/null
+++ b/.github/bug_report.md
@@ -0,0 +1,11 @@
+# Bug
+
+### Descrição
+Descreva detalhadamente o bug.
+
+### Como reproduzir
+Descreva os passos para reproduzir o bug.
+
+### Evidências
+Colocar aqui as evidências do bug.
+
diff --git a/.github/contributing.md b/.github/contributing.md
new file mode 100644
index 00000000..8224937a
--- /dev/null
+++ b/.github/contributing.md
@@ -0,0 +1,35 @@
+# Contribuição
+
+Primeiramente, obrigado por dedicar seu tempo para contribuir!
+
+### Como posso contribuir?
+
+* Faça um fork do projeto;
+* Faça suas alterações;
+* Use o padrão de commits;
+* Crie o pull request para a branch **develop**;
+
+### Pull Requests
+
+Template para os [pull requests](https://github.com/pagarme/woocommerce/blob/master/.github/pull_request_template/pull_request_template.md).
+
+### Mensagens de commit
+
+* As mensagens devem ser feitas em inglês
+* Utilizar o [conventional commits](https://www.conventionalcommits.org/pt-br/v1.0.0/), abaixo segue alguns exemplos de explicações:
+
+| Nomeclatura | Quando utilizar |
+|--------|------------------------------------------|
+| **feat:** | Para novas funcionalidades |
+| **fix:** | Para correções de bugs |
+| **docs:** | Para atualização de uma documentação |
+| **refactor:** | Para refatoração de um código |
+| **perf:** | Para mudanças que melhoram a performance |
+
+Abaixo seguem alguns exemplos de commits:
+
+* feat: adding function to exclude saved credit card to customer
+* fix: pix qr code not showing in e-mail
+* docs: adding contribution section in readme
+* refactor: moving credit card javascript code to requirejs file
+* perf: removing unnecessary order update when access admin order page
diff --git a/.github/data/.htaccess b/.github/data/.htaccess
deleted file mode 100644
index 7fa81ea4..00000000
--- a/.github/data/.htaccess
+++ /dev/null
@@ -1,10 +0,0 @@
-# BEGIN WordPress
-
-RewriteEngine On
-RewriteBase /
-RewriteRule ^index\.php$ - [L]
-RewriteCond %{REQUEST_FILENAME} !-f
-RewriteCond %{REQUEST_FILENAME} !-d
-RewriteRule . /index.php [L]
-
-# END WordPress
\ No newline at end of file
diff --git a/.github/data/Dockerfile b/.github/data/Dockerfile
index e653fcfb..5f860880 100644
--- a/.github/data/Dockerfile
+++ b/.github/data/Dockerfile
@@ -1,7 +1,17 @@
-FROM thiagobarradas/woocommerce:3.5.3-wp5.0.2-php7.2
+ARG WORDPRESS_IMAGE_VERSION=latest
+FROM wordpress:$WORDPRESS_IMAGE_VERSION
MAINTAINER Open Source Team
-COPY . /app/wp-content/plugins/pagarme-payments-for-woocommerce
-RUN mv /app/wp-content/plugins/pagarme-payments-for-woocommerce/.htaccess /app/.htaccess
+WORKDIR /var/www/html/
-WORKDIR /app
+RUN apt-get update \
+ && apt-get install wget -y \
+ && apt-get clean
+
+RUN wget https://github.com/DataDog/dd-trace-php/releases/latest/download/datadog-setup.php -O datadog-setup.php
+
+RUN php datadog-setup.php --php-bin=all --enable-appsec
+
+COPY . ./wp-content
+
+COPY plugins/pagarme-payments-for-woocommerce/.github/data/custom.ini $PHP_INI_DIR/conf.d/
diff --git a/.github/data/custom.ini b/.github/data/custom.ini
new file mode 100644
index 00000000..201a188d
--- /dev/null
+++ b/.github/data/custom.ini
@@ -0,0 +1,4 @@
+file_uploads = On
+upload_max_filesize = 200M
+post_max_size = 200M
+max_execution_time = 600
diff --git a/.github/data/install-zips.sh b/.github/data/install-zips.sh
new file mode 100644
index 00000000..7da79afc
--- /dev/null
+++ b/.github/data/install-zips.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+
+while getopts w:f:m: flag
+do
+ case "${flag}" in
+ w) wcVersion=$OPTARG;;
+ f) wcExtraCheckoutFieldsVersion=$OPTARG;;
+ m) wpMailCatcherVersion=$OPTARG;;
+ esac
+done
+
+installZip() {
+ curl -L $1 -o $2
+ unzip $2 -d $3
+ rm $2
+}
+
+latestStable="latest-stable"
+pluginsDir="plugins"
+themesDir="themes"
+
+wordpressDownloadUrl="https://downloads.wordpress.org"
+
+if [[ -z "$wcVersion" ]]; then
+ wcVersion=$latestStable
+fi
+
+if [[ -z "$wcExtraCheckoutFieldsVersion" ]]; then
+ wcExtraCheckoutFieldsVersion=$latestStable
+fi
+
+if [[ -z "$wpMailCatcherVersion" ]]; then
+ wpMailCatcherVersion=$latestStable
+fi
+
+
+installZip "$wordpressDownloadUrl/plugin/woocommerce.$wcVersion.zip" "woocommerce.zip" "$pluginsDir"
+installZip "$wordpressDownloadUrl/plugin/woocommerce-extra-checkout-fields-for-brazil.$wcExtraCheckoutFieldsVersion.zip" "woocommerce-extra-checkout-fields-for-brazil.zip" "$pluginsDir"
+installZip "$wordpressDownloadUrl/plugin/wp-mail-catcher.$wpMailCatcherVersion.zip" "wp-mail-catcher.zip" "$pluginsDir"
+installZip "$wordpressDownloadUrl/theme/storefront.$latestStable.zip" "storefront.zip" "$themesDir"
diff --git a/.github/data/update-wp-config.php b/.github/data/update-wp-config.php
deleted file mode 100644
index 389f83e7..00000000
--- a/.github/data/update-wp-config.php
+++ /dev/null
@@ -1,13 +0,0 @@
-
\ No newline at end of file
diff --git a/.github/data/wait-for-mysql.sh b/.github/data/wait-for-mysql.sh
deleted file mode 100644
index 50361060..00000000
--- a/.github/data/wait-for-mysql.sh
+++ /dev/null
@@ -1,4 +0,0 @@
-while ! /etc/init.d/mysql status | grep -m1 'is running'; do
- sleep 1
- echo "Waiting for mysql service..."
-done
\ No newline at end of file
diff --git a/.github/feature_request.md b/.github/feature_request.md
new file mode 100644
index 00000000..0ee79355
--- /dev/null
+++ b/.github/feature_request.md
@@ -0,0 +1,4 @@
+# Nova funcionalidade
+
+### Descrição
+Descreva detalhadamente a nova funcionalidade.
diff --git a/.github/pull_request_template/branches/master.md b/.github/pull_request_template/branches/master.md
new file mode 100644
index 00000000..404dbfd4
--- /dev/null
+++ b/.github/pull_request_template/branches/master.md
@@ -0,0 +1,8 @@
+## :sparkles: New Features
+-
+
+## :bug: Bug fixes
+-
+
+## :rocket: Improvements
+-
diff --git a/.github/pull_request_template/pull_request_template.md b/.github/pull_request_template/pull_request_template.md
new file mode 100644
index 00000000..d6068cee
--- /dev/null
+++ b/.github/pull_request_template/pull_request_template.md
@@ -0,0 +1,18 @@
+![Git Merge](https://media.giphy.com/media/cFkiFMDg3iFoI/giphy.gif)
+
+> [!IMPORTANT]
+> Certifique-se de criar o PR para a branch **develop**.
+
+### Qual o tipo de PR é esse? (marque todos os aplicáveis)
+- [ ] Refatoração
+- [ ] Adição de funcionalidade
+- [ ] Correção de bug
+- [ ] Otimização
+- [ ] Atualização de documentação
+
+### Descrição
+Descreva brevemente as alterações feitas neste PR.
+
+
+### Cenários testados
+Descreva brevemente quais foram os cenários testados com as alterações feitas neste PR.
diff --git a/.github/workflows/build_branch.yml b/.github/workflows/build_branch.yml
new file mode 100644
index 00000000..b58b8be1
--- /dev/null
+++ b/.github/workflows/build_branch.yml
@@ -0,0 +1,36 @@
+name: BUILD BRANCH
+
+on:
+ workflow_dispatch:
+ inputs:
+ wordpress_image_version:
+ required: false
+ type: string
+ default: latest
+ woocommerce_version:
+ required: false
+ type: string
+ default: latest-stable
+ woocommerce_extra_checkout_fields_version:
+ required: false
+ type: string
+ default: latest-stable
+ wp_mail_catcher_version:
+ required: false
+ type: string
+ default: latest-stable
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ call-workflow-cd:
+ uses: pagarme/woocommerce/.github/workflows/cd_reusable.yml@master
+ with:
+ tag: ${{ GITHUB_REF#refs/heads/ }}
+ wordpress_image_version: ${{ inputs.wordpress_image_version }}
+ woocommerce_version: ${{ inputs.woocommerce_version }}
+ woocommerce_extra_checkout_fields_version: ${{ inputs.woocommerce_extra_checkout_fields_version }}
+ wp_mail_catcher_version: ${{ inputs.wp_mail_catcher_version }}
+ secrets:
+ inherit
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml
deleted file mode 100644
index c313bca5..00000000
--- a/.github/workflows/cd.yml
+++ /dev/null
@@ -1,83 +0,0 @@
-name: Continuous Delivery
-
-on:
- push:
- branches:
- - develop
- - test
- - stg
- - master
-
-concurrency:
- group: ${{github.workflows}}-${{github.ref}}
- cancel-in-progress: true
-
-jobs:
- publish:
- name: Publish
- container:
- image: docker:rc-git
- runs-on: ubuntu-latest
- env:
- DOCKER_BUILDKIT: 0
- steps:
- -
- name: Checkout Code
- uses: actions/checkout@v3
- -
- name: Copy CI files to root
- run: |
- cp .github/data/.htaccess .
- cp .github/data/Dockerfile .
- cp .github/data/update-wp-config.php .
- cp .github/data/wait-for-mysql.sh .
- -
- name: Build image base for modifications
- run: |
- docker build -t ${{ github.repository }}:latest .
- docker run --name newimage -d -p3306:3306 -p80:80 ${{ github.repository }}:latest
- -
- name: Wait for MySQL Service
- run: |
- ls -la
- docker exec newimage sh /app/wp-content/plugins/${{ vars.PLUGIN_NAME }}/wait-for-mysql.sh
- docker exec newimage rm /app/wp-content/plugins/${{ vars.PLUGIN_NAME }}/wait-for-mysql.sh
- -
- name: Activate and setup Plugin
- run: |
- docker exec newimage wp plugin activate ${{ vars.PLUGIN_NAME }} --allow-root
- docker exec newimage chmod -R 777 /app/wp-content/plugins/${{ vars.PLUGIN_NAME }}
- docker exec newimage mysql -u root -D wordpress -e "REPLACE INTO wp_options (option_name,option_value) VALUES (\"${{ vars.PLUGIN_META_NAME }}\",\"${{ secrets.PLUGIN_CONFIG }}\");"
- docker exec newimage curl -X GET "http://localhost/wp-content/plugins/${{ vars.PLUGIN_NAME }}/update-wp-config.php?url=https://${{ github.ref_name }}${{ secrets.STAGING_URL }}"
- docker exec newimage rm /app/wp-content/plugins/${{ vars.PLUGIN_NAME }}/update-wp-config.php
- docker exec newimage touch test5.txt
- -
- name: Clear useless files
- run: |
- docker exec newimage sh -c "cd /app/wp-content/plugins/${{ vars.PLUGIN_NAME }}" && \
- rm -rf .github .plugin-data .git .gitignore .editorconfig && \
- rm -rf Dockerfile update-wp-config.php wait-for-mysql.sh LICENSE *.MD
- -
- name: Log in to Docker Hub
- uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
- with:
- registry: ${{ secrets.DOCKER_ACCOUNT }}
- username: ${{ secrets.DOCKER_USERNAME }}
- password: ${{ secrets.DOCKER_PASSWORD }}
- -
- name: Extract metadata (tags, labels) for Docker
- id: meta
- uses: docker/metadata-action@v2
- with:
- images: ${{ secrets.DOCKER_ACCOUNT }}/${{ vars.PROJECT_NAME }}
- -
- name: Deploy
- run: |
- sleep 5 && docker stop newimage
- docker commit newimage ${{ secrets.DOCKER_ACCOUNT }}/${{ vars.PROJECT_NAME }}:${{ github.ref_name }}
- docker push "${{ secrets.DOCKER_ACCOUNT }}/${{ vars.PROJECT_NAME }}:${{ github.ref_name }}"
- # -
- # # name: Send deployment webhook to Rancher
- # # run: |
- # # BODY='{"push_data":{"tag":"'"${{ github.ref_name }}"'"},"repository":{"repo_name":"'"${{ secrets.DOCKER_ACCOUNT }}/${{ github.repository }}"'"}}'
-
diff --git a/.github/workflows/cd_master.yml b/.github/workflows/cd_master.yml
new file mode 100644
index 00000000..84a2180b
--- /dev/null
+++ b/.github/workflows/cd_master.yml
@@ -0,0 +1,41 @@
+name: CD MASTER
+
+on:
+ pull_request:
+ branches: [ "master" ]
+ types: closed
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+env:
+ wordpress_version_master: ${{ vars.wordpress_version_master }}
+ woocommerce_version_master: ${{ vars.woocommerce_version_master }}
+ woocommerce_extra_checkout_fields_version_master: ${{ vars.woocommerce_extra_checkout_fields_version_master }}
+ wp_mail_catcher_version_master: ${{ vars.wp_mail_catcher_version_master }}
+jobs:
+ generate-variables:
+ runs-on: ubuntu-latest
+ outputs:
+ wordpress_version_master: ${{ steps.main_step.outputs.wordpress_version_master }}
+ woocommerce_version_master: ${{ steps.main_step.outputs.woocommerce_version_master }}
+ woocommerce_extra_checkout_fields_version_master: ${{ steps.main_step.outputs.woocommerce_extra_checkout_fields_version_master }}
+ wp_mail_catcher_version_master: ${{ steps.main_step.outputs.wp_mail_catcher_version_master }}
+ steps:
+ - id: main_step
+ run: |
+ echo "wordpress_version_master=$wordpress_version_master" >> $GITHUB_OUTPUT
+ echo "woocommerce_version_master=$woocommerce_version_master" >> $GITHUB_OUTPUT
+ echo "woocommerce_extra_checkout_fields_version_master=$woocommerce_extra_checkout_fields_version_master" >> $GITHUB_OUTPUT
+ echo "wp_mail_catcher_version_master=$wp_mail_catcher_version_master" >> $GITHUB_OUTPUT
+ call-workflow-cd:
+ needs:
+ - generate-variables
+ uses: pagarme/woocommerce/.github/workflows/cd_reusable.yml@master
+ with:
+ tag: master
+ wordpress_image_version: ${{ needs.generate-variables.outputs.wordpress_version_master }}
+ woocommerce_version: ${{ needs.generate-variables.outputs.woocommerce_version_master }}
+ woocommerce_extra_checkout_fields_version: ${{ needs.generate-variables.outputs.woocommerce_extra_checkout_fields_version_master }}
+ wp_mail_catcher_version: ${{ needs.generate-variables.outputs.wp_mail_catcher_version_master }}
+ secrets:
+ inherit
diff --git a/.github/workflows/cd_php8.yml b/.github/workflows/cd_php8.yml
new file mode 100644
index 00000000..4c11043a
--- /dev/null
+++ b/.github/workflows/cd_php8.yml
@@ -0,0 +1,41 @@
+name: CD PHP8
+
+on:
+ pull_request:
+ branches: [ "develop" ]
+ types: closed
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+env:
+ wordpress_version_php8: ${{ vars.wordpress_version_php8 }}
+ woocommerce_version_php8: ${{ vars.woocommerce_version_php8 }}
+ woocommerce_extra_checkout_fields_version_php8: ${{ vars.woocommerce_extra_checkout_fields_version_php8 }}
+ wp_mail_catcher_version_php8: ${{ vars.wp_mail_catcher_version_php8 }}
+jobs:
+ generate-variables:
+ runs-on: ubuntu-latest
+ outputs:
+ wordpress_version_php8: ${{ steps.main_step.outputs.wordpress_version_php8 }}
+ woocommerce_version_php8: ${{ steps.main_step.outputs.woocommerce_version_php8 }}
+ woocommerce_extra_checkout_fields_version_php8: ${{ steps.main_step.outputs.woocommerce_extra_checkout_fields_version_php8 }}
+ wp_mail_catcher_version_php8: ${{ steps.main_step.outputs.wp_mail_catcher_version_php8 }}
+ steps:
+ - id: main_step
+ run: |
+ echo "wordpress_version_php8=$wordpress_version_php8" >> $GITHUB_OUTPUT
+ echo "woocommerce_version_php8=$woocommerce_version_php8" >> $GITHUB_OUTPUT
+ echo "woocommerce_extra_checkout_fields_version_php8=$woocommerce_extra_checkout_fields_version_php8" >> $GITHUB_OUTPUT
+ echo "wp_mail_catcher_version_php8=$wp_mail_catcher_version_php8" >> $GITHUB_OUTPUT
+ call-workflow-cd:
+ needs:
+ - generate-variables
+ uses: pagarme/woocommerce/.github/workflows/cd_reusable.yml@develop
+ with:
+ tag: php8
+ wordpress_image_version: ${{ needs.generate-variables.outputs.wordpress_version_php8 }}
+ woocommerce_version: ${{ needs.generate-variables.outputs.woocommerce_version_php8 }}
+ woocommerce_extra_checkout_fields_version: ${{ needs.generate-variables.outputs.woocommerce_extra_checkout_fields_version_php8 }}
+ wp_mail_catcher_version: ${{ needs.generate-variables.outputs.wp_mail_catcher_version_php8 }}
+ secrets:
+ inherit
diff --git a/.github/workflows/cd_reusable.yml b/.github/workflows/cd_reusable.yml
new file mode 100644
index 00000000..971375fa
--- /dev/null
+++ b/.github/workflows/cd_reusable.yml
@@ -0,0 +1,58 @@
+name: CD REUSABLE
+
+on:
+ workflow_call:
+ inputs:
+ tag:
+ required: true
+ type: string
+ wordpress_image_version:
+ required: false
+ type: string
+ default: latest
+ woocommerce_version:
+ required: false
+ type: string
+ default: latest-stable
+ woocommerce_extra_checkout_fields_version:
+ required: false
+ type: string
+ default: latest-stable
+ wp_mail_catcher_version:
+ required: false
+ type: string
+ default: latest-stable
+
+jobs:
+ publish:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout Code
+ uses: actions/checkout@v4
+ with:
+ path: 'plugins/pagarme-payments-for-woocommerce'
+ - name: Download other plugins
+ run: |
+ chmod +x plugins/pagarme-payments-for-woocommerce/.github/data/install-zips.sh \
+ && bash plugins/pagarme-payments-for-woocommerce/.github/data/install-zips.sh -w ${{ inputs.woocommerce_version }} -f ${{ inputs.woocommerce_extra_checkout_fields_version }} -m ${{ inputs.wp_mail_catcher_version }}
+ - name: Log in to Docker Hub
+ uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
+ with:
+ registry: ${{ secrets.DOCKER_ACCOUNT }}
+ username: ${{ secrets.DOCKER_USERNAME }}
+ password: ${{ secrets.DOCKER_PASSWORD }}
+ - name: Extract metadata (tags, labels) for Docker
+ id: meta
+ uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
+ with:
+ images: ${{ secrets.DOCKER_ACCOUNT }}/woocommerce-pagarme
+ - name: Build and push Docker image
+ uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
+ with:
+ build-args: |
+ WORDPRESS_IMAGE_VERSION=${{ inputs.wordpress_image_version }}
+ context: .
+ file: plugins/pagarme-payments-for-woocommerce/.github/data/Dockerfile
+ push: true
+ tags: ${{ secrets.DOCKER_ACCOUNT }}/woocommerce-pagarme:${{ inputs.tag }}
+ labels: ${{ steps.meta.outputs.labels }}
diff --git a/.github/workflows/cd_stg.yml b/.github/workflows/cd_stg.yml
new file mode 100644
index 00000000..ede39bc5
--- /dev/null
+++ b/.github/workflows/cd_stg.yml
@@ -0,0 +1,41 @@
+name: CD STG
+
+on:
+ pull_request:
+ branches: [ "develop" ]
+ types: closed
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+env:
+ wordpress_version_stg: ${{ vars.wordpress_version_stg }}
+ woocommerce_version_stg: ${{ vars.woocommerce_version_stg }}
+ woocommerce_extra_checkout_fields_version_stg: ${{ vars.woocommerce_extra_checkout_fields_version_stg }}
+ wp_mail_catcher_version_stg: ${{ vars.wp_mail_catcher_version_stg }}
+jobs:
+ generate-variables:
+ runs-on: ubuntu-latest
+ outputs:
+ wordpress_version_stg: ${{ steps.main_step.outputs.wordpress_version_stg }}
+ woocommerce_version_stg: ${{ steps.main_step.outputs.woocommerce_version_stg }}
+ woocommerce_extra_checkout_fields_version_stg: ${{ steps.main_step.outputs.woocommerce_extra_checkout_fields_version_stg }}
+ wp_mail_catcher_version_stg: ${{ steps.main_step.outputs.wp_mail_catcher_version_stg }}
+ steps:
+ - id: main_step
+ run: |
+ echo "wordpress_version_stg=$wordpress_version_stg" >> $GITHUB_OUTPUT
+ echo "woocommerce_version_stg=$woocommerce_version_stg" >> $GITHUB_OUTPUT
+ echo "woocommerce_extra_checkout_fields_version_stg=$woocommerce_extra_checkout_fields_version_stg" >> $GITHUB_OUTPUT
+ echo "wp_mail_catcher_version_stg=$wp_mail_catcher_version_stg" >> $GITHUB_OUTPUT
+ call-workflow-cd:
+ needs:
+ - generate-variables
+ uses: pagarme/woocommerce/.github/workflows/cd_reusable.yml@develop
+ with:
+ tag: stg
+ wordpress_image_version: ${{ needs.generate-variables.outputs.wordpress_version_stg }}
+ woocommerce_version: ${{ needs.generate-variables.outputs.woocommerce_version_stg }}
+ woocommerce_extra_checkout_fields_version: ${{ needs.generate-variables.outputs.woocommerce_extra_checkout_fields_version_stg }}
+ wp_mail_catcher_version: ${{ needs.generate-variables.outputs.wp_mail_catcher_version_stg }}
+ secrets:
+ inherit
diff --git a/assets/javascripts/admin/pagarme_settings.js b/assets/javascripts/admin/pagarme_settings.js
index fa686a61..357a2d9b 100644
--- a/assets/javascripts/admin/pagarme_settings.js
+++ b/assets/javascripts/admin/pagarme_settings.js
@@ -1,14 +1,15 @@
/* globals jquery, ajaxurl, pagarme_settings */
+/* jshint esversion: 6 */
( function ($) {
$('.wc_gateways').on(
'click',
'.wc-payment-gateway-method-toggle-enabled',
function () {
- var $link = $(this),
- $row = $link.closest('tr'),
- $toggle = $link.find('.woocommerce-input-toggle');
+ const $link = $(this),
+ $row = $link.closest('tr'),
+ $toggle = $link.find('.woocommerce-input-toggle');
- var data = {
+ const data = {
action: 'woocommerce_toggle_gateway_enabled',
security: pagarme_settings.nonces.gateway_toggle,
gateway_id: $row.data('gateway_id'),
@@ -50,5 +51,30 @@
return false;
}
);
+
+ const allow_no_address_swal = pagarme_settings.allow_no_address_swal;
+ $('#allow_no_address').on(
+ 'change',
+ function () {
+ const element = $(this);
+ const value = element.val();
+ if (value === 'yes') {
+ swal({
+ type: 'warning',
+ title: allow_no_address_swal.title,
+ text: allow_no_address_swal.text,
+ showConfirmButton: true,
+ showCancelButton: true,
+ cancelButtonText: allow_no_address_swal.cancelButtonText,
+ allowOutsideClick: false,
+ }).then(
+ function (confirm) {},
+ function (cancel) {
+ element.val('no');
+ }
+ );
+ }
+ }
+ );
}(jQuery)
);
diff --git a/assets/javascripts/front/checkout/model/payment/card.js b/assets/javascripts/front/checkout/model/payment/card.js
index 965bbbad..ee6d9dcd 100644
--- a/assets/javascripts/front/checkout/model/payment/card.js
+++ b/assets/javascripts/front/checkout/model/payment/card.js
@@ -97,7 +97,7 @@ let pagarmeCard = {
},
getCardDataContingency: async function (cardNumber) {
let oldPrefix = '',
- types= this.getBrands(),
+ types = this.getBrands(),
bin = cardNumber.substring(0, 6),
data;
for (const currentType of types) {
@@ -131,7 +131,7 @@ let pagarmeCard = {
return cardsMethods;
},
loadBrand: async function (event) {
- let elem = event.currentTarget;
+ let elem = event.target;
this.removeBrand(elem);
if (!this.isVisible(elem)) {
return;
@@ -206,6 +206,7 @@ let pagarmeCard = {
if (typeof card == 'undefined') {
throw new Error("Invalid data to change card brand");
}
+
let imageSrc = this.getImageSrc(card);
let imgElem = jQuery(elem).parent().find('img');
jQuery(elem).parents('.pagarme-card-number-row').find(this.brandTarget).attr('value', card[0].brand);
@@ -371,14 +372,14 @@ let pagarmeCard = {
jQuery(document.body).on('updated_checkout', function () {
pagarmeCard.renewEventListener();
let creditCardField = jQuery(pagarmeCard.cardNumberTarget);
- creditCardField.each(function() {
+ creditCardField.each(function () {
if (jQuery(this)?.val() && pagarmeCard.isVisible(jQuery(this)[0])) {
jQuery(this).change();
}
});
});
- jQuery(document).ready(function() {
+ jQuery(document).ready(function () {
jQuery('form.checkout').on('checkout_place_order', function (event) {
return pagarmeCard.canExecute(event);
});
diff --git a/assets/javascripts/front/checkout/model/payment/pix.js b/assets/javascripts/front/checkout/model/payment/pix.js
index 308fee27..b2f199bf 100644
--- a/assets/javascripts/front/checkout/model/payment/pix.js
+++ b/assets/javascripts/front/checkout/model/payment/pix.js
@@ -13,16 +13,29 @@ let pagarmePix = {
if (!elem.length) {
return;
}
- let input = jQuery('').attr({
- value: elem.attr('rawCode')
- }).appendTo(elem.parent()).select();
- document.execCommand('copy', false);
- input.remove();
+ const rawCode = elem.attr('rawCode');
const message = {
type: 'success',
html: 'Código copiado.',
allowOutsideClick: false
};
+
+ if (window.isSecureContext && navigator.clipboard) {
+ navigator.clipboard.writeText(rawCode);
+ new swal(message)
+ return;
+ }
+
+ const input = jQuery('').attr({
+ value: rawCode
+ }).appendTo(elem.parent());
+
+ const [ inputDOMElement ] = input;
+ inputDOMElement.select();
+ inputDOMElement.setSelectionRange(0, input.val().length);
+
+ document.execCommand('copy', false);
+ input.remove();
new swal(message);
}
};
diff --git a/assets/javascripts/front/my-account/wallet.js b/assets/javascripts/front/my-account/wallet.js
index 4648bfc6..c806070a 100644
--- a/assets/javascripts/front/my-account/wallet.js
+++ b/assets/javascripts/front/my-account/wallet.js
@@ -13,14 +13,14 @@ let pagarmeWallet = {
_onClickRemoveCard: function (event) {
event.preventDefault();
swal({
- title: dataSwal.confirm_title,
- text: dataSwal.confirm_text,
+ title: walletConfig.dataSwal.confirm_title,
+ text: walletConfig.dataSwal.confirm_text,
type: 'warning',
showCancelButton: true,
- confirmButtonColor: dataSwal.confirm_color,
- cancelButtonColor: dataSwal.cancel_color,
- confirmButtonText: dataSwal.confirm_button,
- cancelButtonText: dataSwal.cancel_button,
+ confirmButtonColor: walletConfig.dataSwal.confirm_color,
+ cancelButtonColor: walletConfig.dataSwal.cancel_color,
+ confirmButtonText: walletConfig.dataSwal.confirm_button,
+ cancelButtonText: walletConfig.dataSwal.cancel_button,
allowOutsideClick: false,
}).then(this._request.bind(this, event.currentTarget.dataset.value), function () {
});
@@ -29,7 +29,7 @@ let pagarmeWallet = {
swal.showLoading();
jQuery.ajax({
method: 'post',
- url: apiRoute,
+ url: walletConfig.apiRoute,
data: {
card_id: cardId
}
@@ -63,4 +63,4 @@ let pagarmeWallet = {
},
}
-pagarmeWallet.start();
\ No newline at end of file
+pagarmeWallet.start();
diff --git a/assets/stylesheets/admin/notice.css b/assets/stylesheets/admin/notice.css
index 7c031a1d..0d060844 100644
--- a/assets/stylesheets/admin/notice.css
+++ b/assets/stylesheets/admin/notice.css
@@ -12,12 +12,12 @@
margin-right: 1em;
}
-.pagarme-notice .pagarme-notice-message-container a {
+.pagarme-notice .pagarme-notice-message-container a.button {
margin-right: 1em;
cursor: pointer;
}
-.pagarme-notice .pagarme-notice-message-container a:last-child {
+.pagarme-notice .pagarme-notice-message-container a.button:last-child {
margin-right: 0;
}
@@ -28,4 +28,4 @@
.pagarme-notice .pagarme-notice-message-container ul li {
font-style: italic;
-}
\ No newline at end of file
+}
diff --git a/composer.json b/composer.json
index 02007ee4..cd6d2108 100644
--- a/composer.json
+++ b/composer.json
@@ -2,7 +2,7 @@
"name": "pagarme/woocommerce-pagarme-payments",
"description": "Pagar.me module for Woocommerce",
"type": "wordpress-plugin",
- "version": "3.1.8",
+ "version": "3.1.9",
"license": "GPL",
"autoload": {
"psr-4": {
@@ -11,8 +11,7 @@
},
"require": {
"mashape/unirest-php": "^3.0",
- "pagarme/ecommerce-module-core": "2.1.0",
- "psr/log": "1.1.4",
- "pagarme/pagarmecoreapi": "5.6.2"
+ "pagarme/ecommerce-module-core": "2.3.*",
+ "psr/log": "1.1.4"
}
}
diff --git a/constants.php b/constants.php
index d7af280e..0b6c8ba2 100644
--- a/constants.php
+++ b/constants.php
@@ -12,7 +12,7 @@ function wc_pagarme_define($name, $value)
wc_pagarme_define('WCMP_SLUG', 'woo-pagarme-payments');
wc_pagarme_define('WCMP_PREFIX', 'pagarme');
-wc_pagarme_define('WCMP_VERSION', '3.1.8');
+wc_pagarme_define('WCMP_VERSION', '3.1.9');
wc_pagarme_define('WCMP_ROOT_PATH', dirname(__FILE__) . '/');
wc_pagarme_define('WCMP_ROOT_SRC', WCMP_ROOT_PATH . 'src/');
wc_pagarme_define('WCMP_ROOT_FILE', WCMP_ROOT_PATH . WCMP_SLUG . '.php');
diff --git a/docs/README.md b/docs/README.md
index 65b34c57..3678d58b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,41 +1,43 @@
-# Pagar.me módulo para WooCommerce #
-**Contributors:** [Pagar.me](https://profiles.wordpress.org/pagarme)
+![Pagar.me e WooCommerce logo](https://github.com/pagarme/woocommerce/blob/master/docs/images/pagarme+woocommerce-white.png#gh-dark-mode-only)
+![Pagar.me e WooCommerce logo](https://github.com/pagarme/woocommerce/blob/master/docs/images/pagarme+woocommerce.png#gh-light-mode-only)
+
+# Pagar.me módulo para WooCommerce
+
**Tags:** ecommerce, e-commerce, store, sales, sell, shop, cart, checkout, woocommerce, pagarme, payments, creditcard
-**Requires at least:** 5.0
-**Tested up to:** 5.7
-**Stable tag:** 2.0.5
-**Requires PHP:** 7.1
+
**License:** MIT
+
**License URI:** https://github.com/pagarme/woocommerce/blob/master/LICENSE
-Módulo de integração da Pagar.me com o WooCommerce. Aceite pagamentos de cartão de crédito, boleto, multimeios e aumente a sua conversão.
+Módulo de integração da Pagar.me com o WooCommerce. Aceite pagamentos de cartão de crédito, pix, boleto, voucher e multimeios, e aumente a sua conversão.
-## Descrição ##
+## Descrição
A inteligência do seu pagamento - Soluções focadas em aumentar sua conversão!
Pagamentos tem que ser fáceis. São muitos passos por trás de uma simples transação financeira. Mas o seu consumidor não precisa saber disso. Nossas soluções estão disponíveis para ajuda-lo a aumentar sua conversão e oferecer a melhor experiência no momento do pagamento para o seu cliente.
-## Compatibilidade ##
+## Contribuição
+
+Se você está interessado em contribuir para o desenvolvimento deste projeto, ficamos felizes em receber sua ajuda! No [contributing.md](https://github.com/pagarme/woocommerce/blob/master/.github/contributing.md) está o guia de como contribuir com o projeto.
+
+## Compatibilidade
+- Requer Wordpress 4.1 ou posterior para funcionar.
- Requer WooCommerce 3.9 ou posterior para funcionar.
- Requer versão do PHP maior ou igual a 7.1.
-## Instalação do plugin: ##
+## Instalação do plugin
- Envie os arquivos do plugin para a pasta wp-content/plugins, ou instale usando o instalador de plugins do WordPress.
- Ative o plugin.
-## Requerimentos: ##
+## Requerimentos
-- [Conta na Pagar.me] (http://www.pagar.me/)
-- [WooCommerce] (https://wordpress.org/plugins/woocommerce/)
-- [WooCommerce Extra Checkout Fields for Brazil](https://wordpress.org/plugins/woocommerce-extra-checkout-fields-for-brazil/) em sua última versão
+- [Conta na Pagar.me](http://www.pagar.me/)
+- [WooCommerce](https://wordpress.org/plugins/woocommerce/)
-## Configurações ##
+## Contribuidores
-- Após a instalação e ativação do plugin acesse o menu WooCommerce > Configurações > Finalizar Compra > Pagar.me Pagamentos
-- Habilite o pagamento
-- Selecione o ambiente (Produção ou Sandbox)
-- Insira as chaves (pública e privada)
-- Em seguida selecione quais meios de pagamento deseja utilizar
\ No newline at end of file
+| ![eduardobattisti avatar](https://avatars.githubusercontent.com/u/56602897?s=60&v=4)
[eduardobattisti](https://github.com/eduardobattisti) |
+|----------------------------------------------------------------------------------------------------------------------------------|
diff --git a/docs/images/pagarme+woocommerce-white.png b/docs/images/pagarme+woocommerce-white.png
new file mode 100644
index 00000000..c5e3d0f8
Binary files /dev/null and b/docs/images/pagarme+woocommerce-white.png differ
diff --git a/docs/images/pagarme+woocommerce.png b/docs/images/pagarme+woocommerce.png
new file mode 100644
index 00000000..1bdedd0b
Binary files /dev/null and b/docs/images/pagarme+woocommerce.png differ
diff --git a/languages/woo-pagarme-payments-pt_BR.mo b/languages/woo-pagarme-payments-pt_BR.mo
index 20b2ad23..5044c248 100644
Binary files a/languages/woo-pagarme-payments-pt_BR.mo and b/languages/woo-pagarme-payments-pt_BR.mo differ
diff --git a/languages/woo-pagarme-payments-pt_BR.po b/languages/woo-pagarme-payments-pt_BR.po
index aa4a3df5..d5c8bfdf 100644
--- a/languages/woo-pagarme-payments-pt_BR.po
+++ b/languages/woo-pagarme-payments-pt_BR.po
@@ -5,7 +5,7 @@ msgstr ""
"Project-Id-Version: WooCommerce Pagar.me Payments 1.0\n"
"Report-Msgid-Bugs-To: https://wordpress.org/support/plugin/woo-pagarme-payments\n"
"POT-Creation-Date: 2018-06-22 13:58-0300\n"
-"PO-Revision-Date: 2023-09-18 18:31-0300\n"
+"PO-Revision-Date: 2023-11-17 16:02-0300\n"
"Last-Translator: Pagar.me\n"
"Language-Team: \n"
"Language: pt_BR\n"
@@ -13,7 +13,7 @@ msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
-"X-Generator: Poedit 3.3.2\n"
+"X-Generator: Poedit 3.4.1\n"
"X-Poedit-SourceCharset: UTF-8\n"
"X-Poedit-KeywordsList: __;_e;__ngettext:1,2;_n:1,2;__ngettext_noop:1,2;_n_noop:1,2;_c;_nc:1,2;_x:1,2c;_ex:1,2c;"
"_nx:4c,1,2;_nx_noop:4c,1,2\n"
@@ -423,6 +423,17 @@ msgstr "Logs"
msgid "Log Pagar.me events, you can check this log in WooCommerce>Status>Logs."
msgstr "Registra eventos da Pagar.me, você pode conferir esse arquivo de log em WooCommerce>Status>Logs."
+msgid "Allow order without address"
+msgstr "Permitir compras sem endereço"
+
+#: src/Controller/Settings.php:109
+msgid ""
+"For PSP customers with Pagar.me Antifraud active, it is mandatory to fill in all address fields. %sRead documentation "
+"»%s"
+msgstr ""
+"Para clientes PSP com o Antifraude Pagar.me ativo, é obrigatório preencher todos os campos de endereço. %sLeia a "
+"documentação »%s"
+
#: src/Controller/Gateways/CreditCard.php:115 src/Controller/Gateways/CreditCard.php:157
#: src/Controller/Gateways/Pix.php:59 src/Controller/Gateways/Voucher.php:72 src/Controller/Gateways/Voucher.php:102
msgid "This field is required."
@@ -833,6 +844,11 @@ msgstr "Os seguintes campos de checkout são obrigatórios, mas não foram encon
msgid "Please, make sure to include them for Pagar.me module to work."
msgstr "Por favor, certifique-se de incluí-los para que o módulo da Pagar.me funcione."
+msgid "You can install %s or any other plugin of your choice to add the missing fields. %sRead documentation »%s"
+msgstr ""
+"Você pode instalar o %s ou qualquer outro plugin de sua escolha para adicionar os campos ausentes. %sLeia a "
+"documentação »%s"
+
#. Description of the plugin/theme
msgid "Enable Pagar.me Gateway for WooCommerce"
msgstr "Habilita o gateway de pagamento Pagar.me para o WooCommerce"
@@ -1142,6 +1158,9 @@ msgstr "Houve um problema com a troca de pagamento."
msgid "Error creating subscription free trial."
msgstr "Erro ao criar a avaliação gratuita da assinatura."
+msgid "Installment Fee"
+msgstr "Taxa de parcelamento"
+
#: src/Controller/HubAccounts.php:160
msgid "Access Dash Configurations"
msgstr "Acessar Configurações da Dash"
@@ -1244,3 +1263,6 @@ msgstr "As configurações da Dash não foram recuperadas. Por favor, tente nova
#: templates/adminhtml/system/config/form/field/hub/integration.phtml:25
msgid "Access Pagar.me Dash"
msgstr "Acessar o Dash da Pagar.me"
+
+msgid "If your Pagar.me Antifraud is active, orders will fail."
+msgstr "Se o seu Antifraude Pagar.me estiver ativo, os pedidos irão falhar."
diff --git a/package.json b/package.json
index 21a560ef..79ec883d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "woo-pagarme-payments",
- "version": "3.1.8",
+ "version": "3.1.9",
"description": "Pagar.me module for Woocommerce",
"main": "woo-pagarme-payments.php",
"dependencies": {},
diff --git a/readme.txt b/readme.txt
index 7fb5825e..1d760482 100644
--- a/readme.txt
+++ b/readme.txt
@@ -4,7 +4,7 @@ Tags: payments, pagarme, ecommerce, e-commerce, store, sales, sell, shop, cart,
Requires at least: 4.1
Tested up to: 6.3
Requires PHP: 7.1
-Stable tag: 3.1.8
+Stable tag: 3.1.9
License: MIT
License URI: https://github.com/pagarme/woocommerce/blob/master/LICENSE
@@ -22,21 +22,23 @@ Nosso processo de instalação é simples e bem detalhado:
== Changelog ==
Lançamos versões regularmente com melhorias, correções e atualizações.
-= 3.1.8 (14/11/2023) =
-Você pode conferir essas atualizações aqui: [Github](https://github.com/pagarme/woocommerce/releases/tag/3.1.8)
+= 3.1.9 (13/12/2023) =
+Você pode conferir essas atualizações aqui: [Github](https://github.com/pagarme/woocommerce/releases/tag/3.1.9)
+
+* **Novas implementações:**
+ * Permitir compras sem endereço
+ * Exibição dos valores das taxas de parcelas de cartão nos pedidos
* **Correções:**
- * Mensagem de domínio incorreto
+ * Código Pix não é copiado
+ * Colar cartão de crédito em IOS não finaliza o pedido
+ * Notice do php no bloco de wallets
-= 3.1.7 (07/11/2023) =
-Você pode conferir essas atualizações aqui: [Github](https://github.com/pagarme/woocommerce/releases/tag/3.1.7)
+= 3.1.8 (14/11/2023) =
+Você pode conferir essas atualizações aqui: [Github](https://github.com/pagarme/woocommerce/releases/tag/3.1.8)
* **Correções:**
- * Falha ao renovar pedido manualmente com cartão de crédito.
- * Falha na validação do cartão de crédito ao trocar meio de entrega.
- * Alto uso de memória no recebimento de webhook de Charge.
- * Falha na visualização do parcelamento para 2 cartões de crédito
- * Pedidos com reembolso na charge exibem erro no admin
+ * Mensagem de domínio incorreto
== Upgrade Notice ==
Nosso plugin agora é compatível com Woocommerce Subscriptions
diff --git a/src/Action/ActionsRunner.php b/src/Action/ActionsRunner.php
new file mode 100644
index 00000000..c19ae217
--- /dev/null
+++ b/src/Action/ActionsRunner.php
@@ -0,0 +1,19 @@
+actionClasses as $actionClass) {
+ $class = sprintf(__NAMESPACE__ . '\%s', $actionClass);
+ $action = new $class();
+ $action->run();
+ }
+ }
+}
diff --git a/src/Action/OrderActions.php b/src/Action/OrderActions.php
new file mode 100644
index 00000000..630e5356
--- /dev/null
+++ b/src/Action/OrderActions.php
@@ -0,0 +1,50 @@
+isPagarmePaymentMethod() && $order->get_meta('pagarme_card_tax') > 0) {
+ $total = $order->get_meta('pagarme_card_tax');
+ echo "
+ " . __('Installment Fee', 'woo-pagarme-payments') . ": |
+ |
+ " . wc_price($total) . " |
+
";
+ }
+ }
+
+ public function showInstallmentFeesToCustomer($total_rows, $order, $tax_display)
+ {
+ $orderPagarme = new Order($order->get_id());
+ $total = $order->get_total();
+ $installmentsValue = $orderPagarme->get_meta('pagarme_card_tax');
+ if (empty($orderPagarme->get_meta('pagarme_card_tax'))) {
+ $installmentsValue = $orderPagarme->calculateInstallmentFee(
+ $orderPagarme->getTotalAmountByCharges(),
+ $order->get_total()
+ );
+ $total = $orderPagarme->getTotalAmountByCharges();
+ }
+ if ($orderPagarme->isPagarmePaymentMethod() && $installmentsValue > 0) {
+ array_pop($total_rows);
+ $total_rows['pagarme_installment_fee']['label'] = __('Installment Fee', 'woo-pagarme-payments');
+ $total_rows['pagarme_installment_fee']['value'] = wc_price($installmentsValue);
+ $total_rows['order_total']['label'] = __('Total', 'woocommerce');
+ $total_rows['order_total']['value'] = wc_price($total);
+ return $total_rows;
+ }
+ return $total_rows;
+ }
+}
diff --git a/src/Action/RunnerInterface.php b/src/Action/RunnerInterface.php
new file mode 100644
index 00000000..c3104801
--- /dev/null
+++ b/src/Action/RunnerInterface.php
@@ -0,0 +1,11 @@
+cards;
+ return $customer->get_cards();
}
private function addDataToJs()
{
wp_localize_script(
WCMP_JS_HANDLER_BASE_NAME . 'wallet',
- 'apiRoute',
- $this->getApiRoute()
- );
- wp_localize_script(
- WCMP_JS_HANDLER_BASE_NAME . 'wallet',
- 'dataSwal',
- $this->getSwalData()
+ 'walletConfig',
+ $this->getWalletConfig()
);
}
+ private function getWalletConfig()
+ {
+ return [
+ 'apiRoute' => $this->getApiRoute(),
+ 'dataSwal' => $this->getSwalData()
+ ];
+ }
+
private function getApiRoute()
{
return get_home_url(null, '/wc-api/' . Account::WALLET_ENDPOINT);
@@ -72,7 +75,7 @@ private function getApiRoute()
private function getSwalData()
{
- $swalData = [
+ return [
'title' => __('Waiting...', 'woo-pagarme-payments'),
'text' => __('We are processing your request.', 'woo-pagarme-payments'),
'confirm_title' => __('Are you sure?', 'woo-pagarme-payments'),
@@ -82,6 +85,5 @@ private function getSwalData()
'confirm_color' => '#3085d6',
'cancel_color' => '#d33',
];
- return $swalData;
}
}
diff --git a/src/Block/Adminhtml/System/Config/Form/AbstractField.php b/src/Block/Adminhtml/System/Config/Form/AbstractField.php
index d5569dc8..e76c80dc 100644
--- a/src/Block/Adminhtml/System/Config/Form/AbstractField.php
+++ b/src/Block/Adminhtml/System/Config/Form/AbstractField.php
@@ -310,6 +310,13 @@ public function getDefault()
*/
public function setDescription($description)
{
+ if (is_array($description)){
+ $this->description = vsprintf(
+ __($description['format'], 'woo-pagarme-payments'),
+ $description['values']
+ );
+ return $this;
+ }
$this->description = __($description, 'woo-pagarme-payments');
return $this;
}
diff --git a/src/Block/Order/EmailPaymentDetails.php b/src/Block/Order/EmailPaymentDetails.php
index 503b1502..457e30e5 100644
--- a/src/Block/Order/EmailPaymentDetails.php
+++ b/src/Block/Order/EmailPaymentDetails.php
@@ -12,7 +12,6 @@
namespace Woocommerce\Pagarme\Block\Order;
use Woocommerce\Pagarme\Block\Template;
-use Woocommerce\Pagarme\Controller\Gateways\AbstractGateway;
use Woocommerce\Pagarme\Model\Order;
defined('ABSPATH') || exit;
@@ -48,18 +47,4 @@ public function getCharges()
}
return null;
}
-
- /**
- * @param Order $order
- * @return bool
- */
- public function isPagarmePaymentMethod(Order $order)
- {
- if (property_exists($order, 'wc_order')) {
- $paymentMethod = $order->wc_order->get_payment_method();
- return $paymentMethod === AbstractGateway::PAGARME
- || 0 === strpos($paymentMethod, AbstractGateway::WC_PAYMENT_PAGARME);
- }
- return false;
- }
}
diff --git a/src/Block/Order/PaymentDetails.php b/src/Block/Order/PaymentDetails.php
index 3e588e34..fc2d11c0 100644
--- a/src/Block/Order/PaymentDetails.php
+++ b/src/Block/Order/PaymentDetails.php
@@ -12,7 +12,6 @@
namespace Woocommerce\Pagarme\Block\Order;
use Woocommerce\Pagarme\Block\Template;
-use Woocommerce\Pagarme\Controller\Gateways\AbstractGateway;
use Woocommerce\Pagarme\Model\Order;
defined( 'ABSPATH' ) || exit;
@@ -45,14 +44,4 @@ public function getCharges()
}
return null;
}
-
- public function isPagarmePaymentMethod(Order $order)
- {
- if (property_exists($order, 'wc_order')) {
- $paymentMethod = $order->wc_order->get_payment_method();
- return $paymentMethod === AbstractGateway::PAGARME
- || 0 === strpos($paymentMethod, AbstractGateway::WC_PAYMENT_PAGARME);
- }
- return false;
- }
-}
+}
\ No newline at end of file
diff --git a/src/Concrete/WoocommerceCoreSetup.php b/src/Concrete/WoocommerceCoreSetup.php
index be25d6e1..21e3cf9d 100644
--- a/src/Concrete/WoocommerceCoreSetup.php
+++ b/src/Concrete/WoocommerceCoreSetup.php
@@ -241,6 +241,7 @@ private static function fillWithGeneralConfig($dataObj, $storeConfig)
{
$dataObj->enabled = (bool)$storeConfig->getEnabled();
$dataObj->testMode = $storeConfig->getIsSandboxMode();
+ $dataObj->allowNoAddress = $storeConfig->getAllowNoAddress();
$dataObj->sendMail = false;
$dataObj->createOrder = false;
diff --git a/src/Concrete/WoocommercePlatformOrderDecorator.php b/src/Concrete/WoocommercePlatformOrderDecorator.php
index 103503d6..e2d68d0b 100644
--- a/src/Concrete/WoocommercePlatformOrderDecorator.php
+++ b/src/Concrete/WoocommercePlatformOrderDecorator.php
@@ -5,20 +5,17 @@
use Woocommerce\Pagarme\Model\Order;
use Woocommerce\Pagarme\Model\Customer as PagarmeCustomer;
use Woocommerce\Pagarme\Model\Api;
+use Woocommerce\Pagarme\Model\Config;
use Woocommerce\Pagarme\Model\Payment as WCModelPayment;
use Woocommerce\Pagarme\Helper\Utils;
-use Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup as PagarmeSetup;
use Pagarme\Core\Kernel\Abstractions\AbstractPlatformOrderDecorator;
use Pagarme\Core\Kernel\Aggregates\Charge;
use Pagarme\Core\Kernel\Interfaces\PlatformInvoiceInterface;
-use Pagarme\Core\Kernel\Interfaces\PlatformOrderInterface;
use Pagarme\Core\Kernel\Services\MoneyService;
use Pagarme\Core\Kernel\Services\OrderService;
-use Pagarme\Core\Kernel\ValueObjects\Id\CustomerId;
use Pagarme\Core\Kernel\ValueObjects\Id\OrderId;
use Pagarme\Core\Kernel\ValueObjects\OrderState;
use Pagarme\Core\Kernel\ValueObjects\OrderStatus;
-use Pagarme\Core\Kernel\ValueObjects\PaymentMethod;
use Pagarme\Core\Payment\Aggregates\Address;
use Pagarme\Core\Payment\Aggregates\Customer;
use Pagarme\Core\Payment\Aggregates\Item;
@@ -31,15 +28,12 @@
use Pagarme\Core\Payment\Aggregates\Shipping;
use Pagarme\Core\Payment\Factories\PaymentFactory;
use Pagarme\Core\Payment\Repositories\CustomerRepository as CoreCustomerRepository;
-use Pagarme\Core\Payment\Repositories\SavedCardRepository;
use Pagarme\Core\Payment\ValueObjects\CustomerPhones;
use Pagarme\Core\Payment\ValueObjects\CustomerType;
use Pagarme\Core\Payment\ValueObjects\Phone;
use Pagarme\Core\Recurrence\Services\RecurrenceService;
use Pagarme\Core\Kernel\Services\LocalizationService;
use Pagarme\Core\Kernel\Services\LogService;
-use Pagarme\Core\Kernel\Aggregates\Transaction;
-use Pagarme\Core\Kernel\ValueObjects\TransactionType;
use WC_Order;
class WoocommercePlatformOrderDecorator extends AbstractPlatformOrderDecorator
@@ -1078,6 +1072,11 @@ public function getShipping()
protected function getAddress($platformAddress)
{
+ $config = new Config();
+ if ($config->getAllowNoAddress()) {
+ return null;
+ }
+
$address = new Address();
$this->validateAddressFields($platformAddress);
@@ -1129,4 +1128,9 @@ public function getTotalCanceled()
{
return $this->getPlatformOrder()->get_total_refunded();
}
+
+ public function handleSplitOrder()
+ {
+ // woocommerce does not have split order;
+ }
}
diff --git a/src/Controller/Checkout.php b/src/Controller/Checkout.php
index 11b4c3eb..73f5dab7 100644
--- a/src/Controller/Checkout.php
+++ b/src/Controller/Checkout.php
@@ -34,7 +34,6 @@ public function __construct(
add_action('woocommerce_view_order', [$paymentDetails, 'render']);
add_action('wp_ajax_xqRhBHJ5sW', array($this, 'build_installments'));
add_action('wp_ajax_nopriv_xqRhBHJ5sW', array($this, 'build_installments'));
- add_filter('wcbcf_billing_fields', array($this, 'set_required_fields'));
$this->payment_methods = [
'credit_card' => __('Credit card', 'woo-pagarme-payments'),
'billet' => __('Boleto', 'woo-pagarme-payments'),
@@ -113,13 +112,6 @@ public function build_installments()
exit();
}
- public function set_required_fields($fields)
- {
- $fields['billing_neighborhood']['required'] = true;
-
- return $fields;
- }
-
public function parse_cards($data, $key = 'card')
{
if (isset($data[$key])) {
diff --git a/src/Controller/Orders.php b/src/Controller/Orders.php
index 614b858d..66afeb0b 100644
--- a/src/Controller/Orders.php
+++ b/src/Controller/Orders.php
@@ -87,17 +87,24 @@ public function set_order_canceled(Order $order, $body)
public function add_meta_boxes()
{
- wp_register_script('pagarme-adminhmlt-order-view-cancel-capture', $this->jsUrl('sales/order/view/cancel-capture'), ['jquery'], false);
- wp_enqueue_script('pagarme-adminhmlt-order-view-cancel-capture');
- foreach ($this->blockOrder->getMetaBoxes() as $metaBox) {
- add_meta_box(
- $metaBox->getCode(),
- $metaBox->getTitle(),
- [$metaBox, 'toHtml'],
- ['shop_order', 'woocommerce_page_wc-orders'],
- 'advanced',
- 'high'
- );
+ global $theorder;
+ if($theorder === null) {
+ return;
+ }
+ $order = new Order($theorder->get_id());
+ if ($order->isPagarmePaymentMethod()){
+ wp_register_script('pagarme-adminhmlt-order-view-cancel-capture', $this->jsUrl('sales/order/view/cancel-capture'), ['jquery'], false);
+ wp_enqueue_script('pagarme-adminhmlt-order-view-cancel-capture');
+ foreach ($this->blockOrder->getMetaBoxes() as $metaBox) {
+ add_meta_box(
+ $metaBox->getCode(),
+ $metaBox->getTitle(),
+ [$metaBox, 'toHtml'],
+ ['shop_order', 'woocommerce_page_wc-orders'],
+ 'advanced',
+ 'high'
+ );
+ }
}
}
diff --git a/src/Controller/Settings.php b/src/Controller/Settings.php
index 91982bbb..4297c6aa 100644
--- a/src/Controller/Settings.php
+++ b/src/Controller/Settings.php
@@ -35,6 +35,9 @@ class Settings
/** @var string */
const WC_PAYMENT_GATEWAY = 'WC_Payment_Gateway';
+ /** @var string */
+ const PAGARME_DOCS_ANTIFRAUD_URL = 'https://docs.pagar.me/reference/vis%C3%A3o-geral-sobre-antifraude-1';
+
/** @var Gateway */
public $model;
@@ -85,14 +88,19 @@ public function admin_scripts()
{
wp_register_script('pagarme_settings', $this->jsUrl('pagarme_settings'), array('jquery'), false, true);
wp_enqueue_script('pagarme_settings');
- wp_register_style('woocommerce_admin_styles', WC()->plugin_url() . '/assets/css/admin.css', array());
+ wp_register_style('woocommerce_admin_styles', WC()->plugin_url() . '/assets/css/admin.css');
wp_enqueue_style('woocommerce_admin_styles');
$params = array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonces' => array(
'gateway_toggle' => wp_create_nonce('woocommerce-toggle-payment-gateway-enabled'),
- )
+ ),
+ 'allow_no_address_swal' => array(
+ 'title' => __('Are you sure?', 'woo-pagarme-payments'),
+ 'text' => __('If your Pagar.me Antifraud is active, orders will fail.', 'woo-pagarme-payments'),
+ 'cancelButtonText' => __('Cancel', 'woo-pagarme-payments'),
+ ),
);
wp_localize_script('pagarme_settings', 'pagarme_settings', $params);
}
@@ -127,6 +135,23 @@ private function setSectionsFields(array $value = null)
'options' => $this->yesNoOptions->toLabelsArray(),
'default' => strtolower(Yesno::NO),
],
+ [
+ 'fieldObject' => Select::class,
+ 'id' => 'allow_no_address',
+ 'title' => 'Allow order without address',
+ 'options' => $this->yesNoOptions->toLabelsArray(),
+ 'default' => strtolower(Yesno::NO),
+ 'description' => [
+ 'format' => 'For PSP customers with Pagar.me Antifraud active, it is mandatory to fill'
+ . ' in all address fields. %sRead documentation »%s',
+ 'values' => [
+ '',
+ ''
+ ]
+ ],
+ ],
[
'fieldObject' => Select::class,
'id' => 'enable_logs',
@@ -140,7 +165,7 @@ private function setSectionsFields(array $value = null)
]
];
- if (empty($this->config->getIsPaymentEnabled()) && $this->config->getHubInstallId()) {
+ if (empty($this->config->getAccountId()) && $this->config->getHubInstallId()) {
$this->sectionsFields['section'][0]['fields'][] =
[
'fieldObject' => Select::class,
diff --git a/src/Core.php b/src/Core.php
index 2a478c43..8be88f76 100644
--- a/src/Core.php
+++ b/src/Core.php
@@ -7,6 +7,7 @@
}
use Woocommerce\Pagarme\Helper\Utils;
+use Woocommerce\Pagarme\Action\ActionsRunner;
class Core
{
@@ -28,6 +29,7 @@ private function __construct()
self::admin_enqueue_scripts();
self::front_enqueue_scripts();
add_filter('script_loader_tag', [$this, 'addNoDeferToPagespeed'], 10, 2);
+ self::addActionsRunners();
}
public static function load_textdomain()
@@ -301,6 +303,12 @@ public function addNoDeferToPagespeed($tag, $handle) {
return str_replace( ' src', ' data-pagespeed-no-defer src', $tag );
}
+ private function addActionsRunners()
+ {
+ $actions = new ActionsRunner();
+ $actions->run();
+ }
+
public static function credit_card_errors_pt_br()
{
return array(
diff --git a/src/Helper/Utils.php b/src/Helper/Utils.php
index a073fc1f..68c1a082 100644
--- a/src/Helper/Utils.php
+++ b/src/Helper/Utils.php
@@ -670,32 +670,24 @@ public static function build_customer_address_from_order(Order $order)
public static function build_document_from_order(Order $order)
{
+ if (!empty($order->billing_cpf)) {
+ return array(
+ 'type' => 'individual',
+ 'value' => $order->billing_cpf,
+ );
+ }
- $wcbcf_options = get_option('wcbcf_settings'); //WooCommerce Extra Checkout Fields
-
- $cpf = array(
- 'type' => 'individual',
- 'value' => $order->billing_cpf,
- );
-
- $cnpj = array(
- 'type' => 'company',
- 'value' => $order->billing_cnpj,
- );
-
- switch ($wcbcf_options['person_type']) {
- case 1:
- return ($order->billing_persontype == 1) ? $cpf : $cnpj;
- case 2:
- return $cpf;
- case 3:
- return $cnpj;
- default:
- return array(
- 'type' => '',
- 'value' => '',
+ if (!empty($order->billing_cnpj)) {
+ return array(
+ 'type' => 'company',
+ 'value' => $order->billing_cnpj,
);
}
+
+ return array(
+ 'type' => '',
+ 'value' => '',
+ );
}
public static function build_customer_phones_from_order(Order $order)
diff --git a/src/Model/Checkout.php b/src/Model/Checkout.php
index ff5a2184..cf94f39f 100644
--- a/src/Model/Checkout.php
+++ b/src/Model/Checkout.php
@@ -127,6 +127,9 @@ public function process(WC_Order $wc_order = null, string $type = CheckoutTypes:
);
$order = new Order($wc_order->get_id());
+ $totalWithInstallments = $order->getTotalAmountByCharges();
+ $order->pagarme_card_tax = $order->calculateInstallmentFee($totalWithInstallments, $wc_order->get_total());
+ $order->wc_order->set_total($this->getTotalValue($wc_order, $totalWithInstallments));
$order->payment_method = $fields['payment_method'];
WC()->cart->empty_cart();
if ($response) {
@@ -240,4 +243,12 @@ private function extractOrderValue(array &$fields, PaymentRequestInterface $paym
}
}
}
+
+ private function getTotalValue($wc_order, $totalWithInstallments)
+ {
+ if ($totalWithInstallments > 0) {
+ return $totalWithInstallments;
+ }
+ return $wc_order->get_total();
+ }
}
diff --git a/src/Model/Config.php b/src/Model/Config.php
index 86521b8d..c2273faa 100644
--- a/src/Model/Config.php
+++ b/src/Model/Config.php
@@ -262,6 +262,11 @@ public function getMulticustomers()
return $this->isEnabled('multicustomers');
}
+ public function getAllowNoAddress()
+ {
+ return $this->isEnabled('allow_no_address');
+ }
+
public function getCcAllowSave()
{
return $this->isEnabled('cc_allow_save');
diff --git a/src/Model/FeatureCompatibilization.php b/src/Model/FeatureCompatibilization.php
index bdd38616..5b90a192 100644
--- a/src/Model/FeatureCompatibilization.php
+++ b/src/Model/FeatureCompatibilization.php
@@ -19,7 +19,7 @@ private function getFeatures()
'analytics' => false,
'new_navigation' => false,
'product_block_editor' => true,
- 'cart_checkout_blocks' => true,
+ 'cart_checkout_blocks' => false,
'woocommerce_custom_orders_table_enabled' => true,
'woocommerce_custom_orders_table_data_sync_enabled' => true,
];
diff --git a/src/Model/Order.php b/src/Model/Order.php
index 3baaab26..b170012d 100644
--- a/src/Model/Order.php
+++ b/src/Model/Order.php
@@ -8,8 +8,9 @@
use Pagarme\Core\Kernel\ValueObjects\OrderStatus;
use Pagarme\Core\Kernel\Services\OrderService;
-// WooCommerce
use WC_Order;
+use Woocommerce\Pagarme\Helper\Utils;
+use Woocommerce\Pagarme\Controller\Gateways\AbstractGateway;
class Order extends Meta
{
@@ -58,7 +59,7 @@ class Order extends Meta
public function __construct($ID = false)
{
parent::__construct($ID);
- $this->wc_order = new WC_Order($this->ID);
+ $this->wc_order = $this->getWcOrder($ID);
$this->settings = new Config();
}
/** phpcs:enable */
@@ -220,4 +221,45 @@ public function needs_processing() {
}
return $needs_processing;
}
+
+ /**
+ * @return float
+ */
+ public function getTotalAmountByCharges()
+ {
+ $valueTotal = 0;
+ foreach($this->get_charges() as $charge) {
+ $valueTotal += $charge->getAmount();
+ }
+ return $valueTotal/100;
+ }
+
+ /**
+ * @param mixed $totalWithInstallmentFee
+ * @param mixed $totalWithoutInstallmentsFee
+ * @return float
+ */
+ public function calculateInstallmentFee($totalWithInstallmentFee, $totalWithoutInstallmentsFee)
+ {
+ return Utils::str_to_float($totalWithInstallmentFee) - Utils::str_to_float($totalWithoutInstallmentsFee);
+ }
+
+ public function isPagarmePaymentMethod()
+ {
+ if (property_exists($this, 'wc_order')) {
+ $paymentMethod = $this->wc_order->get_payment_method();
+ return $paymentMethod === AbstractGateway::PAGARME
+ || 0 === strpos($paymentMethod, AbstractGateway::WC_PAYMENT_PAGARME);
+ }
+ return false;
+ }
+
+ public function getWcOrder($id = false)
+ {
+ global $theorder;
+ if(is_null($theorder) || ((int)$id !== $theorder->get_id() && $id !== false)) {
+ return new WC_Order($id);
+ }
+ return $theorder;
+ }
}
diff --git a/src/Model/Payment/Data/AbstractPayment.php b/src/Model/Payment/Data/AbstractPayment.php
index f7736218..1e493cb5 100644
--- a/src/Model/Payment/Data/AbstractPayment.php
+++ b/src/Model/Payment/Data/AbstractPayment.php
@@ -22,7 +22,7 @@
class AbstractPayment extends DataObject
{
/** @var string */
- protected $identifier = 'pix';
+ protected $identifier = '';
/**
* @return void
diff --git a/src/Model/Subscription.php b/src/Model/Subscription.php
index 83c12830..40fde1bc 100644
--- a/src/Model/Subscription.php
+++ b/src/Model/Subscription.php
@@ -15,8 +15,6 @@
}
use WC_Order;
-use WC_Subscription;
-use WC_Subscriptions_Cart;
use Woocommerce\Pagarme\Controller\Orders;
use Woocommerce\Pagarme\Service\LogService;
use Woocommerce\Pagarme\Service\CardService;
@@ -169,7 +167,7 @@ public function processSubscription($amountToCharge, WC_Order $wc_order)
public function processChangePaymentSubscription($subscription)
{
try {
- $subscription = new WC_Subscription($subscription);
+ $subscription = new \WC_Subscription($subscription);
$newPaymentMethod = wc_clean($_POST['payment_method']);
if ('woo-pagarme-payments-credit_card' == $newPaymentMethod) {
$pagarmeCustomer = $this->getPagarmeCustomer($subscription);
@@ -257,10 +255,10 @@ private function createCreditCard($pagarmeCustomer)
/**
* Save card information on table post_meta
* @param array $card
- * @param WC_Subscription $subscription
+ * @param \WC_Subscription $subscription
* @return void
*/
- private function saveCardInSubscription(array $card, WC_Subscription $subscription)
+ private function saveCardInSubscription(array $card, \WC_Subscription $subscription)
{
$subscription->add_meta_data('_pagarme_payment_subscription', json_encode($card), true);
$subscription->save();
@@ -356,7 +354,7 @@ public static function hasSubscriptionProductInCart()
if (!self::hasSubscriptionPlugin()) {
return false;
}
- return WC_Subscriptions_Cart::cart_contains_subscription() || wcs_cart_contains_renewal();
+ return \WC_Subscriptions_Cart::cart_contains_subscription() || wcs_cart_contains_renewal();
}
/**
@@ -367,7 +365,7 @@ public static function hasSubscriptionFreeTrial()
if (!self::hasSubscriptionPlugin()) {
return false;
}
- return WC_Subscriptions_Cart::all_cart_items_have_free_trial();
+ return \WC_Subscriptions_Cart::all_cart_items_have_free_trial();
}
/**
@@ -381,7 +379,7 @@ public static function getRecurrenceCycle()
if (wcs_cart_contains_renewal()) {
return "subsequent";
}
- if (WC_Subscriptions_Cart::cart_contains_subscription()) {
+ if (\WC_Subscriptions_Cart::cart_contains_subscription()) {
return "first";
}
return null;
diff --git a/templates/adminhtml/system/config/form/field/main.phtml b/templates/adminhtml/system/config/form/field/main.phtml
index 76c9eb43..c81a80c6 100644
--- a/templates/adminhtml/system/config/form/field/main.phtml
+++ b/templates/adminhtml/system/config/form/field/main.phtml
@@ -14,14 +14,14 @@ if ( ! defined( 'ABSPATH' ) ) {
}
?>
-
+
includeTemplate($this->template, $this);
?>
getDescription()) : ?>
-
= esc_html($this->getDescription()) ?>
+
= $this->getDescription() ?>
diff --git a/templates/order/email-payment-details.phtml b/templates/order/email-payment-details.phtml
index ef5da265..1fefe5e7 100644
--- a/templates/order/email-payment-details.phtml
+++ b/templates/order/email-payment-details.phtml
@@ -1,4 +1,5 @@
-isPagarmePaymentMethod($this->getOrder())) : ?>
+getOrder()->isPagarmePaymentMethod()) : ?>
= __('Payment Data', 'woo-pagarme-payments'); ?>
getCharges()) : ?>
getCharges() as $charge) : ?>
=
- $this->createBlock(EmailCharge::class,
+ $this->createBlock(
+ EmailCharge::class,
'pagarme.order.email',
[
'charge' => $charge
@@ -39,4 +41,4 @@ if (!function_exists('add_action')) {
-
+
\ No newline at end of file
diff --git a/templates/order/payment-details.phtml b/templates/order/payment-details.phtml
index 6e4395d0..72be1dd7 100644
--- a/templates/order/payment-details.phtml
+++ b/templates/order/payment-details.phtml
@@ -1,4 +1,5 @@
-isPagarmePaymentMethod($this->getOrder())) : ?>
+getOrder()->isPagarmePaymentMethod()) : ?>
= __('Payment Data', 'woo-pagarme-payments'); ?>
getCharges()) : ?>
getCharges() as $charge) : ?>
=
- $this->createBlock(Charge::class,
+ $this->createBlock(
+ Charge::class,
'pagarme.order.charge',
[
'charge' => $charge
@@ -35,4 +37,4 @@ if (!function_exists('add_action')) {
= __('No records found.', 'woo-pagarme-payments'); ?>
-
+
\ No newline at end of file
diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php
index afef3fa2..7824d8f7 100644
--- a/vendor/composer/ClassLoader.php
+++ b/vendor/composer/ClassLoader.php
@@ -42,35 +42,37 @@
*/
class ClassLoader
{
- /** @var ?string */
+ /** @var \Closure(string):void */
+ private static $includeFile;
+
+ /** @var string|null */
private $vendorDir;
// PSR-4
/**
- * @var array[]
- * @psalm-var array
>
+ * @var array>
*/
private $prefixLengthsPsr4 = array();
/**
- * @var array[]
- * @psalm-var array>
+ * @var array>
*/
private $prefixDirsPsr4 = array();
/**
- * @var array[]
- * @psalm-var array
+ * @var list
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
- * @var array[]
- * @psalm-var array>
+ * List of PSR-0 prefixes
+ *
+ * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
+ *
+ * @var array>>
*/
private $prefixesPsr0 = array();
/**
- * @var array[]
- * @psalm-var array
+ * @var list
*/
private $fallbackDirsPsr0 = array();
@@ -78,8 +80,7 @@ class ClassLoader
private $useIncludePath = false;
/**
- * @var string[]
- * @psalm-var array
+ * @var array
*/
private $classMap = array();
@@ -87,29 +88,29 @@ class ClassLoader
private $classMapAuthoritative = false;
/**
- * @var bool[]
- * @psalm-var array
+ * @var array
*/
private $missingClasses = array();
- /** @var ?string */
+ /** @var string|null */
private $apcuPrefix;
/**
- * @var self[]
+ * @var array
*/
private static $registeredLoaders = array();
/**
- * @param ?string $vendorDir
+ * @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
+ self::initializeIncludeClosure();
}
/**
- * @return string[]
+ * @return array>
*/
public function getPrefixes()
{
@@ -121,8 +122,7 @@ public function getPrefixes()
}
/**
- * @return array[]
- * @psalm-return array>
+ * @return array>
*/
public function getPrefixesPsr4()
{
@@ -130,8 +130,7 @@ public function getPrefixesPsr4()
}
/**
- * @return array[]
- * @psalm-return array
+ * @return list
*/
public function getFallbackDirs()
{
@@ -139,8 +138,7 @@ public function getFallbackDirs()
}
/**
- * @return array[]
- * @psalm-return array
+ * @return list
*/
public function getFallbackDirsPsr4()
{
@@ -148,8 +146,7 @@ public function getFallbackDirsPsr4()
}
/**
- * @return string[] Array of classname => path
- * @psalm-return array
+ * @return array Array of classname => path
*/
public function getClassMap()
{
@@ -157,8 +154,7 @@ public function getClassMap()
}
/**
- * @param string[] $classMap Class to filename map
- * @psalm-param array $classMap
+ * @param array $classMap Class to filename map
*
* @return void
*/
@@ -175,24 +171,25 @@ public function addClassMap(array $classMap)
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
- * @param string $prefix The prefix
- * @param string[]|string $paths The PSR-0 root directories
- * @param bool $prepend Whether to prepend the directories
+ * @param string $prefix The prefix
+ * @param list|string $paths The PSR-0 root directories
+ * @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
+ $paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
- (array) $paths,
+ $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
- (array) $paths
+ $paths
);
}
@@ -201,19 +198,19 @@ public function add($prefix, $paths, $prepend = false)
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
- $this->prefixesPsr0[$first][$prefix] = (array) $paths;
+ $this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
- (array) $paths,
+ $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
- (array) $paths
+ $paths
);
}
}
@@ -222,9 +219,9 @@ public function add($prefix, $paths, $prepend = false)
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
- * @param string $prefix The prefix/namespace, with trailing '\\'
- * @param string[]|string $paths The PSR-4 base directories
- * @param bool $prepend Whether to prepend the directories
+ * @param string $prefix The prefix/namespace, with trailing '\\'
+ * @param list|string $paths The PSR-4 base directories
+ * @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
@@ -232,17 +229,18 @@ public function add($prefix, $paths, $prepend = false)
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
+ $paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
- (array) $paths,
+ $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
- (array) $paths
+ $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
@@ -252,18 +250,18 @@ public function addPsr4($prefix, $paths, $prepend = false)
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
- $this->prefixDirsPsr4[$prefix] = (array) $paths;
+ $this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
- (array) $paths,
+ $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
- (array) $paths
+ $paths
);
}
}
@@ -272,8 +270,8 @@ public function addPsr4($prefix, $paths, $prepend = false)
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
- * @param string $prefix The prefix
- * @param string[]|string $paths The PSR-0 base directories
+ * @param string $prefix The prefix
+ * @param list|string $paths The PSR-0 base directories
*
* @return void
*/
@@ -290,8 +288,8 @@ public function set($prefix, $paths)
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
- * @param string $prefix The prefix/namespace, with trailing '\\'
- * @param string[]|string $paths The PSR-4 base directories
+ * @param string $prefix The prefix/namespace, with trailing '\\'
+ * @param list|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
@@ -425,7 +423,8 @@ public function unregister()
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
- includeFile($file);
+ $includeFile = self::$includeFile;
+ $includeFile($file);
return true;
}
@@ -476,9 +475,9 @@ public function findFile($class)
}
/**
- * Returns the currently registered loaders indexed by their corresponding vendor directories.
+ * Returns the currently registered loaders keyed by their corresponding vendor directories.
*
- * @return self[]
+ * @return array
*/
public static function getRegisteredLoaders()
{
@@ -555,18 +554,26 @@ private function findFileWithExtension($class, $ext)
return false;
}
-}
-/**
- * Scope isolated include.
- *
- * Prevents access to $this/self from included files.
- *
- * @param string $file
- * @return void
- * @private
- */
-function includeFile($file)
-{
- include $file;
+ /**
+ * @return void
+ */
+ private static function initializeIncludeClosure()
+ {
+ if (self::$includeFile !== null) {
+ return;
+ }
+
+ /**
+ * Scope isolated include.
+ *
+ * Prevents access to $this/self from included files.
+ *
+ * @param string $file
+ * @return void
+ */
+ self::$includeFile = \Closure::bind(static function($file) {
+ include $file;
+ }, null, null);
+ }
}
diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php
index c6b54af7..51e734a7 100644
--- a/vendor/composer/InstalledVersions.php
+++ b/vendor/composer/InstalledVersions.php
@@ -98,7 +98,7 @@ public static function isInstalled($packageName, $includeDevRequirements = true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
- return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']);
+ return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === false;
}
}
@@ -119,7 +119,7 @@ public static function isInstalled($packageName, $includeDevRequirements = true)
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
- $constraint = $parser->parseConstraints($constraint);
+ $constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
@@ -328,7 +328,9 @@ private static function getInstalled()
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
- $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
+ /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */
+ $required = require $vendorDir.'/composer/installed.php';
+ $installed[] = self::$installedByVendor[$vendorDir] = $required;
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
@@ -340,12 +342,17 @@ private static function getInstalled()
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
- self::$installed = require __DIR__ . '/installed.php';
+ /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */
+ $required = require __DIR__ . '/installed.php';
+ self::$installed = $required;
} else {
self::$installed = array();
}
}
- $installed[] = self::$installed;
+
+ if (self::$installed !== array()) {
+ $installed[] = self::$installed;
+ }
return $installed;
}
diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json
index df314515..bcf6bbae 100644
--- a/vendor/composer/installed.json
+++ b/vendor/composer/installed.json
@@ -171,17 +171,17 @@
},
{
"name": "monolog/monolog",
- "version": "2.9.1",
- "version_normalized": "2.9.1.0",
+ "version": "2.9.2",
+ "version_normalized": "2.9.2.0",
"source": {
"type": "git",
"url": "https://github.com/Seldaek/monolog.git",
- "reference": "f259e2b15fb95494c83f52d3caad003bbf5ffaa1"
+ "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/Seldaek/monolog/zipball/f259e2b15fb95494c83f52d3caad003bbf5ffaa1",
- "reference": "f259e2b15fb95494c83f52d3caad003bbf5ffaa1",
+ "url": "https://api.github.com/repos/Seldaek/monolog/zipball/437cb3628f4cf6042cc10ae97fc2b8472e48ca1f",
+ "reference": "437cb3628f4cf6042cc10ae97fc2b8472e48ca1f",
"shasum": ""
},
"require": {
@@ -227,7 +227,7 @@
"rollbar/rollbar": "Allow sending log messages to Rollbar",
"ruflin/elastica": "Allow sending log messages to an Elastic Search server"
},
- "time": "2023-02-06T13:44:46+00:00",
+ "time": "2023-10-27T15:25:26+00:00",
"type": "library",
"extra": {
"branch-alias": {
@@ -260,7 +260,7 @@
],
"support": {
"issues": "https://github.com/Seldaek/monolog/issues",
- "source": "https://github.com/Seldaek/monolog/tree/2.9.1"
+ "source": "https://github.com/Seldaek/monolog/tree/2.9.2"
},
"funding": [
{
@@ -276,23 +276,23 @@
},
{
"name": "pagarme/ecommerce-module-core",
- "version": "2.1.0",
- "version_normalized": "2.1.0.0",
+ "version": "2.3.1",
+ "version_normalized": "2.3.1.0",
"source": {
"type": "git",
"url": "https://github.com/pagarme/ecommerce-module-core.git",
- "reference": "f4bd3a74cdc1b6bf5db38edb4b7442878b221bc1"
+ "reference": "9c9e927cea9b1bf90a499d2146f042f1f7f1c921"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/pagarme/ecommerce-module-core/zipball/f4bd3a74cdc1b6bf5db38edb4b7442878b221bc1",
- "reference": "f4bd3a74cdc1b6bf5db38edb4b7442878b221bc1",
+ "url": "https://api.github.com/repos/pagarme/ecommerce-module-core/zipball/9c9e927cea9b1bf90a499d2146f042f1f7f1c921",
+ "reference": "9c9e927cea9b1bf90a499d2146f042f1f7f1c921",
"shasum": ""
},
"require": {
"ext-json": "*",
"monolog/monolog": "<3",
- "pagarme/pagarmecoreapi": "5.6.1",
+ "pagarme/pagarmecoreapi": "v5.6.3",
"php": ">=7.1"
},
"require-dev": {
@@ -301,7 +301,7 @@
"nesbot/carbon": "1.39.0",
"phpunit/phpunit": "^5 | ^6 | ^7 | ^8 | ^9"
},
- "time": "2023-03-22T17:36:14+00:00",
+ "time": "2023-11-14T15:38:42+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -322,23 +322,23 @@
],
"description": "Core component for Pagar.me e-commerce platform modules.",
"support": {
- "source": "https://github.com/pagarme/ecommerce-module-core/tree/2.1.0"
+ "source": "https://github.com/pagarme/ecommerce-module-core/tree/2.3.1"
},
"install-path": "../pagarme/ecommerce-module-core"
},
{
"name": "pagarme/pagarmecoreapi",
- "version": "5.6.2",
- "version_normalized": "5.6.2.0",
+ "version": "v5.6.3",
+ "version_normalized": "5.6.3.0",
"source": {
"type": "git",
"url": "https://github.com/pagarme/pagarme-core-api-php.git",
- "reference": "1e6caa95deb7b17223c0458e8f4c901e851e8590"
+ "reference": "49e0d222c50c69ac3e0debea9b69202e6555d3ef"
},
"dist": {
"type": "zip",
- "url": "https://api.github.com/repos/pagarme/pagarme-core-api-php/zipball/1e6caa95deb7b17223c0458e8f4c901e851e8590",
- "reference": "1e6caa95deb7b17223c0458e8f4c901e851e8590",
+ "url": "https://api.github.com/repos/pagarme/pagarme-core-api-php/zipball/49e0d222c50c69ac3e0debea9b69202e6555d3ef",
+ "reference": "49e0d222c50c69ac3e0debea9b69202e6555d3ef",
"shasum": ""
},
"require": {
@@ -347,12 +347,12 @@
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*",
- "php": ">=5.4.0"
+ "php": ">=7.1"
},
"require-dev": {
"squizlabs/php_codesniffer": "^2.7"
},
- "time": "2023-06-19T19:03:26+00:00",
+ "time": "2023-09-28T18:22:12+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
@@ -381,7 +381,7 @@
],
"support": {
"issues": "https://github.com/pagarme/pagarme-core-api-php/issues",
- "source": "https://github.com/pagarme/pagarme-core-api-php/tree/5.6.2"
+ "source": "https://github.com/pagarme/pagarme-core-api-php/tree/v5.6.3"
},
"install-path": "../pagarme/pagarmecoreapi"
},
diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php
index 03599cd8..d7b8f3b3 100644
--- a/vendor/composer/installed.php
+++ b/vendor/composer/installed.php
@@ -1,8 +1,8 @@
array(
'name' => 'pagarme/woocommerce-pagarme-payments',
- 'pretty_version' => '3.0.1',
- 'version' => '3.0.1.0',
+ 'pretty_version' => '3.1.8',
+ 'version' => '3.1.8.0',
'reference' => NULL,
'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../../',
@@ -38,35 +38,35 @@
'dev_requirement' => false,
),
'monolog/monolog' => array(
- 'pretty_version' => '2.9.1',
- 'version' => '2.9.1.0',
- 'reference' => 'f259e2b15fb95494c83f52d3caad003bbf5ffaa1',
+ 'pretty_version' => '2.9.2',
+ 'version' => '2.9.2.0',
+ 'reference' => '437cb3628f4cf6042cc10ae97fc2b8472e48ca1f',
'type' => 'library',
'install_path' => __DIR__ . '/../monolog/monolog',
'aliases' => array(),
'dev_requirement' => false,
),
'pagarme/ecommerce-module-core' => array(
- 'pretty_version' => '2.1.0',
- 'version' => '2.1.0.0',
- 'reference' => 'f4bd3a74cdc1b6bf5db38edb4b7442878b221bc1',
+ 'pretty_version' => '2.3.1',
+ 'version' => '2.3.1.0',
+ 'reference' => '9c9e927cea9b1bf90a499d2146f042f1f7f1c921',
'type' => 'library',
'install_path' => __DIR__ . '/../pagarme/ecommerce-module-core',
'aliases' => array(),
'dev_requirement' => false,
),
'pagarme/pagarmecoreapi' => array(
- 'pretty_version' => '5.6.2',
- 'version' => '5.6.2.0',
- 'reference' => '1e6caa95deb7b17223c0458e8f4c901e851e8590',
+ 'pretty_version' => 'v5.6.3',
+ 'version' => '5.6.3.0',
+ 'reference' => '49e0d222c50c69ac3e0debea9b69202e6555d3ef',
'type' => 'library',
'install_path' => __DIR__ . '/../pagarme/pagarmecoreapi',
'aliases' => array(),
'dev_requirement' => false,
),
'pagarme/woocommerce-pagarme-payments' => array(
- 'pretty_version' => '3.0.1',
- 'version' => '3.0.1.0',
+ 'pretty_version' => '3.1.8',
+ 'version' => '3.1.8.0',
'reference' => NULL,
'type' => 'wordpress-plugin',
'install_path' => __DIR__ . '/../../',
diff --git a/vendor/monolog/monolog/CHANGELOG.md b/vendor/monolog/monolog/CHANGELOG.md
index 8a8c6512..aca1bdd0 100644
--- a/vendor/monolog/monolog/CHANGELOG.md
+++ b/vendor/monolog/monolog/CHANGELOG.md
@@ -1,3 +1,9 @@
+### 2.9.2 (2023-10-27)
+
+ * Fixed display_errors parsing in ErrorHandler which did not support string values (#1804)
+ * Fixed bug where the previous error handler would not be restored in some cases where StreamHandler fails (#1815)
+ * Fixed normalization error when normalizing incomplete classes (#1833)
+
### 2.9.1 (2023-02-06)
* Fixed Logger not being serializable anymore (#1792)
diff --git a/vendor/monolog/monolog/src/Monolog/ErrorHandler.php b/vendor/monolog/monolog/src/Monolog/ErrorHandler.php
index 576f1713..1406d34e 100644
--- a/vendor/monolog/monolog/src/Monolog/ErrorHandler.php
+++ b/vendor/monolog/monolog/src/Monolog/ErrorHandler.php
@@ -198,7 +198,7 @@ private function handleException(\Throwable $e): void
($this->previousExceptionHandler)($e);
}
- if (!headers_sent() && !ini_get('display_errors')) {
+ if (!headers_sent() && in_array(strtolower((string) ini_get('display_errors')), ['0', '', 'false', 'off', 'none', 'no'], true)) {
http_response_code(500);
}
diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php
index b31b2971..e6e78983 100644
--- a/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php
+++ b/vendor/monolog/monolog/src/Monolog/Formatter/LineFormatter.php
@@ -155,7 +155,7 @@ protected function normalizeException(\Throwable $e, int $depth = 0): string
do {
$depth++;
if ($depth > $this->maxNormalizeDepth) {
- $str .= '\n[previous exception] Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
+ $str .= "\n[previous exception] Over " . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
break;
}
diff --git a/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php b/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php
index 5441bc0a..f926a842 100644
--- a/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php
+++ b/vendor/monolog/monolog/src/Monolog/Formatter/NormalizerFormatter.php
@@ -174,6 +174,9 @@ protected function normalize($data, int $depth = 0)
if ($data instanceof \JsonSerializable) {
/** @var null|scalar|array $value */
$value = $data->jsonSerialize();
+ } elseif (\get_class($data) === '__PHP_Incomplete_Class') {
+ $accessor = new \ArrayObject($data);
+ $value = (string) $accessor['__PHP_Incomplete_Class_Name'];
} elseif (method_exists($data, '__toString')) {
/** @var string $value */
$value = $data->__toString();
diff --git a/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php b/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php
index 65183512..82c048e1 100644
--- a/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php
+++ b/vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php
@@ -135,11 +135,14 @@ protected function write(array $record): void
$this->createDir($url);
$this->errorMessage = null;
set_error_handler([$this, 'customErrorHandler']);
- $stream = fopen($url, 'a');
- if ($this->filePermission !== null) {
- @chmod($url, $this->filePermission);
+ try {
+ $stream = fopen($url, 'a');
+ if ($this->filePermission !== null) {
+ @chmod($url, $this->filePermission);
+ }
+ } finally {
+ restore_error_handler();
}
- restore_error_handler();
if (!is_resource($stream)) {
$this->stream = null;
diff --git a/vendor/pagarme/ecommerce-module-core/README.md b/vendor/pagarme/ecommerce-module-core/README.md
index 14fa2667..e821a2a7 100644
--- a/vendor/pagarme/ecommerce-module-core/README.md
+++ b/vendor/pagarme/ecommerce-module-core/README.md
@@ -1,9 +1,5 @@
[![Latest Stable Version](https://poser.pugx.org/pagarme/ecommerce-module-core/v/stable)](https://packagist.org/packages/pagarme/ecommerce-module-core)
-[![Sonarcloud Status](https://sonarcloud.io/api/project_badges/measure?project=pagarme_ecommerce-module-core&metric=alert_status)](https://sonarcloud.io/dashboard?id=pagarme_ecommerce-module-core)
-[![SonarCloud Coverage](https://sonarcloud.io/api/project_badges/measure?project=pagarme_ecommerce-module-core&metric=coverage)](https://sonarcloud.io/component_measures/metric/coverage/list?id=pagarme_ecommerce-module-core)
-[![SonarCloud Bugs](https://sonarcloud.io/api/project_badges/measure?project=pagarme_ecommerce-module-core&metric=bugs)](https://sonarcloud.io/component_measures/metric/reliability_rating/list?id=pagarme_ecommerce-module-core)
-[![SonarCloud Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=pagarme_ecommerce-module-core&metric=vulnerabilities)](https://sonarcloud.io/component_measures/metric/security_rating/list?id=pagarme_ecommerce-module-core)
# Pagar.me/E-commerce module core
@@ -13,7 +9,7 @@ This is the repository of Pagar.me's payment module core for all supported e-com
- [Pagar.me Magento payment module for Magento 2.3+](https://github.com/pagarme/magento2).
## Dependencies
-* ``PHP`` Version 7.1 - 7.4
+* ``PHP`` Version 7.1 - 8.1
## Install
Require by composer
diff --git a/vendor/pagarme/ecommerce-module-core/catalog-info.yaml b/vendor/pagarme/ecommerce-module-core/catalog-info.yaml
new file mode 100644
index 00000000..4989ab4b
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/catalog-info.yaml
@@ -0,0 +1,21 @@
+---
+apiVersion: backstage.io/v1alpha1
+kind: Component
+metadata:
+ name: ECOMMERCE MODULE CORE
+ title: ECOMMERCE MODULE CORE
+ description: Modulo opensource para unificação de integração para a P&G
+ namespace: pagarme-psp
+ annotations:
+ legacy.stone.tech/owner-email: opensource@pagar.me
+ legacy.stone.tech/prod-date: 2021-03-30
+ labels:
+ legacy.stone.tech/internal-user-auth-base: not-applicable
+ legacy.stone.tech/access-request-type: not-applicable
+ legacy.stone.tech/handle-lgpd: false
+ legacy.stone.tech/customer-auth-method: not-applicable
+ stone.tech/endpoint-type: none
+spec:
+ type: library
+ lifecycle: production
+ owner: pagarme/opensource-apps-team
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/composer.json b/vendor/pagarme/ecommerce-module-core/composer.json
index b291b508..9219d50f 100644
--- a/vendor/pagarme/ecommerce-module-core/composer.json
+++ b/vendor/pagarme/ecommerce-module-core/composer.json
@@ -2,7 +2,7 @@
"name": "pagarme/ecommerce-module-core",
"description": "Core component for Pagar.me e-commerce platform modules.",
"license": "MIT",
- "version": "2.1.0",
+ "version": "2.3.1",
"authors": [
{
"name":"Open Source Team"
@@ -12,7 +12,7 @@
"require": {
"php": ">=7.1",
"monolog/monolog": "<3",
- "pagarme/pagarmecoreapi": "5.6.1",
+ "pagarme/pagarmecoreapi": "v5.6.3",
"ext-json": "*"
},
"require-dev": {
diff --git a/vendor/pagarme/ecommerce-module-core/integrityDeploy.php b/vendor/pagarme/ecommerce-module-core/integrityDeploy.php
index 1835d24b..02669f1d 100644
--- a/vendor/pagarme/ecommerce-module-core/integrityDeploy.php
+++ b/vendor/pagarme/ecommerce-module-core/integrityDeploy.php
@@ -15,7 +15,7 @@
$moduleCoreSetupReflection = new ReflectionClass($concretePlatformCoreSetupClass);
$concreteCoreSetupFilename = $moduleCoreSetupReflection->getFileName();
-$concreteDir = explode(DIRECTORY_SEPARATOR, $concreteCoreSetupFilename);
+$concreteDir = explode(DIRECTORY_SEPARATOR, $concreteCoreSetupFilename ?? '');
array_pop($concreteDir);
$concreteDir = implode(DIRECTORY_SEPARATOR, $concreteDir);
diff --git a/vendor/pagarme/ecommerce-module-core/src/Hub/Repositories/InstallTokenRepository.php b/vendor/pagarme/ecommerce-module-core/src/Hub/Repositories/InstallTokenRepository.php
index f5c62514..9541db62 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Hub/Repositories/InstallTokenRepository.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Hub/Repositories/InstallTokenRepository.php
@@ -43,17 +43,15 @@ protected function update(AbstractEntity &$object)
$created_at_timestamp = $stdObject->createdAtTimestamp;
$expire_at_timestamp = $stdObject->expireAtTimestamp;
- $query = "
- UPDATE `$table`" .
+ $query = "UPDATE `$table`" .
" SET " .
"
token = '$token' ,
used = $used ,
- created_at_timestamp = $created_at_timestamp ,
+ created_at_timestamp = $created_at_timestamp ,
expire_at_timestamp = $expire_at_timestamp
" .
- " WHERE id = {$stdObject->id}"
- ;
+ " WHERE id = {$stdObject->id}";
$this->db->query($query);
}
@@ -63,6 +61,18 @@ public function delete(AbstractEntity $object)
// TODO: Implement delete() method.
}
+ public function deleteAllInactive()
+ {
+ $table =
+ $this->db->getTable(AbstractDatabaseDecorator::TABLE_HUB_INSTALL_TOKEN);
+
+ $currentTime = time();
+ $query = "DELETE FROM `$table`"
+ . " WHERE used <> 1";
+
+ $this->db->query($query);
+ }
+
public function find($objectId)
{
// TODO: Implement find() method.
@@ -74,7 +84,7 @@ public function findByPagarmeId(AbstractValidString $pagarmeId)
$this->db->getTable(AbstractDatabaseDecorator::TABLE_HUB_INSTALL_TOKEN);
$token = $pagarmeId->getValue();
-
+
$query = "SELECT * FROM `$table` as t ";
$query .= "WHERE t.token = '$token';";
@@ -93,10 +103,11 @@ public function listEntities($limit, $listDisabled)
$table =
$this->db->getTable(AbstractDatabaseDecorator::TABLE_HUB_INSTALL_TOKEN);
- $query = "SELECT * FROM `$table` as t";
+ $query = "SELECT * FROM `$table` as t"
+ . " WHERE used = 0";
if (!$listDisabled) {
- $query .= " WHERE t.expire_at_timestamp > " . time();
+ $query .= " AND t.expire_at_timestamp > " . time();
}
if ($limit !== 0) {
@@ -116,4 +127,4 @@ public function listEntities($limit, $listDisabled)
return $installTokens;
}
-}
\ No newline at end of file
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Hub/Services/HubIntegrationService.php b/vendor/pagarme/ecommerce-module-core/src/Hub/Services/HubIntegrationService.php
index 2f3710fd..f224a09e 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Hub/Services/HubIntegrationService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Hub/Services/HubIntegrationService.php
@@ -29,16 +29,17 @@ public function startHubIntegration($installSeed)
{
$tokenRepo = new InstallTokenRepository();
- $enabledTokens = $tokenRepo->listEntities(0, false);
+ $notExpiredTokens = $tokenRepo->listEntities(0, true);
- //expire all tokens
- foreach ($enabledTokens as $enabledToken) {
- $enabledToken->setExpireAtTimestamp(
- $enabledToken->getCreatedAtTimestamp() - 1000
- );
- $tokenRepo->save($enabledToken);
+ if (count($notExpiredTokens) === 1) {
+ $activeToken = current($notExpiredTokens);
+ if ($activeToken->getExpireAtTimestamp() > time()) {
+ return $activeToken->getToken();
+ }
}
+ $tokenRepo->deleteAllInactive();
+
$installFactory = new InstallTokenFactory();
$installToken = $installFactory->createFromSeed($installSeed);
@@ -58,7 +59,7 @@ public function endHubIntegration(
$rawToken = $installToken;
$installToken = $tokenRepo->findByPagarmeId(new HubInstallToken($installToken));
-
+
if (is_null($installToken)) {
$message = "Received an invalid installToken. NULL: $rawToken";
$exception = new \Exception($message);
diff --git a/vendor/pagarme/ecommerce-module-core/src/Hub/ValueObjects/HubInstallToken.php b/vendor/pagarme/ecommerce-module-core/src/Hub/ValueObjects/HubInstallToken.php
index 1d7b3a57..a075a85f 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Hub/ValueObjects/HubInstallToken.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Hub/ValueObjects/HubInstallToken.php
@@ -8,6 +8,6 @@ final class HubInstallToken extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/\w{64}$/', $value) === 1;
+ return preg_match('/\w{64}$/', $value ?? '') === 1;
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractDatabaseDecorator.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractDatabaseDecorator.php
index b8c9a19a..6ce2cbbd 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractDatabaseDecorator.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractDatabaseDecorator.php
@@ -19,6 +19,7 @@ abstract class AbstractDatabaseDecorator
const TABLE_RECURRENCE_CHARGE = 12;
const TABLE_RECURRENCE_SUBSCRIPTION = 13;
const TABLE_RECURRENCE_SUBSCRIPTION_ITEM = 14;
+ const TABLE_RECIPIENTS = 15;
protected $db;
protected $tablePrefix;
@@ -57,4 +58,4 @@ abstract protected function doQuery($query);
abstract protected function doFetch($query);
abstract protected function formatResults($query);
abstract protected function setLastInsertId($insertId);
-}
\ No newline at end of file
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractModuleCoreSetup.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractModuleCoreSetup.php
index d93ccee1..b400c718 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractModuleCoreSetup.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractModuleCoreSetup.php
@@ -241,7 +241,7 @@ public static function getModuleConcreteDir()
$moduleCoreSetupReflection = new ReflectionClass($concretePlatformCoreSetupClass);
$concreteCoreSetupFilename = $moduleCoreSetupReflection->getFileName();
- $concreteDir = explode(DIRECTORY_SEPARATOR, $concreteCoreSetupFilename);
+ $concreteDir = explode(DIRECTORY_SEPARATOR, $concreteCoreSetupFilename ?? '');
array_pop($concreteDir);
self::$moduleConcreteDir = implode(DIRECTORY_SEPARATOR, $concreteDir);
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractPlatformOrderDecorator.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractPlatformOrderDecorator.php
index 4691f4cb..ec2c32fc 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractPlatformOrderDecorator.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Abstractions/AbstractPlatformOrderDecorator.php
@@ -35,6 +35,7 @@ public function getPlatformOrder()
public function setPlatformOrder($platformOrder)
{
$this->platformOrder = $platformOrder;
+ $this->handleSplitOrder();
}
public function setStatus(OrderStatus $status)
@@ -42,10 +43,7 @@ public function setStatus(OrderStatus $status)
$currentStatus = '';
try {
$currentStatus = $this->getStatus();
- } catch(\Exception $e) {
-
- } catch(\Throwable $e) {
-
+ } catch (\Throwable $e) {
}
$statusInfo = (object)[
@@ -53,13 +51,13 @@ public function setStatus(OrderStatus $status)
"to" => $status,
];
- $this->logService->orderInfo(
- $this->getCode(),
- 'Status Change',
- $statusInfo
- );
+ $this->logService->orderInfo(
+ $this->getCode(),
+ 'Status Change',
+ $statusInfo
+ );
- $this->setStatusAfterLog($status);
+ $this->setStatusAfterLog($status);
}
public function setState(OrderState $state)
@@ -67,10 +65,7 @@ public function setState(OrderState $state)
$currentState = '';
try {
$currentState = $this->getState();
- } catch(\Exception $e) {
-
- } catch(\Throwable $e) {
-
+ } catch (\Throwable $e) {
}
$stateInfo = (object)[
@@ -204,4 +199,4 @@ public function getPaymentMethod()
abstract protected function addMPHistoryComment($message, $notifyCustomer);
abstract protected function setStatusAfterLog(OrderStatus $status);
abstract protected function setStateAfterLog(OrderState $state);
-}
\ No newline at end of file
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
index 9b5a8ad0..f31fdabd 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Configuration.php
@@ -9,6 +9,7 @@
use Pagarme\Core\Kernel\ValueObjects\AbstractValidString;
use Pagarme\Core\Kernel\ValueObjects\Configuration\AddressAttributes;
use Pagarme\Core\Kernel\ValueObjects\Configuration\CardConfig;
+use Pagarme\Core\Kernel\ValueObjects\Configuration\MarketplaceConfig;
use Pagarme\Core\Kernel\ValueObjects\Configuration\PixConfig;
use Pagarme\Core\Kernel\ValueObjects\Configuration\RecurrenceConfig;
use Pagarme\Core\Kernel\ValueObjects\Configuration\VoucherConfig;
@@ -100,6 +101,9 @@ final class Configuration extends AbstractEntity
/** @var AddressAttributes */
private $addressAttributes;
+ /** @var bool */
+ private $allowNoAddress;
+
/** @var string */
private $cardStatementDescriptor;
@@ -170,8 +174,14 @@ final class Configuration extends AbstractEntity
*/
private $accountId;
+ /**
+ * @var MarketplaceConfig
+ */
+ private $marketplaceConfig;
+
public function __construct()
{
+ $this->allowNoAddress = false;
$this->saveCards = false;
$this->saveVoucherCards = false;
$this->multiBuyer = false;
@@ -236,6 +246,22 @@ public function getPixConfig()
return $this->pixConfig;
}
+ /**
+ * @param MarketplaceConfig $marketplaceConfig
+ */
+ public function setMarketplaceConfig(MarketplaceConfig $marketplaceConfig)
+ {
+ $this->marketplaceConfig = $marketplaceConfig;
+ }
+
+ /**
+ * @return MarketplaceConfig
+ */
+ public function getMarketplaceConfig()
+ {
+ return $this->marketplaceConfig;
+ }
+
/**
* @return VoucherConfig
*/
@@ -587,7 +613,7 @@ public function setAntifraudMinAmount($antifraudMinAmount)
$numbers = '/([^0-9])/i';
$replace = '';
- $minAmount = preg_replace($numbers, $replace, $antifraudMinAmount);
+ $minAmount = preg_replace($numbers, $replace, $antifraudMinAmount ?? '');
if ($minAmount < 0) {
$minAmount = 0;
@@ -619,6 +645,22 @@ protected function getAddressAttributes()
return $this->addressAttributes;
}
+ /**
+ * @return bool
+ */
+ protected function getAllowNoAddress()
+ {
+ return $this->allowNoAddress;
+ }
+
+ /**
+ * @param bool $allowNoAddress
+ */
+ public function setAllowNoAddress($allowNoAddress)
+ {
+ $this->allowNoAddress = $allowNoAddress;
+ }
+
/**
* @param AddressAttributes $addressAttributes
*/
@@ -735,7 +777,7 @@ public function setBoletoDueDays($boletoDueDays)
throw new InvalidParamException("Boleto due days should be an integer!", $boletoDueDays);
}
- $this->boletoDueDays = (int)$boletoDueDays;
+ $this->boletoDueDays = (int) $boletoDueDays;
}
/**
@@ -782,6 +824,7 @@ public function jsonSerialize()
"merchantId" => $this->getMerchantId(),
"accountId" => $this->getAccountId(),
"addressAttributes" => $this->getAddressAttributes(),
+ "allowNoAddress" => $this->getAllowNoAddress(),
"keys" => $this->keys,
"cardOperation" => $this->cardOperation,
"installmentsEnabled" => $this->isInstallmentsEnabled(),
@@ -801,7 +844,8 @@ public function jsonSerialize()
"createOrder" => $this->isCreateOrderEnabled(),
"voucherConfig" => $this->getVoucherConfig(),
"debitConfig" => $this->getDebitConfig(),
- "pixConfig" => $this->getPixConfig()
+ "pixConfig" => $this->getPixConfig(),
+ "marketplaceConfig" => $this->getMarketplaceConfig()
];
}
@@ -901,7 +945,7 @@ public function __call($method, $arguments)
{
$methodSplited = explode(
"_",
- preg_replace('/(?<=\\w)(?=[A-Z])/', "_$1", $method)
+ preg_replace('/(?<=\\w)(?=[A-Z])/',"_$1", $method ?? '')
);
$targetObject = $this;
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Order.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Order.php
index de34db88..c7aac1ee 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Order.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Aggregates/Order.php
@@ -192,6 +192,25 @@ public function updateCharge(ChargeInterface $updatedCharge, $overwriteId = fals
$this->addCharge($updatedCharge);
}
+ public function getSplitInfo()
+ {
+ $splitInfo = [];
+ foreach ($this->getCharges() as $charge) {
+ $transaction = $charge->getLastTransaction();
+ $postData = $transaction->getPostData();
+ $chargeId = $transaction->getChargeId()->getValue();
+ if (empty($postData->split)) {
+ continue;
+ }
+ foreach($postData->split as $split) {
+ $splitInfo[$chargeId][] = $split->recipient->name .
+ ' (' . $split->recipient->id . ') - ' .
+ $split->type . ': ' . $split->amount;
+ }
+ }
+ return $splitInfo;
+ }
+
/**
* Specify data which should be serialized to JSON
*
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/ChargeFactory.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/ChargeFactory.php
index d4da8bd1..a5130877 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/ChargeFactory.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/ChargeFactory.php
@@ -126,25 +126,25 @@ private function extractTransactionsFromDbData($dbData)
$transactions = [];
if (isset($dbData['tran_id']) && $dbData['tran_id'] !== null) {
$tranId = explode(',', $dbData['tran_id']);
- $tranPagarmeId = explode(',', $dbData['tran_pagarme_id']);
- $tranChargeId = explode(',', $dbData['tran_charge_id']);
- $tranAmount = explode(',', $dbData['tran_amount']);
- $tranPaidAmount = explode(',', $dbData['tran_paid_amount']);
- $tranType = explode(',', $dbData['tran_type']);
- $tranStatus = explode(',', $dbData['tran_status']);
- $tranCreatedAt = explode(',', $dbData['tran_created_at']);
-
- $tranAcquirerNsu = explode(',', $dbData['tran_acquirer_nsu']);
- $tranAcquirerTid = explode(',', $dbData['tran_acquirer_tid']);
+ $tranPagarmeId = explode(',', $dbData['tran_pagarme_id'] ?? '');
+ $tranChargeId = explode(',', $dbData['tran_charge_id'] ?? '');
+ $tranAmount = explode(',', $dbData['tran_amount'] ?? '');
+ $tranPaidAmount = explode(',', $dbData['tran_paid_amount'] ?? '');
+ $tranType = explode(',', $dbData['tran_type'] ?? '');
+ $tranStatus = explode(',', $dbData['tran_status'] ?? '');
+ $tranCreatedAt = explode(',', $dbData['tran_created_at'] ?? '');
+
+ $tranAcquirerNsu = explode(',', $dbData['tran_acquirer_nsu'] ?? '');
+ $tranAcquirerTid = explode(',', $dbData['tran_acquirer_tid'] ?? '');
$tranAcquirerAuthCode = explode(
',',
- $dbData['tran_acquirer_auth_code']
- );
- $tranAcquirerName = explode(',', $dbData['tran_acquirer_name']);
- $tranAcquirerMessage = explode(',', $dbData['tran_acquirer_message']);
- $tranBoletoUrl = explode(',', $dbData['tran_boleto_url']);
- $tranCardData = explode('---', $dbData['tran_card_data']);
- $tranData = explode('---', $dbData['tran_data']);
+ $dbData['tran_acquirer_auth_code'] ?? ''
+ );
+ $tranAcquirerName = explode(',', $dbData['tran_acquirer_name'] ?? '');
+ $tranAcquirerMessage = explode(',', $dbData['tran_acquirer_message'] ?? '');
+ $tranBoletoUrl = explode(',', $dbData['tran_boleto_url'] ?? '');
+ $tranCardData = explode('---', $dbData['tran_card_data'] ?? '');
+ $tranData = explode('---', $dbData['tran_data'] ?? '');
foreach ($tranId as $index => $id) {
$transaction = [
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/ConfigurationFactory.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/ConfigurationFactory.php
index 0016996b..3ff694d9 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/ConfigurationFactory.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/ConfigurationFactory.php
@@ -5,6 +5,7 @@
use Pagarme\Core\Kernel\Abstractions\AbstractEntity;
use Pagarme\Core\Kernel\Aggregates\Configuration;
use Pagarme\Core\Kernel\Factories\Configurations\DebitConfigFactory;
+use Pagarme\Core\Kernel\Factories\Configurations\MarketplaceConfigFactory;
use Pagarme\Core\Kernel\Factories\Configurations\PixConfigFactory;
use Pagarme\Core\Kernel\Factories\Configurations\RecurrenceConfigFactory;
use Pagarme\Core\Kernel\Factories\Configurations\VoucherConfigFactory;
@@ -81,11 +82,19 @@ public function createFromJsonData($json)
$config->setBoletoCreditCardEnabled($data->boletoCreditCardEnabled);
$config->setTwoCreditCardsEnabled($data->twoCreditCardsEnabled);
- if (empty($data->createOrder)){
+ if (empty($data->createOrder)) {
$data->createOrder = false;
}
$config->setCreateOrderEnabled($data->createOrder);
+ if (!empty($data->merchantId)) {
+ $config->setMerchantId($data->merchantId);
+ }
+
+ if (!empty($data->accountId)) {
+ $config->setAccountId($data->accountId);
+ }
+
if (!empty($data->sendMail)) {
$config->setSendMailEnabled($data->sendMail);
}
@@ -132,7 +141,7 @@ public function createFromJsonData($json)
$config->setHubEnvironment($data->hubEnvironment);
}
- if (!empty($data->keys) ) {
+ if (!empty($data->keys)) {
if (!isset($data->publicKey)) {
$index = Configuration::KEY_PUBLIC;
$data->publicKey = $data->keys->$index;
@@ -179,7 +188,7 @@ public function createFromJsonData($json)
$config->setBoletoBankCode($data->boletoBankCode);
}
if (!empty($data->boletoDueDays)) {
- $config->setBoletoDueDays((int) $data->boletoDueDays);
+ $config->setBoletoDueDays((int)$data->boletoDueDays);
}
if (!empty($data->saveCards)) {
@@ -206,7 +215,7 @@ public function createFromJsonData($json)
if (!empty($data->voucherConfig)) {
$config->setVoucherConfig(
(new VoucherConfigFactory)
- ->createFromDbData($data->voucherConfig)
+ ->createFromDbData($data->voucherConfig)
);
}
@@ -223,10 +232,21 @@ public function createFromJsonData($json)
);
}
+ if (!empty($data->allowNoAddress)) {
+ $config->setAllowNoAddress($data->allowNoAddress);
+ }
+
+ if (!empty($data->marketplaceConfig)) {
+ $config->setMarketplaceConfig(
+ (new MarketplaceConfigFactory())
+ ->createFromDbData($data->marketplaceConfig)
+ );
+ }
+
return $config;
}
- private function createCardConfigs($data,Configuration $config)
+ private function createCardConfigs($data, Configuration $config)
{
try {
foreach ($data->cardConfigs as $cardConfig) {
@@ -243,16 +263,18 @@ private function createCardConfigs($data,Configuration $config)
)
);
}
- } catch (Exception $e) {}
+ } catch (Exception $e) {
+
+ }
}
private function createPublicKey($key)
{
try {
return new TestPublicKey($key);
- } catch(\Exception $e) {
+ } catch (\Exception $e) {
- } catch(\Throwable $e) {
+ } catch (\Throwable $e) {
}
@@ -263,17 +285,17 @@ private function createSecretKey($key)
{
try {
return new TestSecretKey($key);
- } catch(\Exception $e) {
+ } catch (\Exception $e) {
- } catch(\Throwable $e) {
+ } catch (\Throwable $e) {
}
try {
return new SecretKey($key);
- } catch(\Exception $e) {
+ } catch (\Exception $e) {
- } catch(\Throwable $e) {
+ } catch (\Throwable $e) {
}
@@ -282,7 +304,7 @@ private function createSecretKey($key)
/**
*
- * @param array $dbData
+ * @param array $dbData
* @return AbstractEntity
*/
public function createFromDbData($dbData)
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/Configurations/MarketplaceConfigFactory.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/Configurations/MarketplaceConfigFactory.php
new file mode 100644
index 00000000..59f72bf0
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/Configurations/MarketplaceConfigFactory.php
@@ -0,0 +1,57 @@
+enabled)) {
+ $marketplaceConfig->setEnabled(
+ (bool) $data->enabled
+ );
+ }
+
+ if (isset($data->responsibilityForProcessingFees)) {
+ $marketplaceConfig->setResponsibilityForProcessingFees(
+ $data->responsibilityForProcessingFees
+ );
+ }
+
+ if (isset($data->responsibilityForChargebacks)) {
+ $marketplaceConfig->setResponsibilityForChargebacks(
+ $data->responsibilityForChargebacks
+ );
+ }
+
+ if (isset($data->responsibilityForReceivingSplitRemainder)) {
+ $marketplaceConfig->setResponsibilityForReceivingSplitRemainder(
+ $data->responsibilityForReceivingSplitRemainder
+ );
+ }
+
+ if (isset($data->responsibilityForReceivingExtrasAndDiscounts)) {
+ $marketplaceConfig->setResponsibilityForReceivingExtrasAndDiscounts(
+ $data->responsibilityForReceivingExtrasAndDiscounts
+ );
+ }
+
+ if (isset($data->mainRecipientId)) {
+ $marketplaceConfig->setMainRecipientId(
+ $data->mainRecipientId
+ );
+ }
+
+ return $marketplaceConfig;
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/OrderFactory.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/OrderFactory.php
index 27126001..74b97896 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/OrderFactory.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/OrderFactory.php
@@ -132,7 +132,7 @@ public function createFromPlatformData(
$order->setPagarmeId(new OrderId($orderId));
- $baseStatus = explode('_', $platformOrder->getStatus());
+ $baseStatus = explode('_', $platformOrder->getStatus() ?? '');
$status = $baseStatus[0];
for ($i = 1; $i < count($baseStatus); $i++) {
$status .= ucfirst(($baseStatus[$i]));
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/TransactionFactory.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/TransactionFactory.php
index cee59258..41086123 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/TransactionFactory.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Factories/TransactionFactory.php
@@ -20,7 +20,7 @@ public function createFromPostData($postData)
$transaction->setPagarmeId(new TransactionId($postData['id']));
- $baseStatus = explode('_', $postData['status']);
+ $baseStatus = explode('_', $postData['status'] ?? '');
$status = $baseStatus[0];
for ($i = 1; $i < count($baseStatus); $i++) {
$status .= ucfirst(($baseStatus[$i]));
@@ -34,7 +34,7 @@ public function createFromPostData($postData)
}
$transaction->setStatus(TransactionStatus::$status());
- $baseType = explode('_', $postData['transaction_type']);
+ $baseType = explode('_', $postData['transaction_type'] ?? '');
$type = $baseType[0];
for ($i = 1; $i < count($baseType); $i++) {
$type .= ucfirst(($baseType[$i]));
@@ -142,7 +142,7 @@ public function createFromDbData($dbData)
$transaction->setAcquirerTid($dbData['acquirer_tid']);
$transaction->setAcquirerAuthCode($dbData['acquirer_auth_code']);
- $baseStatus = explode('_', $dbData['status']);
+ $baseStatus = explode('_', $dbData['status'] ?? '');
$status = $baseStatus[0];
for ($i = 1; $i < count($baseStatus); $i++) {
$status .= ucfirst(($baseStatus[$i]));
@@ -156,7 +156,7 @@ public function createFromDbData($dbData)
}
$transaction->setStatus(TransactionStatus::$status());
- $baseType = explode('_', $dbData['type']);
+ $baseType = explode('_', $dbData['type'] ?? '');
$type = $baseType[0];
for ($i = 1; $i < count($baseType); $i++) {
$type .= ucfirst(($baseType[$i]));
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Helper/StringFunctionsHelper.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Helper/StringFunctionsHelper.php
index 2fa99f41..e7e1b5c3 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Helper/StringFunctionsHelper.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Helper/StringFunctionsHelper.php
@@ -132,7 +132,7 @@ final public function removeSpecialCharacters($str)
return preg_replace(
"/[^a-zA-Z ]/",
'',
- $str
+ $str ?? ''
);
}
@@ -143,7 +143,7 @@ public function cleanStrToDb($str)
return str_replace(
"'",
"`",
- strip_tags($str)
+ strip_tags($str ?? '')
);
}
@@ -161,7 +161,7 @@ public static function removeLineBreaks($text)
preg_replace(
$pattern,
' ',
- $text
+ $text ?? ''
)
);
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/I18N/ENUS.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/I18N/ENUS.php
index faebf4cd..c44c8f91 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/I18N/ENUS.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/I18N/ENUS.php
@@ -94,6 +94,13 @@ protected function getTable()
"The sum of payments is greater than the order amount! Review the information and try again." => null,
"The card brand '%s' or the amount %.2f doesn't allow %d installment(s)! Please review the information and try again." => null,
"Passed value:" => null,
+ "ChargeId: %s - Split rules:" => null,
+ "name" => null,
+ "documentType" => null,
+ "type" => null,
+ "holderName" => null,
+ "holderType" => null,
+ "holderDocument" => null,
];
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/I18N/PTBR.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/I18N/PTBR.php
index 6561ebc1..744d7e12 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/I18N/PTBR.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/I18N/PTBR.php
@@ -95,6 +95,13 @@ protected function getTable()
"The sum of payments is greater than the order amount! Review the information and try again." => "A soma dos pagamentos é maior do que o valor do pedido! Verifique as informações de sua compra e tente novamente.",
"The card brand '%s' or the amount %.2f doesn't allow %d installment(s)! Please review the information and try again." => "A bandeira do cartão '%s' ou o valor %.2f não permite %d parcela(s)! Por favor revise os dados e tente novamente.",
"Passed value:" => "Valor informado:",
+ "ChargeId: %s - Split rules:" => "ChargeId: %s - Regras de Split:",
+ "name" => "Nome",
+ "documentType" => "Tipo do Documento",
+ "type" => "Tipo",
+ "holderName" => "Nome do Titular",
+ "holderType" => "Tipo do Titular",
+ "holderDocument" => "Documento do Titular",
];
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Interfaces/PlatformOrderInterface.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Interfaces/PlatformOrderInterface.php
index bb4e1227..1e5cca79 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Interfaces/PlatformOrderInterface.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Interfaces/PlatformOrderInterface.php
@@ -5,6 +5,7 @@
use Pagarme\Core\Kernel\ValueObjects\Id\OrderId;
use Pagarme\Core\Kernel\ValueObjects\OrderState;
use Pagarme\Core\Kernel\ValueObjects\OrderStatus;
+use Pagarme\Core\Marketplace\Aggregates\Split;
use Pagarme\Core\Payment\Aggregates\Customer;
use Pagarme\Core\Payment\Aggregates\Item;
use Pagarme\Core\Payment\Aggregates\Payments\AbstractPayment;
@@ -77,7 +78,7 @@ public function getCode();
public function getData();
/**
*
- * @return OrderId
+ * @return OrderId
*/
public function getPagarmeId();
@@ -99,6 +100,9 @@ public function getPaymentMethodCollection();
/** @return null|Shipping */
public function getShipping();
+ /** @return null|Split */
+ public function handleSplitOrder();
+
/** @since 1.6.5 */
public function getTotalCanceled();
@@ -119,4 +123,4 @@ public function sendEmail($message);
* @return string
*/
public function getStatusLabel(OrderStatus $orderStatus);
-}
\ No newline at end of file
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Log/BlurData.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Log/BlurData.php
index ece3fff9..0510242b 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Log/BlurData.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Log/BlurData.php
@@ -23,22 +23,22 @@ class BlurData
*/
public function getBlurMethod(string $method)
{
- return 'blur' . str_replace(' ', '', ucwords(str_replace('_', ' ', $method)));
+ return 'blur' . str_replace(' ', '', ucwords(str_replace('_', ' ', $method ?? '')));
}
/**
* @param string $value
- * @param $delimiter
+ * @param int $delimiter
* @return string
*/
- private function blurStringSensitiveData(?string $value, $delimiter)
+ private function blurStringSensitiveData($value, $delimiter)
{
- $value = $value ?? "";
+ if (empty($value)) {
+ return '';
+ }
$displayed = substr($value, 0, $delimiter);
- $blur = str_repeat("*", strlen($value));
- $blur = substr($blur, $delimiter);
- $result = "$displayed $blur";
- return $result;
+ $blur = str_repeat("*", strlen($value) - $delimiter);
+ return $displayed . $blur;
}
/**
@@ -95,7 +95,7 @@ public function blurStreet(string $street)
*/
public function blurDocument(string $document)
{
- return preg_replace('/\B[^@.]/', '*', $document);
+ return preg_replace('/\B[^@.]/', '*', $document ?? '');
}
/**
@@ -177,7 +177,7 @@ public function blurNeighborhood(?string $neighborhood)
public function blurHolderName(?string $holderName)
{
$holderName = $holderName ?? "";
- return preg_replace('/^.{8}/', '$1**', $holderName);
+ return preg_replace('/^.{8}/', '$1**', $holderName ?? '');
}
/**
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Repositories/ConfigurationRepository.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Repositories/ConfigurationRepository.php
index 201756fd..59319cdd 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Repositories/ConfigurationRepository.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Repositories/ConfigurationRepository.php
@@ -22,7 +22,7 @@ private function removeSpecialCharacters($jsonEncoded)
preg_replace(
$this->pattern,
' ',
- $jsonEncoded
+ $jsonEncoded ?? ''
)
);
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/LocalizationService.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/LocalizationService.php
index 3fb2652a..6aa843e2 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/LocalizationService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/LocalizationService.php
@@ -49,7 +49,7 @@ private function translateDashboard($string)
private function getI18NTableOrDefaultFor($locale)
{
- $langClass = str_replace('_', '', $locale);
+ $langClass = str_replace('_', '', $locale ?? '');
$langClass = strtoupper($langClass);
$langClass = "Pagarme\\Core\\Kernel\\I18N\\$langClass";
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/LogService.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/LogService.php
index 5514ec3a..39e3e6d9 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/LogService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/LogService.php
@@ -76,12 +76,15 @@ public function __construct(
public function info($message, $sourceObject = null)
{
try {
+
$logObject = $this->prepareObject($sourceObject);
$logObject = $this->blurSensitiveData($logObject);
$this->monolog->info($message, $logObject);
- } catch (\Throwable $throwable) {
+ } catch (\Throwable $th) {
+ //throw $th;
}
+
}
/**
@@ -90,9 +93,15 @@ public function info($message, $sourceObject = null)
*/
public function exception(\Exception $exception)
{
- $logObject = $this->prepareObject($exception);
- $code = ' | Exception code: ' . $exception->getCode();
- $this->monolog->error($exception->getMessage() . $code, $logObject);
+ try {
+
+ $logObject = $this->prepareObject($exception);
+ $code = ' | Exception code: ' . $exception->getCode();
+ $this->monolog->error($exception->getMessage() . $code, $logObject);
+
+ } catch (\Throwable $th) {
+ //throw $th;
+ }
}
/**
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/MoneyService.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/MoneyService.php
index 137b20bf..af53f7b2 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/MoneyService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/MoneyService.php
@@ -36,7 +36,7 @@ public function removeSeparators($amount)
return str_replace(
['.', ','],
"",
- $amount
+ $amount ?? ''
);
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/OrderService.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/OrderService.php
index 2a6f24f9..21577910 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/OrderService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/Services/OrderService.php
@@ -257,8 +257,7 @@ public function createOrderAtPagarme(PlatformOrderInterface $platformOrder)
//build PaymentOrder based on platformOrder
$paymentOrder = $this->extractPaymentOrderFromPlatformOrder($platformOrder);
- $orderInfo = $this->getOrderInfo($platformOrder);
-
+
$i18n = new LocalizationService();
//Send through the APIService to pagarme
@@ -296,6 +295,14 @@ public function createOrderAtPagarme(PlatformOrderInterface $platformOrder)
$order = $orderFactory->createFromPostData($response);
$order->setPlatformOrder($platformOrder);
+ $split = $order->getSplitInfo();
+ foreach ($split as $chargeId => $splitInfo) {
+ $platformOrder->addHistoryComment(
+ $i18n->getDashboard('ChargeId: %s - Split rules:',
+ $chargeId) . '
' . join('
', $splitInfo)
+ );
+ }
+
$handler = $this->getResponseHandler($order);
$handler->handle($order, $paymentOrder);
@@ -334,7 +341,7 @@ public function createOrderAtPagarme(PlatformOrderInterface $platformOrder)
private function getResponseHandler($response)
{
$responseClass = get_class($response);
- $responseClass = explode('\\', $responseClass);
+ $responseClass = explode('\\', $responseClass ?? '');
$responseClass =
'Pagarme\\Core\\Payment\\Services\\ResponseHandlers\\' .
@@ -397,10 +404,15 @@ public function extractPaymentOrderFromPlatformOrder(
$order->setCode($platformOrder->getCode());
$shipping = $platformOrder->getShipping();
- if (!$shipping && $shipping !== null) {
+ if (!empty($shipping) && !empty($shipping->getAmount())) {
$order->setShipping($shipping);
}
+ $splitData = $platformOrder->handleSplitOrder();
+ if ($splitData !== null) {
+ $order->setSplitData($splitData);
+ }
+
return $order;
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Configuration/MarketplaceConfig.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Configuration/MarketplaceConfig.php
new file mode 100644
index 00000000..0a6fc39f
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Configuration/MarketplaceConfig.php
@@ -0,0 +1,239 @@
+enabled;
+ }
+
+ /**
+ * @param bool $enabled
+ * @return MarketplaceConfig
+ */
+ public function setEnabled($enabled)
+ {
+ $this->enabled = $enabled;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getResponsibilityForProcessingFees()
+ {
+ return $this->responsibilityForProcessingFees;
+ }
+
+ /**
+ * @param $responsibilityForProcessingFees
+ * @return MarketplaceConfig
+ */
+ public function setResponsibilityForProcessingFees(
+ $responsibilityForProcessingFees
+ ) {
+ $this->responsibilityForProcessingFees = $responsibilityForProcessingFees;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getResponsibilityForChargebacks()
+ {
+ return $this->responsibilityForChargebacks;
+ }
+
+ /**
+ * @param $responsibilityForChargebacks
+ * @return MarketplaceConfig
+ */
+ public function setResponsibilityForChargebacks(
+ $responsibilityForChargebacks
+ ) {
+ $this->responsibilityForChargebacks = $responsibilityForChargebacks;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getResponsibilityForReceivingSplitRemainder()
+ {
+ return $this->responsibilityForReceivingSplitRemainder;
+ }
+
+ /**
+ * @param $responsibilityForReceivingSplitRemainder
+ * @return MarketplaceConfig
+ */
+ public function setResponsibilityForReceivingSplitRemainder(
+ $responsibilityForReceivingSplitRemainder
+ ) {
+ $this->responsibilityForReceivingSplitRemainder
+ = $responsibilityForReceivingSplitRemainder;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getResponsibilityForReceivingExtrasAndDiscounts()
+ {
+ return $this->responsibilityForReceivingExtrasAndDiscounts;
+ }
+
+ /**
+ * @param $responsibilityForReceivingExtrasAndDiscounts
+ * @return MarketplaceConfig
+ */
+ public function setResponsibilityForReceivingExtrasAndDiscounts(
+ $responsibilityForReceivingExtrasAndDiscounts
+ ) {
+ $this->responsibilityForReceivingExtrasAndDiscounts
+ = $responsibilityForReceivingExtrasAndDiscounts;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getMainRecipientId()
+ {
+ return $this->mainRecipientId;
+ }
+
+ /**
+ * @param $mainRecipientId
+ * @return MarketplaceConfig
+ */
+ public function setMainRecipientId(
+ $mainRecipientId
+ ) {
+ $this->mainRecipientId = $mainRecipientId;
+ return $this;
+ }
+
+ /**
+ * @param $option
+ * @return bool
+ */
+ public function getSplitMainOptionConfig($option)
+ {
+ $optionMethod = 'get' . ucfirst($option);
+
+ if (!method_exists($this, $optionMethod)) {
+ return;
+ }
+
+ $responsible = $this->$optionMethod();
+
+ if ($responsible == self::MARKETPLACE_SELLERS
+ || $responsible == self::MARKETPLACE
+ ) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * @param $option
+ * @return bool
+ */
+ public function getSplitSecondaryOptionConfig($option)
+ {
+ $optionMethod = 'get' . ucfirst($option);
+
+ if (!method_exists($this, $optionMethod)) {
+ return;
+ }
+
+ $responsible = $this->$optionMethod();
+
+ if ($responsible == self::MARKETPLACE_SELLERS
+ || $responsible == self::SELLERS
+ ) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * To check the structural equality of value objects,
+ * this method should be implemented in this class children.
+ *
+ * @param $object
+ * @return bool
+ */
+ protected function isEqual($object)
+ {
+ return
+ $this->enabled === $object->isEnabled() &&
+ $this->responsibilityForProcessingFees ===
+ $object->getResponsibilityForProcessingFees() &&
+ $this->responsibilityForChargebacks ===
+ $object->getResponsibilityForChargebacks() &&
+ $this->responsibilityForReceivingSplitRemainder ===
+ $object->responsibilityForReceivingSplitRemainder &&
+ $this->responsibilityForReceivingExtrasAndDiscounts ===
+ $object->responsibilityForReceivingExtrasAndDiscounts &&
+ $this->mainRecipientId ===
+ $object->mainRecipientId;
+ }
+
+ /**
+ * Specify data which should be serialized to JSON
+ * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
+ * @return mixed data which can be serialized by json_encode,
+ * which is a value of any type other than a resource.
+ * @since 5.4.0
+ */
+ #[\ReturnTypeWillChange]
+ public function jsonSerialize()
+ {
+ return [
+ "enabled" => $this->enabled,
+ "responsibilityForProcessingFees" =>
+ $this->responsibilityForProcessingFees,
+ "responsibilityForChargebacks" =>
+ $this->responsibilityForChargebacks,
+ "responsibilityForReceivingSplitRemainder" =>
+ $this->responsibilityForReceivingSplitRemainder,
+ "responsibilityForReceivingExtrasAndDiscounts" =>
+ $this->responsibilityForReceivingExtrasAndDiscounts,
+ "mainRecipientId" =>
+ $this->mainRecipientId,
+ ];
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/AccountId.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/AccountId.php
index 561aafe6..15c19355 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/AccountId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/AccountId.php
@@ -8,6 +8,6 @@ class AccountId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^acc_\w{16}$/', $value) === 1;
+ return preg_match('/^acc_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/ChargeId.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/ChargeId.php
index 4d792020..c6fbca31 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/ChargeId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/ChargeId.php
@@ -8,6 +8,6 @@ class ChargeId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^ch_\w{16}$/', $value) === 1;
+ return preg_match('/^ch_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/CustomerId.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/CustomerId.php
index 3e69e819..e622c991 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/CustomerId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/CustomerId.php
@@ -8,6 +8,6 @@ class CustomerId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^cus_\w{16}$/', $value) === 1;
+ return preg_match('/^cus_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/CycleId.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/CycleId.php
index 11cfc0c2..5e9ac0d4 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/CycleId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/CycleId.php
@@ -8,6 +8,6 @@ class CycleId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^cycle_\w{16}$/', $value) === 1;
+ return preg_match('/^cycle_\w{16}$/', $value ?? '') === 1;
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/GUID.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/GUID.php
index e612241b..fd05b33a 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/GUID.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/GUID.php
@@ -8,6 +8,6 @@ class GUID extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^\w{8}-(\w{4}-){3}\w{12}$/', $value) === 1;
+ return preg_match('/^\w{8}-(\w{4}-){3}\w{12}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/InvoiceId.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/InvoiceId.php
index d3fd2ea9..49803755 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/InvoiceId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/InvoiceId.php
@@ -8,6 +8,6 @@ class InvoiceId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^in_\w{16}$/', $value) === 1;
+ return preg_match('/^in_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/MerchantId.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/MerchantId.php
index 12ffcc5f..804d068f 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/MerchantId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/MerchantId.php
@@ -8,6 +8,6 @@ class MerchantId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^merch_\w{16}$/', $value) === 1;
+ return preg_match('/^merch_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/OrderId.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/OrderId.php
index fbab7112..30693eee 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/OrderId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/OrderId.php
@@ -18,6 +18,6 @@ public function __construct($orderId)
protected function validateValue($value)
{
- return preg_match('/^or_\w{16}$/', $value) === 1;
+ return preg_match('/^or_\w{16}$/', $value ?? '') === 1;
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/RecipientId.php b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/RecipientId.php
new file mode 100644
index 00000000..164f89cc
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/src/Kernel/ValueObjects/Id/RecipientId.php
@@ -0,0 +1,14 @@
+getModuleRoot(),'', $path);
+ $dir = str_replace($this->getModuleRoot(),'', $path ?? '');
return
$ignoreVendor
&& (
diff --git a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/InstallDataSource/ComposerInstallDataSource.php b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/InstallDataSource/ComposerInstallDataSource.php
index 7ce2ad74..e57c6533 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/InstallDataSource/ComposerInstallDataSource.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/InstallDataSource/ComposerInstallDataSource.php
@@ -18,7 +18,7 @@ public function __construct()
$this->integrityFilePath = $concreteDir . DIRECTORY_SEPARATOR . 'integrityData';
- $composerJsonFilePath = explode(DIRECTORY_SEPARATOR, $concreteDir);
+ $composerJsonFilePath = explode(DIRECTORY_SEPARATOR, $concreteDir ?? '');
array_pop($composerJsonFilePath);
$this->composerJsonFilePath = implode(DIRECTORY_SEPARATOR, $composerJsonFilePath);
@@ -72,7 +72,7 @@ protected function getInstallDirs()
protected function getModuleRoot()
{
- $moduleRoot = explode(DIRECTORY_SEPARATOR, $this->composerJsonFilePath);
+ $moduleRoot = explode(DIRECTORY_SEPARATOR, $this->composerJsonFilePath ?? '');
array_pop($moduleRoot);
$moduleRoot = implode(DIRECTORY_SEPARATOR, $moduleRoot);
diff --git a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/InstallDataSource/ModmanInstallDataSource.php b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/InstallDataSource/ModmanInstallDataSource.php
index 67103690..7087d5f2 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/InstallDataSource/ModmanInstallDataSource.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/InstallDataSource/ModmanInstallDataSource.php
@@ -51,18 +51,18 @@ protected function getInstallDirs()
$rawData = file_get_contents($this->modmanFilePath);
$lines = [];
- preg_match_all('/^(?!#).+/m', $rawData, $lines);
+ preg_match_all('/^(?!#).+/m', $rawData ?? '', $lines);
$lines = array_pop($lines);
array_walk(
$lines, function (&$line) {
- $data = explode(' ', $line);
+ $data = explode(' ', $line ?? '');
$line = end($data);
}
);
$platformRootDir = '';
foreach ($lines as $line) {
- $platformRootDir = str_replace($line, '', $this->modmanFilePath);
+ $platformRootDir = str_replace($line, '', $this->modmanFilePath ?? '');
if (strlen($platformRootDir) >= strlen($this->modmanFilePath)) {
$platformRootDir = '';
}
@@ -90,18 +90,18 @@ protected function getModuleRoot()
$rawData = file_get_contents($this->modmanFilePath);
$lines = [];
- preg_match_all('/^(?!#).+/m', $rawData, $lines);
+ preg_match_all('/^(?!#).+/m', $rawData ?? '', $lines);
$lines = array_pop($lines);
array_walk(
$lines, function (&$line) {
- $data = explode(' ', $line);
+ $data = explode(' ', $line ?? '');
$line = end($data);
}
);
$platformRootDir = '';
foreach ($lines as $line) {
- $platformRootDir = str_replace($line, '', $this->modmanFilePath);
+ $platformRootDir = str_replace($line, '', $this->modmanFilePath ?? '');
if (strlen($platformRootDir) >= strlen($this->modmanFilePath)) {
$platformRootDir = '';
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/IntegrityInfoRetrieverService.php b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/IntegrityInfoRetrieverService.php
index 26ba21a7..5ce83eba 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/IntegrityInfoRetrieverService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/IntegrityInfoRetrieverService.php
@@ -44,7 +44,7 @@ public function getModuleInstallDataSource()
$classes = scandir($installDataSourcesDir);
array_walk(
$classes, function (&$class) {
- $class = str_replace('InstallDataSource.php', '', $class);
+ $class = str_replace('InstallDataSource.php', '', $class ?? '');
}
);
$classes = array_filter(
@@ -92,7 +92,7 @@ private function getIntegrityInfo(InstallDataSourceInterface $dataInstallSource)
$cleanFilename = str_replace(
$rootDir,
'',
- $file
+ $file ?? ''
);
$fileHashs[$cleanFilename] = $this->generateFileHash($file);
}
@@ -183,7 +183,7 @@ private function detectRootDir($files)
{
$dirCount = [];
foreach ($files as $file) {
- $explodedPath = explode(DIRECTORY_SEPARATOR, $file);
+ $explodedPath = explode(DIRECTORY_SEPARATOR, $file ?? '');
array_pop($explodedPath);
@@ -227,7 +227,7 @@ private function generateIntegrityFile(InstallDataSourceInterface $dataSource)
$cleanFilename = str_replace(
$rootDir,
'',
- $file
+ $file ?? ''
);
$fileHashs[$cleanFilename] = $this->generateFileHash($file);
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/LogDownloadInfoRetrieverService.php b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/LogDownloadInfoRetrieverService.php
index e4681316..6566c913 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/LogDownloadInfoRetrieverService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/LogDownloadInfoRetrieverService.php
@@ -13,7 +13,7 @@ public function retrieveInfo($value)
$logInfo = $logInfoRetrievierService->retrieveInfo('');
$validLogFiles = $logInfo->files;
- $params = explode(':', $value);
+ $params = explode(':', $value ?? '');
try {
$extension = $params[0];
@@ -32,7 +32,7 @@ public function retrieveInfo($value)
private function handleDownload($extension, $file)
{
- $downloadFileName = str_replace(DIRECTORY_SEPARATOR, "_", $file);
+ $downloadFileName = str_replace(DIRECTORY_SEPARATOR, "_", $file ?? '');
if ($extension != "zip") {
return $this->downloadLog($downloadFileName, $file);
diff --git a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/LogInfoRetrieverService.php b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/LogInfoRetrieverService.php
index a87ec5e2..1fd2bba5 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/LogInfoRetrieverService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Maintenance/Services/LogInfoRetrieverService.php
@@ -51,12 +51,12 @@ public function retrieveInfo($value)
$uriZip =
ltrim(preg_replace(
'/' . $needle . '/',
- 'logDownload=zip:' . $encoded, $requestURI
+ 'logDownload=zip:' . $encoded, $requestURI ?? ''
), '/');
$uriRaw =
ltrim(preg_replace(
'/' . $needle . '/',
- 'logDownload=raw:' . $encoded, $requestURI
+ 'logDownload=raw:' . $encoded, $requestURI ?? ''
), '/');
$donwloadURIs[] = [
@@ -74,7 +74,7 @@ public function retrieveInfo($value)
private function filterLogFilesByDate($dateQuery, $files)
{
- $dates = explode(':', $dateQuery);
+ $dates = explode(':', $dateQuery ?? '');
if (empty($dates)) {
return $files;
@@ -92,7 +92,7 @@ private function filterLogFilesByDate($dateQuery, $files)
foreach ($files as $file) {
$matchDate = [];
- preg_match('/\d{4}-\d{2}-\d{2}/', $file, $matchDate);
+ preg_match('/\d{4}-\d{2}-\d{2}/', $file ?? '', $matchDate);
if (!isset($matchDate[0])) {
$result[] = $file;
@@ -124,7 +124,7 @@ private function scanDirs($dirs)
}
$foundFile = $logDir . DIRECTORY_SEPARATOR . $foundFile;
- $foundFile = preg_replace('/\\' .DIRECTORY_SEPARATOR. '{2,}/', DIRECTORY_SEPARATOR, $foundFile);
+ $foundFile = preg_replace('/\\' .DIRECTORY_SEPARATOR. '{2,}/', DIRECTORY_SEPARATOR, $foundFile ?? '');
if (is_dir($foundFile)) {
$files = array_merge(
diff --git a/vendor/pagarme/ecommerce-module-core/src/Marketplace/Aggregates/Recipient.php b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Aggregates/Recipient.php
new file mode 100644
index 00000000..a10d72e5
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Aggregates/Recipient.php
@@ -0,0 +1,653 @@
+i18n = new LocalizationService();
+ }
+
+ /**
+ * @return string
+ */
+ public function getExternalId()
+ {
+ return $this->externalId;
+ }
+
+ /**
+ * @param string $externalId
+ * @return Recipient
+ */
+ public function setExternalId($externalId)
+ {
+ $this->externalId = $externalId;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getName()
+ {
+ return $this->name;
+ }
+
+ /**
+ * @param string $name
+ * @return Recipient
+ * @throws InvalidParamException
+ */
+ public function setName($name)
+ {
+ if (empty($name)) {
+ $inputName = $this->i18n->getDashboard('name');
+ $message = $this->i18n->getDashboard(
+ "The %s should not be empty!",
+ $inputName
+ );
+
+ throw new \Exception($message, 400);
+ }
+
+ $this->name = $name;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getEmail()
+ {
+ return $this->email;
+ }
+
+ /**
+ * @param string $email
+ * @return Recipient
+ */
+ public function setEmail($email)
+ {
+ $this->email = $email;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getDocumentType()
+ {
+ return $this->documentType;
+ }
+
+ /**
+ * @param string $documentType
+ * @return Recipient
+ * @throws InvalidParamException
+ */
+ public function setDocumentType($documentType)
+ {
+ if (empty($documentType)) {
+ $inputName = $this->i18n->getDashboard('documentType');
+ $message = $this->i18n->getDashboard(
+ "The %s should not be empty!",
+ $inputName
+ );
+
+ throw new \Exception($message, 400);
+ }
+
+ $this->documentType = $documentType;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getDocument()
+ {
+ return $this->document;
+ }
+
+ /**
+ * @param string $document
+ * @return Recipient
+ * @throws InvalidParamException
+ */
+ public function setDocument($document)
+ {
+ if (empty($document)) {
+ $inputName = $this->i18n->getDashboard('document');
+ $message = $this->i18n->getDashboard(
+ "The %s should not be empty!",
+ $inputName
+ );
+
+ throw new \Exception($message, 400);
+ }
+
+ $this->document = $document;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getType()
+ {
+ return $this->type;
+ }
+
+ /**
+ * @param string $type
+ * @return Recipient
+ * @throws InvalidParamException
+ */
+ public function setType($type)
+ {
+ if (empty($type)) {
+ $inputName = $this->i18n->getDashboard('type');
+ $message = $this->i18n->getDashboard(
+ "The %s should not be empty!",
+ $inputName
+ );
+
+ throw new \Exception($message, 400);
+ }
+
+ $this->type = $type;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getHolderName()
+ {
+ return $this->holderName;
+ }
+
+ /**
+ * @param string $holderName
+ * @return Recipient
+ * @throws InvalidParamException
+ */
+ public function setHolderName($holderName)
+ {
+ if (empty($holderName)) {
+ $inputName = $this->i18n->getDashboard('holderName');
+ $message = $this->i18n->getDashboard(
+ "The %s should not be empty!",
+ $inputName
+ );
+
+ throw new \Exception($message, 400);
+ }
+
+ $this->holderName = $holderName;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getHolderType()
+ {
+ return $this->holderType;
+ }
+
+ /**
+ * @param string $holderType
+ * @return Recipient
+ * @throws InvalidParamException
+ */
+ public function setHolderType($holderType)
+ {
+ if (empty($holderType)) {
+ $inputName = $this->i18n->getDashboard('holderType');
+ $message = $this->i18n->getDashboard(
+ "The %s should not be empty!",
+ $inputName
+ );
+
+ throw new \Exception($message, 400);
+ }
+
+ $this->holderType = $holderType;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getHolderDocument()
+ {
+ return $this->holderDocument;
+ }
+
+ /**
+ * @param string $holderDocument
+ * @return Recipient
+ * @throws InvalidParamException
+ */
+ public function setHolderDocument($holderDocument)
+ {
+ if (empty($holderDocument)) {
+ $inputName = $this->i18n->getDashboard('holderDocument');
+ $message = $this->i18n->getDashboard(
+ "The %s should not be empty!",
+ $inputName
+ );
+
+ throw new \Exception($message, 400);
+ }
+
+ $this->holderDocument = $holderDocument;
+
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getBank()
+ {
+ return $this->bank;
+ }
+
+ /**
+ * @param string $bank
+ * @return Recipient
+ */
+ public function setBank($bank)
+ {
+ $this->bank = $bank;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getBranchNumber()
+ {
+ return $this->branchNumber;
+ }
+
+ /**
+ * @param string $branchNumber
+ * @return Recipient
+ */
+ public function setBranchNumber($branchNumber)
+ {
+ $this->branchNumber = $branchNumber;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getBranchCheckDigit()
+ {
+ return $this->branchCheckDigit;
+ }
+
+ /**
+ * @param string $branchCkeckDigit
+ * @return Recipient
+ */
+ public function setBranchCheckDigit($branchCkeckDigit)
+ {
+ $this->branchCheckDigit = $branchCkeckDigit;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountNumber()
+ {
+ return $this->accountNumber;
+ }
+
+ /**
+ * @param string $accountNumber
+ * @return Recipient
+ */
+ public function setAccountNumber($accountNumber)
+ {
+ $this->accountNumber = $accountNumber;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountCheckDigit()
+ {
+ return $this->accountCheckDigit;
+ }
+
+ /**
+ * @param string $accountCheckDigit
+ * @return Recipient
+ */
+ public function setAccountCheckDigit($accountCheckDigit)
+ {
+ $this->accountCheckDigit = $accountCheckDigit;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getAccountType()
+ {
+ return $this->accountType;
+ }
+
+ /**
+ * @param string $accountType
+ * @return Recipient
+ */
+ public function setAccountType($accountType)
+ {
+ $this->accountType = $accountType;
+ return $this;
+ }
+
+ /**
+ * @return bool
+ */
+ public function getTransferEnabled()
+ {
+ return $this->transferEnabled;
+ }
+
+ /**
+ * @param string $transferEnabled
+ * @return Recipient
+ */
+ public function setTransferEnabled($transferEnabled)
+ {
+ $this->transferEnabled = ($transferEnabled == 0) ? false : true;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getTransferInterval()
+ {
+ return $this->transferInterval;
+ }
+
+ /**
+ * @param string $transferInterval
+ * @return Recipient
+ */
+ public function setTransferInterval($transferInterval)
+ {
+ $this->transferInterval = $transferInterval;
+ return $this;
+ }
+
+ /**
+ * @return int
+ */
+ public function getTransferDay()
+ {
+ return $this->transferDay;
+ }
+
+ /**
+ * @param int $transferDay
+ * @return Recipient
+ */
+ public function setTransferDay($transferDay)
+ {
+ $this->transferDay = $transferDay;
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getCreatedAt()
+ {
+ return $this->createdAt;
+ }
+
+ /**
+ * @param \DateTime $createdAt
+ * @return ProductSubscription
+ */
+ public function setCreatedAt(\DateTime $createdAt)
+ {
+ $this->createdAt = $createdAt->format(self::DATE_FORMAT);
+ return $this;
+ }
+
+ /**
+ * @return string
+ */
+ public function getUpdatedAt()
+ {
+ return $this->updatedAt;
+ }
+
+ /**
+ * @param \DateTime $updatedAt
+ * @return ProductSubscription
+ */
+ public function setUpdatedAt(\DateTime $updatedAt)
+ {
+ $this->updatedAt = $updatedAt->format(self::DATE_FORMAT);
+ return $this;
+ }
+
+ public function convertToSdkRequest($update = false)
+ {
+ if ($update) {
+ return $this->convertToSdkUpdateRequest();
+ }
+
+ return $this->convertToSdkCreateRequest();
+ }
+
+ private function convertToSdkCreateRequest(): CreateRecipientRequest
+ {
+ $recipientRequest = new CreateRecipientRequest();
+
+ $recipientRequest->name = $this->getName();
+ $recipientRequest->email = $this->getEmail();
+ $recipientRequest->document = $this->getDocument();
+ $recipientRequest->type = $this->getType();
+
+ $recipientRequest->defaultBankAccount = $this->createBankAccountRequest();
+
+ $recipientRequest->transferSettings = $this->createTransferSettings();
+
+ return $recipientRequest;
+ }
+
+ /**
+ * @return array
+ */
+ private function convertToSdkUpdateRequest(): array
+ {
+ return [
+ new UpdateRecipientRequest(
+ ...array(
+ $this->getName(),
+ $this->getEmail(),
+ null,
+ $this->getType(),
+ 'active',
+ null
+ )
+ ),
+ new UpdateRecipientBankAccountRequest(
+ $this->createBankAccountRequest()
+ ),
+ $this->createTransferSettings(),
+ ];
+ }
+
+ /**
+ * @return CreateBankAccountRequest
+ */
+ protected function createBankAccountRequest(): CreateBankAccountRequest
+ {
+ $defaultBankAccount = new CreateBankAccountRequest();
+ $defaultBankAccount
+ ->holderName = $this->getHolderName();
+ $defaultBankAccount
+ ->holderType = $this->getHolderType();
+ $defaultBankAccount
+ ->holderDocument = $this->getDocument();
+ $defaultBankAccount
+ ->bank = $this->getBank();
+ $defaultBankAccount
+ ->branchNumber = $this->getBranchNumber();
+ $defaultBankAccount
+ ->branchCheckDigit = $this->getBranchCheckDigit();
+ $defaultBankAccount
+ ->accountNumber = $this->getAccountNumber();
+ $defaultBankAccount
+ ->accountCheckDigit = $this->getAccountCheckDigit();
+ $defaultBankAccount
+ ->type = $this->getAccountType();
+
+ return $defaultBankAccount;
+ }
+
+ /**
+ * @return CreateTransferSettingsRequest
+ */
+ protected function createTransferSettings(): CreateTransferSettingsRequest
+ {
+ $transferSettings = new CreateTransferSettingsRequest();
+ $transferSettings
+ ->transferEnabled = $this->getTransferEnabled();
+ $transferSettings
+ ->transferInterval = $this->getTransferInterval();
+ $transferSettings
+ ->transferDay = $this->getTransferDay();
+
+ return $transferSettings;
+ }
+
+ /**
+ * Specify data which should be serialized to JSON
+ * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
+ * @return mixed data which can be serialized by json_encode,
+ * which is a value of any type other than a resource.
+ * @since 5.4.0
+ */
+ #[\ReturnTypeWillChange]
+ public function jsonSerialize()
+ {
+ $obj = new \stdClass();
+
+ $obj->id = $this->getId();
+ $obj->recipientId = $this->getPagarmeId();
+ $obj->externalId = $this->getExternalId();
+ $obj->name = $this->getName();
+ $obj->email = $this->getEmail();
+ $obj->documentType = $this->getDocumentType();
+ $obj->document = $this->getDocument();
+ $obj->holderName = $this->getHolderName();
+ $obj->holderDocument = $this->getHolderDocument();
+ $obj->bank = $this->getBank();
+ $obj->branchNumber = $this->getBranchNumber();
+ $obj->branchCheckDigit = $this->getBranchCheckDigit();
+ $obj->accountNumber = $this->getAccountNumber();
+ $obj->accountCheckDigit = $this->getAccountCheckDigit();
+ $obj->accountType = $this->getAccountType();
+ $obj->transferEnabled = $this->getTransferEnabled();
+ $obj->transferInterval = $this->getTransferInterval();
+ $obj->transferDay = $this->getTransferDay();
+ $obj->createdAt = $this->getCreatedAt();
+ $obj->updatedAt = $this->getUpdatedAt();
+
+ return $obj;
+ }
+
+ public function bankAccountEquals(UpdateRecipientBankAccountRequest $bankAccountRequest): bool
+ {
+ return $this->getBank() == $bankAccountRequest->bankAccount->bank &&
+ $this->getBranchNumber() == $bankAccountRequest->bankAccount->branchNumber &&
+ $this->getBranchCheckDigit() == $bankAccountRequest->bankAccount->branchCheckDigit &&
+ $this->getAccountNumber() == $bankAccountRequest->bankAccount->accountNumber &&
+ $this->getAccountCheckDigit() == $bankAccountRequest->bankAccount->accountCheckDigit &&
+ $this->getAccountType() == $bankAccountRequest->bankAccount->type;
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Marketplace/Aggregates/Split.php b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Aggregates/Split.php
new file mode 100644
index 00000000..7629f67f
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Aggregates/Split.php
@@ -0,0 +1,193 @@
+marketplaceConfig = $moduleConfig->getMarketplaceConfig();
+ }
+ }
+
+ public function getMainRecipientOptionConfig(){
+ if (!$this->marketplaceConfig) {
+ return null;
+ }
+
+ return $this->marketplaceConfig
+ ->getMainRecipientId();
+ }
+
+ public function getMainChargeProcessingFeeOptionConfig()
+ {
+ if (!$this->marketplaceConfig) {
+ return null;
+ }
+
+ return $this->marketplaceConfig
+ ->getSplitMainOptionConfig('responsibilityForProcessingFees');
+ }
+
+ public function getMainLiableOptionConfig()
+ {
+ if (!$this->marketplaceConfig) {
+ return null;
+ }
+
+ return $this->marketplaceConfig
+ ->getSplitMainOptionConfig('responsibilityForChargebacks');
+ }
+
+ public function getSecondaryChargeProcessingFeeOptionConfig()
+ {
+ if (!$this->marketplaceConfig) {
+ return null;
+ }
+
+ return $this->marketplaceConfig
+ ->getSplitSecondaryOptionConfig('responsibilityForProcessingFees');
+ }
+
+ public function getSecondaryLiableOptionConfig()
+ {
+ if (!$this->marketplaceConfig) {
+ return null;
+ }
+
+ return $this->marketplaceConfig
+ ->getSplitSecondaryOptionConfig('responsibilityForChargebacks');
+ }
+
+ public function getSellersData()
+ {
+ return $this->sellersData;
+ }
+
+ /**
+ * @param array $sellersData
+ */
+ public function setSellersData($sellersData)
+ {
+ $this->sellersData = $sellersData;
+ }
+
+ public function getMarketplaceData()
+ {
+ return $this->marketplaceData;
+ }
+
+ /**
+ * @param array $marketplaceData
+ */
+ public function setMarketplaceData($marketplaceData)
+ {
+ $this->marketplaceData = $marketplaceData;
+ }
+
+ /**
+ * @return int
+ */
+ public function getMarketplaceComission()
+ {
+ $marketplaceData = $this->marketplaceData;
+ return $marketplaceData['totalCommission'];
+ }
+
+ /**
+ * @param int $commission
+ */
+ public function setCommission($commission)
+ {
+ if ($commission < 0) {
+ throw new InvalidParamException("Commission should be greater or equal to 0!", $commission);
+ }
+
+ $this->commission = $commission;
+ }
+
+ /**
+ * @return int
+ */
+ public function getCommission()
+ {
+ return $this->commission;
+ }
+
+ /**
+ * @param RecipientId $recipientId
+ */
+ public function setRecipientId($recipientId)
+ {
+ $this->recipientId = $recipientId;
+ }
+
+ /**
+ * @return RecipientId
+ */
+ public function getRecipientId()
+ {
+ return $this->recipientId;
+ }
+
+ public function convertMainToSDKRequest()
+ {
+ $splitRequest = new CreateSplitRequest();
+
+ $splitRequest->type = 'flat';
+ $splitRequest->recipientId = $this->getRecipientId();
+ $splitRequest->amount = $this->getCommission();
+
+ $splitRequest->options = new CreateSplitOptionsRequest();
+
+ $splitRequest->options->chargeProcessingFee = $this->getMainChargeProcessingFeeOptionConfig();
+ $splitRequest->options->liable = $this->getMainLiableOptionConfig();
+ $splitRequest->options->chargeRemainderFee = true;
+
+ return $splitRequest;
+ }
+
+ public function convertSecondaryToSDKRequest()
+ {
+ $splitRequest = new CreateSplitRequest();
+
+ $splitRequest->type = 'flat';
+ $splitRequest->recipientId = $this->getRecipientId();
+ $splitRequest->amount = $this->getCommission();
+
+ $splitRequest->options = new CreateSplitOptionsRequest();
+
+ $splitRequest->options->chargeProcessingFee = $this->getSecondaryChargeProcessingFeeOptionConfig();
+ $splitRequest->options->liable = $this->getSecondaryLiableOptionConfig();
+ $splitRequest->options->chargeRemainderFee = false;
+
+ return $splitRequest;
+ }
+ #[\ReturnTypeWillChange]
+ public function jsonSerialize()
+ {
+ $obj = new \stdClass();
+
+ $obj->sellersData = $this->getSellersData();
+ $obj->marketplaceData = $this->getMarketplaceData();
+
+ return $obj;
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Marketplace/Factories/RecipientFactory.php b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Factories/RecipientFactory.php
new file mode 100644
index 00000000..bae4e0ce
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Factories/RecipientFactory.php
@@ -0,0 +1,272 @@
+recipient = new Recipient();
+ }
+
+ public function createFromPostData($postData)
+ {
+ if (!is_array($postData)) {
+ return;
+ }
+
+ $this->setId($postData);
+ $this->setRecipientId($postData);
+ $this->setExternalId($postData);
+ $this->setName($postData);
+ $this->setEmail($postData);
+ $this->setDocumentType($postData);
+ $this->setDocument($postData);
+ $this->setType($postData, self::TYPE_BY_DOCUMENT);
+ $this->setHolderName($postData);
+ $this->setHolderDocument($postData);
+ $this->setHolderType($postData);
+ $this->setBank($postData);
+ $this->setBranchNumber($postData);
+ $this->setBranchCheckDigit($postData);
+ $this->setAccountNumber($postData);
+ $this->setAccountCheckDigit($postData);
+ $this->setAccountType($postData);
+ $this->setTransferEnabled($postData);
+ $this->setTransferInterval($postData);
+ $this->setTransferDay($postData);
+
+ return $this->recipient;
+ }
+
+ public function createFromDbData($dbData)
+ {
+ if (!is_array($dbData)) {
+ return;
+ }
+
+ $this->recipient->setId($dbData['id'])
+ ->setExternalId($dbData['external_id'])
+ ->setName($dbData['name'])
+ ->setEmail($dbData['email'])
+ ->setDocumentType($dbData['document_type'])
+ ->setDocument($dbData['document'])
+ ->setType($dbData['document_type'] == 'cpf' ? 'individual' : 'company')
+ ->setPagarmeId(new RecipientId($dbData['pagarme_id']));
+
+ if (self::TYPE_BY_DOCUMENT) {
+ $this->recipient->setType($this->getTypeByDocument($this->recipient->getDocument()));
+ }
+
+ $this->setCreatedAt($dbData);
+ $this->setUpdatedAt($dbData);
+
+
+ return $this->recipient;
+ }
+
+ private function getTypeByDocument($document)
+ {
+ if ($document) {
+ $document = preg_replace("/[^0-9]/", "", $document ?? '');
+ return strlen($document) > 11 ? 'company' : 'individual';
+ }
+ }
+
+ private function setId($postData)
+ {
+ if (array_key_exists('id', $postData)) {
+ $this->recipient->setId($postData['id']);
+ return;
+ }
+ }
+
+ private function setExternalId($postData)
+ {
+ if (array_key_exists('external_id', $postData)) {
+ $this->recipient->setExternalId($postData['external_id']);
+ return;
+ }
+ }
+
+ private function setName($postData)
+ {
+ if (array_key_exists('name', $postData)) {
+ $this->recipient->setName($postData['name']);
+ return;
+ }
+ }
+
+ private function setEmail($postData)
+ {
+ if (array_key_exists('email', $postData)) {
+ $this->recipient->setEmail($postData['email']);
+ return;
+ }
+ }
+
+ private function setDocumentType($postData)
+ {
+ if (array_key_exists('document_type', $postData)) {
+ $this->recipient->setDocumentType($postData['document_type']);
+ }
+ return;
+ }
+
+ private function setDocument($postData)
+ {
+ if (array_key_exists('document', $postData)) {
+ $this->recipient->setDocument($postData['document']);
+ return;
+ }
+ }
+
+ private function setType($postData , $byDocument = false)
+ {
+ if (array_key_exists('type', $postData)) {
+ $this->recipient->setType($postData['type']);
+ }
+ if ($byDocument && array_key_exists('document', $postData)) {
+ $this->recipient->setType($this->getTypeByDocument($postData['document']));
+ }
+ return;
+ }
+
+ private function setHolderName($postData)
+ {
+ if (array_key_exists('holder_name', $postData)) {
+ $this->recipient->setHolderName($postData['holder_name']);
+ return;
+ }
+ }
+
+ private function setHolderDocument($postData)
+ {
+ if (array_key_exists('holder_document', $postData)) {
+ $this->recipient->setHolderDocument($postData['holder_document']);
+ return;
+ }
+ }
+
+ private function setHolderType($postData)
+ {
+ if (array_key_exists('holder_type', $postData)) {
+ $this->recipient->setHolderType($postData['holder_type']);
+ return;
+ }
+ }
+
+ private function setBank($postData)
+ {
+ if (array_key_exists('bank', $postData)) {
+ $this->recipient->setBank($postData['bank']);
+ return;
+ }
+ }
+
+ private function setBranchNumber($postData)
+ {
+ if (array_key_exists('branch_number', $postData)) {
+ $this->recipient->setBranchNumber($postData['branch_number']);
+ return;
+ }
+ }
+
+ private function setBranchCheckDigit($postData)
+ {
+ if (array_key_exists('branch_check_digit', $postData)) {
+ $this->recipient->setBranchCheckDigit($postData['branch_check_digit']);
+ return;
+ }
+ }
+
+ private function setAccountNumber($postData)
+ {
+ if (array_key_exists('account_number', $postData)) {
+ $this->recipient->setAccountNumber($postData['account_number']);
+ return;
+ }
+ }
+
+ private function setAccountCheckDigit($postData)
+ {
+ if (array_key_exists('account_check_digit', $postData)) {
+ $this->recipient->setAccountCheckDigit($postData['account_check_digit']);
+ return;
+ }
+ }
+
+ private function setAccountType($postData)
+ {
+ if (array_key_exists('account_type', $postData)) {
+ $this->recipient->setAccountType($postData['account_type']);
+ return;
+ }
+ }
+
+ private function setTransferEnabled($postData)
+ {
+ if (array_key_exists('transfer_enabled', $postData)) {
+ $this->recipient->setTransferEnabled($postData['transfer_enabled']);
+ return;
+ }
+ }
+
+ private function setTransferInterval($postData)
+ {
+ if (array_key_exists('transfer_interval', $postData)) {
+ $this->recipient->setTransferInterval($postData['transfer_interval']);
+ return;
+ }
+ }
+
+ private function setTransferDay($postData)
+ {
+ if (array_key_exists('transfer_day', $postData)) {
+ $this->recipient->setTransferDay($postData['transfer_day']);
+ return;
+ }
+ }
+
+ private function setRecipientId($postData)
+ {
+ if (array_key_exists('recipient_id', $postData)) {
+ $this->recipient->setPagarmeId(new RecipientId($postData['recipient_id']));
+ return;
+ }
+ }
+
+ private function setUpdatedAt($postData)
+ {
+ if (isset($postData['updated_at'])) {
+ $this->recipient->setUpdatedAt(
+ new \Datetime($postData['updated_at'])
+ );
+ return;
+ }
+ }
+
+ private function setCreatedAt($postData)
+ {
+ if (isset($postData['created_at'])) {
+ $this->recipient->setCreatedAt(
+ new \Datetime($postData['created_at'])
+ );
+ return;
+ }
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Marketplace/Interfaces/RecipientInterface.php b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Interfaces/RecipientInterface.php
new file mode 100644
index 00000000..42bff96e
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Interfaces/RecipientInterface.php
@@ -0,0 +1,83 @@
+db->getTable(
+ AbstractDatabaseDecorator::TABLE_RECIPIENTS
+ );
+
+ $query = "
+ INSERT INTO $table (
+ `external_id`,
+ `name`,
+ `email`,
+ `document_type`,
+ `document`,
+ `pagarme_id`
+ ) VALUES (
+ '{$object->getExternalId()}',
+ '{$object->getName()}',
+ '{$object->getEmail()}',
+ '{$object->getDocumentType()}',
+ '{$object->getDocument()}',
+ '{$object->getPagarmeId()->getValue()}'
+ )
+ ";
+
+ $this->db->query($query);
+ }
+
+ protected function update(AbstractEntity &$object)
+ {
+ $table = $this->db->getTable(
+ AbstractDatabaseDecorator::TABLE_RECIPIENTS
+ );
+
+ $query = "
+ UPDATE $table SET
+ `external_id`='{$object->getExternalId()}',
+ `name`='{$object->getName()}',
+ `email`='{$object->getEmail()}',
+ `pagarme_id`='{$object->getPagarmeId()->getValue()}'
+ WHERE `id`='{$object->getId()}'
+ ";
+
+ $this->db->query($query);
+ }
+
+ public function delete(AbstractEntity $object)
+ {
+ $table = $this->db->getTable(
+ AbstractDatabaseDecorator::TABLE_RECIPIENTS
+ );
+
+ $query = "DELETE FROM $table WHERE id = {$object->getId()}";
+
+ return $this->db->query($query);
+ }
+
+ public function find($objectId)
+ {
+ $table = $this->db->getTable(
+ AbstractDatabaseDecorator::TABLE_RECIPIENTS
+ );
+
+ $query = "SELECT * FROM $table WHERE id = $objectId";
+
+ $result = $this->db->fetch($query);
+
+ if ($result->num_rows === 0) {
+ return null;
+ }
+
+ $recipientFactory = new RecipientFactory();
+
+ return $recipientFactory->createFromDbData($result->row);
+ }
+
+ public function findByPagarmeId(AbstractValidString $pagarmeId)
+ {
+ $table = $this->db->getTable(
+ AbstractDatabaseDecorator::TABLE_RECIPIENTS
+ );
+
+ $query = "SELECT * FROM {$table} WHERE pagarme_id = {$pagarmeId}";
+
+ $result = $this->db->fetch($query);
+
+ if ($result->num_rows === 0) {
+ return null;
+ }
+
+ $recipientFactory = new RecipientFactory();
+
+ return $recipientFactory->createFromDbData($result->row);
+ }
+
+ /**
+ * @param Recipient $recipient
+ * @param GetBankAccountResponse $bankAccount
+ * @return Recipient
+ * @throws InvalidParamException
+ */
+ public function attachBankAccount(Recipient $recipient, GetBankAccountResponse $bankAccount): Recipient
+ {
+ try {
+ $recipient->setHolderName($bankAccount->holderName);
+ $recipient->setHolderType($bankAccount->holderType);
+ $recipient->setHolderDocument($recipient->getDocument());
+ $recipient->setBank($bankAccount->bank);
+ $recipient->setBranchNumber($bankAccount->branchNumber);
+ $recipient->setBranchCheckDigit($bankAccount->branchCheckDigit);
+ $recipient->setAccountNumber($bankAccount->accountNumber);
+ $recipient->setAccountCheckDigit($bankAccount->accountCheckDigit);
+ $recipient->setAccountType($bankAccount->type);
+ } catch (InvalidParamException $e) {
+ }
+
+ return $recipient;
+ }
+
+ public function attachTransferSettings(Recipient $recipient, GetTransferSettingsResponse $transferSettings): Recipient
+ {
+ $recipient->setTransferEnabled($transferSettings->transferEnabled);
+ $recipient->setTransferDay($transferSettings->transferDay);
+ $recipient->setTransferInterval($transferSettings->transferInterval);
+ return $recipient;
+ }
+
+ public function attachDocumentFromDb(Recipient $recipient)
+ {
+ $recipientFromDb = $this->find($recipient->getId());
+ $recipient->setDocument($recipientFromDb->getDocument());
+
+ return $recipient;
+ }
+
+ public function listEntities($limit, $listDisabled)
+ {
+ // TODO: Implement listEntities() method.
+ }
+
+ public function findBySellerId($sellerId)
+ {
+ $table = $this->db->getTable(
+ AbstractDatabaseDecorator::TABLE_RECIPIENTS
+ );
+
+ $query = "SELECT * FROM `$table` as t ";
+ $query .= "WHERE t.external_id = '$sellerId';";
+
+ $result = $this->db->fetch($query);
+
+ if ($result->num_rows === 0) {
+ return [];
+ }
+
+ return $result->row;
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Marketplace/Services/RecipientService.php b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Services/RecipientService.php
new file mode 100644
index 00000000..583a1ba9
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/src/Marketplace/Services/RecipientService.php
@@ -0,0 +1,273 @@
+config = AbstractModuleCoreSetup::getModuleConfiguration();
+
+ if ($this->config->getSecretKey() != null) {
+ $secretKey = $this->config->getSecretKey()->getValue();
+ }
+
+ $password = '';
+ Configuration::$basicAuthPassword = '';
+
+ $this->pagarmeCoreApi = new PagarmeCoreApiClient($secretKey, $password);
+ $this->logService = new LogService('RecipientService', true);
+ $this->recipientRepository = new RecipientRepository();
+ $this->recipientFactory = new RecipientFactory();
+ $this->i18n = new LocalizationService();
+ }
+
+ public function saveFormRecipient($formData)
+ {
+ $recipientFactory = $this->recipientFactory;
+
+ $recipient = $recipientFactory->createFromPostData($formData);
+
+ $recipientId = $recipient->getPagarmeId();
+
+ if (!$recipientId && empty($formData['existing_recipient'])) {
+ $result = $this->createRecipientAtPagarme($recipient);
+ $recipientId = $result->id;
+ }
+
+ $recipient->setPagarmeId(new RecipientId($recipientId));
+
+ return $this->saveRecipient($recipient);
+ }
+
+ public function createRecipientAtPagarme(Recipient $recipient)
+ {
+ $createRecipientRequest = $recipient->convertToSdkRequest();
+ $recipientController = $this->pagarmeCoreApi->getRecipients();
+
+ try {
+ $logService = $this->logService;
+ $logService->info(
+ 'Create recipient request: ' .
+ json_encode($createRecipientRequest, JSON_PRETTY_PRINT)
+ );
+
+ $result = $recipientController->createRecipient(
+ $createRecipientRequest
+ );
+
+ $logService->info(
+ 'Create recipient response: ' .
+ json_encode($result, JSON_PRETTY_PRINT)
+ );
+
+ return $result;
+ } catch (\Exception $exception) {
+ $logService->exception($exception);
+ throw new \Exception(__("Can't create recipient. Please review the information and try again."));
+ }
+ }
+
+ public function updateRecipientAtPagarme(Recipient $recipient)
+ {
+ $recipient = $this->recipientRepository->attachDocumentFromDb($recipient);
+
+ /**
+ * @var UpdateRecipientRequest $updateRecipientRequest
+ * @var UpdateTransferSettingsRequest $updateTransferSettingsRequest
+ * @var UpdateRecipientBankAccountRequest $updateBankAccountRequest
+ */
+ list($updateRecipientRequest, $updateBankAccountRequest, $updateTransferSettingsRequest) = $recipient->convertToSdkRequest(true);
+ $recipientController = $this->pagarmeCoreApi->getRecipients();
+
+ $recipientPrevious = $this->attachBankAccount($recipient);
+
+ try {
+ $logService = $this->logService;
+ //Update Recipient
+ $logService->info(
+ 'Update recipient request: ' .
+ json_encode($updateRecipientRequest, JSON_PRETTY_PRINT)
+ );
+
+ $result = $recipientController->updateRecipient(
+ $recipient->getPagarmeId(),
+ $updateRecipientRequest
+ );
+
+ $logService->info(
+ 'Update recipient response: ' .
+ json_encode($result, JSON_PRETTY_PRINT)
+ );
+
+ //Update Default Bank Account
+ if (!$recipientPrevious->bankAccountEquals($updateBankAccountRequest)) {
+ $logService->info(
+ 'Update bank account request: ' .
+ json_encode($updateBankAccountRequest, JSON_PRETTY_PRINT)
+ );
+
+ $result = $recipientController->updateRecipientDefaultBankAccount(
+ $recipient->getPagarmeId(),
+ $updateBankAccountRequest
+ );
+
+ $logService->info(
+ 'Update bank account response: ' .
+ json_encode($result, JSON_PRETTY_PRINT)
+ );
+ }
+
+ //Update Transfer Settings
+ $logService->info(
+ 'Update transfer settings request: ' .
+ json_encode($updateBankAccountRequest, JSON_PRETTY_PRINT)
+ );
+
+ $result = $recipientController->updateRecipientTransferSettings(
+ $recipient->getPagarmeId(),
+ $updateTransferSettingsRequest
+ );
+
+ $logService->info(
+ 'Update transfer settings response: ' .
+ json_encode($result, JSON_PRETTY_PRINT)
+ );
+
+ return $result;
+ } catch (\Exception $exception) {
+ $logService->exception($exception);
+ throw new \Exception(__("Can't update recipient. Please review the information and try again."));
+ }
+ }
+
+ public function saveRecipient(Recipient $recipient)
+ {
+ $action = !!$recipient->getId() ? ['Editing a', 'edited'] : ['Creating new', 'created'];
+ $this->logService->info("{$action[0]} recipient at platform");
+ $this->recipientRepository->save($recipient);
+ $this->logService->info("Recipient {$action[1]}: " . $recipient->getId());
+
+ return $recipient;
+ }
+
+ /**
+ * @param $sellerId
+ * @throws CouldNotSaveException
+ */
+ public function findRecipient($sellerId)
+ {
+ $recipient = $this->recipientRepository->findBySellerId($sellerId);
+
+ if (empty($recipient)) {
+ $this->logService->info(
+ __("The seller does not have a registered recipient.")
+ );
+
+ $message = $this->i18n->getDashboard(
+ "Payment could not be made. " .
+ "Please contact the store administrator."
+ );
+
+ throw new \Exception($message);
+ }
+
+ return $recipient;
+ }
+
+ public function findById(int $recipientId)
+ {
+ return $this->recipientRepository->find($recipientId);
+ }
+
+ public function attachBankAccount(Recipient $recipient)
+ {
+ try {
+ $bankAccount = $this->pagarmeCoreApi->getRecipients()->getRecipient($recipient->getPagarmeId())->defaultBankAccount;
+ } catch (APIException $e) {
+ throw $e;
+ }
+ return $this->recipientRepository->attachBankAccount($recipient, $bankAccount);
+ }
+
+ public function attachTransferSettings(Recipient $recipient)
+ {
+ try {
+ $transferSettings = $this->pagarmeCoreApi->getRecipients()->getRecipient($recipient->getPagarmeId())->transferSettings;
+ } catch (APIException $e) {
+ throw $e;
+ }
+ return $this->recipientRepository->attachTransferSettings($recipient, $transferSettings);
+ }
+
+ public function findByPagarmeId($pagarmeId)
+ {
+ $recipientController = $this->pagarmeCoreApi->getRecipients();
+ try {
+ $logService = $this->logService;
+ return $recipientController->getRecipient($pagarmeId);
+ } catch (APIException $e) {
+ $logService->exception($e);
+ throw new \Exception(__("Can't get recipient. Please review the information and try again."));
+ }
+ }
+
+ public function delete($id)
+ {
+ $recipient = $this->recipientRepository->find($id);
+
+ if (empty($recipient)) {
+ throw new \Exception("Recipient not found - ID : {$id} ");
+ }
+
+ return $this->recipientRepository->delete($recipient);
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Account.php b/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Account.php
index 34cb55aa..b4f61292 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Account.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Account.php
@@ -248,11 +248,11 @@ public function validate($storeSettings = null)
$this->validateMultiPayments();
if ($storeSettings) {
- $this->setError($this->getCreditCardSettings()->validate($storeSettings));
- $this->setError($this->getBilletSettings()->validate($storeSettings));
- $this->setError($this->getPixSettings()->validate($storeSettings));
- $this->setError($this->getVoucherSettings()->validate($storeSettings));
- $this->setError($this->getDebitCardSettings()->validate($storeSettings));
+ $this->addError($this->getCreditCardSettings()->validate($storeSettings));
+ $this->addError($this->getBilletSettings()->validate($storeSettings));
+ $this->addError($this->getPixSettings()->validate($storeSettings));
+ $this->addError($this->getVoucherSettings()->validate($storeSettings));
+ $this->addError($this->getDebitCardSettings()->validate($storeSettings));
}
return $this;
@@ -261,7 +261,7 @@ public function validate($storeSettings = null)
private function validateAccountEnabled()
{
if (!$this->isAccountEnabled()) {
- $this->setError(self::ACCOUNT_DISABLED);
+ $this->addError(self::ACCOUNT_DISABLED);
}
}
@@ -273,7 +273,7 @@ private function validateDomain($storeSettings = null)
{
$domains = $this->getDomains();
if (empty($domains) && (empty($storeSettings) || !$storeSettings->isSandbox())) {
- $this->setError(self::DOMAIN_EMPTY);
+ $this->addError(self::DOMAIN_EMPTY);
return;
}
@@ -290,7 +290,7 @@ private function validateDomain($storeSettings = null)
}
}
- $this->setError(self::DOMAIN_INCORRECT);
+ $this->addError(self::DOMAIN_INCORRECT);
}
/**
@@ -315,7 +315,7 @@ private function validateWebhooks($storeSettings = null)
}
}
- $this->setError(self::WEBHOOK_INCORRECT);
+ $this->addError(self::WEBHOOK_INCORRECT);
}
private function validateMultiBuyer()
@@ -346,7 +346,7 @@ private function validateEnabledSetting($setting, $error)
{
$methodName = "is{$setting}Enabled";
if (!$this->$methodName()) {
- $this->setError($error);
+ $this->addError($error);
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Card.php b/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Card.php
index 160a3455..3d075230 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Card.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Card.php
@@ -28,7 +28,7 @@ public function setCardId($cardId)
{
$this->cardId = $cardId;
}
-
+
public function getCardId()
{
return $this->cardId;
@@ -36,7 +36,7 @@ public function getCardId()
public function isValid()
{
- if (empty($token)) {
+ if (empty($this->getToken())) {
return new InvalidArgumentException("Token not valid");
}
return true;
diff --git a/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Customer/Phones.php b/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Customer/Phones.php
index 74e03832..239ec605 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Customer/Phones.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Middle/Model/Customer/Phones.php
@@ -2,11 +2,11 @@
namespace Pagarme\Core\Middle\Model\Customer;
-use Pagarme\Core\Middle\Interfaces\ConvertToLegacyInterface;
-use Pagarme\Core\Payment\ValueObjects\CustomerPhones;
use Pagarme\Core\Payment\ValueObjects\Phone;
-use PagarmeCoreApiLib\Models\CreatePhonesRequest;
use PagarmeCoreApiLib\Models\CreatePhoneRequest;
+use PagarmeCoreApiLib\Models\CreatePhonesRequest;
+use Pagarme\Core\Payment\ValueObjects\CustomerPhones;
+use Pagarme\Core\Middle\Interfaces\ConvertToLegacyInterface;
class Phones implements ConvertToLegacyInterface
{
diff --git a/vendor/pagarme/ecommerce-module-core/src/Middle/Model/ModelWithErrors.php b/vendor/pagarme/ecommerce-module-core/src/Middle/Model/ModelWithErrors.php
index bb3c844f..c540f8c0 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Middle/Model/ModelWithErrors.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Middle/Model/ModelWithErrors.php
@@ -30,7 +30,7 @@ public function setErrors(array $errors)
* @param string|null $error
* @return void
*/
- public function setError($error = null)
+ public function addError($error = null)
{
if (empty($error)) {
return;
diff --git a/vendor/pagarme/ecommerce-module-core/src/Middle/Proxy/CustomerProxy.php b/vendor/pagarme/ecommerce-module-core/src/Middle/Proxy/CustomerProxy.php
index 0c061d63..07ca58bd 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Middle/Proxy/CustomerProxy.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Middle/Proxy/CustomerProxy.php
@@ -1,7 +1,7 @@
country = $this->country ?? "BR";
$brazilianZipCodeLength = 8;
if (strtoupper($this->country) === 'BR') {
- $zipCode = sprintf("%0${brazilianZipCodeLength}s", $zipCode);
+ $zipCode = sprintf("%0{$brazilianZipCodeLength}s", $zipCode);
$zipCode = substr($zipCode, 0, $brazilianZipCodeLength);
return $zipCode;
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Customer.php b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Customer.php
index 66c49c43..6fd08da8 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Customer.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Customer.php
@@ -165,18 +165,18 @@ public function getAddress()
/**
* @param Address $address
*/
- public function setAddress(Address $address)
+ public function setAddress(?Address $address)
{
$this->address = $address;
}
/**
- * Specify data which should be serialized to JSON
- * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
- * @return mixed data which can be serialized by json_encode,
- * which is a value of any type other than a resource.
- * @since 5.4.0
- */
+ * Specify data which should be serialized to JSON
+ * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
+ * @return mixed data which can be serialized by json_encode,
+ * which is a value of any type other than a resource.
+ * @since 5.4.0
+ */
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
@@ -209,7 +209,7 @@ public function getTypeValue()
public function getAddressToSDK()
{
if ($this->getAddress() !== null) {
- return $this->getAddress()->convertToSDKRequest();
+ return $this->getAddress()->convertToSDKRequest();
}
return null;
}
@@ -217,7 +217,7 @@ public function getAddressToSDK()
public function getPhonesToSDK()
{
if ($this->getPhones() !== null) {
- return $this->getPhones()->convertToSDKRequest();
+ return $this->getPhones()->convertToSDKRequest();
}
return null;
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Item.php b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Item.php
index 5fac1af6..e10a0914 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Item.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Item.php
@@ -67,8 +67,8 @@ public function getName()
*/
public function setName($name)
{
- if (preg_match('/[^a-zA-Z0-9 ]+/i', $name)) {
- $name = preg_replace('/[^a-zA-Z0-9 ]+/i', '', $name);
+ if (preg_match('/[^a-zA-Z0-9 ]+/i', $name ?? '')) {
+ $name = preg_replace('/[^a-zA-Z0-9 ]+/i', '', $name ?? '');
}
$this->name = $name;
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Order.php b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Order.php
index 810b5fb1..5fba2ce4 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Order.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Order.php
@@ -5,6 +5,7 @@
use PagarmeCoreApiLib\Models\CreateOrderRequest;
use Pagarme\Core\Kernel\Abstractions\AbstractEntity;
use Pagarme\Core\Kernel\Services\LocalizationService;
+use Pagarme\Core\Marketplace\Aggregates\Split;
use Pagarme\Core\Payment\Aggregates\Payments\AbstractPayment;
use Pagarme\Core\Payment\Aggregates\Payments\SavedCreditCardPayment;
use Pagarme\Core\Payment\Interfaces\ConvertibleToSDKRequestsInterface;
@@ -31,6 +32,8 @@ final class Order extends AbstractEntity implements ConvertibleToSDKRequestsInte
/** @var boolean */
private $closed;
+ private $splitData;
+
/** @var boolean */
private $antifraudEnabled;
@@ -99,7 +102,7 @@ public function getPaymentMethod()
*/
public function setPaymentMethod($paymentMethodName)
{
- $replace = str_replace('_', '', $paymentMethodName);
+ $replace = str_replace('_', '', $paymentMethodName ?? '');
$paymentMethodObject = $replace . 'PaymentMethod';
$this->paymentMethod = $this->$paymentMethodObject();
@@ -201,7 +204,7 @@ private function validatePaymentInvariants(AbstractPayment $payment)
private function discoverPaymentMethod(AbstractPayment $payment)
{
$paymentClass = get_class($payment);
- $paymentClass = explode ('\\', $paymentClass);
+ $paymentClass = explode ('\\', $paymentClass ?? '');
$paymentClass = end($paymentClass);
return $paymentClass;
}
@@ -276,13 +279,31 @@ public function setAntifraudEnabled($antifraudEnabled)
}
/**
- * Specify data which should be serialized to JSON
- * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
- * @return mixed data which can be serialized by json_encode,
- * which is a value of any type other than a resource.
- * @since 5.4.0
+
+ * @return Split|null
+ */
+ public function getSplitData()
+ {
+ return $this->splitData;
+ }
+
+ /**
+ * @param Split|null $splitData
+ */
+ public function setSplitData($splitData)
+ {
+ $this->splitData = $splitData;
+ }
+
+ /**
+ * Specify data which should be serialized to JSON
+ * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
+ * @return mixed data which can be serialized by json_encode,
+ * which is a value of any type other than a resource.
+ * @since 5.4.0
*/
#[\ReturnTypeWillChange]
+
public function jsonSerialize()
{
$obj = new \stdClass();
@@ -320,6 +341,10 @@ public function convertToSDKRequest()
$orderRequest->payments[] = $payment->convertToSDKRequest();
}
+ if (!empty($this->getSplitData())){
+ $orderRequest = $this->fixRoundedValuesInCharges($orderRequest);
+ }
+
$orderRequest->items = [];
foreach ($this->getItems() as $item) {
$orderRequest->items[] = $item->convertToSDKRequest();
@@ -333,6 +358,103 @@ public function convertToSDKRequest()
return $orderRequest;
}
+ private function fixRoundedValuesInCharges(&$orderRequest){
+
+ if(count($orderRequest->payments) < 2){
+ return $orderRequest;
+ }
+
+ $firstChargeAmount = $orderRequest->payments[0]->amount;
+ $firstChargePercentageOfTotal = $firstChargeAmount / $this->getAmount();
+
+ if ($firstChargePercentageOfTotal !== 0.5){
+ return $orderRequest;
+ }
+
+ $orderSplitData = $this->getSplitData();
+
+ $wrongValuesPerRecipient = $this->getRecipientWrongValuesMap($orderRequest, $orderSplitData);
+
+ if (!$wrongValuesPerRecipient){
+ return $orderRequest;
+ }
+
+ $orderRequest = $this->fixRoundedValues($wrongValuesPerRecipient, $orderRequest);
+
+ return $orderRequest;
+
+ }
+
+ private function getRecipientWrongValuesMap($orderRequest, $splitData){
+ $map = [];
+
+ $marketplaceId = $splitData->getMainRecipientOptionConfig();
+ $map[$marketplaceId] = $splitData->getMarketplaceComission();
+
+ foreach ($splitData->getSellersData() as $key => $sellerData) {
+ $sellerId = $sellerData['pagarmeId'];
+ $sellerCommission = $sellerData['commission'];
+
+ $map[$sellerId] = $sellerCommission;
+ }
+
+
+ foreach ($orderRequest->payments as $key => $paymentObject) {
+ $paymentSplitDetails = $paymentObject->split;
+
+ foreach ($paymentSplitDetails as $key => $paymentSplitDetailsObject) {
+ $amountPerCharge = $paymentSplitDetailsObject->amount;
+ $chargeRecipientId = $paymentSplitDetailsObject->recipientId;
+
+ $map[$chargeRecipientId] -= $amountPerCharge;
+ }
+ }
+
+ foreach ($map as $recipientId => $wrongValue) {
+ if ($wrongValue !== 0){
+ return $map;
+ }
+ }
+
+ return false;
+ }
+
+ private function fixRoundedValues($wrongValuesMap, &$orderRequest){
+
+ foreach ($wrongValuesMap as $recipientId => $wrongValue) {
+ $payments = $orderRequest->payments;
+
+ foreach ($payments as $key => &$paymentRequest) {
+ $paymentRequestAmount = $paymentRequest->amount;
+ $splitedAmount = 0;
+ $recipientSplitData = null;
+
+ foreach ($paymentRequest->split as $key => &$splitRequest) {
+ $splitedAmount += $splitRequest->amount;
+
+ if($splitRequest->recipientId === $recipientId){
+ $recipientSplitData = $splitRequest;
+ }
+ }
+
+ if ($splitedAmount === $paymentRequestAmount){
+ continue;
+ }
+
+ $amountRemovableFromCharge = $splitedAmount - $paymentRequestAmount;
+
+ $recipientSplitData->amount -= $amountRemovableFromCharge;
+
+ $mustRemoveFromOtherCharges = $wrongValue + $amountRemovableFromCharge;
+
+ if (!$mustRemoveFromOtherCharges){
+ break;
+ }
+ }
+ }
+ return $orderRequest;
+ }
+
private function creditcardPaymentMethod()
{
return PaymentMethod::credit_card();
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Payments/AbstractPayment.php b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Payments/AbstractPayment.php
index 062f7ab0..6fc4de22 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Payments/AbstractPayment.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Payments/AbstractPayment.php
@@ -4,6 +4,8 @@
use PagarmeCoreApiLib\Models\CreatePaymentRequest;
use Pagarme\Core\Kernel\Abstractions\AbstractEntity;
+use Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup as MPSetup;
+use Pagarme\Core\Marketplace\Aggregates\Split;
use Pagarme\Core\Payment\Interfaces\ConvertibleToSDKRequestsInterface;
use Pagarme\Core\Payment\Interfaces\HaveOrderInterface;
use Pagarme\Core\Payment\Traits\WithAmountTrait;
@@ -11,13 +13,16 @@
use Pagarme\Core\Payment\Traits\WithOrderTrait;
abstract class AbstractPayment
- extends AbstractEntity
- implements ConvertibleToSDKRequestsInterface, HaveOrderInterface
+extends AbstractEntity
+implements ConvertibleToSDKRequestsInterface, HaveOrderInterface
{
use WithAmountTrait;
use WithCustomerTrait;
use WithOrderTrait;
+
+ protected $moduleConfig;
+
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
@@ -42,6 +47,7 @@ abstract static public function getBaseCode();
*/
public function convertToSDKRequest()
{
+ $this->moduleConfig = MPSetup::getModuleConfiguration();
$newPayment = new CreatePaymentRequest();
$newPayment->amount = $this->getAmount();
@@ -53,12 +59,62 @@ public function convertToSDKRequest()
$newPayment->customer = $this->getCustomer()->convertToSDKRequest();
}
+ $marketplaceConfig = $this->moduleConfig->getMarketplaceConfig();
+ if ($marketplaceConfig && $marketplaceConfig->isEnabled()) {
+ $newPayment->split = static::getSplitData();
+ $newPayment->split = $this->extractRequestsFromArray(
+ $newPayment->split
+ );
+ }
+
$newPayment->metadata = static::getMetadata();
return $newPayment;
}
abstract protected function convertToPrimitivePaymentRequest();
+ protected function getSplitData()
+ {
+ $splitOrderData = $this->order->getSplitData();
+
+ if (!$splitOrderData) {
+ return null;
+ }
+ $percentageOfPayment = $this->getAmount() / $this->order->getAmount();
+ $splitMainRecipient = new Split();
+
+ $marketplaceCommission = intval(
+ round(
+ $splitOrderData->getMarketplaceComission() * $percentageOfPayment
+ )
+ );
+
+ $splitMainRecipient->setCommission(
+ $marketplaceCommission
+ );
+
+ $splitMainRecipient->setRecipientId($this->moduleConfig->getMarketplaceConfig()->getMainRecipientId());
+ $splitMainRecipientRequest = $splitMainRecipient
+ ->convertMainToSDKRequest();
+
+ foreach ($splitOrderData->getSellersData() as $seller) {
+ $splitRecipient = new Split();
+
+ $sellerCommission = intval(
+ round(
+ $seller['commission'] * $percentageOfPayment
+ )
+ );
+
+ $splitRecipient->setCommission($sellerCommission);
+ $splitRecipient->setRecipientId($seller['pagarmeId']);
+ $splitRecipientRequests[] = $splitRecipient
+ ->convertSecondaryToSDKRequest();
+ }
+
+ return [$splitMainRecipientRequest, $splitRecipientRequests];
+ }
+
protected function getMetadata()
{
return null;
@@ -66,11 +122,35 @@ protected function getMetadata()
private function cammel2SnakeCase($cammelCaseString)
{
- preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $cammelCaseString, $matches);
+ preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $cammelCaseString ?? '', $matches);
$ret = $matches[0];
foreach ($ret as &$match) {
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
+
+ /**
+ * @param array|null $splitArray
+ * @return array|null
+ */
+ private function extractRequestsFromArray($splitArray)
+ {
+ if (empty($splitArray)) {
+ return null;
+ }
+
+ $splitRecipientRequests = $splitArray[1];
+
+ foreach ($splitRecipientRequests as $request) {
+ array_push(
+ $splitArray,
+ $request
+ );
+ }
+
+ unset($splitArray[1]);
+ $splitArray = array_values($splitArray);
+ return $splitArray;
+ }
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Shipping.php b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Shipping.php
index 5947ab27..c0ca66e3 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Shipping.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/Aggregates/Shipping.php
@@ -80,18 +80,18 @@ public function getAddress()
/**
* @param Address $address
*/
- public function setAddress(Address $address)
+ public function setAddress(?Address $address)
{
$this->address = $address;
}
/**
- * Specify data which should be serialized to JSON
- * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
- * @return mixed data which can be serialized by json_encode,
- * which is a value of any type other than a resource.
- * @since 5.4.0
- */
+ * Specify data which should be serialized to JSON
+ * @link https://php.net/manual/en/jsonserializable.jsonserialize.php
+ * @return mixed data which can be serialized by json_encode,
+ * which is a value of any type other than a resource.
+ * @since 5.4.0
+ */
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
@@ -119,7 +119,9 @@ public function convertToSDKRequest()
$shippingRequest->recipientPhone = $this->getRecipientPhone()
->getFullNumber();
- $shippingRequest->address = $this->getAddress()->convertToSDKRequest();
+ if ($this->getAddress() !== null) {
+ $shippingRequest->address = $this->getAddress()->convertToSDKRequest();
+ }
return $shippingRequest;
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/Factories/PaymentFactory.php b/vendor/pagarme/ecommerce-module-core/src/Payment/Factories/PaymentFactory.php
index 2f55b9e1..d90cef2d 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/Factories/PaymentFactory.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/Factories/PaymentFactory.php
@@ -126,7 +126,7 @@ private function createBasePayments(
$payment->setAmount($cardData->amount);
$payment->setInstallments($cardData->installments);
- $payment->setRecurrenceCycle($cardData->recurrenceCycle);
+ $payment->setRecurrenceCycle($cardData->recurrenceCycle ?? null);
//setting amount with interest
if (strcmp($cardDataIndex, \Pagarme\Core\Kernel\ValueObjects\PaymentMethod::VOUCHER)) {
@@ -182,7 +182,7 @@ private function createCustomer($paymentData)
private function getAmountWithInterestForCreditCard(
AbstractCreditCardPayment $payment,
- $config
+ $config
) {
$installmentService = new InstallmentService();
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/Services/CardService.php b/vendor/pagarme/ecommerce-module-core/src/Payment/Services/CardService.php
index b5bfb627..726def5b 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/Services/CardService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/Services/CardService.php
@@ -83,10 +83,8 @@ public function saveCards(Order $order)
) {
$savedCardRepository->save($savedCard);
$this->logService->info(
- $order->getCode(),
"Card '{$savedCard->getPagarmeId()->getValue()}' saved."
);
-
}
}
}
@@ -96,4 +94,4 @@ public function getLogService()
{
return new LogService("Card Service", true);
}
-}
\ No newline at end of file
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/BoletoBank.php b/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/BoletoBank.php
index 5385d811..b3c5b4e6 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/BoletoBank.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/BoletoBank.php
@@ -138,11 +138,11 @@ protected function isEqual($object)
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
- $obj = new \stdClass();
+ $obj = new \stdClass();
- $obj->code = $this->getCode();
- $obj->name = $this->getName();
+ $obj->code = $this->getCode();
+ $obj->name = $this->getName();
- return $obj;
+ return $obj;
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/CardId.php b/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/CardId.php
index f0301335..84388088 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/CardId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/CardId.php
@@ -6,6 +6,6 @@ final class CardId extends AbstractCardIdentifier
{
protected function validateValue($value)
{
- return preg_match('/card_\w{16}$/', $value) === 1;
+ return preg_match('/card_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/CardToken.php b/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/CardToken.php
index cab6b0ae..32cb3ff7 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/CardToken.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/CardToken.php
@@ -6,6 +6,6 @@ final class CardToken extends AbstractCardIdentifier
{
protected function validateValue($value)
{
- return preg_match('/token_\w{16}$/', $value) === 1;
+ return preg_match('/token_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/Phone.php b/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/Phone.php
index c11a5de3..0011fae3 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/Phone.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Payment/ValueObjects/Phone.php
@@ -23,7 +23,7 @@ final class Phone extends AbstractValueObject implements ConvertibleToSDKRequest
*/
public function __construct($phone)
{
- $phone = preg_replace('/(?!\d)./', '', $phone);
+ $phone = preg_replace('/(?!\d)./', '', $phone ?? '');
$phone = sprintf("%05s", $phone);
$this->countryCode = new NumericString(55);
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Plan.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Plan.php
index f3fbbae1..9f199756 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Plan.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Plan.php
@@ -8,8 +8,6 @@
use Pagarme\Core\Kernel\Exceptions\InvalidParamException;
use Pagarme\Core\Recurrence\Interfaces\RecurrenceEntityInterface;
use Pagarme\Core\Recurrence\ValueObjects\IntervalValueObject;
-use Pagarme\Core\Kernel\ValueObjects\NumericString;
-use Pagarme\Core\Recurrence\ValueObjects\PlanId;
use Pagarme\Core\Recurrence\Interfaces\ProductPlanInterface;
final class Plan extends AbstractEntity implements RecurrenceEntityInterface, ProductPlanInterface
@@ -35,6 +33,8 @@ final class Plan extends AbstractEntity implements RecurrenceEntityInterface, Pr
private $items;
private $trialPeriodDays;
+ private $applyDiscountInAllProductCycles;
+
/**
* @return string
*/
@@ -383,6 +383,22 @@ public function setTrialPeriodDays($trialPeriodDays)
$this->trialPeriodDays = $trialPeriodDays;
}
+ /**
+ * @return bool
+ */
+ public function getApplyDiscountInAllProductCycles()
+ {
+ return boolval($this->applyDiscountInAllProductCycles);
+ }
+
+ /**
+ * @param bool $applyDiscountInAllProductCycles
+ */
+ public function setApplyDiscountInAllProductCycles($applyDiscountInAllProductCycles)
+ {
+ $this->applyDiscountInAllProductCycles = $applyDiscountInAllProductCycles;
+ }
+
/**
* Specify data which should be serialized to JSON
* @link https://php.net/manual/en/jsonserializable.jsonserialize.php
@@ -409,6 +425,7 @@ public function jsonSerialize()
$obj->updatedAt = $this->getUpdatedAt();
$obj->trialPeriodDays = $this->getTrialPeriodDays();
$obj->items = $this->getItems();
+ $obj->applyDiscountInAllProductCycles = $this->getApplyDiscountInAllProductCycles();
return $obj;
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/ProductSubscription.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/ProductSubscription.php
index 320bc3d2..98f09631 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/ProductSubscription.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/ProductSubscription.php
@@ -32,6 +32,8 @@ class ProductSubscription extends AbstractEntity implements ProductSubscriptionI
private $createdAt;
/** @var string */
private $updatedAt;
+ /** @var bool */
+ private $applyDiscountInAllProductCycles;
/**
* @return int
@@ -219,6 +221,22 @@ public function setUpdatedAt(\DateTime $updatedAt)
return $this;
}
+ /**
+ * @return bool
+ */
+ public function getApplyDiscountInAllProductCycles()
+ {
+ return boolval($this->applyDiscountInAllProductCycles);
+ }
+
+ /**
+ * @param bool $applyDiscountInAllProductCycles
+ */
+ public function setApplyDiscountInAllProductCycles($applyDiscountInAllProductCycles)
+ {
+ $this->applyDiscountInAllProductCycles = $applyDiscountInAllProductCycles;
+ }
+
/**
* Specify data which should be serialized to JSON
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
@@ -241,6 +259,7 @@ public function jsonSerialize()
$obj->repetitions = $this->getRepetitions();
$obj->createdAt = $this->getCreatedAt();
$obj->updatedAt = $this->getUpdatedAt();
+ $obj->applyDiscountInAllProductCycles = $this->getApplyDiscountInAllProductCycles();
return $obj;
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Repetition.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Repetition.php
index f94cba88..4ad60538 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Repetition.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Repetition.php
@@ -2,7 +2,6 @@
namespace Pagarme\Core\Recurrence\Aggregates;
-use Magento\Framework\Exception\LocalizedException;
use Pagarme\Core\Kernel\Abstractions\AbstractEntity;
use Pagarme\Core\Kernel\Exceptions\InvalidParamException;
use Pagarme\Core\Recurrence\Interfaces\RepetitionInterface;
@@ -10,6 +9,7 @@
class Repetition extends AbstractEntity implements RepetitionInterface
{
const DATE_FORMAT = 'Y-m-d H:i:s';
+ const INTERVAL_DAY = 'day';
const INTERVAL_WEEK = 'week';
const INTERVAL_MONTH = 'month';
const INTERVAL_YEAR = 'year';
@@ -95,7 +95,6 @@ public function setCreatedAt(\DateTime $createdAt)
public function getUpdatedAt()
{
return $this->updatedAt;
- return $this;
}
/**
@@ -176,7 +175,7 @@ public function jsonSerialize()
*/
public function getIntervalType()
{
- return $this->interval;
+ return $this->getInterval();
}
/**
@@ -197,6 +196,7 @@ public function getIntervalTypeLabel()
public function getAvailablesInterval()
{
return [
+ self::INTERVAL_DAY,
self::INTERVAL_WEEK,
self::INTERVAL_MONTH,
self::INTERVAL_YEAR
@@ -209,8 +209,11 @@ public function getAvailablesInterval()
*/
public function checkRepetitionIsCompatible(Repetition $repetitionObject)
{
- if (($this->getInterval() == $repetitionObject->getInterval()) &&
- ($this->getIntervalCount() == $repetitionObject->getIntervalCount())) {
+ if (
+ $this->getInterval() === $repetitionObject->getInterval()
+ && $this->getIntervalCount() === $repetitionObject->getIntervalCount()
+ && $this->getCycles() === $repetitionObject->getCycles()
+ ) {
return true;
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/SubProduct.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/SubProduct.php
index 8051e6a7..7d79127d 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/SubProduct.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/SubProduct.php
@@ -129,8 +129,8 @@ public function getName()
*/
public function setName($name)
{
- if (preg_match('/[^a-zA-Z0-9 ]+/i', $name)) {
- $name = preg_replace('/[^a-zA-Z0-9 ]+/i', '', $name);
+ if (preg_match('/[^a-zA-Z0-9 ]+/i', $name ?? '')) {
+ $name = preg_replace('/[^a-zA-Z0-9 ]+/i', '', $name ?? '');
}
$this->name = substr($name, 0, 256);
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Subscription.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Subscription.php
index 9b68a15d..cefa8aa7 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Subscription.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Aggregates/Subscription.php
@@ -516,7 +516,7 @@ public function applyOrderStatusFromCharges()
$this->setStatus(SubscriptionStatus::$currentStatus());
}
}
-
+
/**
* @param ChargeInterface[] $charges
*/
@@ -635,7 +635,7 @@ private function setCardData(CreateSubscriptionRequest $subscriptionRequest)
}
$card = new CreateCardRequest();
- if ($this->getCustomer()->getAddress() != null) {
+ if ($this->getCustomer()->getAddress() !== null) {
$card->billingAddress = $this->getCustomer()->getAddress()->convertToSDKRequest();
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/PlanFactory.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/PlanFactory.php
index e8d79f47..9626acbc 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/PlanFactory.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/PlanFactory.php
@@ -2,15 +2,10 @@
namespace Pagarme\Core\Recurrence\Factories;
-use Magento\Catalog\Block\Product\Price;
-use Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup as MPSetup;
use Pagarme\Core\Kernel\Interfaces\FactoryInterface;
use Pagarme\Core\Recurrence\Aggregates\Plan;
-use Pagarme\Core\Recurrence\Aggregates\SubProduct;
use Pagarme\Core\Recurrence\ValueObjects\DueValueObject;
-use Pagarme\Core\Recurrence\ValueObjects\IntervalValueObject;
use Pagarme\Core\Recurrence\ValueObjects\PlanId;
-use Pagarme\Core\Recurrence\ValueObjects\PricingSchemeValueObject as PricingScheme;
class PlanFactory implements FactoryInterface
{
@@ -27,7 +22,6 @@ private function setPagarmeId($postData)
{
if (!empty($postData['plan_id'])) {
$this->plan->setPagarmeId(new PlanId($postData['plan_id']));
- return;
}
}
@@ -35,7 +29,6 @@ private function setIntervalType($postData)
{
if (isset($postData['interval_type'])) {
$this->intervalType = $postData['interval_type'];
- return;
}
}
@@ -43,7 +36,6 @@ private function setIntervalCount($postData)
{
if (isset($postData['interval_count'])) {
$this->intervalCount = $postData['interval_count'];
- return;
}
}
@@ -61,7 +53,6 @@ private function setName($postData)
{
if (isset($postData['name'])) {
$this->plan->setName($postData['name']);
- return;
}
}
@@ -69,7 +60,6 @@ private function setDescription($postData)
{
if (isset($postData['description'])) {
$this->plan->setDescription($postData['description']);
- return;
}
}
@@ -82,7 +72,6 @@ private function setCreditCard($postData)
{
if (isset($postData['credit_card']) && is_bool($postData['credit_card'])) {
$this->plan->setCreditCard($postData['credit_card']);
- return;
}
}
@@ -90,7 +79,6 @@ private function setBoleto($postData)
{
if (isset($postData['boleto']) && is_bool($postData['boleto'])) {
$this->plan->setBoleto($postData['boleto']);
- return;
}
}
@@ -98,7 +86,6 @@ private function setAllowInstallments($postData)
{
if (isset($postData['installments']) && is_bool($postData['installments'])) {
$this->plan->setAllowInstallments($postData['installments']);
- return;
}
}
@@ -106,7 +93,6 @@ private function setProductId($postData)
{
if (isset($postData['product_id'])) {
$this->plan->setProductId($postData['product_id']);
- return;
}
}
@@ -114,7 +100,6 @@ private function setUpdatedAt($postData)
{
if (isset($postData['updated_at'])) {
$this->plan->setUpdatedAt(new \Datetime($postData['updated_at']));
- return;
}
}
@@ -122,7 +107,6 @@ private function setCreatedAt($postData)
{
if (isset($postData['created_at'])) {
$this->plan->setCreatedAt(new \Datetime($postData['created_at']));
- return;
}
}
@@ -130,7 +114,6 @@ private function setStatus($postData)
{
if (isset($postData['status'])) {
$this->plan->setStatus($postData['status']);
- return;
}
}
@@ -142,7 +125,6 @@ private function setInterval()
if (isset($intervalType) && isset($intervalCount)) {
$this->plan->setIntervalType($intervalType);
$this->plan->setIntervalCount($intervalCount);
- return;
}
}
@@ -157,7 +139,6 @@ private function setItems($postData)
}
$this->plan->setItems($items);
- return;
}
}
@@ -166,7 +147,16 @@ private function setTrialDays($postData)
if (isset($postData['trial_period_days'])) {
$this->plan->setTrialPeriodDays((int) $postData['trial_period_days']);
}
- return;
+ }
+
+ private function setApplyDiscountInAllProductCycles($postData)
+ {
+ if (
+ isset($postData['apply_discount_in_all_product_cycles'])
+ && is_bool($postData['apply_discount_in_all_product_cycles'])
+ ) {
+ $this->plan->setApplyDiscountInAllProductCycles($postData['apply_discount_in_all_product_cycles']);
+ }
}
/**
@@ -197,6 +187,7 @@ public function createFromPostData($postData)
$this->setInterval();
$this->setItems($postData);
$this->setTrialDays($postData);
+ $this->setApplyDiscountInAllProductCycles($postData);
return $this->plan;
}
@@ -222,6 +213,7 @@ public function createFromDbData($dbData)
$this->setItems($dbData);
$this->setTrialDays($dbData);
+ $this->plan->setApplyDiscountInAllProductCycles(boolval($dbData['apply_discount_in_all_product_cycles'] ?? false));
$this->plan->setCreditCard(boolval($dbData['credit_card']));
$this->plan->setAllowInstallments(boolval($dbData['installments']));
$this->plan->setBoleto(boolval($dbData['boleto']));
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/ProductSubscriptionFactory.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/ProductSubscriptionFactory.php
index cac9ef3a..5f68816d 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/ProductSubscriptionFactory.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/ProductSubscriptionFactory.php
@@ -38,6 +38,7 @@ public function createFromPostData($postData)
$this->setRepetitions($postData);
$this->setUpdatedAt($postData);
$this->setCreatedAt($postData);
+ $this->setApplyDiscountInAllProductCycles($postData);
return $this->productSubscription;
}
@@ -60,7 +61,8 @@ public function createFromDbData($dbData)
->setBoleto(boolval($dbData['boleto']))
->setAllowInstallments(boolval($dbData['allow_installments']))
->setSellAsNormalProduct(boolval($dbData['sell_as_normal_product']))
- ->setBillingType($dbData['billing_type']);
+ ->setBillingType($dbData['billing_type'])
+ ->setApplyDiscountInAllProductCycles($dbData['apply_discount_in_all_product_cycles'] ?? false);
$this->setCreatedAt($dbData);
$this->setUpdatedAt($dbData);
@@ -94,7 +96,6 @@ private function setId($postData)
{
if (!empty($postData['id'])) {
$this->productSubscription->setId($postData['id']);
- return;
}
}
@@ -107,7 +108,6 @@ private function setCreditCard($postData)
{
if (isset($postData['credit_card']) && is_bool($postData['credit_card'])) {
$this->productSubscription->setCreditCard($postData['credit_card']);
- return;
}
}
@@ -115,7 +115,6 @@ private function setBoleto($postData)
{
if (isset($postData['boleto']) && is_bool($postData['boleto'])) {
$this->productSubscription->setBoleto($postData['boleto']);
- return;
}
}
@@ -128,7 +127,6 @@ private function setSellAsNormalProduct($postData)
$this->productSubscription->setSellAsNormalProduct(
$postData['sell_as_normal_product']
);
- return;
}
}
@@ -141,7 +139,6 @@ private function setAllowInstallments($postData)
$this->productSubscription->setAllowInstallments(
$postData['allow_installments']
);
- return;
}
}
@@ -149,7 +146,6 @@ private function setProductId($postData)
{
if (isset($postData['product_id'])) {
$this->productSubscription->setProductId($postData['product_id']);
- return;
}
}
@@ -159,7 +155,6 @@ private function setUpdatedAt($postData)
$this->productSubscription->setUpdatedAt(
new \Datetime($postData['updated_at'])
);
- return;
}
}
@@ -169,7 +164,16 @@ private function setCreatedAt($postData)
$this->productSubscription->setCreatedAt(
new \Datetime($postData['created_at'])
);
- return;
}
}
-}
\ No newline at end of file
+
+ private function setApplyDiscountInAllProductCycles($postData)
+ {
+ if (
+ isset($postData['apply_discount_in_all_product_cycles'])
+ && is_bool($postData['apply_discount_in_all_product_cycles'])
+ ) {
+ $this->productSubscription->setApplyDiscountInAllProductCycles($postData['apply_discount_in_all_product_cycles']);
+ }
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/TreatFactoryChargeDataBase.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/TreatFactoryChargeDataBase.php
index 2944ce37..9ef19f6c 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/TreatFactoryChargeDataBase.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Factories/TreatFactoryChargeDataBase.php
@@ -9,24 +9,24 @@ protected function extractTransactionsFromDbData($dbData)
$transactions = [];
if ($dbData['tran_id'] !== null) {
$tranId = explode(',', $dbData['tran_id']);
- $tranPagarmeId = explode(',', $dbData['tran_pagarme_id']);
- $tranChargeId = explode(',', $dbData['tran_charge_id']);
- $tranAmount = explode(',', $dbData['tran_amount']);
- $tranPaidAmount = explode(',', $dbData['tran_paid_amount']);
- $tranType = explode(',', $dbData['tran_type']);
- $tranStatus = explode(',', $dbData['tran_status']);
- $tranCreatedAt = explode(',', $dbData['tran_created_at']);
+ $tranPagarmeId = explode(',', $dbData['tran_pagarme_id'] ?? '');
+ $tranChargeId = explode(',', $dbData['tran_charge_id'] ?? '');
+ $tranAmount = explode(',', $dbData['tran_amount'] ?? '');
+ $tranPaidAmount = explode(',', $dbData['tran_paid_amount'] ?? '');
+ $tranType = explode(',', $dbData['tran_type'] ?? '');
+ $tranStatus = explode(',', $dbData['tran_status'] ?? '');
+ $tranCreatedAt = explode(',', $dbData['tran_created_at'] ?? '');
- $tranAcquirerNsu = explode(',', $dbData['tran_acquirer_nsu']);
- $tranAcquirerTid = explode(',', $dbData['tran_acquirer_tid']);
+ $tranAcquirerNsu = explode(',', $dbData['tran_acquirer_nsu'] ?? '');
+ $tranAcquirerTid = explode(',', $dbData['tran_acquirer_tid'] ?? '');
$tranAcquirerAuthCode = explode(
',',
- $dbData['tran_acquirer_auth_code']
- );
- $tranAcquirerName = explode(',', $dbData['tran_acquirer_name']);
- $tranAcquirerMessage = explode(',', $dbData['tran_acquirer_message']);
- $tranBoletoUrl = explode(',', $dbData['tran_boleto_url']);
- $tranCardData = explode('---', $dbData['tran_card_data']);
+ $dbData['tran_acquirer_auth_code'] ?? ''
+ );
+ $tranAcquirerName = explode(',', $dbData['tran_acquirer_name'] ?? '');
+ $tranAcquirerMessage = explode(',', $dbData['tran_acquirer_message'] ?? '');
+ $tranBoletoUrl = explode(',', $dbData['tran_boleto_url'] ?? '');
+ $tranCardData = explode('---', $dbData['tran_card_data'] ?? '');
foreach ($tranId as $index => $id) {
$transaction = [
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Repositories/PlanRepository.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Repositories/PlanRepository.php
index 3d49a0e6..b26b0384 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Repositories/PlanRepository.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Repositories/PlanRepository.php
@@ -19,9 +19,9 @@ protected function create(AbstractEntity &$object)
);
$query = "
- INSERT INTO $table
+ INSERT INTO $table
(
- interval_type,
+ interval_type,
interval_count,
name,
description,
@@ -32,9 +32,10 @@ protected function create(AbstractEntity &$object)
boleto,
billing_type,
status,
- trial_period_days
+ trial_period_days,
+ apply_discount_in_all_product_cycles
)
- VALUES
+ VALUES
(
'{$object->getIntervalType()}',
'{$object->getIntervalCount()}',
@@ -47,8 +48,9 @@ protected function create(AbstractEntity &$object)
'{$object->getBoleto()}',
'{$object->getBillingType()}',
'{$object->getStatus()}',
- '{$object->getTrialPeriodDays()}'
- )
+ '{$object->getTrialPeriodDays()}',
+ '{$object->getApplyDiscountInAllProductCycles()}'
+ )
";
$this->db->query($query);
@@ -76,7 +78,8 @@ protected function update(AbstractEntity &$object)
`boleto` = '{$object->getBoleto()}',
`billing_type` = '{$object->getBillingType()}',
`status` = '{$object->getStatus()}',
- `trial_period_days` = '{$object->getTrialPeriodDays()}'
+ `trial_period_days` = '{$object->getTrialPeriodDays()}',
+ `apply_discount_in_all_product_cycles` = '{$object->getApplyDiscountInAllProductCycles()}'
WHERE id = {$object->getId()}
";
@@ -206,4 +209,4 @@ private function genericFind($row)
return $plan;
}
-}
\ No newline at end of file
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Repositories/ProductSubscriptionRepository.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Repositories/ProductSubscriptionRepository.php
index e185b028..c5b53d7a 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Repositories/ProductSubscriptionRepository.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Repositories/ProductSubscriptionRepository.php
@@ -23,14 +23,16 @@ protected function create(AbstractEntity &$object)
`allow_installments`,
`boleto`,
`sell_as_normal_product`,
- `billing_type`
+ `billing_type`,
+ `apply_discount_in_all_product_cycles`
) VALUES (
'{$object->getProductId()}',
'{$object->getCreditCard()}',
'{$object->getAllowInstallments()}',
'{$object->getBoleto()}',
'{$object->getSellAsNormalProduct()}',
- '{$object->getBillingType()}'
+ '{$object->getBillingType()}',
+ '{$object->getApplyDiscountInAllProductCycles()}'
)
";
@@ -48,13 +50,14 @@ protected function update(AbstractEntity &$object)
);
$query = "
- UPDATE $table SET
+ UPDATE $table SET
`product_id` = '{$object->getProductId()}',
`credit_card` = '{$object->getCreditCard()}',
`allow_installments` = '{$object->getAllowInstallments()}',
`boleto` = '{$object->getBoleto()}',
`sell_as_normal_product` = '{$object->getSellAsNormalProduct()}',
- `billing_type` = '{$object->getBillingType()}'
+ `billing_type` = '{$object->getBillingType()}',
+ `apply_discount_in_all_product_cycles` = '{$object->getApplyDiscountInAllProductCycles()}'
WHERE id = {$object->getId()}
";
@@ -126,7 +129,7 @@ public function find($objectId)
public function findByPagarmeId(AbstractValidString $pagarmeId)
{
- return; // TODO: Implement findByPagarmeId() method.
+ // TODO: Implement findByPagarmeId() method.
}
public function listEntities($limit, $listDisabled)
@@ -190,4 +193,4 @@ public function findByProductId($productId)
return $productSubscription;
}
-}
\ No newline at end of file
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/CartRules/CurrentProduct.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/CartRules/CurrentProduct.php
index 038cee5c..bec24601 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/CartRules/CurrentProduct.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/CartRules/CurrentProduct.php
@@ -8,11 +8,31 @@
class CurrentProduct
{
+ /**
+ * @var bool
+ */
protected $isNormalProduct = false;
+
+ /**
+ * @var RepetitionInterface
+ */
protected $repetitionSelected;
+
+ /**
+ * @var ProductSubscriptionInterface
+ */
protected $productSubscriptionSelected;
+
+ /**
+ * @var ProductPlanInterface
+ */
protected $productPlanSelected;
+ /**
+ * @var int
+ */
+ protected $quantity;
+
/**
* @return RepetitionInterface
*/
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/PlanService.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/PlanService.php
index c992e460..759d7656 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/PlanService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/PlanService.php
@@ -16,6 +16,11 @@
class PlanService
{
+ /**
+ * @var PagarmeCoreApiClient
+ */
+ private $pagarmeCoreApiClient;
+
public function __construct()
{
AbstractModuleCoreSetup::bootstrap();
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/RecurrenceService.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/RecurrenceService.php
index a88d809c..fdb334fd 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/RecurrenceService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/RecurrenceService.php
@@ -114,4 +114,21 @@ public function getProductDecorated($id)
return $product;
}
-}
\ No newline at end of file
+
+ public function getGreatestCyclesFromItems($items)
+ {
+ $cycles = 1;
+ foreach ($items ?? [] as $item) {
+ if ($item->getCycles() === null) {
+ $cycles = $item->getCycles();
+ break;
+ }
+
+ if ($cycles < $item->getCycles()) {
+ $cycles = $item->getCycles();
+ }
+ }
+
+ return $cycles;
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/RepetitionService.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/RepetitionService.php
index ba25e740..1cf19e49 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/RepetitionService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/RepetitionService.php
@@ -62,7 +62,7 @@ public function getCycleTitle(Repetition $repetition)
$totalAmount = $numberFormatter->format($totalAmount);
- return $intervalLabel . " - ({$totalAmount})";
+ return $intervalLabel . " - {$totalAmount}";
}
/**
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/SubscriptionService.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/SubscriptionService.php
index 2e330655..208ffd3d 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/SubscriptionService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/Services/SubscriptionService.php
@@ -3,42 +3,36 @@
namespace Pagarme\Core\Recurrence\Services;
use Pagarme\Core\Kernel\Abstractions\AbstractModuleCoreSetup as MPSetup;
-use Pagarme\Core\Kernel\Aggregates\Order;
use Pagarme\Core\Kernel\ValueObjects\PaymentMethod as PaymentMethod;
use Pagarme\Core\Payment\ValueObjects\CardId;
use Pagarme\Core\Payment\ValueObjects\CardToken;
use Pagarme\Core\Payment\ValueObjects\Discounts;
use Pagarme\Core\Recurrence\Aggregates\Increment;
use Pagarme\Core\Recurrence\Aggregates\Plan;
-use Pagarme\Core\Recurrence\Aggregates\ProductSubscription;
use Pagarme\Core\Recurrence\Factories\ChargeFactory;
-use Pagarme\Core\Kernel\Factories\OrderFactory;
use Pagarme\Core\Kernel\Interfaces\PlatformOrderInterface;
use Pagarme\Core\Kernel\Services\APIService;
use Pagarme\Core\Kernel\Services\LocalizationService;
use Pagarme\Core\Kernel\Services\OrderLogService;
use Pagarme\Core\Kernel\Services\OrderService;
-use Pagarme\Core\Kernel\ValueObjects\Id\ChargeId;
use Pagarme\Core\Kernel\ValueObjects\Id\SubscriptionId;
use Pagarme\Core\Kernel\ValueObjects\OrderState;
use Pagarme\Core\Kernel\ValueObjects\OrderStatus;
use Pagarme\Core\Payment\Aggregates\Order as PaymentOrder;
use Pagarme\Core\Payment\Services\ResponseHandlers\ErrorExceptionHandler;
-use Pagarme\Core\Payment\ValueObjects\CustomerType;
use Pagarme\Core\Kernel\Aggregates\Charge;
use Pagarme\Core\Recurrence\Aggregates\Invoice;
use Pagarme\Core\Recurrence\Aggregates\SubProduct;
use Pagarme\Core\Recurrence\Aggregates\Subscription;
use Pagarme\Core\Recurrence\Factories\InvoiceFactory;
-use Pagarme\Core\Recurrence\Factories\SubProductFactory;
use Pagarme\Core\Recurrence\Repositories\SubscriptionRepository;
use Pagarme\Core\Recurrence\ValueObjects\PricingSchemeValueObject as PricingScheme;
use Pagarme\Core\Recurrence\ValueObjects\SubscriptionStatus;
-use Pagarme\Core\Recurrence\Repositories\ChargeRepository;
use Pagarme\Core\Recurrence\Factories\SubscriptionFactory;
final class SubscriptionService
{
+ const CAN_CREATE_PAYMENT_MESSAGE = "Can't create payment. Please review the information and try again.";
private $logService;
/**
* @var LocalizationService
@@ -47,6 +41,8 @@ final class SubscriptionService
private $subscriptionItems;
private $apiService;
+ private $recurrenceService;
+
public function __construct()
{
$this->logService = new OrderLogService();
@@ -81,10 +77,7 @@ public function createSubscriptionAtPagarme(PlatformOrderInterface $platformOrde
$forceCreateOrder = MPSetup::getModuleConfiguration()->isCreateOrderEnabled();
if ($subscriptionResponse === null) {
- $message = $i18n->getDashboard(
- "Can't create payment. " .
- "Please review the information and try again."
- );
+ $message = $i18n->getDashboard(self::CAN_CREATE_PAYMENT_MESSAGE);
throw new \Exception($message, 400);
}
@@ -106,10 +99,7 @@ public function createSubscriptionAtPagarme(PlatformOrderInterface $platformOrde
}
if (!$forceCreateOrder) {
- $message = $i18n->getDashboard(
- "Can't create payment. " .
- "Please review the information and try again."
- );
+ $message = $i18n->getDashboard(self::CAN_CREATE_PAYMENT_MESSAGE);
throw new \Exception($message, 400);
}
}
@@ -128,16 +118,13 @@ public function createSubscriptionAtPagarme(PlatformOrderInterface $platformOrde
$forceCreateOrder &&
!$this->checkResponseStatus($originalSubscriptionResponse)
) {
- $message = $i18n->getDashboard(
- "Can't create payment. " .
- "Please review the information and try again."
- );
+ $message = $i18n->getDashboard(self::CAN_CREATE_PAYMENT_MESSAGE);
throw new \Exception($message, 400);
}
return [$response];
- } catch(\Exception $e) {
+ } catch (\Exception $e) {
$exceptionHandler = new ErrorExceptionHandler();
$paymentOrder = new PaymentOrder;
$paymentOrder->setCode($platformOrder->getcode());
@@ -160,10 +147,60 @@ private function setDiscountCycleSubscription(
return;
}
- $discountSubscription = Discounts::FLAT((($discountOrder * -1) * 100), 1);
+ $cycles = $this->getDiscountCycles($platformOrder, $subscription);
+ $discountSubscription = Discounts::FLAT((($discountOrder * -1) * 100), $cycles);
$subscription->setDiscounts([$discountSubscription]);
}
+ private function getDiscountCycles($platformOrder, $subscription)
+ {
+ $orderService = new OrderService();
+ $order = $orderService->extractPaymentOrderFromPlatformOrder($platformOrder);
+ $subscriptionItems = $this->getSubscriptionItems($order);
+ $cycles = 1;
+
+ if (!empty($subscriptionItems)) {
+ $subscriptionItems = array_filter($subscriptionItems);
+ }
+
+ $changeCycle = true;
+ $planItems = [];
+ foreach ($subscriptionItems as $subscriptionItem) {
+ if ($subscriptionItem instanceof Plan) {
+ $planItems = $subscriptionItem->getItems();
+ }
+ if (empty($subscriptionItem->getApplyDiscountInAllProductCycles())) {
+ $changeCycle = false;
+ break;
+ }
+ }
+
+ $items = $subscription->getItems();
+
+ if (empty($items) && !empty($planItems) && $subscription->getPlanId()) {
+ $items = $planItems;
+ }
+
+ if ($changeCycle) {
+ $validSubscriptionItems = array_filter($items, [$this, 'isValidSubscriptionItem']);
+ $cycles = $this->getRecurrenceService()
+ ->getGreatestCyclesFromItems($validSubscriptionItems);
+ }
+
+ return $cycles;
+ }
+
+ /**
+ * @param mixed $item
+ * @return bool
+ */
+ private function isValidSubscriptionItem($item)
+ {
+ return method_exists($item, 'getSelectedRepetition')
+ && method_exists($item, 'getRecurrenceType')
+ && (!empty($item->getSelectedRepetition() || $item->getRecurrenceType() === Plan::RECURRENCE_TYPE));
+ }
+
private function extractSubscriptionDataFromOrder(PaymentOrder $order)
{
$subscription = new Subscription();
@@ -174,22 +211,20 @@ private function extractSubscriptionDataFromOrder(PaymentOrder $order)
$this->fillCreditCardData($subscription, $order);
$plan = $this->extractPlanFromOrder($order);
- if ($plan == null) {
- $this->fillSubscriptionItems(
- $subscription,
- $order
- );
- $this->fillDescription($subscription);
- }
+ $this->fillSubscriptionItems(
+ $subscription,
+ $order
+ );
+ $this->fillDescription($subscription);
$this->fillPlanId($subscription, $plan);
$this->fillInterval($subscription, $plan);
- if ($order->getPaymentMethod() == PaymentMethod::boleto()) {
+ if ($order->getPaymentMethod() === PaymentMethod::boleto()) {
$this->fillBoletoData($subscription);
}
- if ($order->getShipping() != null) {
+ if ($order->getShipping() !== null) {
$this->fillShipping($subscription, $order);
}
@@ -224,7 +259,7 @@ private function getSubscriptionSettings($order)
{
$items = $this->getSubscriptionItems($order);
- if (empty($items[0]) || count($items) == 0) {
+ if (empty($items[0]) || empty($items)) {
throw new \Exception('Recurrence items not found', 400);
}
@@ -237,13 +272,12 @@ private function getSubscriptionSettings($order)
*/
private function getSubscriptionItems(PaymentOrder $order)
{
- $recurrenceService = new RecurrenceService();
$items = [];
foreach ($order->getItems() as $product) {
if ($product->getType() !== null) {
$items[] =
- $recurrenceService
+ $this->getRecurrenceService()
->getRecurrenceProductByProductId(
$product->getCode()
);
@@ -258,6 +292,9 @@ private function extractSubscriptionItemsFromOrder($order)
$subscriptionItems = [];
foreach ($order->getItems() as $item) {
+ if (method_exists($item, 'getPagarmeId') && $item->getPagarmeId()) {
+ continue;
+ }
$subProduct = new SubProduct();
$cycles = 1;
$selectedOption = $item->getSelectedOption();
@@ -278,19 +315,6 @@ private function extractSubscriptionItemsFromOrder($order)
$pricingScheme = PricingScheme::UNIT($item->getAmount());
$subProduct->setPricingScheme($pricingScheme);
- $increment = new Increment();
-
- $shippingAmount = 0;
- if($order->getShipping() != null) {
- $shippingAmount = $order->getShipping()->getAmount();
- }
-
- $increment->setValue($shippingAmount);
- $increment->setIncrementType('flat');
- $increment->setCycles($cycles);
-
- $subProduct->setIncrement($increment);
-
$subscriptionItems[] = $subProduct;
}
@@ -462,7 +486,7 @@ public function isSubscription($platformOrder)
private function getResponseHandler($response)
{
$responseClass = get_class($response);
- $responseClass = explode('\\', $responseClass);
+ $responseClass = explode('\\', $responseClass ?? '');
$responseClass =
'Pagarme\\Core\\Recurrence\\Services\\ResponseHandlers\\' .
@@ -490,7 +514,8 @@ private function getSubscriptionMissingData(&$subscriptionResponse, $subscriptio
$subscriptionResponse['plan_id'] = $subscription->getPlanIdValue();
- $this->setProductIdOnSubscriptionItems($subscriptionResponse, $subscription); //@todo Remove when be implemented the "code" on mark1
+ //@todo Remove when be implemented the "code" on mark1
+ $this->setProductIdOnSubscriptionItems($subscriptionResponse, $subscription);
}
/**
@@ -657,4 +682,12 @@ public function getSavedSubscription(SubscriptionId $subscriptionId)
$subscriptionRepository = new SubscriptionRepository();
return $subscriptionRepository->findByPagarmeId($subscriptionId);
}
-}
\ No newline at end of file
+
+ private function getRecurrenceService()
+ {
+ if (empty($this->recurrenceService)) {
+ $this->recurrenceService = new RecurrenceService();
+ }
+ return $this->recurrenceService;
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/InvoiceIdValueObject.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/InvoiceIdValueObject.php
index fdf29b45..44d45306 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/InvoiceIdValueObject.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/InvoiceIdValueObject.php
@@ -8,6 +8,6 @@ class InvoiceIdValueObject extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/in_\w{16}$/', $value) === 1;
+ return preg_match('/in_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/PlanId.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/PlanId.php
index 3ab62d53..452fc218 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/PlanId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/PlanId.php
@@ -8,6 +8,6 @@ class PlanId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^plan_\w{16}$/', $value) === 1;
+ return preg_match('/^plan_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/PlanItemId.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/PlanItemId.php
index ae9f4ecd..9d3aa2a0 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/PlanItemId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/PlanItemId.php
@@ -8,6 +8,6 @@ class PlanItemId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^pi_\w{16}$/', $value) === 1;
+ return preg_match('/^pi_\w{16}$/', $value ?? '') === 1;
}
}
\ No newline at end of file
diff --git a/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/SubscriptionItemId.php b/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/SubscriptionItemId.php
index 9710738e..ddcec3ad 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/SubscriptionItemId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Recurrence/ValueObjects/SubscriptionItemId.php
@@ -8,6 +8,6 @@ class SubscriptionItemId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/^si_\w{16}$/', $value) === 1;
+ return preg_match('/^si_\w{16}$/', $value ?? '') === 1;
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Webhook/Aggregates/Webhook.php b/vendor/pagarme/ecommerce-module-core/src/Webhook/Aggregates/Webhook.php
index 7ef3cb65..61ab4c03 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Webhook/Aggregates/Webhook.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Webhook/Aggregates/Webhook.php
@@ -19,6 +19,11 @@ class Webhook extends AbstractEntity
*/
protected $entity;
+ /**
+ * @var string
+ */
+ protected $component;
+
/**
*
* @return WebhookType
diff --git a/vendor/pagarme/ecommerce-module-core/src/Webhook/Services/AbstractHandlerService.php b/vendor/pagarme/ecommerce-module-core/src/Webhook/Services/AbstractHandlerService.php
index aa3e8fd2..987e33a1 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Webhook/Services/AbstractHandlerService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Webhook/Services/AbstractHandlerService.php
@@ -20,7 +20,7 @@ abstract class AbstractHandlerService
public function getActionHandle($action)
{
- $baseActions = explode('_', $action);
+ $baseActions = explode('_', $action ?? '');
$action = '';
foreach ($baseActions as $baseAction) {
$action .= ucfirst($baseAction);
@@ -81,7 +81,7 @@ public function handle(Webhook $webhook)
protected function getValidEntity()
{
$childClassName = substr(strrchr(static::class, "\\"), 1);
- $childEntity = str_replace('HandlerService', '', $childClassName);
+ $childEntity = str_replace('HandlerService', '', $childClassName ?? '');
return strtolower($childEntity);
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Webhook/Services/ChargeRecurrenceService.php b/vendor/pagarme/ecommerce-module-core/src/Webhook/Services/ChargeRecurrenceService.php
index 621b04f1..23ec3040 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Webhook/Services/ChargeRecurrenceService.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Webhook/Services/ChargeRecurrenceService.php
@@ -98,7 +98,9 @@ public function handlePaid(Webhook $webhook)
if ($charge->getPaidAmount() == 0) {
$charge->setPaidAmount($paidAmount);
}
-
+ if ($charge->getSubscriptionId() === null) {
+ $charge->setSubscriptionId($this->order->getSubscriptionId()->getValue());
+ }
$chargeRepository->save($charge);
$this->order->setCurrentCharge($charge);
@@ -271,7 +273,7 @@ protected function handleRefunded(Webhook $webhook)
*/
protected function handleChargedback(Webhook $webhook)
{
-
+
$order = $this->order;
$invoiceService = new InvoiceService();
$subscriptionRepository = new SubscriptionRepository();
@@ -283,7 +285,7 @@ protected function handleChargedback(Webhook $webhook)
$charge = $webhook->getEntity();
$transaction = $charge->getLastTransaction();
-
+
$outdatedCharge = $this->chargeRepository->findByPagarmeId(
$charge->getPagarmeId()
);
@@ -291,26 +293,26 @@ protected function handleChargedback(Webhook $webhook)
if ($outdatedCharge !== null) {
$charge = $outdatedCharge;
}
- /**
+ /**
* @var Charge $outdatedCharge
*/
if ($transaction !== null) {
$outdatedCharge->addTransaction($transaction);
}
-
+
$charge->cancel();
$order->updateCharge($charge);
$order->applyOrderStatusFromCharges();
-
+
$charge->failed();
$invoiceService->setChargedbackStatus($charge);
-
+
$history = $i18n->getDashboard('Subscription canceled');
$order->getPlatformOrder()->addHistoryComment($history);
$subscriptionRepository->save($order);
-
+
return [
"message" => 'Subscription cancel registered',
"code" => 200
@@ -528,14 +530,14 @@ public function prepareHistoryComment(ChargeInterface $charge)
$history .= ". " . $i18n->getDashboard(
"Extra amount paid: %.2f",
$moneyService->centsToFloat($extraValue)
- );
+ );
}
if ($extraValue < 0) {
$history .= ". " . $i18n->getDashboard(
"Remaining amount: %.2f",
$moneyService->centsToFloat(abs($extraValue))
- );
+ );
}
$refundedAmount = $charge->getRefundedAmount();
@@ -570,7 +572,7 @@ public function prepareHistoryComment(ChargeInterface $charge)
$history .= ' ' . $i18n->getDashboard(
'Refunded amount: %.2f',
$amountInCurrency
- );
+ );
$history .= " (" . $i18n->getDashboard('until now') . ")";
diff --git a/vendor/pagarme/ecommerce-module-core/src/Webhook/ValueObjects/WebhookId.php b/vendor/pagarme/ecommerce-module-core/src/Webhook/ValueObjects/WebhookId.php
index cfe9d3ae..b94d04ea 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Webhook/ValueObjects/WebhookId.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Webhook/ValueObjects/WebhookId.php
@@ -8,6 +8,6 @@ class WebhookId extends AbstractValidString
{
protected function validateValue($value)
{
- return preg_match('/hook_\w{16}$/', $value) === 1;
+ return preg_match('/hook_\w{16}$/', $value ?? '') === 1;
}
}
diff --git a/vendor/pagarme/ecommerce-module-core/src/Webhook/ValueObjects/WebhookType.php b/vendor/pagarme/ecommerce-module-core/src/Webhook/ValueObjects/WebhookType.php
index 4d86194d..a9a09d64 100644
--- a/vendor/pagarme/ecommerce-module-core/src/Webhook/ValueObjects/WebhookType.php
+++ b/vendor/pagarme/ecommerce-module-core/src/Webhook/ValueObjects/WebhookType.php
@@ -26,7 +26,7 @@ private function __construct($entityType, $action)
static public function fromPostType($postType)
{
- $data = explode('.', $postType);
+ $data = explode('.', $postType ?? '');
return new self($data[0], $data[1]);
}
diff --git a/vendor/pagarme/ecommerce-module-core/tests/Kernel/ValueObjects/OrderStateTest.php b/vendor/pagarme/ecommerce-module-core/tests/Kernel/ValueObjects/OrderStateTest.php
index 2c3a8d67..a1de0fab 100644
--- a/vendor/pagarme/ecommerce-module-core/tests/Kernel/ValueObjects/OrderStateTest.php
+++ b/vendor/pagarme/ecommerce-module-core/tests/Kernel/ValueObjects/OrderStateTest.php
@@ -56,7 +56,7 @@ public function allOrderStateConstantsDefinedInTheClassShouldBeInstantiable()
foreach ($constants as $const => $state) {
$const = strtolower($const);
- $const = explode('_', $const);
+ $const = explode('_', $const ?? '');
foreach ($const as &$c) {
$c = ucfirst($c);
}
diff --git a/vendor/pagarme/ecommerce-module-core/tests/Kernel/ValueObjects/ValidStringTestTrait.php b/vendor/pagarme/ecommerce-module-core/tests/Kernel/ValueObjects/ValidStringTestTrait.php
index ef6606e3..dab6d520 100644
--- a/vendor/pagarme/ecommerce-module-core/tests/Kernel/ValueObjects/ValidStringTestTrait.php
+++ b/vendor/pagarme/ecommerce-module-core/tests/Kernel/ValueObjects/ValidStringTestTrait.php
@@ -10,7 +10,7 @@ protected function doValidStringTest()
{
$class = self::class;
$class = substr($class, 0, strlen($class) -4);
- $class = str_replace('\\Test\\', '\\', $class);
+ $class = str_replace('\\Test\\', '\\', $class ?? '');
$validStringObject = new $class(self::VALID1);
$this->assertEquals(self::VALID1, $validStringObject->getValue());
diff --git a/vendor/pagarme/ecommerce-module-core/tests/Marketplace/Aggregates/SplitTest.php b/vendor/pagarme/ecommerce-module-core/tests/Marketplace/Aggregates/SplitTest.php
new file mode 100644
index 00000000..660c6f34
--- /dev/null
+++ b/vendor/pagarme/ecommerce-module-core/tests/Marketplace/Aggregates/SplitTest.php
@@ -0,0 +1,53 @@
+split = new Split();
+ }
+
+ public function testSplitObject()
+ {
+ $this->split->setRecipientId(new RecipientId('rp_1234567890123457'));
+ $this->split->setCommission(10);
+
+
+ $this->assertEquals(10, $this->split->getCommission());
+ $this->assertEquals('rp_1234567890123457', $this->split->getRecipientId());
+ }
+
+ public function testSplitShouldBeCreated()
+ {
+ $split = new Split();
+ $this->assertTrue($split !== null);
+ }
+
+ /**
+ * @throws InvalidParamException
+ * @expectedExceptionMessage Commission should be greater or equal to 0! Passed value: -10
+ * @expectedExceptionCode 400
+ */
+ public function testShouldThrowAnExceptionIfCommissionIsInvalid()
+ {
+ $this->expectException(InvalidParamException::class);
+
+ $this->split->setCommission(-10);
+ }
+
+ public function testExpectedAnObjectRecipientIdToSetRecipientId()
+ {
+ $recipientId = Mockery::mock(RecipientId::class);
+ $this->split->setRecipientId($recipientId);
+
+ $this->assertEquals($recipientId, $this->split->getRecipientId());
+ $this->assertInstanceOf(RecipientId::class, $this->split->getRecipientId());
+ }
+}
diff --git a/vendor/pagarme/ecommerce-module-core/tests/Recurrence/Aggregates/SubscriptionTest.php b/vendor/pagarme/ecommerce-module-core/tests/Recurrence/Aggregates/SubscriptionTest.php
index 7a39e8be..835609f4 100644
--- a/vendor/pagarme/ecommerce-module-core/tests/Recurrence/Aggregates/SubscriptionTest.php
+++ b/vendor/pagarme/ecommerce-module-core/tests/Recurrence/Aggregates/SubscriptionTest.php
@@ -201,11 +201,6 @@ public function testShouldReturnACreateSubscriptionRequestObjectWithCardBillingA
$this->subscription->setShipping($shipping);
- $card = new CreateCardRequest();
- $card->billingAddress = $this->subscription->getCustomer()
- ->getAddress()->convertToSDKRequest();
- $this->subscription->card = $card;
-
$sdkObject = $this->subscription->convertToSdkRequest();
$this->assertInstanceOf(CreateSubscriptionRequest::class, $sdkObject);
@@ -225,11 +220,6 @@ public function testShouldReturnACreateSubscriptionRequestObjectWithSavedCardBil
$this->subscription->setShipping($shipping);
- $card = new CreateCardRequest();
- $card->billingAddress = $this->subscription->getCustomer()
- ->getAddress()->convertToSDKRequest();
- $this->subscription->card = $card;
-
$sdkObject = $this->subscription->convertToSdkRequest();
$this->assertInstanceOf(CreateSubscriptionRequest::class, $sdkObject);
diff --git a/vendor/pagarme/ecommerce-module-core/tests/mock/Concrete/Migrate.php b/vendor/pagarme/ecommerce-module-core/tests/mock/Concrete/Migrate.php
index 5322c3cb..b7ae43a4 100644
--- a/vendor/pagarme/ecommerce-module-core/tests/mock/Concrete/Migrate.php
+++ b/vendor/pagarme/ecommerce-module-core/tests/mock/Concrete/Migrate.php
@@ -46,7 +46,7 @@ public function runConfigurationMigration()
$stmt = $this->db->prepare($insert);
$config = json_encode([
- "enabled" => true
+ "enabled" => true
]);
$stmt->bindValue(':data', $config, SQLITE3_TEXT);
diff --git a/vendor/pagarme/ecommerce-module-core/tests/mock/ValidStringMock.php b/vendor/pagarme/ecommerce-module-core/tests/mock/ValidStringMock.php
index dc8eb086..e1057087 100644
--- a/vendor/pagarme/ecommerce-module-core/tests/mock/ValidStringMock.php
+++ b/vendor/pagarme/ecommerce-module-core/tests/mock/ValidStringMock.php
@@ -14,6 +14,6 @@ class ValidStringMock extends AbstractValidString
protected function validateValue($value)
{
- return preg_match(self::VALIDATION_REGEX, $value) === 1;
+ return preg_match(self::VALIDATION_REGEX, $value ?? '') === 1;
}
}
diff --git a/vendor/pagarme/pagarmecoreapi/composer.json b/vendor/pagarme/pagarmecoreapi/composer.json
index 0292916a..89e5fc97 100644
--- a/vendor/pagarme/pagarmecoreapi/composer.json
+++ b/vendor/pagarme/pagarmecoreapi/composer.json
@@ -14,7 +14,7 @@
}
],
"require": {
- "php": ">=5.4.0",
+ "php": ">=7.1",
"ext-curl": "*",
"ext-json": "*",
"ext-mbstring": "*",
@@ -29,4 +29,4 @@
"PagarmeCoreApiLib\\": "src/"
}
}
-}
\ No newline at end of file
+}
diff --git a/vendor/pagarme/pagarmecoreapi/src/Controllers/BaseController.php b/vendor/pagarme/pagarmecoreapi/src/Controllers/BaseController.php
index f991e595..8ba137e5 100644
--- a/vendor/pagarme/pagarmecoreapi/src/Controllers/BaseController.php
+++ b/vendor/pagarme/pagarmecoreapi/src/Controllers/BaseController.php
@@ -24,7 +24,7 @@ class BaseController
* User-agent to be sent with API calls
* @var string
*/
- const USER_AGENT = 'PagarmeCoreApi - PHP 5.7.0';
+ const USER_AGENT = 'PagarmeCoreApi - PHP 5.6.3';
/**
* HttpCallBack instance associated with this controller
diff --git a/vendor/pagarme/pagarmecoreapi/src/Models/GetAccountResponse.php b/vendor/pagarme/pagarmecoreapi/src/Models/GetAccountResponse.php
index a623dd2d..193b0461 100644
--- a/vendor/pagarme/pagarmecoreapi/src/Models/GetAccountResponse.php
+++ b/vendor/pagarme/pagarmecoreapi/src/Models/GetAccountResponse.php
@@ -246,12 +246,42 @@ class GetAccountResponse implements JsonSerializable
*/
public $pixSettings;
-
public function __construct()
{
+ if (30 == func_num_args()) {
+ $this->id = func_get_arg(0);
+ $this->secretKey = func_get_arg(1);
+ $this->publicKey = func_get_arg(2);
+ $this->name = func_get_arg(3);
+ $this->timeZone = func_get_arg(4);
+ $this->defaultCurrency = func_get_arg(5);
+ $this->status = func_get_arg(6);
+ $this->domains = func_get_arg(7);
+ $this->antifraudSettings = func_get_arg(8);
+ $this->mundipaggSettings = func_get_arg(9);
+ $this->pagarmeSettings = func_get_arg(10);
+ $this->creditCardSettings = func_get_arg(11);
+ $this->debitCardSettings = func_get_arg(12);
+ $this->voucherSettings = func_get_arg(13);
+ $this->boletoSettings = func_get_arg(14);
+ $this->bankTransferSettings = func_get_arg(15);
+ $this->walletSettings = func_get_arg(16);
+ $this->safetypaySettings = func_get_arg(17);
+ $this->facebookSettings = func_get_arg(18);
+ $this->generalSettings = func_get_arg(19);
+ $this->webhookSettings = func_get_arg(20);
+ $this->splitSettings = func_get_arg(21);
+ $this->subscriptionSettings = func_get_arg(22);
+ $this->orderSettings = func_get_arg(23);
+ $this->notificationSettings = func_get_arg(24);
+ $this->cancellationSettings = func_get_arg(25);
+ $this->renewCardSettings = func_get_arg(26);
+ $this->cashSettings = func_get_arg(27);
+ $this->checkoutSettings = func_get_arg(28);
+ $this->pixSettings = func_get_arg(29);
+ }
}
-
/**
* Encode this object to JSON
*/
diff --git a/woo-pagarme-payments.php b/woo-pagarme-payments.php
index 64654abe..8246e203 100644
--- a/woo-pagarme-payments.php
+++ b/woo-pagarme-payments.php
@@ -1,7 +1,7 @@
getAllowNoAddress()) {
+ $requiredFields[] = 'billing_address_1';
+ $requiredFields[] = 'billing_number';
+ $requiredFields[] = 'billing_address_2';
+ $requiredFields[] = 'billing_neighborhood';
+ $requiredFields[] = 'billing_country';
+ $requiredFields[] = 'billing_city';
+ $requiredFields[] = 'billing_state';
+ $requiredFields[] = 'billing_postcode';
+ }
$checkoutFields = WC()->countries->get_address_fields(WC()->countries->get_base_country());
foreach ($requiredFields as $field) {
@@ -257,6 +253,20 @@ function wcmpAdminNoticeCheckoutFields()
$message .= '';
$message .= __('Please, make sure to include them for Pagar.me module to work.', 'woo-pagarme-payments');
+ $message .= '
';
+ $message .= sprintf(
+ __('You can install %s or any other plugin of your choice to add the missing fields. %sRead '
+ . 'documentation »%s', 'woo-pagarme-payments'),
+ sprintf(
+ 'Brazilian Market on WooCommerce',
+ BRAZILIAN_MARKET_URL
+ ),
+ sprintf(
+ '',
+ PAGARME_REQUIREMENTS_URL
+ ),
+ ''
+ );
wcmpRenderAdminNoticeHtml($message);
}
@@ -278,7 +288,6 @@ function wcmpLoadInstances()
function wcmpPluginsLoadedCheck()
{
$woocommerce = class_exists('WooCommerce');
- $checkoutFields = class_exists('Extra_Checkout_Fields_For_Brazil');
add_action('in_plugin_update_message-' . WCMP_PLUGIN_BASE, function ($pluginData) {
versionUpdateWarning(WCMP_VERSION, $pluginData['new_version']);
});
@@ -287,10 +296,6 @@ function wcmpPluginsLoadedCheck()
wcmpLoadNotice('AdminNoticeWoocommerce');
}
- if (!$checkoutFields) {
- wcmpLoadNotice('AdminNoticeExtraCheckouts');
- }
-
if ($woocommerce) {
wcmpLoadInstances();
}