diff --git a/.dockerignore b/.dockerignore index b9f3dd9..06a0ac7 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,7 +1,7 @@ -/web/bin/vendor/ -/tmp/ -/tmp/* -/node_modules/ -/.git -/.gitignore -/.github/ +/web/bin/vendor/ +/tmp/ +/tmp/* +/node_modules/ +/.git +/.gitignore +/.github/ diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 4c361ce..439c06f 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,55 +1,55 @@ -# Copilot / AI agent instructions for idae.api - -This file provides concise, repository-specific guidance so an AI coding agent can be immediately productive. - -**Big Picture:** -- **API core:** PHP application under the `web/` folder. Entry points are `web/index.php` and the router in [web/bin/classes/ClassRouter.php](web/bin/classes/ClassRouter.php#L1-L120). Requests under `/api/` are dispatched to the API layer. -- **Routing → API → Query:** Requests go through `Router` → `IdaeApiRest` ([web/bin/engine/Idae/Api/IdaeApiRest.php](web/bin/engine/Idae/Api/IdaeApiRest.php#L1-L220)) → `IdaeQuery` (data layer). The API supports two main endpoints: `/api/idql/[scheme]` (idql JSON payloads) and `/api/*` (generic REST handlers). -- **Data store:** MongoDB via the `mongodb/mongodb` PHP driver (see `web/bin/composer.json`). `IdaeQuery` performs collection operations (find, group, distinct, parallel). -- **Node helpers:** A small Node process for sockets/crons lives under `web/bin/node/` (e.g. `app_https_main.js`). It is started by the project's start scripts. - -**Entrypoints & important files:** -- `web/index.php` — bootstrap for HTTP requests. -- [web/bin/classes/ClassRouter.php](web/bin/classes/ClassRouter.php#L1-L120) — route definitions, shows `/api/idql/[*:scheme]` and `/api/[*:uri_vars]` handlers. -- [web/bin/engine/Idae/Api/IdaeApiRest.php](web/bin/engine/Idae/Api/IdaeApiRest.php#L1-L220) — main API parser/dispatcher and JSON output formats (`raw`, `raw_casted`, `html`). Look here for accepted query shapes and response format. -- `web/conf.inc.php` — environment setup, `include_once('bin/vendor/autoload.php')`, XDebug and HTTP headers; important for running locally. -- `web/bin/composer.json` — PHP dependencies and dev tools (phpunit). -- `web/bin/node/` — Node socket & cron helpers (started by `auto_start.sh` / `auto_start.bat`). - -**Request patterns & examples** -- Idql POST example (route defined in `ClassRouter`): - - POST /api/idql/products - Body (application/json): - { - "method": "find", - "scheme": "products", - "limit": 10, - "page": 0, - "where": {"status": "active"} - } - -- Generic REST example: any method to `/api/<...>` is routed to `IdaeApiRest::doRest()`; query params are read from `$_GET` or JSON body depending on method. - -**Project conventions & gotchas** -- Environment bootstrap expects `$_SERVER['CONF_INC']` or to include `web/conf.inc.php` from entrypoints. When running tests or CLI, ensure `CONF_INC` is set or include the file manually. -- Autoload uses `web/bin/vendor/autoload.php` (run `composer install` in `web/bin`). -- Many internal classes are namespaced under `Idae\\` or live inside `web/bin/engine/Idae` — prefer following existing namespacing and class-factory patterns. -- Query format: `IdaeApiRest` uses a parsed array with keys like `scheme`, `method`, `limit`, `page`, `where`, `proj`, `parallel`. Inspect `IdaeApiRest::doQuery()` for behaviors like `parallel` and `distinct` branches. -- Output modes: `raw` (JSON envelope), `raw_casted` (casts using scheme fields), `html` — code paths depend on `output_method` parsed by `IdaeApiParser`. - -**Developer workflow & commands** -- Install PHP deps: `cd web/bin && composer install` (creates `web/bin/vendor`). -- Run tests: `cd web/bin && ./vendor/bin/phpunit` (or platform-appropriate vendor binary). -- Start node socket (Linux): `./auto_start.sh` uses `forever` to run `web/bin/node/app_https/app_https_main.js`. On Windows run node directly for quick tests: `node web/bin/node/app_https/app_https_main.js`. -- Web server: project is designed to run behind Apache/nginx with document root at `web/`; ensure `web/conf.inc.php` is reachable and `bin/vendor/autoload.php` exists. - -**Where to make changes** -- Add HTTP endpoints: modify `ClassRouter::routes()` to add AltoRouter routes and point to a class#method or a callable. -- Add business logic: implement/extend under `web/bin/engine/Idae` or `web/bin/classes/` following current namespace patterns. - -**What to watch for when editing** -- Avoid changing the request parsing and output conventions unless you update `IdaeApiParser` and `IdaeApiRest` together. -- Many files assume `json_encode(..., JSON_PRETTY_PRINT)` responses and set headers in `IdaeApiRest::json_response()`; keep compatible responses. - -If anything above is unclear or you want more detail about a specific area (database mapping, `IdaeQuery` internals, or Node socket), tell me which part and I will expand or add short code examples. +# Copilot / AI agent instructions for idae.api + +This file provides concise, repository-specific guidance so an AI coding agent can be immediately productive. + +**Big Picture:** +- **API core:** PHP application under the `web/` folder. Entry points are `web/index.php` and the router in [web/bin/classes/ClassRouter.php](web/bin/classes/ClassRouter.php#L1-L120). Requests under `/api/` are dispatched to the API layer. +- **Routing → API → Query:** Requests go through `Router` → `IdaeApiRest` ([web/bin/engine/Idae/Api/IdaeApiRest.php](web/bin/engine/Idae/Api/IdaeApiRest.php#L1-L220)) → `IdaeQuery` (data layer). The API supports two main endpoints: `/api/idql/[scheme]` (idql JSON payloads) and `/api/*` (generic REST handlers). +- **Data store:** MongoDB via the `mongodb/mongodb` PHP driver (see `web/bin/composer.json`). `IdaeQuery` performs collection operations (find, group, distinct, parallel). +- **Node helpers:** A small Node process for sockets/crons lives under `web/bin/node/` (e.g. `app_https_main.js`). It is started by the project's start scripts. + +**Entrypoints & important files:** +- `web/index.php` — bootstrap for HTTP requests. +- [web/bin/classes/ClassRouter.php](web/bin/classes/ClassRouter.php#L1-L120) — route definitions, shows `/api/idql/[*:scheme]` and `/api/[*:uri_vars]` handlers. +- [web/bin/engine/Idae/Api/IdaeApiRest.php](web/bin/engine/Idae/Api/IdaeApiRest.php#L1-L220) — main API parser/dispatcher and JSON output formats (`raw`, `raw_casted`, `html`). Look here for accepted query shapes and response format. +- `web/conf.inc.php` — environment setup, `include_once('bin/vendor/autoload.php')`, XDebug and HTTP headers; important for running locally. +- `web/bin/composer.json` — PHP dependencies and dev tools (phpunit). +- `web/bin/node/` — Node socket & cron helpers (started by `auto_start.sh` / `auto_start.bat`). + +**Request patterns & examples** +- Idql POST example (route defined in `ClassRouter`): + + POST /api/idql/products + Body (application/json): + { + "method": "find", + "scheme": "products", + "limit": 10, + "page": 0, + "where": {"status": "active"} + } + +- Generic REST example: any method to `/api/<...>` is routed to `IdaeApiRest::doRest()`; query params are read from `$_GET` or JSON body depending on method. + +**Project conventions & gotchas** +- Environment bootstrap expects `$_SERVER['CONF_INC']` or to include `web/conf.inc.php` from entrypoints. When running tests or CLI, ensure `CONF_INC` is set or include the file manually. +- Autoload uses `web/bin/vendor/autoload.php` (run `composer install` in `web/bin`). +- Many internal classes are namespaced under `Idae\\` or live inside `web/bin/engine/Idae` — prefer following existing namespacing and class-factory patterns. +- Query format: `IdaeApiRest` uses a parsed array with keys like `scheme`, `method`, `limit`, `page`, `where`, `proj`, `parallel`. Inspect `IdaeApiRest::doQuery()` for behaviors like `parallel` and `distinct` branches. +- Output modes: `raw` (JSON envelope), `raw_casted` (casts using scheme fields), `html` — code paths depend on `output_method` parsed by `IdaeApiParser`. + +**Developer workflow & commands** +- Install PHP deps: `cd web/bin && composer install` (creates `web/bin/vendor`). +- Run tests: `cd web/bin && ./vendor/bin/phpunit` (or platform-appropriate vendor binary). +- Start node socket (Linux): `./auto_start.sh` uses `forever` to run `web/bin/node/app_https/app_https_main.js`. On Windows run node directly for quick tests: `node web/bin/node/app_https/app_https_main.js`. +- Web server: project is designed to run behind Apache/nginx with document root at `web/`; ensure `web/conf.inc.php` is reachable and `bin/vendor/autoload.php` exists. + +**Where to make changes** +- Add HTTP endpoints: modify `ClassRouter::routes()` to add AltoRouter routes and point to a class#method or a callable. +- Add business logic: implement/extend under `web/bin/engine/Idae` or `web/bin/classes/` following current namespace patterns. + +**What to watch for when editing** +- Avoid changing the request parsing and output conventions unless you update `IdaeApiParser` and `IdaeApiRest` together. +- Many files assume `json_encode(..., JSON_PRETTY_PRINT)` responses and set headers in `IdaeApiRest::json_response()`; keep compatible responses. + +If anything above is unclear or you want more detail about a specific area (database mapping, `IdaeQuery` internals, or Node socket), tell me which part and I will expand or add short code examples. diff --git a/.github/hooks/context-mode.json b/.github/hooks/context-mode.json new file mode 100644 index 0000000..ca21b79 --- /dev/null +++ b/.github/hooks/context-mode.json @@ -0,0 +1,13 @@ +{ + "hooks": { + "PreToolUse": [ + { "type": "command", "command": "context-mode hook vscode-copilot pretooluse" } + ], + "PostToolUse": [ + { "type": "command", "command": "context-mode hook vscode-copilot posttooluse" } + ], + "SessionStart": [ + { "type": "command", "command": "context-mode hook vscode-copilot sessionstart" } + ] + } + } \ No newline at end of file diff --git a/.gitignore b/.gitignore index f835844..69ade30 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ -tmp/ -.idea/ -/.idea/workspace.xml -/web/bin/vendor/ +tmp/ +.idea/ +/.idea/workspace.xml +/web/bin/vendor/ node_modules/ \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index b7a5156..f85f1dd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,63 +1,63 @@ -FROM php:7.4-apache - -# Install system deps (include dev libs needed to build PHP extensions) -RUN apt-get update && apt-get install -y --no-install-recommends \ - git \ - unzip \ - curl \ - libzip-dev \ - libicu-dev \ - libxml2-dev \ - libpng-dev \ - libjpeg-dev \ - libfreetype6-dev \ - libwebp-dev \ - libonig-dev \ - libssl-dev \ - libsasl2-dev \ - libkrb5-dev \ - cmake \ - build-essential \ - pkg-config \ - ca-certificates \ - && rm -rf /var/lib/apt/lists/* - -# PHP extensions commonly used by the project -RUN docker-php-ext-configure gd --with-jpeg --with-freetype \ - && docker-php-ext-install -j$(nproc) gd mbstring bcmath xml zip pcntl - -# Install and enable mongodb extension via PECL (try older releases compatible with PHP 7.4) -RUN pecl channel-update pecl.php.net \ - && (pecl install mongodb-1.8.2 || pecl install mongodb-1.10.0 || pecl install mongodb) \ - && docker-php-ext-enable mongodb || true - -# Enable apache modules and set document root to /var/www/html/web -RUN a2enmod rewrite -ENV APACHE_DOCUMENT_ROOT=/var/www/html/web -RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf \ - && sed -ri -e 's!!!g' /etc/apache2/apache2.conf - -# Turn on short_open_tag (project uses short tags ` /usr/local/etc/php/conf.d/short-open-tag.ini - -# Install Composer -RUN curl -sS https://getcomposer.org/installer | php -- --quiet --install-dir=/usr/local/bin --filename=composer - -# Copy app sources -WORKDIR /var/www/html -COPY . /var/www/html - -# Copy entrypoint and make executable -COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh -RUN chmod +x /usr/local/bin/docker-entrypoint.sh - -# Install PHP dependencies inside the container (web/bin composer.json) -WORKDIR /var/www/html/web/bin -RUN composer install --no-interaction --prefer-dist || true - -# Ensure correct permissions -RUN chown -R www-data:www-data /var/www/html && chmod -R 755 /var/www/html - -EXPOSE 80 -ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] -CMD ["apache2-foreground"] +FROM php:7.4-apache + +# Install system deps (include dev libs needed to build PHP extensions) +RUN apt-get update && apt-get install -y --no-install-recommends \ + git \ + unzip \ + curl \ + libzip-dev \ + libicu-dev \ + libxml2-dev \ + libpng-dev \ + libjpeg-dev \ + libfreetype6-dev \ + libwebp-dev \ + libonig-dev \ + libssl-dev \ + libsasl2-dev \ + libkrb5-dev \ + cmake \ + build-essential \ + pkg-config \ + ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +# PHP extensions commonly used by the project +RUN docker-php-ext-configure gd --with-jpeg --with-freetype \ + && docker-php-ext-install -j$(nproc) gd mbstring bcmath xml zip pcntl + +# Install and enable mongodb extension via PECL (try older releases compatible with PHP 7.4) +RUN pecl channel-update pecl.php.net \ + && (pecl install mongodb-1.8.2 || pecl install mongodb-1.10.0 || pecl install mongodb) \ + && docker-php-ext-enable mongodb || true + +# Enable apache modules and set document root to /var/www/html/web +RUN a2enmod rewrite +ENV APACHE_DOCUMENT_ROOT=/var/www/html/web +RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf \ + && sed -ri -e 's!!!g' /etc/apache2/apache2.conf + +# Turn on short_open_tag (project uses short tags ` /usr/local/etc/php/conf.d/short-open-tag.ini + +# Install Composer +RUN curl -sS https://getcomposer.org/installer | php -- --quiet --install-dir=/usr/local/bin --filename=composer + +# Copy app sources +WORKDIR /var/www/html +COPY . /var/www/html + +# Copy entrypoint and make executable +COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh +RUN chmod +x /usr/local/bin/docker-entrypoint.sh + +# Install PHP dependencies inside the container (web/bin composer.json) +WORKDIR /var/www/html/web/bin +RUN composer install --no-interaction --prefer-dist || true + +# Ensure correct permissions +RUN chown -R www-data:www-data /var/www/html && chmod -R 755 /var/www/html + +EXPOSE 80 +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] +CMD ["apache2-foreground"] diff --git a/README.md b/README.md index bcd2128..de13053 100644 --- a/README.md +++ b/README.md @@ -1,258 +1,258 @@ -# idae.api - -This repository contains the idae.api PHP project — a lightweight REST / IDQL API backed by MongoDB, designed to run under the `web/` document root. The codebase is organized around a router → API parser → query layer pattern and includes Docker helper scripts and test infrastructure (PHPUnit + Docker Compose). - -**Quick links** - -- Entrypoint: [web/index.php](web/index.php) -- Router: [web/bin/classes/ClassRouter.php](web/bin/classes/ClassRouter.php) -- API dispatcher: [web/bin/engine/Idae/Api/IdaeApiRest.php](web/bin/engine/Idae/Api/IdaeApiRest.php) -- Query layer: [web/bin/engine/Idae/Query/IdaeQuery.php](web/bin/engine/Idae/Query/IdaeQuery.php) -- Tests: [web/bin/tests](web/bin/tests) -- Docker compose: [docker-compose.yml](docker-compose.yml) - -## Overview - -The API exposes two main types of endpoints: - -- `/api/idql/` — accepts an IDQL JSON payload describing DB operations (find, group, distinct, parallel, etc.). -- `/api/*` — generic REST paths routed to `IdaeApiRest::doRest()`; query params and JSON body are used depending on the HTTP method. - -The project uses MongoDB as the datastore (via the `mongodb/mongodb` library and `ext-mongodb`) and contains a small Node helper process under `web/bin/node` for sockets/crons. - -## Example: IDQL request (curl) - -POST /api/idql/products - -Request body (JSON): - -```json -{ - "method": "find", - "scheme": "products", - "limit": 10, - "page": 0, - "where": {"status": "active"} -} -``` - -Example curl call: - -```bash -curl -X POST \ - -H "Content-Type: application/json" \ - -d '{"method":"find","scheme":"products","limit":10,"where":{"status":"active"}}' \ - http://localhost:8081/api/idql/products -``` - -Response format is JSON and depends on the parser `output_method` (commonly `raw` or `raw_casted`). See `IdaeApiRest` for envelope details. - -## Advanced IDQL example (curl + expected response) - -This example demonstrates using `parallel`, `group` and `distinct` together in an IDQL POST to the `/api/idql/` endpoint. - -1) `parallel` request (two sub-queries: `find` + `distinct`) - -Request (POST /api/idql/dashboard): - -```json -{ - "parallel": [ - {"method":"find","scheme":"users","limit":5,"where":{"active":1},"proj":{"idusers":1,"nomusers":1,"email":1}}, - {"method":"distinct","scheme":"products","distinct":"category","where":{"status":"active"}} - ], - "scheme": "dashboard" -} -``` - -curl: - -```bash -curl -X POST \ - -H "Content-Type: application/json" \ - -d '{"parallel":[{"method":"find","scheme":"users","limit":5,"where":{"active":1}},{"method":"distinct","scheme":"products","distinct":"category","where":{"status":"active"}}],"scheme":"dashboard"}' \ - http://localhost:8081/api/idql/dashboard -``` - -Expected response (raw envelope): - -```json -{ - "rs": { - "0": [ - {"idusers":123,"nomusers":"Dupont","email":"dupont@example.com"}, - {"idusers":124,"nomusers":"Martin","email":"martin@example.com"} - ], - "1": ["electronics","books","home"] - }, - "options": { /* api options echoed */ }, - "query": { /* parsed idql echo */ }, - "record_count": 2 -} -``` - -2) `group` request (aggregation) - -Request (POST /api/idql/orders): - -```json -{ - "method":"group", - "scheme":"orders", - "group":"iddate", - "where": {"status":"completed"}, - "limit": 10 -} -``` - -curl: - -```bash -curl -X POST -H "Content-Type: application/json" -d '{"method":"group","scheme":"orders","group":"iddate","where":{"status":"completed"},"limit":10}' http://localhost:8081/api/idql/orders -``` - -Expected response (excerpt): - -```json -{ - "rs": [ - {"_id":{"month":5,"year":2025},"count":42,"group":[ /* docs */ ]}, - {"_id":{"month":6,"year":2025},"count":37,"group":[ /* docs */ ]} - ], - "options": { }, - "query": { }, - "record_count": 2 -} -``` - -Notes: - -- `parallel` is executed sequentially by `IdaeApiRest::doQuery()` (recursive iteration) and returns an object indexed by position. -- `group` uses the aggregation pipeline in `IdaeQuery::group()` and returns documents of the form `{_id, count, group}`. -- Projected fields may include `id` (e.g. `idusers`) — `IdaeApiRest` adds `id` to the projection when a projection is supplied. - -## Example: Generic REST request (curl) - -Any method to `/api/<...>` is routed into the REST handler. Example GET: - -```bash -curl "http://localhost:8081/api/products?limit=10&status=active"t'as rie -``` - -POST example with body: - -```bash -curl -X POST http://localhost:8081/api/products \ - -H "Content-Type: application/json" \ - -d '{"name":"New product","price":12.5}' -``` - -The REST handler maps the input into `IdaeQuery` calls according to the scheme configuration. - -## Running locally with Docker - -The repo includes a `docker-compose.yml` describing two services: `app` (PHP + Apache) and `mongo` (MongoDB). By default the compose file mounts an init script that creates a test DB and test user for integration tests. - -Start services: - -```bash -docker compose up -d --build -``` - -To use a host-installed MongoDB instead of the included `mongo` service, set the `MDB_HOST` environment variable to `host.docker.internal` (Windows) or your host IP. Example: - -```bash -docker compose up -d --build -docker compose exec app bash -lc "export MDB_HOST=host.docker.internal && composer install" -``` - -There is an override `docker-compose.override.yml` provided to run Mongo with `--noauth` for local development. That override intentionally avoids mounting the init script. - -## Tests (unit + integration) - -Project tests live under `web/bin/tests`. PHPUnit configuration: `web/bin/phpunit.xml`. - -Unit tests run quickly inside the `app` container: - -```bash -docker compose exec app bash -lc "cd /var/www/html/web/bin && ./vendor/bin/phpunit --testsuite unit -c phpunit.xml" -``` - -Integration tests require a Mongo instance reachable from the `app` container. Two options: - -- Use the included `mongo` service and the default init script (creates `idae_test` DB and `idae_test_user`). -- Use a host Mongo and set `MDB_HOST=host.docker.internal`; a fixture loader is provided to insert test data into the target DB. - -Fixture loader (idempotent): `web/bin/tests/fixtures/fixture_loader.php` - -Run it inside the `app` container (example using host-mapped Mongo): - -```bash -docker compose exec app bash -lc "cd /var/www/html/web/bin && MDB_HOST=host.docker.internal MDB_USER=admin MDB_PASS=gwetme2011 php tests/fixtures/fixture_loader.php" -``` - -Then run integration tests: - -```bash -docker compose exec app bash -lc "cd /var/www/html/web/bin && MDB_HOST=host.docker.internal MDB_USER=admin MDB_PASS=gwetme2011 php vendor/phpunit/phpunit/phpunit --testsuite integration -c phpunit.xml" -``` - -Notes: some environments require `ext-mongodb` / libmongoc built with SSL to use SCRAM authentication. For local dev we provide a no-auth override and the fixture loader to keep tests reproducible. - -## Configuration & environment variables - -The application reads its runtime constants from `web/bin/config/constants.php`. Important env vars you may set in Docker or your environment: - -- `MDB_HOST` — Mongo host (default `mongo` in compose). Use `host.docker.internal` to connect to host Mongo from container. -- `MDB_USER`, `MDB_PASSWORD` — Mongo admin/user credentials. -- `MDB_PREFIX` — optional DB prefix used by the app. - -You can provide overrides by exporting environment variables before starting containers or by editing `web/bin/config/env_constants.php` which is included when present. - -## Code pointers and conventions - -- Database access is centralized in `web/bin/engine/Idae/Query/IdaeQuery.php`. -- The connection singleton is implemented in `web/bin/engine/Idae/Connect/IdaeConnect.php`. -- API parsing and routing are in `web/bin/engine/Idae/Api`. -- Templates and view fragments live under `web/bin/templates`. - -If you add new schemes or change the API parsing behavior, follow existing patterns (IdaeApiParser → IdaeApiRest → IdaeQuery) to keep behavior consistent. - -## Contributing & running the dev workflow - -1. Clone repository and open at project root. -2. Build and run containers with Docker Compose. -3. Run `composer install` in the container or locally (project vendors are installed by the build step in Dockerfile by default). -4. Run unit tests, then integration tests with the fixture loader if using a host Mongo. - -Suggested commands (copy/paste): - -```bash -# Build and start -docker compose up -d --build - -# Install dependencies inside container (if needed) -docker compose exec app bash -lc "cd /var/www/html/web/bin && composer install --no-interaction" - -# Load fixtures (host Mongo example) -docker compose exec app bash -lc "cd /var/www/html/web/bin && MDB_HOST=host.docker.internal MDB_USER=admin MDB_PASS=gwetme2011 php tests/fixtures/fixture_loader.php" - -# Run tests -docker compose exec app bash -lc "cd /var/www/html/web/bin && php vendor/phpunit/phpunit/phpunit --testsuite unit -c phpunit.xml" -docker compose exec app bash -lc "cd /var/www/html/web/bin && MDB_HOST=host.docker.internal MDB_USER=admin MDB_PASS=gwetme2011 php vendor/phpunit/phpunit/phpunit --testsuite integration -c phpunit.xml" -``` - -## Troubleshooting - -- If integration tests fail with authentication errors mentioning SCRAM_SHA and libmongoc SSL, the PHP container's Mongo driver has been built without SSL/SASL support. Fix options: - - Use host Mongo (host.docker.internal) and admin creds (quick workaround). - - Rebuild the PHP image ensuring `libssl-dev` and SASL build dependencies are present and `pecl install mongodb` picks up SSL (longer). - -- If containers cannot resolve the `mongo` service name, ensure you run `docker compose` from the repository root and that the network is up (`docker compose up -d`). - -## Next steps and ideas - -- Add a small `Makefile` or Composer script to run `fixture_loader.php` automatically before integration tests. -- Add a GitHub Actions workflow that builds the PHP image, starts services, runs the fixture loader, and executes both test suites. - +# idae.api + +This repository contains the idae.api PHP project — a lightweight REST / IDQL API backed by MongoDB, designed to run under the `web/` document root. The codebase is organized around a router → API parser → query layer pattern and includes Docker helper scripts and test infrastructure (PHPUnit + Docker Compose). + +**Quick links** + +- Entrypoint: [web/index.php](web/index.php) +- Router: [web/bin/classes/ClassRouter.php](web/bin/classes/ClassRouter.php) +- API dispatcher: [web/bin/engine/Idae/Api/IdaeApiRest.php](web/bin/engine/Idae/Api/IdaeApiRest.php) +- Query layer: [web/bin/engine/Idae/Query/IdaeQuery.php](web/bin/engine/Idae/Query/IdaeQuery.php) +- Tests: [web/bin/tests](web/bin/tests) +- Docker compose: [docker-compose.yml](docker-compose.yml) + +## Overview + +The API exposes two main types of endpoints: + +- `/api/idql/` — accepts an IDQL JSON payload describing DB operations (find, group, distinct, parallel, etc.). +- `/api/*` — generic REST paths routed to `IdaeApiRest::doRest()`; query params and JSON body are used depending on the HTTP method. + +The project uses MongoDB as the datastore (via the `mongodb/mongodb` library and `ext-mongodb`) and contains a small Node helper process under `web/bin/node` for sockets/crons. + +## Example: IDQL request (curl) + +POST /api/idql/products + +Request body (JSON): + +```json +{ + "method": "find", + "scheme": "products", + "limit": 10, + "page": 0, + "where": {"status": "active"} +} +``` + +Example curl call: + +```bash +curl -X POST \ + -H "Content-Type: application/json" \ + -d '{"method":"find","scheme":"products","limit":10,"where":{"status":"active"}}' \ + http://localhost:8081/api/idql/products +``` + +Response format is JSON and depends on the parser `output_method` (commonly `raw` or `raw_casted`). See `IdaeApiRest` for envelope details. + +## Advanced IDQL example (curl + expected response) + +This example demonstrates using `parallel`, `group` and `distinct` together in an IDQL POST to the `/api/idql/` endpoint. + +1) `parallel` request (two sub-queries: `find` + `distinct`) + +Request (POST /api/idql/dashboard): + +```json +{ + "parallel": [ + {"method":"find","scheme":"users","limit":5,"where":{"active":1},"proj":{"idusers":1,"nomusers":1,"email":1}}, + {"method":"distinct","scheme":"products","distinct":"category","where":{"status":"active"}} + ], + "scheme": "dashboard" +} +``` + +curl: + +```bash +curl -X POST \ + -H "Content-Type: application/json" \ + -d '{"parallel":[{"method":"find","scheme":"users","limit":5,"where":{"active":1}},{"method":"distinct","scheme":"products","distinct":"category","where":{"status":"active"}}],"scheme":"dashboard"}' \ + http://localhost:8081/api/idql/dashboard +``` + +Expected response (raw envelope): + +```json +{ + "rs": { + "0": [ + {"idusers":123,"nomusers":"Dupont","email":"dupont@example.com"}, + {"idusers":124,"nomusers":"Martin","email":"martin@example.com"} + ], + "1": ["electronics","books","home"] + }, + "options": { /* api options echoed */ }, + "query": { /* parsed idql echo */ }, + "record_count": 2 +} +``` + +2) `group` request (aggregation) + +Request (POST /api/idql/orders): + +```json +{ + "method":"group", + "scheme":"orders", + "group":"iddate", + "where": {"status":"completed"}, + "limit": 10 +} +``` + +curl: + +```bash +curl -X POST -H "Content-Type: application/json" -d '{"method":"group","scheme":"orders","group":"iddate","where":{"status":"completed"},"limit":10}' http://localhost:8081/api/idql/orders +``` + +Expected response (excerpt): + +```json +{ + "rs": [ + {"_id":{"month":5,"year":2025},"count":42,"group":[ /* docs */ ]}, + {"_id":{"month":6,"year":2025},"count":37,"group":[ /* docs */ ]} + ], + "options": { }, + "query": { }, + "record_count": 2 +} +``` + +Notes: + +- `parallel` is executed sequentially by `IdaeApiRest::doQuery()` (recursive iteration) and returns an object indexed by position. +- `group` uses the aggregation pipeline in `IdaeQuery::group()` and returns documents of the form `{_id, count, group}`. +- Projected fields may include `id` (e.g. `idusers`) — `IdaeApiRest` adds `id` to the projection when a projection is supplied. + +## Example: Generic REST request (curl) + +Any method to `/api/<...>` is routed into the REST handler. Example GET: + +```bash +curl "http://localhost:8081/api/products?limit=10&status=active"t'as rie +``` + +POST example with body: + +```bash +curl -X POST http://localhost:8081/api/products \ + -H "Content-Type: application/json" \ + -d '{"name":"New product","price":12.5}' +``` + +The REST handler maps the input into `IdaeQuery` calls according to the scheme configuration. + +## Running locally with Docker + +The repo includes a `docker-compose.yml` describing two services: `app` (PHP + Apache) and `mongo` (MongoDB). By default the compose file mounts an init script that creates a test DB and test user for integration tests. + +Start services: + +```bash +docker compose up -d --build +``` + +To use a host-installed MongoDB instead of the included `mongo` service, set the `MDB_HOST` environment variable to `host.docker.internal` (Windows) or your host IP. Example: + +```bash +docker compose up -d --build +docker compose exec app bash -lc "export MDB_HOST=host.docker.internal && composer install" +``` + +There is an override `docker-compose.override.yml` provided to run Mongo with `--noauth` for local development. That override intentionally avoids mounting the init script. + +## Tests (unit + integration) + +Project tests live under `web/bin/tests`. PHPUnit configuration: `web/bin/phpunit.xml`. + +Unit tests run quickly inside the `app` container: + +```bash +docker compose exec app bash -lc "cd /var/www/html/web/bin && ./vendor/bin/phpunit --testsuite unit -c phpunit.xml" +``` + +Integration tests require a Mongo instance reachable from the `app` container. Two options: + +- Use the included `mongo` service and the default init script (creates `idae_test` DB and `idae_test_user`). +- Use a host Mongo and set `MDB_HOST=host.docker.internal`; a fixture loader is provided to insert test data into the target DB. + +Fixture loader (idempotent): `web/bin/tests/fixtures/fixture_loader.php` + +Run it inside the `app` container (example using host-mapped Mongo): + +```bash +docker compose exec app bash -lc "cd /var/www/html/web/bin && MDB_HOST=host.docker.internal MDB_USER=admin MDB_PASS=gwetme2011 php tests/fixtures/fixture_loader.php" +``` + +Then run integration tests: + +```bash +docker compose exec app bash -lc "cd /var/www/html/web/bin && MDB_HOST=host.docker.internal MDB_USER=admin MDB_PASS=gwetme2011 php vendor/phpunit/phpunit/phpunit --testsuite integration -c phpunit.xml" +``` + +Notes: some environments require `ext-mongodb` / libmongoc built with SSL to use SCRAM authentication. For local dev we provide a no-auth override and the fixture loader to keep tests reproducible. + +## Configuration & environment variables + +The application reads its runtime constants from `web/bin/config/constants.php`. Important env vars you may set in Docker or your environment: + +- `MDB_HOST` — Mongo host (default `mongo` in compose). Use `host.docker.internal` to connect to host Mongo from container. +- `MDB_USER`, `MDB_PASSWORD` — Mongo admin/user credentials. +- `MDB_PREFIX` — optional DB prefix used by the app. + +You can provide overrides by exporting environment variables before starting containers or by editing `web/bin/config/env_constants.php` which is included when present. + +## Code pointers and conventions + +- Database access is centralized in `web/bin/engine/Idae/Query/IdaeQuery.php`. +- The connection singleton is implemented in `web/bin/engine/Idae/Connect/IdaeConnect.php`. +- API parsing and routing are in `web/bin/engine/Idae/Api`. +- Templates and view fragments live under `web/bin/templates`. + +If you add new schemes or change the API parsing behavior, follow existing patterns (IdaeApiParser → IdaeApiRest → IdaeQuery) to keep behavior consistent. + +## Contributing & running the dev workflow + +1. Clone repository and open at project root. +2. Build and run containers with Docker Compose. +3. Run `composer install` in the container or locally (project vendors are installed by the build step in Dockerfile by default). +4. Run unit tests, then integration tests with the fixture loader if using a host Mongo. + +Suggested commands (copy/paste): + +```bash +# Build and start +docker compose up -d --build + +# Install dependencies inside container (if needed) +docker compose exec app bash -lc "cd /var/www/html/web/bin && composer install --no-interaction" + +# Load fixtures (host Mongo example) +docker compose exec app bash -lc "cd /var/www/html/web/bin && MDB_HOST=host.docker.internal MDB_USER=admin MDB_PASS=gwetme2011 php tests/fixtures/fixture_loader.php" + +# Run tests +docker compose exec app bash -lc "cd /var/www/html/web/bin && php vendor/phpunit/phpunit/phpunit --testsuite unit -c phpunit.xml" +docker compose exec app bash -lc "cd /var/www/html/web/bin && MDB_HOST=host.docker.internal MDB_USER=admin MDB_PASS=gwetme2011 php vendor/phpunit/phpunit/phpunit --testsuite integration -c phpunit.xml" +``` + +## Troubleshooting + +- If integration tests fail with authentication errors mentioning SCRAM_SHA and libmongoc SSL, the PHP container's Mongo driver has been built without SSL/SASL support. Fix options: + - Use host Mongo (host.docker.internal) and admin creds (quick workaround). + - Rebuild the PHP image ensuring `libssl-dev` and SASL build dependencies are present and `pecl install mongodb` picks up SSL (longer). + +- If containers cannot resolve the `mongo` service name, ensure you run `docker compose` from the repository root and that the network is up (`docker compose up -d`). + +## Next steps and ideas + +- Add a small `Makefile` or Composer script to run `fixture_loader.php` automatically before integration tests. +- Add a GitHub Actions workflow that builds the PHP image, starts services, runs the fixture loader, and executes both test suites. + --- \ No newline at end of file diff --git a/bmad/artifacts/audit-baseline-2026-03-07.md b/bmad/artifacts/audit-baseline-2026-03-07.md index b0b26f6..f0e85cb 100644 --- a/bmad/artifacts/audit-baseline-2026-03-07.md +++ b/bmad/artifacts/audit-baseline-2026-03-07.md @@ -13,4 +13,4 @@ Recommended next steps: - Create PRD (bmad plan prd) - Run composer install in web/bin and verify vendor presence - Run `bmad audit --full` for deeper static analysis - + diff --git a/bmad/artifacts/audit-full-2026-03-07.md b/bmad/artifacts/audit-full-2026-03-07.md index 1c61158..abaf8d4 100644 --- a/bmad/artifacts/audit-full-2026-03-07.md +++ b/bmad/artifacts/audit-full-2026-03-07.md @@ -1,105 +1,105 @@ -# Audit — Full — 2026-03-07 - -Summary - -- Project: idae.api (PHP + MongoDB) -- Entrypoints: web/index.php → web/bin/classes/ClassRouter.php → web/bin/engine/Idae/Api/IdaeApiRest.php → web/bin/engine/Idae/Query/IdaeQuery.php -- Tests: web/bin/tests (phpunit) — unit + integration (fixture loader provided) -- Docker: docker-compose.yml defines 'app' (PHP/Apache) and 'mongo' services; an init script and default credentials are present for local testing. - -Scope & files inspected - -- web/bin/composer.json (dependencies & php platform) -- docker-compose.yml -- web/index.php -- web/bin/classes/ClassRouter.php -- web/bin/engine/Idae/Api/IdaeApiRest.php -- web/bin/engine/Idae/Query/IdaeQuery.php -- web/bin/phpunit.xml and tests folder - -Key Findings - -1) Stack & dependencies -- Composer lists PHP platform 7.4.33 and requires: mongodb/mongodb (1.6.x-dev), alcaeus/mongo-php-adapter, mustache, altorouter, nayjest/str-case-converter, phpunit ^8.4, predis/predis. -- Using a dev-version (1.6.x-dev) for mongodb/mongodb is risky; prefer a stable release pinned with semantic versioning. - -2) Entrypoints & routing -- Routing is clear and minimal: AltoRouter in ClassRouter registers /api/idql/[scheme] and /api/[*]. The router delegates to IdaeApiRest which parses and dispatches IDQL and generic REST requests. - -3) Query layer and DB access -- IdaeQuery centralizes MongoDB access but often materializes entire cursors with iterator_to_array(), and does nested findOne() per-row lookups. This may cause high memory usage and slow N+1 database patterns on large datasets. -- Several methods toggle global ini settings (mongo.long_as_object), and debug flags (ini_set('display_errors',55)) are present; those should be removed/controlled per-environment. - -4) Tests & CI readiness -- PHPUnit configuration (phpunit.xml) declares both unit and integration suites. Integration tests require a running MongoDB and a fixture loader (web/bin/tests/fixtures/fixture_loader.php). -- No CI pipeline detected in repository; recommend adding GitHub Actions (or similar) to run unit tests and optionally integration tests with a Mongo service. - -5) Docker & secrets -- docker-compose.yml contains plain text defaults for MDB_USER/MDB_PASSWORD and MONGO_INITDB_ROOT_PASSWORD (used for local integration tests). Committed credentials should be considered test-only and rotated; replace with environment variables or Docker secrets in shared repos. - -6) Security & input handling -- IdaeApiRest::getJson() handles JSON content types but returns an empty array on invalid JSON after calling json_response(400, 'Invalid JSON!'). Consider explicit exit or throwing an exception so invalid payloads do not continue processing. -- CORS appears permissive (project notes indicate Access-Control-Allow-Origin: *) — acceptable for local dev but review for production. - -7) Performance -- Aggressive use of iterator_to_array() and returning full documents can lead to high memory consumption; prefer streaming or pagination for large result sets. -- 'parallel' queries are executed sequentially in code (recursive doQuery calls) — name may be misleading; consider real parallelization only where safe. - -8) Maintainability & code hygiene -- Several debug statements, var_dump/die lines, and magic ini toggles are present. Add logging instead of echo/var_dump and ensure production config disables debug. -- Naming and file organization follow a consistent router→API→query pattern which is good; conform to PSR-12 whitespace/style for new code. - -Recommendations (prioritized) - -1. Stability & dependencies - - Replace dev-version mongodb/mongodb with a stable release (use the version compatible with your PHP target). Run `composer update` and test. - - Upgrade PHP to a supported LTS (8.1 or 8.2), update Dockerfile and CI accordingly. - -2. CI / Tests - - Add a GitHub Actions workflow to run `composer install` and unit tests; optionally run integration tests in a job that brings up MongoDB and runs fixture_loader.php. - - Add `composer audit` and a security scan step to CI. - -3. Code & performance - - Refactor IdaeQuery::find and related methods to avoid iterator_to_array() where possible; implement streaming, cursor batching, or paginate by default. - - Replace per-row findOne joins with aggregation $lookup or batched prefetch to avoid N+1 queries. - - Remove debug ini_set/display_errors lines; centralize environment-controlled logging. - -4. Security & config - - Remove plaintext credentials from source; use environment variables, .env files excluded from VCS, or Docker secrets for production. - - Harden CORS and response headers for production. - - Validate and sanitize all incoming payloads strictly (IdaeApiParser/IdaeApiRest layer). - -5. Operational - - Rebuild Docker image ensuring ext-mongodb is compiled with SSL if SCRAM authentication is used by CI/production. - - Add a Makefile or composer scripts to run fixture loader and tests easily. - -Actionable next steps - -- Run: `cd web/bin && composer install` and run unit tests: `./vendor/bin/phpunit --testsuite unit`. -- Implement GH Actions: `php composer install` + unit test job; add optional integration job with mongo service and fixture loader. -- Create developer stories for: (S1) Refactor query memory usage, (S2) Rebuild Docker / upgrade PHP + drivers, (S3) Add CI + security scanning, (S4) Remove debug and stabilize logging. - -Appendix — files discovered - -- docker-compose.yml -- web/index.php -- web/bin/classes/ClassRouter.php -- web/bin/engine/Idae/Api/IdaeApiRest.php -- web/bin/engine/Idae/Query/IdaeQuery.php -- web/bin/composer.json -- web/bin/phpunit.xml -- web/bin/tests/ - -Commands - -- Local dev: - - `docker compose up -d --build` - - `cd web/bin && composer install` - - `cd web/bin && ./vendor/bin/phpunit --testsuite unit` - -- Recommended CI snippet (GitHub Actions): - - job: composer install + run phpunit - ---- - -Generated by bmad-master audit on 2026-03-07. +# Audit — Full — 2026-03-07 + +Summary + +- Project: idae.api (PHP + MongoDB) +- Entrypoints: web/index.php → web/bin/classes/ClassRouter.php → web/bin/engine/Idae/Api/IdaeApiRest.php → web/bin/engine/Idae/Query/IdaeQuery.php +- Tests: web/bin/tests (phpunit) — unit + integration (fixture loader provided) +- Docker: docker-compose.yml defines 'app' (PHP/Apache) and 'mongo' services; an init script and default credentials are present for local testing. + +Scope & files inspected + +- web/bin/composer.json (dependencies & php platform) +- docker-compose.yml +- web/index.php +- web/bin/classes/ClassRouter.php +- web/bin/engine/Idae/Api/IdaeApiRest.php +- web/bin/engine/Idae/Query/IdaeQuery.php +- web/bin/phpunit.xml and tests folder + +Key Findings + +1) Stack & dependencies +- Composer lists PHP platform 7.4.33 and requires: mongodb/mongodb (1.6.x-dev), alcaeus/mongo-php-adapter, mustache, altorouter, nayjest/str-case-converter, phpunit ^8.4, predis/predis. +- Using a dev-version (1.6.x-dev) for mongodb/mongodb is risky; prefer a stable release pinned with semantic versioning. + +2) Entrypoints & routing +- Routing is clear and minimal: AltoRouter in ClassRouter registers /api/idql/[scheme] and /api/[*]. The router delegates to IdaeApiRest which parses and dispatches IDQL and generic REST requests. + +3) Query layer and DB access +- IdaeQuery centralizes MongoDB access but often materializes entire cursors with iterator_to_array(), and does nested findOne() per-row lookups. This may cause high memory usage and slow N+1 database patterns on large datasets. +- Several methods toggle global ini settings (mongo.long_as_object), and debug flags (ini_set('display_errors',55)) are present; those should be removed/controlled per-environment. + +4) Tests & CI readiness +- PHPUnit configuration (phpunit.xml) declares both unit and integration suites. Integration tests require a running MongoDB and a fixture loader (web/bin/tests/fixtures/fixture_loader.php). +- No CI pipeline detected in repository; recommend adding GitHub Actions (or similar) to run unit tests and optionally integration tests with a Mongo service. + +5) Docker & secrets +- docker-compose.yml contains plain text defaults for MDB_USER/MDB_PASSWORD and MONGO_INITDB_ROOT_PASSWORD (used for local integration tests). Committed credentials should be considered test-only and rotated; replace with environment variables or Docker secrets in shared repos. + +6) Security & input handling +- IdaeApiRest::getJson() handles JSON content types but returns an empty array on invalid JSON after calling json_response(400, 'Invalid JSON!'). Consider explicit exit or throwing an exception so invalid payloads do not continue processing. +- CORS appears permissive (project notes indicate Access-Control-Allow-Origin: *) — acceptable for local dev but review for production. + +7) Performance +- Aggressive use of iterator_to_array() and returning full documents can lead to high memory consumption; prefer streaming or pagination for large result sets. +- 'parallel' queries are executed sequentially in code (recursive doQuery calls) — name may be misleading; consider real parallelization only where safe. + +8) Maintainability & code hygiene +- Several debug statements, var_dump/die lines, and magic ini toggles are present. Add logging instead of echo/var_dump and ensure production config disables debug. +- Naming and file organization follow a consistent router→API→query pattern which is good; conform to PSR-12 whitespace/style for new code. + +Recommendations (prioritized) + +1. Stability & dependencies + - Replace dev-version mongodb/mongodb with a stable release (use the version compatible with your PHP target). Run `composer update` and test. + - Upgrade PHP to a supported LTS (8.1 or 8.2), update Dockerfile and CI accordingly. + +2. CI / Tests + - Add a GitHub Actions workflow to run `composer install` and unit tests; optionally run integration tests in a job that brings up MongoDB and runs fixture_loader.php. + - Add `composer audit` and a security scan step to CI. + +3. Code & performance + - Refactor IdaeQuery::find and related methods to avoid iterator_to_array() where possible; implement streaming, cursor batching, or paginate by default. + - Replace per-row findOne joins with aggregation $lookup or batched prefetch to avoid N+1 queries. + - Remove debug ini_set/display_errors lines; centralize environment-controlled logging. + +4. Security & config + - Remove plaintext credentials from source; use environment variables, .env files excluded from VCS, or Docker secrets for production. + - Harden CORS and response headers for production. + - Validate and sanitize all incoming payloads strictly (IdaeApiParser/IdaeApiRest layer). + +5. Operational + - Rebuild Docker image ensuring ext-mongodb is compiled with SSL if SCRAM authentication is used by CI/production. + - Add a Makefile or composer scripts to run fixture loader and tests easily. + +Actionable next steps + +- Run: `cd web/bin && composer install` and run unit tests: `./vendor/bin/phpunit --testsuite unit`. +- Implement GH Actions: `php composer install` + unit test job; add optional integration job with mongo service and fixture loader. +- Create developer stories for: (S1) Refactor query memory usage, (S2) Rebuild Docker / upgrade PHP + drivers, (S3) Add CI + security scanning, (S4) Remove debug and stabilize logging. + +Appendix — files discovered + +- docker-compose.yml +- web/index.php +- web/bin/classes/ClassRouter.php +- web/bin/engine/Idae/Api/IdaeApiRest.php +- web/bin/engine/Idae/Query/IdaeQuery.php +- web/bin/composer.json +- web/bin/phpunit.xml +- web/bin/tests/ + +Commands + +- Local dev: + - `docker compose up -d --build` + - `cd web/bin && composer install` + - `cd web/bin && ./vendor/bin/phpunit --testsuite unit` + +- Recommended CI snippet (GitHub Actions): + - job: composer install + run phpunit + +--- + +Generated by bmad-master audit on 2026-03-07. diff --git a/bmad/artifacts/connector.yml b/bmad/artifacts/connector.yml index 252f510..1ad8cd3 100644 --- a/bmad/artifacts/connector.yml +++ b/bmad/artifacts/connector.yml @@ -7,6 +7,6 @@ meta: dictionary: keywords: story: "Atomic dev task. ID pattern: S{sprint}-{seq:02d}." - sprint: "Time-boxed work batch." - - + sprint: "Time-boxed work batch." + + diff --git a/bmad/artifacts/history/status-20260307T143220.yaml b/bmad/artifacts/history/status-20260307T143220.yaml index a57446a..e2e1281 100644 --- a/bmad/artifacts/history/status-20260307T143220.yaml +++ b/bmad/artifacts/history/status-20260307T143220.yaml @@ -8,4 +8,4 @@ artifacts: product_brief: "artifacts/product-brief.md" prd: "artifacts/prd.md" tech_spec: "artifacts/tech-spec.md" - architecture: "artifacts/architecture.md" + architecture: "artifacts/architecture.md" diff --git a/bmad/artifacts/history/status-20260307T144209.yaml b/bmad/artifacts/history/status-20260307T144209.yaml index a484325..79436ff 100644 --- a/bmad/artifacts/history/status-20260307T144209.yaml +++ b/bmad/artifacts/history/status-20260307T144209.yaml @@ -10,4 +10,4 @@ artifacts: product_brief: "artifacts/product-brief.md" prd: "artifacts/prd.md" tech_spec: "artifacts/tech-spec.md" - architecture: "artifacts/architecture.md" + architecture: "artifacts/architecture.md" diff --git a/bmad/artifacts/history/status-20260307T201949.yaml b/bmad/artifacts/history/status-20260307T201949.yaml index a484325..c276a76 100644 --- a/bmad/artifacts/history/status-20260307T201949.yaml +++ b/bmad/artifacts/history/status-20260307T201949.yaml @@ -1,13 +1,13 @@ -phase: - analysis: done - planning: pending -audit: - baseline: true - baseline_file: "artifacts/audit-baseline-2026-03-07.md" - full: true - full_file: "artifacts/audit-full-2026-03-07.md" -artifacts: - product_brief: "artifacts/product-brief.md" - prd: "artifacts/prd.md" - tech_spec: "artifacts/tech-spec.md" - architecture: "artifacts/architecture.md" +phase: + analysis: done + planning: pending +audit: + baseline: true + baseline_file: "artifacts/audit-baseline-2026-03-07.md" + full: true + full_file: "artifacts/audit-full-2026-03-07.md" +artifacts: + product_brief: "artifacts/product-brief.md" + prd: "artifacts/prd.md" + tech_spec: "artifacts/tech-spec.md" + architecture: "artifacts/architecture.md" diff --git a/bmad/artifacts/history/status-20260307T202514.yaml b/bmad/artifacts/history/status-20260307T202514.yaml index e4488ca..92e8e72 100644 --- a/bmad/artifacts/history/status-20260307T202514.yaml +++ b/bmad/artifacts/history/status-20260307T202514.yaml @@ -1,20 +1,20 @@ last_updated: 2026-03-07T20:25:14Z -phase: - analysis: done - planning: done -audit: - baseline: true - baseline_file: "artifacts/audit-baseline-2026-03-07.md" - full: true - full_file: "artifacts/audit-full-2026-03-07.md" -artifacts: - product_brief: "artifacts/product-brief.md" - prd: "artifacts/prd.md" - tech_spec: "artifacts/tech-spec.md" - architecture: "artifacts/architecture.md" - +phase: + analysis: done + planning: done +audit: + baseline: true + baseline_file: "artifacts/audit-baseline-2026-03-07.md" + full: true + full_file: "artifacts/audit-full-2026-03-07.md" +artifacts: + product_brief: "artifacts/product-brief.md" + prd: "artifacts/prd.md" + tech_spec: "artifacts/tech-spec.md" + architecture: "artifacts/architecture.md" + sprints: - sprint-1 - + diff --git a/bmad/artifacts/history/status-20260307T215349.yaml b/bmad/artifacts/history/status-20260307T215349.yaml index d6789e6..3739f75 100644 --- a/bmad/artifacts/history/status-20260307T215349.yaml +++ b/bmad/artifacts/history/status-20260307T215349.yaml @@ -9,4 +9,4 @@ audit: baseline_file: "artifacts/audit-baseline-2026-03-07.md" sprints: [] backlog: [] -last_updated: "2026-03-07T21:53:49Z" +last_updated: "2026-03-07T21:53:49Z" diff --git a/bmad/artifacts/history/status-20260307T221248.yaml b/bmad/artifacts/history/status-20260307T221248.yaml index d6789e6..3739f75 100644 --- a/bmad/artifacts/history/status-20260307T221248.yaml +++ b/bmad/artifacts/history/status-20260307T221248.yaml @@ -9,4 +9,4 @@ audit: baseline_file: "artifacts/audit-baseline-2026-03-07.md" sprints: [] backlog: [] -last_updated: "2026-03-07T21:53:49Z" +last_updated: "2026-03-07T21:53:49Z" diff --git a/bmad/artifacts/prd.md b/bmad/artifacts/prd.md index 3ce4d1e..e365581 100644 --- a/bmad/artifacts/prd.md +++ b/bmad/artifacts/prd.md @@ -80,4 +80,4 @@ Expected outcome: Jobs execute reliably and failures are logged | Date | Author | Change | |---|---|---| | 2026-03-07 | BMAD PM Agent | Initial draft | - + diff --git a/bmad/artifacts/product-brief.md b/bmad/artifacts/product-brief.md index a152474..61daae0 100644 --- a/bmad/artifacts/product-brief.md +++ b/bmad/artifacts/product-brief.md @@ -1,3 +1,3 @@ # Product Brief -Short summary for idae.api project. +Short summary for idae.api project. diff --git a/bmad/artifacts/sprints/sprint-1.md b/bmad/artifacts/sprints/sprint-1.md index 4fe51ad..93a1255 100644 --- a/bmad/artifacts/sprints/sprint-1.md +++ b/bmad/artifacts/sprints/sprint-1.md @@ -5,4 +5,4 @@ Goals: - Add unit tests and CI Stories: S1-01, S1-02, S1-03 - + diff --git a/bmad/artifacts/stories/S1-02.md b/bmad/artifacts/stories/S1-02.md index 37b8c5a..6aba91b 100644 --- a/bmad/artifacts/stories/S1-02.md +++ b/bmad/artifacts/stories/S1-02.md @@ -5,8 +5,11 @@ role: developer description: | Add input validation and error handling to API for idae.api.lan. Implement and test. +status: in-progress +started_at: "2026-03-11T12:00:00Z" + acceptance_criteria: - Endpoint returns expected JSON for sample query. - Input validation present. - Unit tests added and passing. - + diff --git a/bmad/artifacts/stories/S1-04.md b/bmad/artifacts/stories/S1-04.md index 9022a9b..5f79add 100644 --- a/bmad/artifacts/stories/S1-04.md +++ b/bmad/artifacts/stories/S1-04.md @@ -1,15 +1,15 @@ -id: S1-04 -title: Add generic REST endpoint tests and CRUD examples -estimate: 3 -role: developer -description: | - The project already handles IDQL requests; add coverage and examples - for the generic REST `/api/*` handler. Create unit tests exercising GET, - POST, and PATCH routes using sample schemas and verify JSON response - formatting. Update the `examples/curl_examples.sh` file with REST commands. - -status: done -acceptance_criteria: - - Unit tests for `/api/` endpoints exist and pass. - - curl examples demonstrate GET and POST working. +id: S1-04 +title: Add generic REST endpoint tests and CRUD examples +estimate: 3 +role: developer +description: | + The project already handles IDQL requests; add coverage and examples + for the generic REST `/api/*` handler. Create unit tests exercising GET, + POST, and PATCH routes using sample schemas and verify JSON response + formatting. Update the `examples/curl_examples.sh` file with REST commands. + +status: done +acceptance_criteria: + - Unit tests for `/api/` endpoints exist and pass. + - curl examples demonstrate GET and POST working. - Status.yaml backlog is updated and dashboard reflects the story. \ No newline at end of file diff --git a/bmad/artifacts/tech-spec.md b/bmad/artifacts/tech-spec.md index 451722b..215f742 100644 --- a/bmad/artifacts/tech-spec.md +++ b/bmad/artifacts/tech-spec.md @@ -1,3 +1,3 @@ # Tech spec -High-level tech spec placeholder. +High-level tech spec placeholder. diff --git a/bmad/artifacts/tests/S1-01-test-plan.md b/bmad/artifacts/tests/S1-01-test-plan.md index 364ff72..5664eab 100644 --- a/bmad/artifacts/tests/S1-01-test-plan.md +++ b/bmad/artifacts/tests/S1-01-test-plan.md @@ -1,10 +1,10 @@ -story: S1-01 -objective: Verify products find endpoint works -steps: - - Perform GET request to /api/products?query=test - - Expect 200 response with JSON array - - Validate input sanitation - - Run PHP unit tests for query builder -expected_results: - - JSON output matches sample - - No SQL injection +story: S1-01 +objective: Verify products find endpoint works +steps: + - Perform GET request to /api/products?query=test + - Expect 200 response with JSON array + - Validate input sanitation + - Run PHP unit tests for query builder +expected_results: + - JSON output matches sample + - No SQL injection diff --git a/bmad/config.yaml b/bmad/config.yaml index fef56ad..a91721b 100644 --- a/bmad/config.yaml +++ b/bmad/config.yaml @@ -8,4 +8,4 @@ entrypoints: - "web/index.php" - "web/bin" detected_by: "bmad analyze" -detected_at: "2026-03-07T21:53:49Z" +detected_at: "2026-03-07T21:53:49Z" diff --git a/bmad/dashboard.md b/bmad/dashboard.md index 41b4779..139f5a9 100644 --- a/bmad/dashboard.md +++ b/bmad/dashboard.md @@ -4,4 +4,4 @@ Phase 1 – Analysis ✅ Done Phase 2 – Planning ✅ PRD created Phase 3 – Solutioning ⏳ In progress ───────────────────────────────── -👉 Next: bmad dev story +👉 Next: bmad dev story S1-02 (auto) — working: S1-02 diff --git a/bmad/status.yaml b/bmad/status.yaml index 595826f..34d4cec 100644 --- a/bmad/status.yaml +++ b/bmad/status.yaml @@ -3,12 +3,11 @@ phases: analysis: done planning: done solutioning: in-progress -recommendation: "bmad dev story" +recommendation: "bmad dev story S1-02 --auto" audit: baseline: true baseline_file: "artifacts/audit-baseline-2026-03-07.md" sprints: [] backlog: [] -last_updated: "2026-03-07T22:14:32Z" - +last_updated: "2026-03-11T12:00:00Z" diff --git a/docker-compose.override.yml b/docker-compose.override.yml index fe52cc5..20aeb22 100644 --- a/docker-compose.override.yml +++ b/docker-compose.override.yml @@ -1,13 +1,13 @@ -# Override to run Mongo without authentication (useful for local dev/tests) -# Place this file alongside docker-compose.yml; `docker compose up` will automatically -# apply it. It removes the root credentials so the mongo container starts with no -# auth enabled. WARNING: this will recreate the DB when you remove volumes. - -services: - mongo: - environment: [] - # Force mongod to start with authentication disabled for local dev/tests - command: ["mongod", "--noauth", "--bind_ip_all"] - # Ensure we DON'T mount init scripts (which may create users) when running noauth - volumes: - - mongo_data:/data/db +# Override to run Mongo without authentication (useful for local dev/tests) +# Place this file alongside docker-compose.yml; `docker compose up` will automatically +# apply it. It removes the root credentials so the mongo container starts with no +# auth enabled. WARNING: this will recreate the DB when you remove volumes. + +services: + mongo: + environment: [] + # Force mongod to start with authentication disabled for local dev/tests + command: ["mongod", "--noauth", "--bind_ip_all"] + # Ensure we DON'T mount init scripts (which may create users) when running noauth + volumes: + - mongo_data:/data/db diff --git a/docker-compose.yml b/docker-compose.yml index 345c888..d6c7766 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,40 +1,40 @@ -version: '3.8' - -services: - app: - build: . - container_name: idae-app - ports: - - "8081:80" - volumes: - - ./:/var/www/html:cached - environment: - # The project defines MDB_HOST/MDB_USER/MDB_PASSWORD in web/bin/config/constants.php - # Default to the internal docker "mongo" service below. To use a MongoDB running - # on the host machine instead, set MDB_HOST=host.docker.internal (Windows Docker Desktop) - # or MDB_HOST=host.docker.internal:27017 and uncomment if needed. - - MDB_HOST=mongo - - MDB_USER=admin - - MDB_PASSWORD=gwetme2011 - - MDB_PREFIX=maw_ - extra_hosts: - - "host.docker.internal:host-gateway" - restart: unless-stopped - - mongo: - image: mongo:5.0 - container_name: idae-mongo - restart: unless-stopped - environment: - # Initialize root user matching MDB_USER / MDB_PASSWORD used by the `app` service - - MONGO_INITDB_ROOT_USERNAME=admin - - MONGO_INITDB_ROOT_PASSWORD=gwetme2011 - volumes: - - mongo_data:/data/db - - ./web/bin/docker/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro - ports: - - "27017:27017" - -volumes: - mongo_data: - driver: local +version: '3.8' + +services: + app: + build: . + container_name: idae-app + ports: + - "8081:80" + volumes: + - ./:/var/www/html:cached + environment: + # The project defines MDB_HOST/MDB_USER/MDB_PASSWORD in web/bin/config/constants.php + # Default to the internal docker "mongo" service below. To use a MongoDB running + # on the host machine instead, set MDB_HOST=host.docker.internal (Windows Docker Desktop) + # or MDB_HOST=host.docker.internal:27017 and uncomment if needed. + - MDB_HOST=mongo + - MDB_USER=admin + - MDB_PASSWORD=gwetme2011 + - MDB_PREFIX=maw_ + extra_hosts: + - "host.docker.internal:host-gateway" + restart: unless-stopped + + mongo: + image: mongo:5.0 + container_name: idae-mongo + restart: unless-stopped + environment: + # Initialize root user matching MDB_USER / MDB_PASSWORD used by the `app` service + - MONGO_INITDB_ROOT_USERNAME=admin + - MONGO_INITDB_ROOT_PASSWORD=gwetme2011 + volumes: + - mongo_data:/data/db + - ./web/bin/docker/init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro + ports: + - "27017:27017" + +volumes: + mongo_data: + driver: local diff --git a/examples/README.md b/examples/README.md index b7d84ce..6ed15fc 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,27 +1,27 @@ -Examples for idae.api - -This folder contains ready-to-run curl examples for the IDQL endpoints. - -Files: - -- `curl_examples.sh` — Bash script with three examples: - - Simple `find` on `products`. - - `parallel` example combining a `find` and a `distinct`. - - `group` (aggregation) example on `orders`. - -Requirements: - -- `curl` and `jq` installed (jq used for pretty JSON output). -- API reachable at `http://localhost:8081` (adjust `BASE_URL` in the script if needed). - -Run: - -```bash -bash examples/curl_examples.sh -``` - -If you want Windows `.bat` versions or Postman collection, tell me and I will add them. - -Postman collection - +Examples for idae.api + +This folder contains ready-to-run curl examples for the IDQL endpoints. + +Files: + +- `curl_examples.sh` — Bash script with three examples: + - Simple `find` on `products`. + - `parallel` example combining a `find` and a `distinct`. + - `group` (aggregation) example on `orders`. + +Requirements: + +- `curl` and `jq` installed (jq used for pretty JSON output). +- API reachable at `http://localhost:8081` (adjust `BASE_URL` in the script if needed). + +Run: + +```bash +bash examples/curl_examples.sh +``` + +If you want Windows `.bat` versions or Postman collection, tell me and I will add them. + +Postman collection + You can import `examples/postman_collection.json` into Postman (File → Import) — it contains the same three IDQL examples and a `base_url` variable. \ No newline at end of file diff --git a/examples/postman_collection.json b/examples/postman_collection.json index 6e4860b..701c439 100644 --- a/examples/postman_collection.json +++ b/examples/postman_collection.json @@ -1,66 +1,66 @@ -{ - "info": { - "name": "idae.api - IDQL Examples", - "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", - "_postman_id": "idae-api-idql-examples" - }, - "variable": [ - { - "key": "base_url", - "value": "http://localhost:8081" - } - ], - "item": [ - { - "name": "Find products", - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"method\": \"find\",\n \"scheme\": \"products\",\n \"limit\": 5,\n \"where\": {\"status\": \"active\"}\n}" - }, - "url": "{{base_url}}/api/idql/products" - } - }, - { - "name": "Parallel: users find + products distinct", - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"parallel\": [\n {\"method\":\"find\",\"scheme\":\"users\",\"limit\":5,\"where\":{\"active\":1}},\n {\"method\":\"distinct\",\"scheme\":\"products\",\"distinct\":\"category\",\"where\":{\"status\":\"active\"}}\n ],\n \"scheme\": \"dashboard\"\n}" - }, - "url": "{{base_url}}/api/idql/dashboard" - } - }, - { - "name": "Group orders by date", - "request": { - "method": "POST", - "header": [ - { - "key": "Content-Type", - "value": "application/json" - } - ], - "body": { - "mode": "raw", - "raw": "{\n \"method\": \"group\",\n \"scheme\": \"orders\",\n \"group\": \"iddate\",\n \"where\": {\"status\": \"completed\"},\n \"limit\": 10\n}" - }, - "url": "{{base_url}}/api/idql/orders" - } - } - ] -} +{ + "info": { + "name": "idae.api - IDQL Examples", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_postman_id": "idae-api-idql-examples" + }, + "variable": [ + { + "key": "base_url", + "value": "http://localhost:8081" + } + ], + "item": [ + { + "name": "Find products", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"method\": \"find\",\n \"scheme\": \"products\",\n \"limit\": 5,\n \"where\": {\"status\": \"active\"}\n}" + }, + "url": "{{base_url}}/api/idql/products" + } + }, + { + "name": "Parallel: users find + products distinct", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"parallel\": [\n {\"method\":\"find\",\"scheme\":\"users\",\"limit\":5,\"where\":{\"active\":1}},\n {\"method\":\"distinct\",\"scheme\":\"products\",\"distinct\":\"category\",\"where\":{\"status\":\"active\"}}\n ],\n \"scheme\": \"dashboard\"\n}" + }, + "url": "{{base_url}}/api/idql/dashboard" + } + }, + { + "name": "Group orders by date", + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "body": { + "mode": "raw", + "raw": "{\n \"method\": \"group\",\n \"scheme\": \"orders\",\n \"group\": \"iddate\",\n \"where\": {\"status\": \"completed\"},\n \"limit\": 10\n}" + }, + "url": "{{base_url}}/api/idql/orders" + } + } + ] +} diff --git a/master-dashboard.json b/master-dashboard.json index 553fb8c..b192fd4 100644 --- a/master-dashboard.json +++ b/master-dashboard.json @@ -13,5 +13,5 @@ ], "criticalIssues": [], "generatedMarkdown": "# 👑 BMAD Master Dashboard\n> **Scope:** Monorepo Root | **Total Instances:** 1 | **Sync:** 2026-03-07\n\n---\n\n## 🏗️ Project Overview\n\n| Package | Phase | Progress | Status | Action |\n| :--- | :--- | :---: | :---: | :--- |\n| **idae.api.lan** | Analysis | N/A | 🟢 | [Open Dash](bmad/dashboard.md) |\n\n---\n\n## ⚠️ Critical Issues (QA/Bugs)\n- None recorded\n\n---\n\n## 🛠️ Global Actions\n- [🔄 Full Rescan](command:bmad.run?%5B%22dashboard%22%5D)\n- [➕ New Package](command:bmad.run?%5B%22init%22%5D)\n" -} - +} + diff --git a/web/.htaccess b/web/.htaccess index 2b9d9bf..5c0229a 100644 --- a/web/.htaccess +++ b/web/.htaccess @@ -1,19 +1,19 @@ - - -SetEnvif Host "idae.api.lan" CONF_INC=D:\\\boulot\\\wamp64\\\www\\\idae.api.lan\\\web\\\conf.inc.php -php_value session.auto_start 0 -# php_value display_errors On -# -# RewriteEngine On - -# RewriteBase / -# RewriteRule ^index\.php$ - [L] -# RewriteCond %{REQUEST_FILENAME} !-f -# RewriteCond %{REQUEST_FILENAME} !-d -# RewriteRule . /index.php [L] -# - -RewriteEngine on -RewriteCond %{REQUEST_FILENAME} !-f -RewriteCond %{REQUEST_FILENAME} !-d -RewriteRule . index.php [L] + + +SetEnvif Host "idae.api.lan" CONF_INC=D:\\\boulot\\\wamp64\\\www\\\idae.api.lan\\\web\\\conf.inc.php +php_value session.auto_start 0 +# php_value display_errors On +# +# RewriteEngine On + +# RewriteBase / +# RewriteRule ^index\.php$ - [L] +# RewriteCond %{REQUEST_FILENAME} !-f +# RewriteCond %{REQUEST_FILENAME} !-d +# RewriteRule . /index.php [L] +# + +RewriteEngine on +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule . index.php [L] diff --git a/web/.user.ini b/web/.user.ini index 1cf7d16..8c6151f 100644 --- a/web/.user.ini +++ b/web/.user.ini @@ -1,26 +1,26 @@ - -short_open_tag = On -session.auto_start = 0 - -sockets.use_system_read= Off -max_execution_time =259200 -default_socket_timeout =30 -display_errors= On -html_errors = On -output_buffering =On - -post_max_size =120M -upload_max_filesize =120M -LimitRequestBody = 120M -memory_limit= 4G -max_input_vars= 5000 -suhosin.post.max_vars =5000 -suhosin.request.max_vars =5000 - -open_basedir = none -date.timezone = Europe/Paris - -fastcgi_keep_conn on; - -allow_url_fopen = On + +short_open_tag = On +session.auto_start = 0 + +sockets.use_system_read= Off +max_execution_time =259200 +default_socket_timeout =30 +display_errors= On +html_errors = On +output_buffering =On + +post_max_size =120M +upload_max_filesize =120M +LimitRequestBody = 120M +memory_limit= 4G +max_input_vars= 5000 +suhosin.post.max_vars =5000 +suhosin.request.max_vars =5000 + +open_basedir = none +date.timezone = Europe/Paris + +fastcgi_keep_conn on; + +allow_url_fopen = On allow_url_include = On \ No newline at end of file diff --git a/web/auto_start.bat b/web/auto_start.bat index 2a7350e..e9d7475 100644 --- a/web/auto_start.bat +++ b/web/auto_start.bat @@ -1,6 +1,6 @@ - - - -forever start -a --uid tac_tac_shop_mydde /var/www/tac-tac.shop.mydde.fr/web/bin/node/app_https/app_https_main.js; -forever list; -cat /root/.forever/tac_tac_shop_mydde.log; + + + +forever start -a --uid tac_tac_shop_mydde /var/www/tac-tac.shop.mydde.fr/web/bin/node/app_https/app_https_main.js; +forever list; +cat /root/.forever/tac_tac_shop_mydde.log; diff --git a/web/auto_start.sh b/web/auto_start.sh index bdbdfc1..f034af1 100644 --- a/web/auto_start.sh +++ b/web/auto_start.sh @@ -1,6 +1,6 @@ -#!/bin/bash - - -forever start -a --uid tac_tac_shop_mydde /var/www/tac-tac.shop.mydde.fr/web/bin/node/app_https/app_https_main.js; -forever list; -cat /root/.forever/tac_tac_shop_mydde.log; +#!/bin/bash + + +forever start -a --uid tac_tac_shop_mydde /var/www/tac-tac.shop.mydde.fr/web/bin/node/app_https/app_https_main.js; +forever list; +cat /root/.forever/tac_tac_shop_mydde.log; diff --git a/web/bin/.phpunit.result.cache b/web/bin/.phpunit.result.cache index ab353b1..d704c95 100644 --- a/web/bin/.phpunit.result.cache +++ b/web/bin/.phpunit.result.cache @@ -1 +1 @@ -C:37:"PHPUnit\Runner\DefaultTestResultCache":454:{a:2:{s:7:"defects";a:3:{s:37:"IdaeApiParserTest::testParseSimpleUri";i:4;s:56:"IdaeQueryIntegrationTest::testFindOneWithInjectedConnect";i:1;s:70:"ProductsApiTest::test_idql_products_returns_sample_when_db_unavailable";i:4;}s:5:"times";a:3:{s:37:"IdaeApiParserTest::testParseSimpleUri";d:0.059;s:56:"IdaeQueryIntegrationTest::testFindOneWithInjectedConnect";d:0.078;s:70:"ProductsApiTest::test_idql_products_returns_sample_when_db_unavailable";d:4.057;}}} \ No newline at end of file +C:37:"PHPUnit\Runner\DefaultTestResultCache":1137:{a:2:{s:7:"defects";a:6:{s:37:"IdaeApiParserTest::testParseSimpleUri";i:4;s:56:"IdaeQueryIntegrationTest::testFindOneWithInjectedConnect";i:1;s:70:"ProductsApiTest::test_idql_products_returns_sample_when_db_unavailable";i:4;s:54:"IdaeQueryUnitTest::testFindReturnsArrayWithFakeConnect";i:4;s:49:"ValidateQueryTest::test_invalid_where_returns_422";i:4;s:50:"ValidateQueryTest::test_invalid_method_returns_422";i:3;}s:5:"times";a:10:{s:37:"IdaeApiParserTest::testParseSimpleUri";d:0.053;s:56:"IdaeQueryIntegrationTest::testFindOneWithInjectedConnect";d:0.078;s:70:"ProductsApiTest::test_idql_products_returns_sample_when_db_unavailable";d:4.368;s:54:"IdaeQueryUnitTest::testFindReturnsArrayWithFakeConnect";d:4.048;s:70:"RestApiTest::test_rest_get_products_returns_sample_when_db_unavailable";d:4.492;s:71:"RestApiTest::test_rest_post_products_returns_sample_when_db_unavailable";d:4.344;s:50:"ValidateQueryTest::test_missing_scheme_returns_422";d:0.002;s:49:"ValidateQueryTest::test_invalid_limit_returns_422";d:0;s:49:"ValidateQueryTest::test_invalid_where_returns_422";d:0;s:50:"ValidateQueryTest::test_invalid_method_returns_422";d:0;}}} \ No newline at end of file diff --git a/web/bin/TESTS.md b/web/bin/TESTS.md index aa0afae..9816cbd 100644 --- a/web/bin/TESTS.md +++ b/web/bin/TESTS.md @@ -1,28 +1,28 @@ -Tests pour idae.api - -Prérequis -- PHP 7.4 avec l'extension `mongodb` installée -- MongoDB en cours d'exécution pour les tests d'intégration (ou mock) -- Composer dependencies installées: exécuter depuis `web/bin` - -Installation -```bash -cd web/bin -composer install -``` - -Lancer les tests unitaires -```bash -cd web/bin -./vendor/bin/phpunit --testsuite unit -``` - -Lancer les tests d'intégration (MongoDB doit être disponible) -```bash -cd web/bin -./vendor/bin/phpunit --testsuite integration -``` - -Notes -- Le bootstrap `tests/bootstrap.php` inclut `conf.inc.php` si présent pour définir les constantes d'environnement. -- Pour faciliter les tests, `IdaeConnect::setInstance()` permet d'injecter une instance factice dans les tests unitaires. +Tests pour idae.api + +Prérequis +- PHP 7.4 avec l'extension `mongodb` installée +- MongoDB en cours d'exécution pour les tests d'intégration (ou mock) +- Composer dependencies installées: exécuter depuis `web/bin` + +Installation +```bash +cd web/bin +composer install +``` + +Lancer les tests unitaires +```bash +cd web/bin +./vendor/bin/phpunit --testsuite unit +``` + +Lancer les tests d'intégration (MongoDB doit être disponible) +```bash +cd web/bin +./vendor/bin/phpunit --testsuite integration +``` + +Notes +- Le bootstrap `tests/bootstrap.php` inclut `conf.inc.php` si présent pour définir les constantes d'environnement. +- Pour faciliter les tests, `IdaeConnect::setInstance()` permet d'injecter une instance factice dans les tests unitaires. diff --git a/web/bin/classes/ClassAction.php b/web/bin/classes/ClassAction.php index ca199bd..4567a33 100644 --- a/web/bin/classes/ClassAction.php +++ b/web/bin/classes/ClassAction.php @@ -1,1210 +1,1210 @@ - $value_node) { - if (strpos($value_node, ':') === false) { - $values_params[$key_values] = $value_node; - continue; - } - $tmp_node = explode(':', $value_node); - if (sizeof($tmp_node) == 2) { - $values_params[$tmp_node[0]] = $tmp_node[1]; - } elseif (sizeof($tmp_node) == 1) { - $values_params[] = $tmp_node[0]; - } else { - $node_key = $tmp_node[0]; - unset($tmp_node[0]); - $values_params[$node_key] = array_values($tmp_node); - } - } - // - $this->$params['action']($values_params); - } - - function login() { - $table = 'client'; - $Table = ucfirst($table); - $param = $_POST; - $json_message = ['err' => '', - 'msg' => '']; - - foreach ($param as $key => $post) { - - $post = filter_var($post, FILTER_SANITIZE_STRING); - if (strpos($key, 'email') !== false) { - $post = filter_var($post, FILTER_VALIDATE_EMAIL); - } - - $param[$key] = $post; - } - - if (!empty($param['emailClient']) && !empty($param['passwordClient'])) { - - $APP_CLI = new App('client'); - $test_cli = $APP_CLI->findOne(['passwordClient' => md5($param['passwordClient']), - 'emailClient' => $param['emailClient']]); - - if (!empty($test_cli['idclient'])) { - $_SESSION['client'] = $test_cli['private_key']; - $_SESSION['client_identity'] = $test_cli['prenomClient'] . ' ' . $test_cli['nomClient']; - $json_message = ['err' => 0, - 'msg' => 'good']; - } else { - $json_message = ['err' => 1, - 'msg' => 'bad']; - } - - } - - // cart !! - $Cart = new Cart(); - $var_cart = $Cart->get_cart(); - - if (!empty($var_cart['cart_lines']) && !empty($var_cart['cart_adresse'])) { - - } - - echo json_encode($json_message, JSON_FORCE_OBJECT); - } - - function login_multi() { - global $LATTE; - - $param = $_POST; - $type = $parameters['type'] = $_POST['type']; - $Type = ucfirst($type); - $json_message = ['err' => '', - 'msg' => '']; - - foreach ($param as $key => $post) { - - $post = filter_var($post, FILTER_SANITIZE_STRING); - if (strpos($key, 'email') !== false) { - $post = filter_var($post, FILTER_VALIDATE_EMAIL); - } - - $param[$key] = $post; - } - - $login_field = ($type == 'agent') ? "login" : "email"; - - if (!empty($param["$login_field$Type"]) && !empty($param["password$Type"])) { - - $APP_CLI = new App($type); - - $test_cli = $APP_CLI->findOne(["password$Type" => md5($param["password$Type"]), - "$login_field$Type" => $param["$login_field$Type"]]); - if (empty($test_cli["id$type"])) { - $test_cli = $APP_CLI->findOne(["password$Type" => trim($param["password$Type"]), - "$login_field$Type" => trim($param["$login_field$Type"])]); - if (!empty($test_cli["id$type"])) { - $test_cli['private_key'] = md5($test_cli['password' . $Type] . $test_cli['dateCreation' . ucfirst($type)]); - $APP_CLI->update(["id$type" => (int)$test_cli["id$type"]], ['private_key' => $test_cli['private_key']]); - } - } - if (!empty($test_cli["id$type"])) { - unset($_SESSION["client"], $_SESSION["livreur"], $_SESSION["shop"]); - - $IdaeSession = IdaeSession::getInstance(); - $IdaeSession->setSession($type, $test_cli); - - $session = $IdaeSession->get_session(); - - /*$_SESSION["type_session"] = $type; - $_SESSION["idtype_session"] = (int)$test_cli["id$type"]; - $_SESSION["id$type"] = (int)$test_cli["id$type"]; - $_SESSION[$type] = $test_cli['private_key']; - $_SESSION[$type . "_identity"] = $test_cli["prenom$Type"] . ' ' . $test_cli["nom$Type"];*/ - - $json_message = ['err' => 0, - 'msg' => 'good', - 'json' => json_encode($_SESSION)]; - - # join socket pour publication - AppSocket::send_grantIn(['room' => $type . "_" . $test_cli["id$type"]]); // room personnelle de type shop_7 - if ($type == 'livreur') { - $APP_AFF = new App('livreur_affectation'); - $test_aff = $APP_AFF->findOne(["idlivreur" => (int)$test_cli["id$type"], - 'dateDebutLivreur_affectation' => date('Y-M-D')]); - if (!empty($test_aff["idsecteur"])) { - AppSocket::send_grantIn(['room' => "secteur_" . $test_aff["idsecteur"]]); // room secteur - - } - } - $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_success.html", ['type' => $type, - 'data' => $test_cli])); - $json_message['type'] = $type; - } else { - - $json_message = ['err' => 1, - 'msg' => "L'adresse mail ou le mot de passe ne sont pas reconnus"]; - $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_fail.html", ['type' => $type, - 'data' => $test_cli, - 'msg' => "L'adresse mail ou le mot de passe ne sont pas reconnus"])); - - } - - } - - echo json_encode($json_message, JSON_FORCE_OBJECT); - } - - function room_reconnect() { - if (!empty($_SESSION["type_session"])) { - $type = $_SESSION["type_session"]; - $Type = ucfirst($type); - $name_idtype = "id$type"; - $idtype = (int)$_SESSION["idtype_session"]; - $APP_SESSION = new App($type); - $test = $APP_SESSION->findOne([$name_idtype => $idtype]); - if (empty($test[$name_idtype])) return; - AppSocket::send_grantIn(['room' => 'room_' . $type], session_id()); // room total de type shop agent livreur - AppSocket::send_grantIn(['room' => $type . "_" . $test["id$type"]], session_id()); // room personnelle de type shop_7 agent_1 livreur_3 - if ($type == 'livreur') { - $APP_AFF = new App('livreur_affectation'); - $test_aff = $APP_AFF->findOne(["idlivreur" => (int)$test["id$type"], - 'dateDebutLivreur_affectation' => date('Y-M-D')]); - if (!empty($test["idsecteur"])) { - AppSocket::send_grantIn(['room' => "secteur_" . $test["idsecteur"]], session_id()); - } - //NotifySite::notify_idae('send_grantIn livreur'); - } - //NotifySite::notify_idae('Vous êtes connecté !!'); - } - } - - function logout() { - unset($_SESSION['client'], $_SESSION['client_identity']); - } - - function login_multi_retrieve() { - include_once(APPCLASSES . 'ClassSMTP.php'); - global $LATTE; - $param = $_POST; - $type = $_POST['type']; - $Type = ucfirst($type); - $tmp_ssid = session_id(); - $APP_CLI = new App($type); - - $failed = 0; - $json_message = ['msg' => null, - 'err' => 1, - 'success' => null]; - AppSocket::send_cmd('act_notify', ['msg' => 'Recherche du mail utilisateur'], session_id()); - $test_cli = $APP_CLI->findOne(["email$Type" => $param["email$Type"]]); - if (empty($test_cli["id$type"])) { - $json_message['err'] = 1; - $json_message['success'] = null; - $json_message['msg'] = 'Erreur enregistrement non trouvé '; - - AppSocket::send_cmd('act_notify', ['msg' => 'Erreur enregistrement non trouvé '], session_id()); - - echo json_encode($json_message, JSON_FORCE_OBJECT); - - } else { - AppSocket::send_cmd('act_notify', ['msg' => 'Envoi du mail'], session_id()); - - $private_key = $test_cli['private_key']; - $link = HTTPCUSTOMERSITE . "page/login_init/$type/{$private_key}"; - $body = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_init_mail.html", ['type' => $type, - 'Type' => $Type, - 'link' => $link, - 'data' => $test_cli, - 'msg' => "Votre mot de passe"])); - - $mail = new PHPMailer(); - - $mail->IsSMTP(); - $mail->IsHTML(); - $mail->WordWrap = 50; - $mail->SMTPDebug = 0; - $mail->SMTPAuth = true; - $mail->SMTPOptions = [ // PREPROD ? - 'ssl' => ['verify_peer' => false, - 'verify_peer_name' => false, - 'allow_self_signed' => true]]; - $mail->CharSet = 'UTF-8'; - $mail->Hostname = SMTPDOMAIN; - $mail->Helo = SMTPDOMAIN; - $mail->Host = SMTPHOST; - $mail->Username = SMTPUSER; - $mail->Password = SMTPPASS; - $mail->SetFrom(SMTPUSER, 'postmaster tac-tac'); - // $mail->AddReplyTo($_POST['emailFrom'] , $_POST['emailFromName']); - $mail->Subject = "Récupération de votre mot de passe"; - $mail->AltBody = strip_tags($body); - $mail->AddAddress($test_cli["email$Type"], 'destinataire'); - - $mail->MsgHTML($body); - - if (!$mail->Send()) { - AppSocket::send_cmd('act_notify', ['msg' => 'Erreur envoi'], session_id()); - echo "Mailer Error: " . $mail->ErrorInfo; - } else { - $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_retrieve_send.html", ['type' => $type, - 'Type' => $Type, - 'link' => $link, - 'data' => $test_cli, - 'msg' => "Votre mot de passe"])); - $json_message['err'] = 0; - $json_message['success'] = 1; - $json_message['type'] = $type; - $json_message['msg'] = 'Enregistrement trouvé ! '; - $json_message['msg_key'] = $test_cli['private_key']; - - AppSocket::send_cmd('act_notify', ['msg' => 'Email envoyé !'], session_id()); - - echo json_encode($json_message, JSON_FORCE_OBJECT); - } - } - } - - function logout_multi() { - global $LATTE; - $type = $_POST['type']; - $tmp_ssid = session_id(); - $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_dead.html", ['type' => $type])); - echo json_encode($json_message, JSON_FORCE_OBJECT); - - unset($_SESSION[$type], $_SESSION[$type . '_identity']); - // Détruit toutes les variables de session - $_SESSION = []; - - if (ini_get("session.use_cookies")) { - $params = session_get_cookie_params(); - setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]); - } - - session_destroy(); - AppSocket::send_cmd('act_script', ['script' => 'post_logout_shop', - 'arguments' => [], - 'options' => []], $tmp_ssid); - } - - function register_again($post_vars = []) { - global $LATTE; - - $post_vars = array_filter($post_vars); - $param = (sizeof($post_vars) == 0) ? $_POST : $post_vars; - $failed = 0; - $empty_fields = []; - $insert_field = []; - $json_message = ['msg' => null, - 'err' => 1, - 'success' => null]; - $allowed_fields = ['nom', - 'prenom', - 'adresse', - 'codePostal', - 'ville', - 'email', - 'password']; - $type = empty($post_vars['type']) ? 'client' : $post_vars['type']; - $Type = ucfirst($type); - $APP_CLI = new App($type); - - foreach ($param as $key => $post) { - $post = filter_var($post, FILTER_SANITIZE_STRING); - if (strpos($key, 'email') !== false) { - $post = filter_var($post, FILTER_VALIDATE_EMAIL); - } - - if (empty($post)) { - $empty_fields[$key] = $post; - $failed = 1; - } else { - $param[$key] = $post; - } - } - - if ($param["password$Type"] != $param["password$Type" . "_verif"]) { - $json_message['msg'] = ['mauvais mot de passe' => $param["password$Type"]]; - $failed = 1; - } - $test_cli = $APP_CLI->findOne(['private_key' => $param['private_key']], ['_id' => 0]); - if (empty($test_cli["id$type"])) { - $json_message['msg'] = ["$Type absent pour clef " => $param['private_key']]; - $failed = 1; - } - if ($failed == 0) { - $json_message['err'] = 0; - $insert_field["password$Type"] = md5($param["password$Type"]); - $insert_field['private_key'] = md5($test_cli["prenom$Type"] . time() . $test_cli["ville$Type"] . $test_cli["email$Type"] . $test_cli["codePostal$Type"]); - $APP_CLI->update_native(['private_key' => $param['private_key']], $insert_field); - - AppSocket::send_cmd('act_notify', ['msg' => "Modification terminée, nouveau mot de passe $Type "], session_id()); - $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_success.html", ['type' => $type, - 'data' => $insert_field])); - - $_SESSION["type_session"] = $type; - $_SESSION["idtype_session"] = (int)$test_cli["id$type"]; - $_SESSION["id$type"] = (int)$test_cli["id$type"]; - $_SESSION[$type] = $insert_field['private_key']; - $_SESSION[$type . "_identity"] = $test_cli["prenom$Type"] . ' ' . $test_cli["nom$Type"]; - // - $idclient = (int)$test_cli["id$type"]; - $room_client = 'client_' . $idclient; - AppSocket::send_grantIn(['room' => $room_client]); - } - echo json_encode($json_message, JSON_FORCE_OBJECT); - - } - - function register($post_vars = []) { - global $LATTE; - - $type = 'client'; - $Type = ucfirst($type); - $post_vars = array_filter($post_vars); - $param = (sizeof($post_vars) == 0) ? $_POST : $post_vars; - $failed = 0; - $empty_fields = []; - $insert_field = []; - $error_msg = []; - $json_message = ['msg' => null, - 'err' => 1, - 'success' => null]; - $allowed_fields = ['nom', - 'prenom', - 'adresse', - 'codePostal', - 'ville', - 'email', - 'password', - 'telephone']; - $required_fields = ['nom', - 'prenom', - 'password', - 'email']; - $type = 'client'; - $APP_CLI = new App($type); - // Helper::dump($param); - - foreach ($param as $key => $post) { - - $post = filter_var($post, FILTER_SANITIZE_STRING); - if (strpos($key, 'email') !== false) { - $post = filter_var($post, FILTER_VALIDATE_EMAIL); - } - - if (empty($post) && in_array($post, $required_fields)) { - $empty_fields[$key] = $post; - $failed = 1; - } else { - $param[$key] = $post; - } - } - // password idem ? - if (!empty($param['passwordClient']) && $param['passwordClient'] != $param['passwordClient_verif']) { - $json_message['msg'] = ['mauvais mot de passe' => $param['passwordClient'] . ' ' . $param['passwordClient_verif']]; - $error_msg[] = 'Mauvaise vérification du mot de passe'; - $failed = 1; - } - // EMAIL still ? - $test_email = $APP_CLI->findOne(['emailClient' => $param['emailClient']], ['_id' => 0]); - if (!empty($test_email['idclient'])) { - $failed = 1; - } - - // all ok dude ... - if ($failed == 1) { - $json_message['err'] = 1; - $json_message['success'] = null; - - if (!empty($test_email['idclient'])) { - $json_message['msg'] = 'Client existant : ' . $test_email['nomClient']; - $error_msg[] = 'Client déja existant pour cet email ' . $test_email['emailClient']; - } - if (sizeof($empty_fields) != 0) { - $json_message['msg'] = ['Erreur inconnue ' => $empty_fields]; - $error_msg[] = 'Saisie manquante '; - } - //$json_message['msg'] = ['mauvais mot de passe' => $param['passwordClient'] . ' ' . $param['passwordClient_verif']]; - //AppSocket::send_cmd('act_notify', ['msg' => 'Erreur enregistrment '.$json_message['msg']], session_id()); - NotifySite::notify_modal('Erreur enregistrement', 'error', ['mdl_vars' => ['msg_array' => $error_msg]], session_id()); - - echo json_encode($json_message, JSON_FORCE_OBJECT); - - } else { - # ok pour enregistrement - foreach ($allowed_fields as $field) { - $insert_field[$field . 'Client'] = $param[$field . 'Client']; - } - # md5 pour mot de passe - $insert_field['passwordClient'] = md5($insert_field['passwordClient']); - - $insert_field['private_key'] = md5($insert_field['prenomClient'] . time() . $insert_field['villeClient'] . $insert_field['emailClient'] . $insert_field['codePostalClient']); - - // Helper::dump($insert_field); - $json_message['msg'] = ['Client enregistré' => $insert_field]; - $json_message['success'] = 1; - $json_message['err'] = 0; - - $LATTE->setAutoRefresh(true); - if (ENVIRONEMENT != 'PREPROD_LAN') { - $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_success.html", ['type' => $type, - 'data' => $insert_field])); - - } - - $idclient = $APP_CLI->insert($insert_field); - - $_SESSION['client'] = $insert_field['private_key']; - $_SESSION['client_identity'] = $insert_field['prenomClient'] . ' ' . $insert_field['nomClient']; - - // notify ok - $room_client = 'client_' . $idclient; - AppSocket::send_grantIn(['room' => $room_client]); - //AppSocket::send_cmd('act_notify', ['msg' => 'Enregistrement ok '], $room_client); - NotifySite::notify_modal('Enregistrement validé ' . $insert_field['nomClient'], 'success', ['mdl_vars' => ['msg_array' => $error_msg]], $room_client); - - echo json_encode($json_message, JSON_FORCE_OBJECT); - - // NotifySite::notify_modal('Vérification de votre saisie', 'error', ['mdl_vars' => ['msg_array' => $json_message]],$room_client); - - return (int)$idclient; - } - - } - - function create_commande() { - - } - - function delivery_reserv($array_vars = []) { - global $LATTE; - - $idcommande = empty($array_vars['idcommande']) ? (int)$_POST['idcommande'] : (int)$array_vars['idcommande']; - - $APP_COMMANDE = new App("commande"); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $APP_LIVREUR = new App('livreur'); - - if (empty($array_vars['idlivreur'])) { - $_livreur_session = $_SESSION['livreur']; - $arr_livreur = $APP_LIVREUR->findOne(['private_key' => $_livreur_session]); - $idlivreur = (int)$arr_livreur['idlivreur']; - } else { - $arr_livreur = $APP_LIVREUR->findOne(['idlivreur' => (int)$array_vars['idlivreur']]); - $idlivreur = (int)$arr_livreur['idlivreur']; - - } - - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - $idshop = (int)$arr_commande['idshop']; - $idsecteur = (int)$arr_commande['idsecteur']; - $room_livreur = "livreur_$idlivreur"; - - if (empty($arr_commande['idlivreur'])) { - // nombre de commandes en cours !! - $max_commande = 1; - $test_max_commande = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), - 'idlivreur' => $idlivreur, - 'codeCommande_statut' => ['$nin' => ['END']]]); - $test_max_commande_before = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), - 'idsecteur' => $idsecteur, - 'idlivreur' => ['$in' => ['', - null, - 0]], - 'codeCommande_statut' => ['$nin' => ['END']]])->sort(['timeFinPreparationCommande' => 1]); - $test_max_commande_prefin = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), - 'idsecteur' => $idsecteur, - 'idlivreur' => $idlivreur, - 'codeCommande_statut' => ['$in' => ['PREFIN']]])->sort(['timeFinPreparationCommande' => 1]); - // - $arr_test_first = $test_max_commande_before->getNext(); - - if ($arr_test_first['idcommande'] != $idcommande) { - //NotifySite::notify_modal('Merci de prendre la premiere commande disponible', 'error', null, $room_livreur); - - return false; - } - //Helper::dump(iterator_to_array($test_max_commande)); - if ($test_max_commande->count() >= $max_commande) { - NotifySite::notify_idae('trop de commandes ou commande en cours', 'alert', null); - - return false; - } - $insert_field = []; - // statut + livreur - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'RESERV']); - if ((int)$arr_commande['ordreCommande_statut'] < (int)$arr_commande_statut['ordreCommande_statut']) { - // statut "reserv" seulement si pas deja avancée - $insert_field['idcommande_statut'] = (int)$arr_commande_statut['idcommande_statut']; - $insert_field['ordreCommande_statut'] = (int)$arr_commande_statut['ordreCommande_statut']; - $insert_field['codeCommande_statut'] = 'RESERV'; - - } - $insert_field['idlivreur'] = $idlivreur; - $insert_field['timeFinPreparationCommande']; - - return $idcommande; - - } else { - $msg = "Un livreur est déja affecté à cette commande"; - $icon = "ban"; - echo $data_html = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/admin/admin_delivery_command_reserv.html", ['msg' => $msg, - 'icon' => $icon])); - - return false; - } - - return false; - } - - // - function commande_charge($arr_vars = []) { - - $arr_vars = array_filter($arr_vars); - $param = (sizeof($arr_vars) == 0) ? $_POST : $arr_vars; - $param = array_merge($param, json_decode($_SESSION['commande_data'] ?: "{}", JSON_OBJECT_AS_ARRAY)); - - $Cart = new Cart(session_id()); - $arr_cart = $Cart->get_cart(); - - $param = $this->commande_filter_vars($param); - $pre_test = $this->commande_test_info($param); - - if (!empty($pre_test['err'])) { - - NotifySite::notify_modal('Erreur', 'alert', ['mdl_vars' => ['msg_array' => $pre_test['msg']]], session_id()); - - return false; - } - - if ($this->commande_set_info($param) != false) { - $APP_COMMANDE = new App('commande'); - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$this->currentCommande]); - - $parameters['api_key'] = "pk_test_uTCUev6Hzay5EyoYM5fmeRjw"; - $parameters['scr_api_key'] = "sk_test_V46Tk6DpdrbX2nkk4EH7hOLn"; - $cart_centimes = $arr_cart['cart_total'] * 100; - \Stripe\Stripe::setApiKey($parameters['scr_api_key']); - $token = $param['stripeToken']; - - $charge = \Stripe\Charge::create(['amount' => $cart_centimes, - 'currency' => 'eur', - 'source' => $token, - 'metadata' => ['orderId' => $ARR_COMMANDE['codeCommande']], - 'receipt_email' => $param['emailCommande']]); - - if (empty($ARR_COMMANDE['demo_mode'])) { - $table = 'commande'; - $table_value = (int)$this->currentCommande; - $Table = ucfirst($table); - - $Idae = new Idae($table); - $AppMail = new AppMail(); - $instyle = new InStyle(); - $Idae->consolidate_scheme($table_value); - $ARR_COMMANDE = $Idae->findOne(["id$table" => (int)$table_value]); - $Body = $instyle->convert($Idae->fiche_mail($table_value), true); - $AppMail->set_body($Body); - $AppMail->set_destinataire_email($ARR_COMMANDE["email$Table"]); - $AppMail->set_destinataire_name($ARR_COMMANDE["prenom$Table"] . ' ' . $ARR_COMMANDE["nom$Table"]); - $AppMail->set_subject('Votre commande ' . $ARR_COMMANDE["code$Table"] . ' avec TAC-TAC'); - $AppMail->sendMail(); - - } - $return = ['success' => HTTPCUSTOMERSITE . 'commande/commande_end']; - $this->send_data($return); - } else { - // on fail - $return = ['error' => "Une erreur a eu lieu"]; - $this->send_data($return); - } - - } - - function commande_filter_vars($param = []) { - - foreach ($param as $key => $post) { - - $post = filter_var(trim($post), FILTER_SANITIZE_STRING); - if (strpos($key, 'telephone') !== false) { - $post = filter_var($post, FILTER_SANITIZE_NUMBER_INT); - } - if (strpos($key, 'email') !== false) { - $post = filter_var($post, FILTER_VALIDATE_EMAIL); - } - - $param[$key] = $post; - } - - return $param; - } - - function commande_test_info($arr_vars = []) { - $APP_SHOP = new App('shop'); - - $arr_vars = array_filter($arr_vars); - - if (empty($_SESSION['commande_data'])) { - $json_message['err'] = 1; - $json_message['msg'][] = 'pas de commande en cours'; - } - if (sizeof($arr_vars) == 0) { - $json_message['err'] = 1; - $json_message['msg'][] = 'Auncun parametre'; - } - if (sizeof($arr_vars) == 0) { - $json_message['err'] = 1; - $json_message['msg'][] = 'Le panier est vide'; - } - - if (sizeof(json_decode($_SESSION['commande_data'], JSON_OBJECT_AS_ARRAY)) == 0) { - $json_message['err'] = 1; - $json_message['msg'][] = 'La commande est vide'; - } - - if ($arr_vars['demo_mode']) { - $Cart = new Cart('client_demo_' . $arr_vars['idclient']); - $arr_cart = $Cart->get_cart(); - } else { - $Cart = new Cart(); - $arr_cart = $Cart->get_cart(); - } - - $idshop = (int)$arr_cart['idshop']; - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $idsecteur = (int)$ARR_SHOP['idsecteur']; - - $param = $arr_vars; - $json_message = []; - $failed = 0; - $empty_fields = []; - $insert_field = []; - - $required_fields = ['nom', - 'prenom', - 'telephone', - 'adresse', - 'codePostal', - 'ville']; - - foreach ($param as $key => $post) { - - $post = filter_var(trim($post), FILTER_SANITIZE_STRING); - if (strpos($key, 'telephone') !== false) { - $post = filter_var($post, FILTER_SANITIZE_NUMBER_INT); - } - if (strpos($key, 'email') !== false) { - $post = filter_var($post, FILTER_VALIDATE_EMAIL); - } - - if (empty($post) && in_array($key, $required_fields)) { - $empty_fields[$key] = $post; - $json_message['err'] = 1; - $json_message['msg'][] = 'Un champ est manquant : ' . $key; - } else { - $param[$key] = $post; - } - } - - NB_MAX_COMMANDE_SECTEUR_LIVREUR; - - $nb_liv_affect = CommandeQueue::secteur_has_livreur_count($idsecteur); - $nb_commande_wait = CommandeQueue::shop_commande_queue_count($idshop); - - if (($nb_liv_affect * NB_MAX_COMMANDE_SECTEUR_LIVREUR) <= $nb_commande_wait) { - $json_message['err'] = 1; - $json_message['msg'][] = 'Commande impossible actuellement, trop de commandes actuellement en cours pour nos coursiers'; - } - - if ($nb_commande_wait > NB_MAX_COMMANDE_SHOP) { - $json_message['err'] = 1; - $json_message['msg'][] = 'Commande impossible, trop de commandes actuellement en cours'; - } - - $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; - $NOW = date('H:i:s'); - $APP_SH_J = new App('shop_jours'); - $APP_SH_J_SHIFT = new App('shop_jours_shift'); - $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, - 'ordreJours' => $index_jour]); - $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, - 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], - 'actifShop_jours_shift' => 1, - 'heureDebutShop_jours_shift' => ['$lte' => $NOW], - 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); - if (sizeof($arr_sh_shift) != 0) { - $insert_field['idshop_jours_shift'] = (int)$arr_sh_shift[0]['idshop_jours_shift']; - } else { - $json_message['err'] = 1; - $json_message['msg'][] = 'Aune disponibilité restaurant actuellement'; - - } - - return $json_message; - - } - - function commande_set_info($arr_vars = []) { - - $arr_vars = array_filter($arr_vars); - - $param = (sizeof($arr_vars) == 0) ? $_POST : $arr_vars; - $json_message = ['err' => 0, - 'msg' => 'good']; - $failed = 0; - $empty_fields = []; - $insert_field = []; - $allowed_fields = ['nom', - 'prenom', - 'telephone', - 'email', - 'adresse', - 'adresse2', - 'codePostal', - 'ville']; - $required_fields = ['nom', - 'prenom', - 'telephone', - 'adresse', - 'codePostal', - 'ville']; - - $BIN = new Bin(); - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_LIGNE = new App('commande_ligne'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $APP_CLI = new App('client'); - - foreach ($param as $key => $post) { - - $post = filter_var(trim($post), FILTER_SANITIZE_STRING); - if (strpos($key, 'telephone') !== false) { - $post = filter_var($post, FILTER_SANITIZE_NUMBER_INT); - } - if (strpos($key, 'email') !== false) { - $post = filter_var($post, FILTER_VALIDATE_EMAIL); - } - - if (empty($post) && in_array($key, $required_fields)) { - $empty_fields[$key] = $post; - $failed = 1; - } else { - $param[$key] = $post; - } - } - - // all ok dude ... - if ($failed == 1) { - if (sizeof($empty_fields) != 0) { - // Helper::dump($empty_fields); - $json_message = ['err' => 1, - 'msg' => $empty_fields]; - } - $json_message = ['err' => 1, - 'msg' => 'bad champ manquand']; - Helper::dump($json_message); - - return false; - } else { - # - global $LATTE; - # ok pour enregistrement - foreach ($allowed_fields as $field) { - $insert_field[$field . 'Commande'] = $param[$field . 'Commande']; - } - - if ($arr_vars['idclient']) { - $test_cli = $APP_CLI->findOne(['idclient' => (int)$arr_vars['idclient']]); - } else { - $test_cli = $APP_CLI->findOne(['private_key' => $_SESSION['client']]); - } - - // commande_ligne, shop, secteur, produit => from cart - if ($arr_vars['demo_mode']) { - $Cart = new Cart('client_demo_' . $arr_vars['idclient']); - $arr_cart = $Cart->get_cart(); - } else { - $Cart = new Cart(); - $arr_cart = $Cart->get_cart(); - } - - $duree_realisationCommande = DUREE_REALISATION_COMMANDE;// de la prise de commande à la livraison, en minutes - $time_preparation_commande = TIME_PREPARATION_COMMANDE;// rand(4, 7); - $temps_livraison = TEMPS_LIVRAISON_COMMANDE;// rand(4, 7); - - $idshop = (int)$arr_cart['idshop']; - $idsecteur = (int)$arr_cart['idsecteur']; - $idclient = (int)$test_cli['idclient']; - - $nb_commande_wait = CommandeQueue::shop_commande_queue_count($idshop);//$BIN->shop_commande_queue($idshop); - $json_message['infoenplus'] = $nb_commande_wait; - $json_message['infoenplus_encore'] = NB_MAX_COMMANDE_SHOP; - // AppSocket::send_cmd('act_notify', ['msg' => 'test_livreur_affect_free '.sizeof($arr_liv_free).' pour '.$idshop],"secteur_$idsecteur"); - if ($nb_commande_wait > NB_MAX_COMMANDE_SHOP) { - $json_message['err'] = 1; - $json_message['msg'] = 'trop de commandes actuellement'; - if ($arr_vars['demo_mode']) { - } else { - AppSocket::send_cmd('act_notify', ['msg' => 'Commande impossible, trop de commandes actuellement en cours '], session_id()); - } - - return false; - } - ++$nb_commande_wait; - $ordreCommande = $nb_commande_wait; - - $insert_field['idclient'] = $idclient; - $insert_field['dateCommande'] = date('Y-m-d'); - $insert_field['dateCreationCommande'] = date('Y-m-d'); - $insert_field['heureCommande'] = date('H:i:00'); - $insert_field['timeCommande'] = time(); - $insert_field['timeCreationCommande'] = time(); - $insert_field['heureCreationCommande'] = date('H:i:s'); - $insert_field['idshop'] = (int)$arr_cart['idshop']; - $insert_field['idsecteur'] = (int)$arr_cart['idsecteur']; - $insert_field['volumeCommande'] = $arr_cart['cart_total_volume']; - $insert_field['duree_realisationCommande'] = $duree_realisationCommande;//(int)$arr_cart['cart_total_time']; - $insert_field['prixCommande'] = (float)$arr_cart['cart_total']; - $insert_field['prixServiceCommande'] = (float)$arr_cart['cart_sous_total']; - $insert_field['rangCommande'] = "S" . $ordreCommande; - $insert_field['ordreCommande'] = $ordreCommande; - if ($arr_vars['demo_mode']) { - $insert_field['demo_mode'] = $arr_vars['demo_mode']; - $insert_field['dureeLivraisonCommande'] = rand(180, 600); - $insert_field['distanceCommande'] = rand(600, 3000); - } - // - if (empty($idshop)) { - return false; - } - // - // shift ? - $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; - $NOW = date('H:i:s'); - $APP_SHOP = new App('shop'); - $APP_SH_J = new App('shop_jours'); - $APP_SH_J_SHIFT = new App('shop_jours_shift'); - $APP_SHIFT_RUN = new App('shop_jours_shift_run'); - $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, - 'ordreJours' => $index_jour]); - $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, - 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], - 'actifShop_jours_shift' => 1, - 'heureDebutShop_jours_shift' => ['$lte' => $NOW], - 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); - if (sizeof($arr_sh_shift) != 0) { - $insert_field['idshop_jours_shift'] = (int)$arr_sh_shift[0]['idshop_jours_shift']; - } else { - // Aucun shifts !!! - Helper::dump($json_message); - - return false; - } - - // statut - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'START']); - $insert_field['idcommande_statut'] = (int)$arr_commande_statut['idcommande_statut']; - $insert_field['codeCommande_statut'] = $arr_commande_statut['codeCommande_statut']; - $insert_field['nomCommande_statut'] = $arr_commande_statut['nomCommande_statut']; - $insert_field['ordreCommande_statut'] = (int)$arr_commande_statut['ordreCommande_statut']; - - # creation ou recuperation shift_run - $arr_run = ['idshop' => $idshop, - 'idshop_jours_shift' => $insert_field['idshop_jours_shift'], - 'dateDebutShop_jours_shift_run' => date('Y-m-d'), - 'nomShop_jours_shift_run' => date('d-m-Y'), - 'heureDebutShop_jours_shift_run' => $arr_sh_shift[0]['heureDebutShop_jours_shift']]; - // - $idshift_run = $APP_SHIFT_RUN->create_update($arr_run); - $insert_field['idshop_jours_shift_run'] = $idshift_run; - - // fin de préparation - // $attentePreparationCommande = $nb_commande_wait + 1; - // $time_prep = ($time_preparation_commande * 60) * $attentePreparationCommande; - - $insert_field = array_merge($insert_field); - // suivant le nombre de livreur disponibles, voire en attente ( RESERV ) - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => $idshop]); - $cou = $APP_COMMANDE->find(['idshop' => (int)$arr_cart['idshop'], - 'dateCreationCommande' => date('Y-m-d')])->count(); - $count_secteur = $APP_COMMANDE->find(['idsecteur' => (int)$ARR_SHOP['idsecteur'], - 'dateCreationCommande' => date('Y-m-d')])->count(); - ++$cou; - ++$count_secteur; - $num_padded = sprintf("%02d", $cou); - $referenceCommande = sprintf("%03d", $count_secteur); - $codeCommande_facture = date('my') . '-' . $referenceCommande; - $insert_field['codeCommande'] = date('dmy') . '-' . $num_padded . '-' . substr($ARR_SHOP['codeShop'], 0, 3); - $insert_field['referenceCommande'] = "#$referenceCommande"; - - $insert_field['tempsAnnonceCommande'] = CommandeQueue::shop_next_slot($idshop); - /** - * INSERTION COMMANDE - */ - $idcommande = $APP_COMMANDE->insert($insert_field); - $insert_field_more = $BIN->getCommande_queue_periods($idcommande); - $APP_COMMANDE->update(['idcommande' => $idcommande], $insert_field_more); - ClassRangCommande::updateRangShopCommandes($idshop); - $CommandeSlot = new CommandeSlot($idsecteur); - $CommandeSlot->distribute($idsecteur); - - $time_prep = $insert_field_more['timeFinPreparationCommande'] - time(); - - // $APP_COMMANDE->consolidate_scheme($idcommande); - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - - # lignes de commandes - foreach ($arr_cart['cart_lines'] as $cart_line) { - $ins_ligne['idcommande'] = $idcommande; - $ins_ligne['idshop'] = (int)$arr_cart['idshop']; - $ins_ligne['idclient'] = (int)$test_cli['idclient']; - $ins_ligne['idproduit'] = (int)$cart_line['id']['idproduit']; - $ins_ligne['nomProduit'] = $cart_line['id']['nomProduit']; - $ins_ligne['prixCommande_ligne'] = $cart_line['id']['prix_siteProduit']; - $ins_ligne['quantiteCommande_ligne'] = $cart_line['qte']; - $ins_ligne['descriptionCommande_ligne'] = $cart_line['description']; - $ins_ligne['totalCommande_ligne'] = $cart_line['qte'] * $cart_line['id']['prix_siteProduit']; - $idligne_commande = $APP_COMMANDE_LIGNE->insert($ins_ligne); - $APP_COMMANDE_LIGNE->consolidate_scheme($idligne_commande); - } - $_SESSION['commande'] = $idcommande; - $this->currentCommande = $idcommande; - // register commande charges repartitions - $APP_CMD_FACT = new App('commande_facture'); - $charges = AppCharges::get_commandeParts($insert_field['prixCommande'], $insert_field['prixServiceCommande']); - - $vars_charge = array_merge($charges, ['idshop' => $idshop, - 'idcommande' => $idcommande, - 'codeCommande_facture' => $codeCommande_facture, - 'dateCommande_facture' => date('Y-m-d'), - 'heureCommande_facture' => date('h-i-00'),]); - - $APP_CMD_FACT->insert($vars_charge); - $Dispatch = new Dispatch(); - $Dispatch->propose_commande($idcommande); - $Dispatch->propose_commande_shop($idcommande); - - //$Demo = new Demo(); - //$Demo->animate_step(['idcommande'=>$idcommande]); - - $room_sect = 'secteur_' . $idsecteur; - $room_shop = 'shop_' . $idshop; - // - $Notify = new Notify(); - $Notify->notify_commande_change($idcommande); - - SendCmd::play_sound($room_sect); - SendCmd::play_sound($room_shop); - - if (ENVIRONEMENT != 'PREPROD_LAN') { - $Cart->empty_cart("all"); - unset($_SESSION['commande_data']); - } - // demo_mode - if ($arr_vars['demo_mode']) { - // AppSocket::send_cmd('act_notify', ['msg' => 'Step livreur dans '.$time_prep, 'options' => ['sticky' => 1]]); - - AppSocket::run('act_run', ['route' => 'demo/commande_step/idcommande:' . $idcommande, - 'method' => 'POST', - 'vars' => ['mode' => 'set_ready_shop'] + $arr_commande, - 'delay' => $time_prep * 1000]);// $time_prep*100 - - } - if (ENVIRONEMENT == 'PREPROD_LAN') { - // AppSocket::send_cmd('act_notify', ['msg' => 'Nouvelle commande dans '.$time_prep, 'options' => ['sticky' => 1]]); - - } - // $_SESSION['client'] = $insert_field['private_key']; - // $_SESSION['client_identity'] = $insert_field['prenomClient'] . ' ' . $insert_field['nomClient']; - } - - return json_encode($json_message, JSON_FORCE_OBJECT); - } - - function commande_preset_info($arr_vars = []) { - $failed = 0; - $error_msg = []; - $arr_vars = array_filter($arr_vars); - $param = (sizeof($arr_vars) == 0) ? $_POST : $arr_vars; - // - $allowed_fields = ['nom', - 'prenom', - 'telephone', - 'adresse', - 'adresse2', - 'codePostal', - 'ville']; - $required_fields = ['nom', - 'prenom', - 'telephone', - 'email', - 'codePostal', - 'ville', - 'antieme']; - // verify param[email] - // $param['emailCommande'] = $param['emailClient']; - foreach ($param as $key => $post) { - $post = filter_var(trim($post), FILTER_SANITIZE_STRING); - $data_field_name = str_replace('Commande', '', $key); - if (strpos($key, 'telephone') !== false) { - $post_tmp = filter_var($post, FILTER_SANITIZE_NUMBER_INT); - if ($post_tmp != $post) { - $failed = 1; - $error_msg[] = 'Votre numéro de téléphone semble erroné'; - } else { - $post = $post_tmp; - } - } - if (strpos($key, 'email') !== false) { - $post_tmp = filter_var($post, FILTER_VALIDATE_EMAIL); - if ($post_tmp != $post) { - $failed = 1; - $error_msg[] = 'Votre email semble erroné'; - } else { - $post = $post_tmp; - } - } - - if (empty($post) && in_array($data_field_name, $required_fields)) { - $error_fields[$key] = $post; - $failed = 1; - $error_msg[] = "Le $data_field_name doit être saisie"; - } else { - $param[$key] = $post; - } - } - // email ? client - //$param['emailCommande'] = $param['emailClient']; - $APP_CLIENT = new App('client'); - $ARR_CLIENT = $APP_CLIENT->findOne(['emailClient' => $param['emailClient']]); - /*if (!empty($ARR_CLIENT['emailClient'])) { - $failed = 1; - $error_msg[] = "Client déja enregistré"; - }*/ - - if ($failed == 1) { - $json_message = ['err' => 1, - 'msg_arr' => $error_msg]; - NotifySite::notify_modal('Vérification de votre saisie', 'error', ['mdl_vars' => ['msg_array' => $error_msg]], session_id()); - $this->send_data($json_message); - - return false; - } - if (empty($_SESSION['client'])) { - AppSocket::send_cmd('act_notify_reveal', array_merge(['msg' => '$msg', - 'mdl' => '/fragment/login_multi_register', - 'type' => 'info', - 'mdl_vars' => ['type' => 'client'] + $param]), session_id()); - $_SESSION['commande_data'] = json_encode($param, JSON_FORCE_OBJECT); - // AppSocket::send_cmd('act_notify',['msg' => '', 'options'=>['sticky'=>1,'vars' => ['type'=>'client'],'type' => 'info','mdl' => '/fragment/login_multi_register']]); - $json_message = ['err' => 0, - 'msg_arr' => []]; - $this->send_data($json_message); - - } else { - $json_message = ['err' => 0, - 'msg_arr' => []]; - $_SESSION['commande_data'] = json_encode($param, JSON_FORCE_OBJECT); - if (!empty($_SESSION['client'])) { - $json_message['err'] = 2; - } - NotifySite::notify_modal('Saisie correcte', 'success', [], session_id()); - $this->send_data($json_message); - } - } - - function verify_vicinity() { - - $json_message = ['err' => 1, - 'msg' => 'bad']; - $arr_adresse = $_POST['arr_adresse']; - $APP_SHOP = new App('shop'); - $APP_SECTEUR = new App('secteur'); - $rs_sh = $APP_SHOP->find(['codePostalShop' => (string)$arr_adresse['postal_code']], ['_id' => 0]); - $arr_sh = iterator_to_array($rs_sh); - $covered = $rs_sh->count(); - $find_vars = ['gps_indexSecteur' => ['$geoIntersects' => ['$geometry' => ['type' => 'Point', - 'coordinates' => [(float)$arr_adresse['lng'], - (float)$arr_adresse['lat']]]]]]; - $rs_sec = $APP_SECTEUR->find($find_vars, ['_id' => 0]); - $find_vars['count'] = sizeof($rs_sec); - $arr_sect = $rs_sec->getNext(); - $find_vars['secteur'] = $arr_sect; - - if (!preg_match("/^([0-9]+)/", $arr_adresse['name'])) { - $json_message = ['err' => 1, - 'msg' => 'Cette adresse semble non valide']; - // NotifySite::notify_modal('Cette adresse semble non valide', ' ... '); - $this->send_data($json_message); - - return false; - } - if (!empty($arr_sect['idsecteur'])) { - $_SESSION['vicinity'] = $arr_adresse['vicinity']; - $json_message = ['err' => 0, - 'msg' => 'Adresse validée secteur ' . $arr_sect['nomSecteur'], - 'secteur' => $arr_sect]; - $this->send_data($json_message); - - return false; - } else { - $json_message = ['err' => 1, - 'msg' => 'Votre quartier de livraison nest pas encore couvert par TAC-TAC-CITY']; - $this->send_data($json_message); - - return false; - } - - $this->send_data($json_message); - } - - function send_data($json_message) { - echo json_encode($json_message, JSON_FORCE_OBJECT); - } - - function update($vars = []) { - $table = $vars[0]; - $table_value = (int)$vars[1]; - $post_vars = function_prod::cleanPostMongo($_POST['vars'], true); - if (!empty($table) && !empty($table_value)) { - - $APP_TMP = new App($table); - $APP_TMP->update(["id$table" => $table_value], $post_vars); - } - } - - function propose_commande_secteur_pool($vars = []) { - if (empty($vars['idsecteur'])) return false; - $Dispatch = new Dispatch(); - $Dispatch->propose_commande_secteur_pool($vars['idsecteur']); - - } - - private function propose_commande_coursier($vars = []) { - - if (empty($vars['idlivreur'])) return false; - $Dispatch = new Dispatch(); - $Dispatch->propose_commande_coursier($vars['idlivreur']); - - } - - function dump() { - Helper::dump(func_get_args()); - Helper::dump($_POST); - } + $value_node) { + if (strpos($value_node, ':') === false) { + $values_params[$key_values] = $value_node; + continue; + } + $tmp_node = explode(':', $value_node); + if (sizeof($tmp_node) == 2) { + $values_params[$tmp_node[0]] = $tmp_node[1]; + } elseif (sizeof($tmp_node) == 1) { + $values_params[] = $tmp_node[0]; + } else { + $node_key = $tmp_node[0]; + unset($tmp_node[0]); + $values_params[$node_key] = array_values($tmp_node); + } + } + // + $this->$params['action']($values_params); + } + + function login() { + $table = 'client'; + $Table = ucfirst($table); + $param = $_POST; + $json_message = ['err' => '', + 'msg' => '']; + + foreach ($param as $key => $post) { + + $post = filter_var($post, FILTER_SANITIZE_STRING); + if (strpos($key, 'email') !== false) { + $post = filter_var($post, FILTER_VALIDATE_EMAIL); + } + + $param[$key] = $post; + } + + if (!empty($param['emailClient']) && !empty($param['passwordClient'])) { + + $APP_CLI = new App('client'); + $test_cli = $APP_CLI->findOne(['passwordClient' => md5($param['passwordClient']), + 'emailClient' => $param['emailClient']]); + + if (!empty($test_cli['idclient'])) { + $_SESSION['client'] = $test_cli['private_key']; + $_SESSION['client_identity'] = $test_cli['prenomClient'] . ' ' . $test_cli['nomClient']; + $json_message = ['err' => 0, + 'msg' => 'good']; + } else { + $json_message = ['err' => 1, + 'msg' => 'bad']; + } + + } + + // cart !! + $Cart = new Cart(); + $var_cart = $Cart->get_cart(); + + if (!empty($var_cart['cart_lines']) && !empty($var_cart['cart_adresse'])) { + + } + + echo json_encode($json_message, JSON_FORCE_OBJECT); + } + + function login_multi() { + global $LATTE; + + $param = $_POST; + $type = $parameters['type'] = $_POST['type']; + $Type = ucfirst($type); + $json_message = ['err' => '', + 'msg' => '']; + + foreach ($param as $key => $post) { + + $post = filter_var($post, FILTER_SANITIZE_STRING); + if (strpos($key, 'email') !== false) { + $post = filter_var($post, FILTER_VALIDATE_EMAIL); + } + + $param[$key] = $post; + } + + $login_field = ($type == 'agent') ? "login" : "email"; + + if (!empty($param["$login_field$Type"]) && !empty($param["password$Type"])) { + + $APP_CLI = new App($type); + + $test_cli = $APP_CLI->findOne(["password$Type" => md5($param["password$Type"]), + "$login_field$Type" => $param["$login_field$Type"]]); + if (empty($test_cli["id$type"])) { + $test_cli = $APP_CLI->findOne(["password$Type" => trim($param["password$Type"]), + "$login_field$Type" => trim($param["$login_field$Type"])]); + if (!empty($test_cli["id$type"])) { + $test_cli['private_key'] = md5($test_cli['password' . $Type] . $test_cli['dateCreation' . ucfirst($type)]); + $APP_CLI->update(["id$type" => (int)$test_cli["id$type"]], ['private_key' => $test_cli['private_key']]); + } + } + if (!empty($test_cli["id$type"])) { + unset($_SESSION["client"], $_SESSION["livreur"], $_SESSION["shop"]); + + $IdaeSession = IdaeSession::getInstance(); + $IdaeSession->setSession($type, $test_cli); + + $session = $IdaeSession->get_session(); + + /*$_SESSION["type_session"] = $type; + $_SESSION["idtype_session"] = (int)$test_cli["id$type"]; + $_SESSION["id$type"] = (int)$test_cli["id$type"]; + $_SESSION[$type] = $test_cli['private_key']; + $_SESSION[$type . "_identity"] = $test_cli["prenom$Type"] . ' ' . $test_cli["nom$Type"];*/ + + $json_message = ['err' => 0, + 'msg' => 'good', + 'json' => json_encode($_SESSION)]; + + # join socket pour publication + AppSocket::send_grantIn(['room' => $type . "_" . $test_cli["id$type"]]); // room personnelle de type shop_7 + if ($type == 'livreur') { + $APP_AFF = new App('livreur_affectation'); + $test_aff = $APP_AFF->findOne(["idlivreur" => (int)$test_cli["id$type"], + 'dateDebutLivreur_affectation' => date('Y-M-D')]); + if (!empty($test_aff["idsecteur"])) { + AppSocket::send_grantIn(['room' => "secteur_" . $test_aff["idsecteur"]]); // room secteur + + } + } + $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_success.html", ['type' => $type, + 'data' => $test_cli])); + $json_message['type'] = $type; + } else { + + $json_message = ['err' => 1, + 'msg' => "L'adresse mail ou le mot de passe ne sont pas reconnus"]; + $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_fail.html", ['type' => $type, + 'data' => $test_cli, + 'msg' => "L'adresse mail ou le mot de passe ne sont pas reconnus"])); + + } + + } + + echo json_encode($json_message, JSON_FORCE_OBJECT); + } + + function room_reconnect() { + if (!empty($_SESSION["type_session"])) { + $type = $_SESSION["type_session"]; + $Type = ucfirst($type); + $name_idtype = "id$type"; + $idtype = (int)$_SESSION["idtype_session"]; + $APP_SESSION = new App($type); + $test = $APP_SESSION->findOne([$name_idtype => $idtype]); + if (empty($test[$name_idtype])) return; + AppSocket::send_grantIn(['room' => 'room_' . $type], session_id()); // room total de type shop agent livreur + AppSocket::send_grantIn(['room' => $type . "_" . $test["id$type"]], session_id()); // room personnelle de type shop_7 agent_1 livreur_3 + if ($type == 'livreur') { + $APP_AFF = new App('livreur_affectation'); + $test_aff = $APP_AFF->findOne(["idlivreur" => (int)$test["id$type"], + 'dateDebutLivreur_affectation' => date('Y-M-D')]); + if (!empty($test["idsecteur"])) { + AppSocket::send_grantIn(['room' => "secteur_" . $test["idsecteur"]], session_id()); + } + //NotifySite::notify_idae('send_grantIn livreur'); + } + //NotifySite::notify_idae('Vous êtes connecté !!'); + } + } + + function logout() { + unset($_SESSION['client'], $_SESSION['client_identity']); + } + + function login_multi_retrieve() { + include_once(APPCLASSES . 'ClassSMTP.php'); + global $LATTE; + $param = $_POST; + $type = $_POST['type']; + $Type = ucfirst($type); + $tmp_ssid = session_id(); + $APP_CLI = new App($type); + + $failed = 0; + $json_message = ['msg' => null, + 'err' => 1, + 'success' => null]; + AppSocket::send_cmd('act_notify', ['msg' => 'Recherche du mail utilisateur'], session_id()); + $test_cli = $APP_CLI->findOne(["email$Type" => $param["email$Type"]]); + if (empty($test_cli["id$type"])) { + $json_message['err'] = 1; + $json_message['success'] = null; + $json_message['msg'] = 'Erreur enregistrement non trouvé '; + + AppSocket::send_cmd('act_notify', ['msg' => 'Erreur enregistrement non trouvé '], session_id()); + + echo json_encode($json_message, JSON_FORCE_OBJECT); + + } else { + AppSocket::send_cmd('act_notify', ['msg' => 'Envoi du mail'], session_id()); + + $private_key = $test_cli['private_key']; + $link = HTTPCUSTOMERSITE . "page/login_init/$type/{$private_key}"; + $body = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_init_mail.html", ['type' => $type, + 'Type' => $Type, + 'link' => $link, + 'data' => $test_cli, + 'msg' => "Votre mot de passe"])); + + $mail = new PHPMailer(); + + $mail->IsSMTP(); + $mail->IsHTML(); + $mail->WordWrap = 50; + $mail->SMTPDebug = 0; + $mail->SMTPAuth = true; + $mail->SMTPOptions = [ // PREPROD ? + 'ssl' => ['verify_peer' => false, + 'verify_peer_name' => false, + 'allow_self_signed' => true]]; + $mail->CharSet = 'UTF-8'; + $mail->Hostname = SMTPDOMAIN; + $mail->Helo = SMTPDOMAIN; + $mail->Host = SMTPHOST; + $mail->Username = SMTPUSER; + $mail->Password = SMTPPASS; + $mail->SetFrom(SMTPUSER, 'postmaster tac-tac'); + // $mail->AddReplyTo($_POST['emailFrom'] , $_POST['emailFromName']); + $mail->Subject = "Récupération de votre mot de passe"; + $mail->AltBody = strip_tags($body); + $mail->AddAddress($test_cli["email$Type"], 'destinataire'); + + $mail->MsgHTML($body); + + if (!$mail->Send()) { + AppSocket::send_cmd('act_notify', ['msg' => 'Erreur envoi'], session_id()); + echo "Mailer Error: " . $mail->ErrorInfo; + } else { + $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_retrieve_send.html", ['type' => $type, + 'Type' => $Type, + 'link' => $link, + 'data' => $test_cli, + 'msg' => "Votre mot de passe"])); + $json_message['err'] = 0; + $json_message['success'] = 1; + $json_message['type'] = $type; + $json_message['msg'] = 'Enregistrement trouvé ! '; + $json_message['msg_key'] = $test_cli['private_key']; + + AppSocket::send_cmd('act_notify', ['msg' => 'Email envoyé !'], session_id()); + + echo json_encode($json_message, JSON_FORCE_OBJECT); + } + } + } + + function logout_multi() { + global $LATTE; + $type = $_POST['type']; + $tmp_ssid = session_id(); + $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_dead.html", ['type' => $type])); + echo json_encode($json_message, JSON_FORCE_OBJECT); + + unset($_SESSION[$type], $_SESSION[$type . '_identity']); + // Détruit toutes les variables de session + $_SESSION = []; + + if (ini_get("session.use_cookies")) { + $params = session_get_cookie_params(); + setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]); + } + + session_destroy(); + AppSocket::send_cmd('act_script', ['script' => 'post_logout_shop', + 'arguments' => [], + 'options' => []], $tmp_ssid); + } + + function register_again($post_vars = []) { + global $LATTE; + + $post_vars = array_filter($post_vars); + $param = (sizeof($post_vars) == 0) ? $_POST : $post_vars; + $failed = 0; + $empty_fields = []; + $insert_field = []; + $json_message = ['msg' => null, + 'err' => 1, + 'success' => null]; + $allowed_fields = ['nom', + 'prenom', + 'adresse', + 'codePostal', + 'ville', + 'email', + 'password']; + $type = empty($post_vars['type']) ? 'client' : $post_vars['type']; + $Type = ucfirst($type); + $APP_CLI = new App($type); + + foreach ($param as $key => $post) { + $post = filter_var($post, FILTER_SANITIZE_STRING); + if (strpos($key, 'email') !== false) { + $post = filter_var($post, FILTER_VALIDATE_EMAIL); + } + + if (empty($post)) { + $empty_fields[$key] = $post; + $failed = 1; + } else { + $param[$key] = $post; + } + } + + if ($param["password$Type"] != $param["password$Type" . "_verif"]) { + $json_message['msg'] = ['mauvais mot de passe' => $param["password$Type"]]; + $failed = 1; + } + $test_cli = $APP_CLI->findOne(['private_key' => $param['private_key']], ['_id' => 0]); + if (empty($test_cli["id$type"])) { + $json_message['msg'] = ["$Type absent pour clef " => $param['private_key']]; + $failed = 1; + } + if ($failed == 0) { + $json_message['err'] = 0; + $insert_field["password$Type"] = md5($param["password$Type"]); + $insert_field['private_key'] = md5($test_cli["prenom$Type"] . time() . $test_cli["ville$Type"] . $test_cli["email$Type"] . $test_cli["codePostal$Type"]); + $APP_CLI->update_native(['private_key' => $param['private_key']], $insert_field); + + AppSocket::send_cmd('act_notify', ['msg' => "Modification terminée, nouveau mot de passe $Type "], session_id()); + $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_success.html", ['type' => $type, + 'data' => $insert_field])); + + $_SESSION["type_session"] = $type; + $_SESSION["idtype_session"] = (int)$test_cli["id$type"]; + $_SESSION["id$type"] = (int)$test_cli["id$type"]; + $_SESSION[$type] = $insert_field['private_key']; + $_SESSION[$type . "_identity"] = $test_cli["prenom$Type"] . ' ' . $test_cli["nom$Type"]; + // + $idclient = (int)$test_cli["id$type"]; + $room_client = 'client_' . $idclient; + AppSocket::send_grantIn(['room' => $room_client]); + } + echo json_encode($json_message, JSON_FORCE_OBJECT); + + } + + function register($post_vars = []) { + global $LATTE; + + $type = 'client'; + $Type = ucfirst($type); + $post_vars = array_filter($post_vars); + $param = (sizeof($post_vars) == 0) ? $_POST : $post_vars; + $failed = 0; + $empty_fields = []; + $insert_field = []; + $error_msg = []; + $json_message = ['msg' => null, + 'err' => 1, + 'success' => null]; + $allowed_fields = ['nom', + 'prenom', + 'adresse', + 'codePostal', + 'ville', + 'email', + 'password', + 'telephone']; + $required_fields = ['nom', + 'prenom', + 'password', + 'email']; + $type = 'client'; + $APP_CLI = new App($type); + // Helper::dump($param); + + foreach ($param as $key => $post) { + + $post = filter_var($post, FILTER_SANITIZE_STRING); + if (strpos($key, 'email') !== false) { + $post = filter_var($post, FILTER_VALIDATE_EMAIL); + } + + if (empty($post) && in_array($post, $required_fields)) { + $empty_fields[$key] = $post; + $failed = 1; + } else { + $param[$key] = $post; + } + } + // password idem ? + if (!empty($param['passwordClient']) && $param['passwordClient'] != $param['passwordClient_verif']) { + $json_message['msg'] = ['mauvais mot de passe' => $param['passwordClient'] . ' ' . $param['passwordClient_verif']]; + $error_msg[] = 'Mauvaise vérification du mot de passe'; + $failed = 1; + } + // EMAIL still ? + $test_email = $APP_CLI->findOne(['emailClient' => $param['emailClient']], ['_id' => 0]); + if (!empty($test_email['idclient'])) { + $failed = 1; + } + + // all ok dude ... + if ($failed == 1) { + $json_message['err'] = 1; + $json_message['success'] = null; + + if (!empty($test_email['idclient'])) { + $json_message['msg'] = 'Client existant : ' . $test_email['nomClient']; + $error_msg[] = 'Client déja existant pour cet email ' . $test_email['emailClient']; + } + if (sizeof($empty_fields) != 0) { + $json_message['msg'] = ['Erreur inconnue ' => $empty_fields]; + $error_msg[] = 'Saisie manquante '; + } + //$json_message['msg'] = ['mauvais mot de passe' => $param['passwordClient'] . ' ' . $param['passwordClient_verif']]; + //AppSocket::send_cmd('act_notify', ['msg' => 'Erreur enregistrment '.$json_message['msg']], session_id()); + NotifySite::notify_modal('Erreur enregistrement', 'error', ['mdl_vars' => ['msg_array' => $error_msg]], session_id()); + + echo json_encode($json_message, JSON_FORCE_OBJECT); + + } else { + # ok pour enregistrement + foreach ($allowed_fields as $field) { + $insert_field[$field . 'Client'] = $param[$field . 'Client']; + } + # md5 pour mot de passe + $insert_field['passwordClient'] = md5($insert_field['passwordClient']); + + $insert_field['private_key'] = md5($insert_field['prenomClient'] . time() . $insert_field['villeClient'] . $insert_field['emailClient'] . $insert_field['codePostalClient']); + + // Helper::dump($insert_field); + $json_message['msg'] = ['Client enregistré' => $insert_field]; + $json_message['success'] = 1; + $json_message['err'] = 0; + + $LATTE->setAutoRefresh(true); + if (ENVIRONEMENT != 'PREPROD_LAN') { + $json_message['data_html'] = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/login_multi_success.html", ['type' => $type, + 'data' => $insert_field])); + + } + + $idclient = $APP_CLI->insert($insert_field); + + $_SESSION['client'] = $insert_field['private_key']; + $_SESSION['client_identity'] = $insert_field['prenomClient'] . ' ' . $insert_field['nomClient']; + + // notify ok + $room_client = 'client_' . $idclient; + AppSocket::send_grantIn(['room' => $room_client]); + //AppSocket::send_cmd('act_notify', ['msg' => 'Enregistrement ok '], $room_client); + NotifySite::notify_modal('Enregistrement validé ' . $insert_field['nomClient'], 'success', ['mdl_vars' => ['msg_array' => $error_msg]], $room_client); + + echo json_encode($json_message, JSON_FORCE_OBJECT); + + // NotifySite::notify_modal('Vérification de votre saisie', 'error', ['mdl_vars' => ['msg_array' => $json_message]],$room_client); + + return (int)$idclient; + } + + } + + function create_commande() { + + } + + function delivery_reserv($array_vars = []) { + global $LATTE; + + $idcommande = empty($array_vars['idcommande']) ? (int)$_POST['idcommande'] : (int)$array_vars['idcommande']; + + $APP_COMMANDE = new App("commande"); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $APP_LIVREUR = new App('livreur'); + + if (empty($array_vars['idlivreur'])) { + $_livreur_session = $_SESSION['livreur']; + $arr_livreur = $APP_LIVREUR->findOne(['private_key' => $_livreur_session]); + $idlivreur = (int)$arr_livreur['idlivreur']; + } else { + $arr_livreur = $APP_LIVREUR->findOne(['idlivreur' => (int)$array_vars['idlivreur']]); + $idlivreur = (int)$arr_livreur['idlivreur']; + + } + + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + $idshop = (int)$arr_commande['idshop']; + $idsecteur = (int)$arr_commande['idsecteur']; + $room_livreur = "livreur_$idlivreur"; + + if (empty($arr_commande['idlivreur'])) { + // nombre de commandes en cours !! + $max_commande = 1; + $test_max_commande = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), + 'idlivreur' => $idlivreur, + 'codeCommande_statut' => ['$nin' => ['END']]]); + $test_max_commande_before = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), + 'idsecteur' => $idsecteur, + 'idlivreur' => ['$in' => ['', + null, + 0]], + 'codeCommande_statut' => ['$nin' => ['END']]])->sort(['timeFinPreparationCommande' => 1]); + $test_max_commande_prefin = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), + 'idsecteur' => $idsecteur, + 'idlivreur' => $idlivreur, + 'codeCommande_statut' => ['$in' => ['PREFIN']]])->sort(['timeFinPreparationCommande' => 1]); + // + $arr_test_first = $test_max_commande_before->getNext(); + + if ($arr_test_first['idcommande'] != $idcommande) { + //NotifySite::notify_modal('Merci de prendre la premiere commande disponible', 'error', null, $room_livreur); + + return false; + } + //Helper::dump(iterator_to_array($test_max_commande)); + if ($test_max_commande->count() >= $max_commande) { + NotifySite::notify_idae('trop de commandes ou commande en cours', 'alert', null); + + return false; + } + $insert_field = []; + // statut + livreur + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'RESERV']); + if ((int)$arr_commande['ordreCommande_statut'] < (int)$arr_commande_statut['ordreCommande_statut']) { + // statut "reserv" seulement si pas deja avancée + $insert_field['idcommande_statut'] = (int)$arr_commande_statut['idcommande_statut']; + $insert_field['ordreCommande_statut'] = (int)$arr_commande_statut['ordreCommande_statut']; + $insert_field['codeCommande_statut'] = 'RESERV'; + + } + $insert_field['idlivreur'] = $idlivreur; + $insert_field['timeFinPreparationCommande']; + + return $idcommande; + + } else { + $msg = "Un livreur est déja affecté à cette commande"; + $icon = "ban"; + echo $data_html = html_entity_decode($LATTE->renderToString(APPTPL . "fragments/admin/admin_delivery_command_reserv.html", ['msg' => $msg, + 'icon' => $icon])); + + return false; + } + + return false; + } + + // + function commande_charge($arr_vars = []) { + + $arr_vars = array_filter($arr_vars); + $param = (sizeof($arr_vars) == 0) ? $_POST : $arr_vars; + $param = array_merge($param, json_decode($_SESSION['commande_data'] ?: "{}", JSON_OBJECT_AS_ARRAY)); + + $Cart = new Cart(session_id()); + $arr_cart = $Cart->get_cart(); + + $param = $this->commande_filter_vars($param); + $pre_test = $this->commande_test_info($param); + + if (!empty($pre_test['err'])) { + + NotifySite::notify_modal('Erreur', 'alert', ['mdl_vars' => ['msg_array' => $pre_test['msg']]], session_id()); + + return false; + } + + if ($this->commande_set_info($param) != false) { + $APP_COMMANDE = new App('commande'); + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$this->currentCommande]); + + $parameters['api_key'] = "pk_test_uTCUev6Hzay5EyoYM5fmeRjw"; + $parameters['scr_api_key'] = "sk_test_V46Tk6DpdrbX2nkk4EH7hOLn"; + $cart_centimes = $arr_cart['cart_total'] * 100; + \Stripe\Stripe::setApiKey($parameters['scr_api_key']); + $token = $param['stripeToken']; + + $charge = \Stripe\Charge::create(['amount' => $cart_centimes, + 'currency' => 'eur', + 'source' => $token, + 'metadata' => ['orderId' => $ARR_COMMANDE['codeCommande']], + 'receipt_email' => $param['emailCommande']]); + + if (empty($ARR_COMMANDE['demo_mode'])) { + $table = 'commande'; + $table_value = (int)$this->currentCommande; + $Table = ucfirst($table); + + $Idae = new Idae($table); + $AppMail = new AppMail(); + $instyle = new InStyle(); + $Idae->consolidate_scheme($table_value); + $ARR_COMMANDE = $Idae->findOne(["id$table" => (int)$table_value]); + $Body = $instyle->convert($Idae->fiche_mail($table_value), true); + $AppMail->set_body($Body); + $AppMail->set_destinataire_email($ARR_COMMANDE["email$Table"]); + $AppMail->set_destinataire_name($ARR_COMMANDE["prenom$Table"] . ' ' . $ARR_COMMANDE["nom$Table"]); + $AppMail->set_subject('Votre commande ' . $ARR_COMMANDE["code$Table"] . ' avec TAC-TAC'); + $AppMail->sendMail(); + + } + $return = ['success' => HTTPCUSTOMERSITE . 'commande/commande_end']; + $this->send_data($return); + } else { + // on fail + $return = ['error' => "Une erreur a eu lieu"]; + $this->send_data($return); + } + + } + + function commande_filter_vars($param = []) { + + foreach ($param as $key => $post) { + + $post = filter_var(trim($post), FILTER_SANITIZE_STRING); + if (strpos($key, 'telephone') !== false) { + $post = filter_var($post, FILTER_SANITIZE_NUMBER_INT); + } + if (strpos($key, 'email') !== false) { + $post = filter_var($post, FILTER_VALIDATE_EMAIL); + } + + $param[$key] = $post; + } + + return $param; + } + + function commande_test_info($arr_vars = []) { + $APP_SHOP = new App('shop'); + + $arr_vars = array_filter($arr_vars); + + if (empty($_SESSION['commande_data'])) { + $json_message['err'] = 1; + $json_message['msg'][] = 'pas de commande en cours'; + } + if (sizeof($arr_vars) == 0) { + $json_message['err'] = 1; + $json_message['msg'][] = 'Auncun parametre'; + } + if (sizeof($arr_vars) == 0) { + $json_message['err'] = 1; + $json_message['msg'][] = 'Le panier est vide'; + } + + if (sizeof(json_decode($_SESSION['commande_data'], JSON_OBJECT_AS_ARRAY)) == 0) { + $json_message['err'] = 1; + $json_message['msg'][] = 'La commande est vide'; + } + + if ($arr_vars['demo_mode']) { + $Cart = new Cart('client_demo_' . $arr_vars['idclient']); + $arr_cart = $Cart->get_cart(); + } else { + $Cart = new Cart(); + $arr_cart = $Cart->get_cart(); + } + + $idshop = (int)$arr_cart['idshop']; + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $idsecteur = (int)$ARR_SHOP['idsecteur']; + + $param = $arr_vars; + $json_message = []; + $failed = 0; + $empty_fields = []; + $insert_field = []; + + $required_fields = ['nom', + 'prenom', + 'telephone', + 'adresse', + 'codePostal', + 'ville']; + + foreach ($param as $key => $post) { + + $post = filter_var(trim($post), FILTER_SANITIZE_STRING); + if (strpos($key, 'telephone') !== false) { + $post = filter_var($post, FILTER_SANITIZE_NUMBER_INT); + } + if (strpos($key, 'email') !== false) { + $post = filter_var($post, FILTER_VALIDATE_EMAIL); + } + + if (empty($post) && in_array($key, $required_fields)) { + $empty_fields[$key] = $post; + $json_message['err'] = 1; + $json_message['msg'][] = 'Un champ est manquant : ' . $key; + } else { + $param[$key] = $post; + } + } + + NB_MAX_COMMANDE_SECTEUR_LIVREUR; + + $nb_liv_affect = CommandeQueue::secteur_has_livreur_count($idsecteur); + $nb_commande_wait = CommandeQueue::shop_commande_queue_count($idshop); + + if (($nb_liv_affect * NB_MAX_COMMANDE_SECTEUR_LIVREUR) <= $nb_commande_wait) { + $json_message['err'] = 1; + $json_message['msg'][] = 'Commande impossible actuellement, trop de commandes actuellement en cours pour nos coursiers'; + } + + if ($nb_commande_wait > NB_MAX_COMMANDE_SHOP) { + $json_message['err'] = 1; + $json_message['msg'][] = 'Commande impossible, trop de commandes actuellement en cours'; + } + + $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; + $NOW = date('H:i:s'); + $APP_SH_J = new App('shop_jours'); + $APP_SH_J_SHIFT = new App('shop_jours_shift'); + $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, + 'ordreJours' => $index_jour]); + $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, + 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], + 'actifShop_jours_shift' => 1, + 'heureDebutShop_jours_shift' => ['$lte' => $NOW], + 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); + if (sizeof($arr_sh_shift) != 0) { + $insert_field['idshop_jours_shift'] = (int)$arr_sh_shift[0]['idshop_jours_shift']; + } else { + $json_message['err'] = 1; + $json_message['msg'][] = 'Aune disponibilité restaurant actuellement'; + + } + + return $json_message; + + } + + function commande_set_info($arr_vars = []) { + + $arr_vars = array_filter($arr_vars); + + $param = (sizeof($arr_vars) == 0) ? $_POST : $arr_vars; + $json_message = ['err' => 0, + 'msg' => 'good']; + $failed = 0; + $empty_fields = []; + $insert_field = []; + $allowed_fields = ['nom', + 'prenom', + 'telephone', + 'email', + 'adresse', + 'adresse2', + 'codePostal', + 'ville']; + $required_fields = ['nom', + 'prenom', + 'telephone', + 'adresse', + 'codePostal', + 'ville']; + + $BIN = new Bin(); + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_LIGNE = new App('commande_ligne'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $APP_CLI = new App('client'); + + foreach ($param as $key => $post) { + + $post = filter_var(trim($post), FILTER_SANITIZE_STRING); + if (strpos($key, 'telephone') !== false) { + $post = filter_var($post, FILTER_SANITIZE_NUMBER_INT); + } + if (strpos($key, 'email') !== false) { + $post = filter_var($post, FILTER_VALIDATE_EMAIL); + } + + if (empty($post) && in_array($key, $required_fields)) { + $empty_fields[$key] = $post; + $failed = 1; + } else { + $param[$key] = $post; + } + } + + // all ok dude ... + if ($failed == 1) { + if (sizeof($empty_fields) != 0) { + // Helper::dump($empty_fields); + $json_message = ['err' => 1, + 'msg' => $empty_fields]; + } + $json_message = ['err' => 1, + 'msg' => 'bad champ manquand']; + Helper::dump($json_message); + + return false; + } else { + # + global $LATTE; + # ok pour enregistrement + foreach ($allowed_fields as $field) { + $insert_field[$field . 'Commande'] = $param[$field . 'Commande']; + } + + if ($arr_vars['idclient']) { + $test_cli = $APP_CLI->findOne(['idclient' => (int)$arr_vars['idclient']]); + } else { + $test_cli = $APP_CLI->findOne(['private_key' => $_SESSION['client']]); + } + + // commande_ligne, shop, secteur, produit => from cart + if ($arr_vars['demo_mode']) { + $Cart = new Cart('client_demo_' . $arr_vars['idclient']); + $arr_cart = $Cart->get_cart(); + } else { + $Cart = new Cart(); + $arr_cart = $Cart->get_cart(); + } + + $duree_realisationCommande = DUREE_REALISATION_COMMANDE;// de la prise de commande à la livraison, en minutes + $time_preparation_commande = TIME_PREPARATION_COMMANDE;// rand(4, 7); + $temps_livraison = TEMPS_LIVRAISON_COMMANDE;// rand(4, 7); + + $idshop = (int)$arr_cart['idshop']; + $idsecteur = (int)$arr_cart['idsecteur']; + $idclient = (int)$test_cli['idclient']; + + $nb_commande_wait = CommandeQueue::shop_commande_queue_count($idshop);//$BIN->shop_commande_queue($idshop); + $json_message['infoenplus'] = $nb_commande_wait; + $json_message['infoenplus_encore'] = NB_MAX_COMMANDE_SHOP; + // AppSocket::send_cmd('act_notify', ['msg' => 'test_livreur_affect_free '.sizeof($arr_liv_free).' pour '.$idshop],"secteur_$idsecteur"); + if ($nb_commande_wait > NB_MAX_COMMANDE_SHOP) { + $json_message['err'] = 1; + $json_message['msg'] = 'trop de commandes actuellement'; + if ($arr_vars['demo_mode']) { + } else { + AppSocket::send_cmd('act_notify', ['msg' => 'Commande impossible, trop de commandes actuellement en cours '], session_id()); + } + + return false; + } + ++$nb_commande_wait; + $ordreCommande = $nb_commande_wait; + + $insert_field['idclient'] = $idclient; + $insert_field['dateCommande'] = date('Y-m-d'); + $insert_field['dateCreationCommande'] = date('Y-m-d'); + $insert_field['heureCommande'] = date('H:i:00'); + $insert_field['timeCommande'] = time(); + $insert_field['timeCreationCommande'] = time(); + $insert_field['heureCreationCommande'] = date('H:i:s'); + $insert_field['idshop'] = (int)$arr_cart['idshop']; + $insert_field['idsecteur'] = (int)$arr_cart['idsecteur']; + $insert_field['volumeCommande'] = $arr_cart['cart_total_volume']; + $insert_field['duree_realisationCommande'] = $duree_realisationCommande;//(int)$arr_cart['cart_total_time']; + $insert_field['prixCommande'] = (float)$arr_cart['cart_total']; + $insert_field['prixServiceCommande'] = (float)$arr_cart['cart_sous_total']; + $insert_field['rangCommande'] = "S" . $ordreCommande; + $insert_field['ordreCommande'] = $ordreCommande; + if ($arr_vars['demo_mode']) { + $insert_field['demo_mode'] = $arr_vars['demo_mode']; + $insert_field['dureeLivraisonCommande'] = rand(180, 600); + $insert_field['distanceCommande'] = rand(600, 3000); + } + // + if (empty($idshop)) { + return false; + } + // + // shift ? + $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; + $NOW = date('H:i:s'); + $APP_SHOP = new App('shop'); + $APP_SH_J = new App('shop_jours'); + $APP_SH_J_SHIFT = new App('shop_jours_shift'); + $APP_SHIFT_RUN = new App('shop_jours_shift_run'); + $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, + 'ordreJours' => $index_jour]); + $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, + 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], + 'actifShop_jours_shift' => 1, + 'heureDebutShop_jours_shift' => ['$lte' => $NOW], + 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); + if (sizeof($arr_sh_shift) != 0) { + $insert_field['idshop_jours_shift'] = (int)$arr_sh_shift[0]['idshop_jours_shift']; + } else { + // Aucun shifts !!! + Helper::dump($json_message); + + return false; + } + + // statut + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'START']); + $insert_field['idcommande_statut'] = (int)$arr_commande_statut['idcommande_statut']; + $insert_field['codeCommande_statut'] = $arr_commande_statut['codeCommande_statut']; + $insert_field['nomCommande_statut'] = $arr_commande_statut['nomCommande_statut']; + $insert_field['ordreCommande_statut'] = (int)$arr_commande_statut['ordreCommande_statut']; + + # creation ou recuperation shift_run + $arr_run = ['idshop' => $idshop, + 'idshop_jours_shift' => $insert_field['idshop_jours_shift'], + 'dateDebutShop_jours_shift_run' => date('Y-m-d'), + 'nomShop_jours_shift_run' => date('d-m-Y'), + 'heureDebutShop_jours_shift_run' => $arr_sh_shift[0]['heureDebutShop_jours_shift']]; + // + $idshift_run = $APP_SHIFT_RUN->create_update($arr_run); + $insert_field['idshop_jours_shift_run'] = $idshift_run; + + // fin de préparation + // $attentePreparationCommande = $nb_commande_wait + 1; + // $time_prep = ($time_preparation_commande * 60) * $attentePreparationCommande; + + $insert_field = array_merge($insert_field); + // suivant le nombre de livreur disponibles, voire en attente ( RESERV ) + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => $idshop]); + $cou = $APP_COMMANDE->find(['idshop' => (int)$arr_cart['idshop'], + 'dateCreationCommande' => date('Y-m-d')])->count(); + $count_secteur = $APP_COMMANDE->find(['idsecteur' => (int)$ARR_SHOP['idsecteur'], + 'dateCreationCommande' => date('Y-m-d')])->count(); + ++$cou; + ++$count_secteur; + $num_padded = sprintf("%02d", $cou); + $referenceCommande = sprintf("%03d", $count_secteur); + $codeCommande_facture = date('my') . '-' . $referenceCommande; + $insert_field['codeCommande'] = date('dmy') . '-' . $num_padded . '-' . substr($ARR_SHOP['codeShop'], 0, 3); + $insert_field['referenceCommande'] = "#$referenceCommande"; + + $insert_field['tempsAnnonceCommande'] = CommandeQueue::shop_next_slot($idshop); + /** + * INSERTION COMMANDE + */ + $idcommande = $APP_COMMANDE->insert($insert_field); + $insert_field_more = $BIN->getCommande_queue_periods($idcommande); + $APP_COMMANDE->update(['idcommande' => $idcommande], $insert_field_more); + ClassRangCommande::updateRangShopCommandes($idshop); + $CommandeSlot = new CommandeSlot($idsecteur); + $CommandeSlot->distribute($idsecteur); + + $time_prep = $insert_field_more['timeFinPreparationCommande'] - time(); + + // $APP_COMMANDE->consolidate_scheme($idcommande); + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + + # lignes de commandes + foreach ($arr_cart['cart_lines'] as $cart_line) { + $ins_ligne['idcommande'] = $idcommande; + $ins_ligne['idshop'] = (int)$arr_cart['idshop']; + $ins_ligne['idclient'] = (int)$test_cli['idclient']; + $ins_ligne['idproduit'] = (int)$cart_line['id']['idproduit']; + $ins_ligne['nomProduit'] = $cart_line['id']['nomProduit']; + $ins_ligne['prixCommande_ligne'] = $cart_line['id']['prix_siteProduit']; + $ins_ligne['quantiteCommande_ligne'] = $cart_line['qte']; + $ins_ligne['descriptionCommande_ligne'] = $cart_line['description']; + $ins_ligne['totalCommande_ligne'] = $cart_line['qte'] * $cart_line['id']['prix_siteProduit']; + $idligne_commande = $APP_COMMANDE_LIGNE->insert($ins_ligne); + $APP_COMMANDE_LIGNE->consolidate_scheme($idligne_commande); + } + $_SESSION['commande'] = $idcommande; + $this->currentCommande = $idcommande; + // register commande charges repartitions + $APP_CMD_FACT = new App('commande_facture'); + $charges = AppCharges::get_commandeParts($insert_field['prixCommande'], $insert_field['prixServiceCommande']); + + $vars_charge = array_merge($charges, ['idshop' => $idshop, + 'idcommande' => $idcommande, + 'codeCommande_facture' => $codeCommande_facture, + 'dateCommande_facture' => date('Y-m-d'), + 'heureCommande_facture' => date('h-i-00'),]); + + $APP_CMD_FACT->insert($vars_charge); + $Dispatch = new Dispatch(); + $Dispatch->propose_commande($idcommande); + $Dispatch->propose_commande_shop($idcommande); + + //$Demo = new Demo(); + //$Demo->animate_step(['idcommande'=>$idcommande]); + + $room_sect = 'secteur_' . $idsecteur; + $room_shop = 'shop_' . $idshop; + // + $Notify = new Notify(); + $Notify->notify_commande_change($idcommande); + + SendCmd::play_sound($room_sect); + SendCmd::play_sound($room_shop); + + if (ENVIRONEMENT != 'PREPROD_LAN') { + $Cart->empty_cart("all"); + unset($_SESSION['commande_data']); + } + // demo_mode + if ($arr_vars['demo_mode']) { + // AppSocket::send_cmd('act_notify', ['msg' => 'Step livreur dans '.$time_prep, 'options' => ['sticky' => 1]]); + + AppSocket::run('act_run', ['route' => 'demo/commande_step/idcommande:' . $idcommande, + 'method' => 'POST', + 'vars' => ['mode' => 'set_ready_shop'] + $arr_commande, + 'delay' => $time_prep * 1000]);// $time_prep*100 + + } + if (ENVIRONEMENT == 'PREPROD_LAN') { + // AppSocket::send_cmd('act_notify', ['msg' => 'Nouvelle commande dans '.$time_prep, 'options' => ['sticky' => 1]]); + + } + // $_SESSION['client'] = $insert_field['private_key']; + // $_SESSION['client_identity'] = $insert_field['prenomClient'] . ' ' . $insert_field['nomClient']; + } + + return json_encode($json_message, JSON_FORCE_OBJECT); + } + + function commande_preset_info($arr_vars = []) { + $failed = 0; + $error_msg = []; + $arr_vars = array_filter($arr_vars); + $param = (sizeof($arr_vars) == 0) ? $_POST : $arr_vars; + // + $allowed_fields = ['nom', + 'prenom', + 'telephone', + 'adresse', + 'adresse2', + 'codePostal', + 'ville']; + $required_fields = ['nom', + 'prenom', + 'telephone', + 'email', + 'codePostal', + 'ville', + 'antieme']; + // verify param[email] + // $param['emailCommande'] = $param['emailClient']; + foreach ($param as $key => $post) { + $post = filter_var(trim($post), FILTER_SANITIZE_STRING); + $data_field_name = str_replace('Commande', '', $key); + if (strpos($key, 'telephone') !== false) { + $post_tmp = filter_var($post, FILTER_SANITIZE_NUMBER_INT); + if ($post_tmp != $post) { + $failed = 1; + $error_msg[] = 'Votre numéro de téléphone semble erroné'; + } else { + $post = $post_tmp; + } + } + if (strpos($key, 'email') !== false) { + $post_tmp = filter_var($post, FILTER_VALIDATE_EMAIL); + if ($post_tmp != $post) { + $failed = 1; + $error_msg[] = 'Votre email semble erroné'; + } else { + $post = $post_tmp; + } + } + + if (empty($post) && in_array($data_field_name, $required_fields)) { + $error_fields[$key] = $post; + $failed = 1; + $error_msg[] = "Le $data_field_name doit être saisie"; + } else { + $param[$key] = $post; + } + } + // email ? client + //$param['emailCommande'] = $param['emailClient']; + $APP_CLIENT = new App('client'); + $ARR_CLIENT = $APP_CLIENT->findOne(['emailClient' => $param['emailClient']]); + /*if (!empty($ARR_CLIENT['emailClient'])) { + $failed = 1; + $error_msg[] = "Client déja enregistré"; + }*/ + + if ($failed == 1) { + $json_message = ['err' => 1, + 'msg_arr' => $error_msg]; + NotifySite::notify_modal('Vérification de votre saisie', 'error', ['mdl_vars' => ['msg_array' => $error_msg]], session_id()); + $this->send_data($json_message); + + return false; + } + if (empty($_SESSION['client'])) { + AppSocket::send_cmd('act_notify_reveal', array_merge(['msg' => '$msg', + 'mdl' => '/fragment/login_multi_register', + 'type' => 'info', + 'mdl_vars' => ['type' => 'client'] + $param]), session_id()); + $_SESSION['commande_data'] = json_encode($param, JSON_FORCE_OBJECT); + // AppSocket::send_cmd('act_notify',['msg' => '', 'options'=>['sticky'=>1,'vars' => ['type'=>'client'],'type' => 'info','mdl' => '/fragment/login_multi_register']]); + $json_message = ['err' => 0, + 'msg_arr' => []]; + $this->send_data($json_message); + + } else { + $json_message = ['err' => 0, + 'msg_arr' => []]; + $_SESSION['commande_data'] = json_encode($param, JSON_FORCE_OBJECT); + if (!empty($_SESSION['client'])) { + $json_message['err'] = 2; + } + NotifySite::notify_modal('Saisie correcte', 'success', [], session_id()); + $this->send_data($json_message); + } + } + + function verify_vicinity() { + + $json_message = ['err' => 1, + 'msg' => 'bad']; + $arr_adresse = $_POST['arr_adresse']; + $APP_SHOP = new App('shop'); + $APP_SECTEUR = new App('secteur'); + $rs_sh = $APP_SHOP->find(['codePostalShop' => (string)$arr_adresse['postal_code']], ['_id' => 0]); + $arr_sh = iterator_to_array($rs_sh); + $covered = $rs_sh->count(); + $find_vars = ['gps_indexSecteur' => ['$geoIntersects' => ['$geometry' => ['type' => 'Point', + 'coordinates' => [(float)$arr_adresse['lng'], + (float)$arr_adresse['lat']]]]]]; + $rs_sec = $APP_SECTEUR->find($find_vars, ['_id' => 0]); + $find_vars['count'] = sizeof($rs_sec); + $arr_sect = $rs_sec->getNext(); + $find_vars['secteur'] = $arr_sect; + + if (!preg_match("/^([0-9]+)/", $arr_adresse['name'])) { + $json_message = ['err' => 1, + 'msg' => 'Cette adresse semble non valide']; + // NotifySite::notify_modal('Cette adresse semble non valide', ' ... '); + $this->send_data($json_message); + + return false; + } + if (!empty($arr_sect['idsecteur'])) { + $_SESSION['vicinity'] = $arr_adresse['vicinity']; + $json_message = ['err' => 0, + 'msg' => 'Adresse validée secteur ' . $arr_sect['nomSecteur'], + 'secteur' => $arr_sect]; + $this->send_data($json_message); + + return false; + } else { + $json_message = ['err' => 1, + 'msg' => 'Votre quartier de livraison nest pas encore couvert par TAC-TAC-CITY']; + $this->send_data($json_message); + + return false; + } + + $this->send_data($json_message); + } + + function send_data($json_message) { + echo json_encode($json_message, JSON_FORCE_OBJECT); + } + + function update($vars = []) { + $table = $vars[0]; + $table_value = (int)$vars[1]; + $post_vars = function_prod::cleanPostMongo($_POST['vars'], true); + if (!empty($table) && !empty($table_value)) { + + $APP_TMP = new App($table); + $APP_TMP->update(["id$table" => $table_value], $post_vars); + } + } + + function propose_commande_secteur_pool($vars = []) { + if (empty($vars['idsecteur'])) return false; + $Dispatch = new Dispatch(); + $Dispatch->propose_commande_secteur_pool($vars['idsecteur']); + + } + + private function propose_commande_coursier($vars = []) { + + if (empty($vars['idlivreur'])) return false; + $Dispatch = new Dispatch(); + $Dispatch->propose_commande_coursier($vars['idlivreur']); + + } + + function dump() { + Helper::dump(func_get_args()); + Helper::dump($_POST); + } } \ No newline at end of file diff --git a/web/bin/classes/ClassActionPost.php b/web/bin/classes/ClassActionPost.php index 1dd0daa..7aae88d 100644 --- a/web/bin/classes/ClassActionPost.php +++ b/web/bin/classes/ClassActionPost.php @@ -1,139 +1,139 @@ -table; - $Table = ucfirst($this->table); - - $update_vars['dateCreation' . ucfirst($table)] = date('Y-m-d'); - $update_vars['heureCreation' . ucfirst($table)] = date('H:i:s'); - $update_vars['timeCreation' . ucfirst($table)] = time(); - // - $vars = empty($update_vars) ? [] : function_prod::cleanPostMongo($update_vars, 1); - // INSERT - $APP_TABLE = new App($table); - $table_value = $APP_TABLE->insert($vars); - $arr = $APP_TABLE->findOne(["id$table" => $table_value]); - AppSocket::send_cmd('act_add_data', $arr, 'OWN'); - - if (sizeof($arr) != 0) { - SendCmd::notify_mdl('app_fiche_mini', $table, $arr["id$table"], [], session_id()); - } - - echo json_encode($arr, JSON_FORCE_OBJECT); - } - - function app_update($table, $table_value, $arr_one = []) { - if (empty($table_value)) { - return; - } - $table_value = (int)$table_value; - $name_id = "id$table"; - $Table = ucfirst($table); - - $arr_new = $this->findOne([$name_id => $table_value]); - - $Dispatch = new Dispatch(); - $Notify = new Notify(); - $Bin = new Bin(); - - switch ($table) { - case 'commande': - $codeStatut = $arr_new['code' . $Table . '_statut']; - - // livreur dé-assignation - if (empty($arr_one['idlivreur']) && !empty($arr_new['idlivreur'])) { - $Dispatch->remove_propose_commande($table_value); - } - // changement de statut - if (!empty($arr_one['idcommande_statut'])) { - // si vrai changement - if ($arr_one[$name_id . '_statut'] <> $arr_new[$name_id . '_statut']) { - $Dispatch->propose_commande_statut($table_value); - if (ENVIRONEMENT != 'PREPROD_LAN') { - $Dispatch->propose_commande_sound($table_value); - } - $data_reload = "idae/fiche_next_statut/$table/$table_value"; - - AppSocket::reloadModule($data_reload, $table_value); - ClassRangCommande::updateRangShopCommandes($arr_one['idshop']); - $CommandeSlot = new CommandeSlot($arr_one['idsecteur']); - $CommandeSlot->distribute($arr_one['idsecteur']); - } - - if (ENVIRONEMENT == 'PREPROD_LAN') { - /*if ($codeStatut == 'RESERV') { - AppSocket::run('act_run' , [ 'route' => 'demo/commande_step_statut/idcommande:' . $table_value , - 'method' => 'POST' , - 'delay' => 3000 ]); - }*/ - } - if ($codeStatut == 'LIVENCOU' && ($arr_one['demo_mode'] != 1) && ENVIRONEMENT != 'PREPROD_LAN') { - // sms !!! - $apiKey = "9635f9c81664a3d549b4e76f1211963a7595bc88"; - $smspartner = new SMSPartnerAPI(false); - $result = $smspartner->checkCredits("?apiKey=$apiKey"); - $phoneNumber = ($arr_one['demo_mode'] == 1) ? '0688096140' : $arr_one['telephoneCommande']; // 0615956796 - - //send SMS - $fields = ["apiKey" => $apiKey, - "phoneNumbers" => $phoneNumber, - "message" => "La livraison de votre commande est en cours", - "sender" => "TACTACITY"]; - - $result = $smspartner->sendSms($fields); - } - if ($codeStatut == 'END') { - $Dispatch->remove_commande($table_value); - } - } - - if (!empty($_POST['data-reload'])) { - $data_reload = !empty($_POST['data-reload']) ? $_POST['data-reload'] : "idae/fiche_next_statut/$table/$table_value"; - AppSocket::reloadModule($data_reload, $table_value); - } - - $Demo = new Demo(); - $Demo->animate_step(['idcommande' => $table_value]); - - if (ENVIRONEMENT == 'PREPROD_LAN') { - if (!empty($arr_one['idlivreur'])) { - /*AppSocket::run('act_run' , [ 'route' => 'demo/commande_step_statut/idcommande:' . $table_value , - 'method' => 'POST' , - 'delay' => 120000 ]);*/ - } - } - - break; - - case 'livreur_affectation': - if ($table == 'livreur_affectation' && isset($arr_new['actifLivreur_affectation']) && isset($arr_new['idsecteur'])) { - $Notify->notify_livreur_affect($arr_new['idsecteur']); - } - break; - case 'shop': - if ($table == 'shop' && isset($arr_new['tempsAttenteShop']) && isset($arr_new['idsecteur'])) { - $Notify->notify_wait_time_secteur($arr_new['idsecteur']); - } - break; - } - - if ($_POST['data-remove']) { - AppSocket::reloadModule($_POST['data-remove'], $table_value); - } - } - - } +table; + $Table = ucfirst($this->table); + + $update_vars['dateCreation' . ucfirst($table)] = date('Y-m-d'); + $update_vars['heureCreation' . ucfirst($table)] = date('H:i:s'); + $update_vars['timeCreation' . ucfirst($table)] = time(); + // + $vars = empty($update_vars) ? [] : function_prod::cleanPostMongo($update_vars, 1); + // INSERT + $APP_TABLE = new App($table); + $table_value = $APP_TABLE->insert($vars); + $arr = $APP_TABLE->findOne(["id$table" => $table_value]); + AppSocket::send_cmd('act_add_data', $arr, 'OWN'); + + if (sizeof($arr) != 0) { + SendCmd::notify_mdl('app_fiche_mini', $table, $arr["id$table"], [], session_id()); + } + + echo json_encode($arr, JSON_FORCE_OBJECT); + } + + function app_update($table, $table_value, $arr_one = []) { + if (empty($table_value)) { + return; + } + $table_value = (int)$table_value; + $name_id = "id$table"; + $Table = ucfirst($table); + + $arr_new = $this->findOne([$name_id => $table_value]); + + $Dispatch = new Dispatch(); + $Notify = new Notify(); + $Bin = new Bin(); + + switch ($table) { + case 'commande': + $codeStatut = $arr_new['code' . $Table . '_statut']; + + // livreur dé-assignation + if (empty($arr_one['idlivreur']) && !empty($arr_new['idlivreur'])) { + $Dispatch->remove_propose_commande($table_value); + } + // changement de statut + if (!empty($arr_one['idcommande_statut'])) { + // si vrai changement + if ($arr_one[$name_id . '_statut'] <> $arr_new[$name_id . '_statut']) { + $Dispatch->propose_commande_statut($table_value); + if (ENVIRONEMENT != 'PREPROD_LAN') { + $Dispatch->propose_commande_sound($table_value); + } + $data_reload = "idae/fiche_next_statut/$table/$table_value"; + + AppSocket::reloadModule($data_reload, $table_value); + ClassRangCommande::updateRangShopCommandes($arr_one['idshop']); + $CommandeSlot = new CommandeSlot($arr_one['idsecteur']); + $CommandeSlot->distribute($arr_one['idsecteur']); + } + + if (ENVIRONEMENT == 'PREPROD_LAN') { + /*if ($codeStatut == 'RESERV') { + AppSocket::run('act_run' , [ 'route' => 'demo/commande_step_statut/idcommande:' . $table_value , + 'method' => 'POST' , + 'delay' => 3000 ]); + }*/ + } + if ($codeStatut == 'LIVENCOU' && ($arr_one['demo_mode'] != 1) && ENVIRONEMENT != 'PREPROD_LAN') { + // sms !!! + $apiKey = "9635f9c81664a3d549b4e76f1211963a7595bc88"; + $smspartner = new SMSPartnerAPI(false); + $result = $smspartner->checkCredits("?apiKey=$apiKey"); + $phoneNumber = ($arr_one['demo_mode'] == 1) ? '0688096140' : $arr_one['telephoneCommande']; // 0615956796 + + //send SMS + $fields = ["apiKey" => $apiKey, + "phoneNumbers" => $phoneNumber, + "message" => "La livraison de votre commande est en cours", + "sender" => "TACTACITY"]; + + $result = $smspartner->sendSms($fields); + } + if ($codeStatut == 'END') { + $Dispatch->remove_commande($table_value); + } + } + + if (!empty($_POST['data-reload'])) { + $data_reload = !empty($_POST['data-reload']) ? $_POST['data-reload'] : "idae/fiche_next_statut/$table/$table_value"; + AppSocket::reloadModule($data_reload, $table_value); + } + + $Demo = new Demo(); + $Demo->animate_step(['idcommande' => $table_value]); + + if (ENVIRONEMENT == 'PREPROD_LAN') { + if (!empty($arr_one['idlivreur'])) { + /*AppSocket::run('act_run' , [ 'route' => 'demo/commande_step_statut/idcommande:' . $table_value , + 'method' => 'POST' , + 'delay' => 120000 ]);*/ + } + } + + break; + + case 'livreur_affectation': + if ($table == 'livreur_affectation' && isset($arr_new['actifLivreur_affectation']) && isset($arr_new['idsecteur'])) { + $Notify->notify_livreur_affect($arr_new['idsecteur']); + } + break; + case 'shop': + if ($table == 'shop' && isset($arr_new['tempsAttenteShop']) && isset($arr_new['idsecteur'])) { + $Notify->notify_wait_time_secteur($arr_new['idsecteur']); + } + break; + } + + if ($_POST['data-remove']) { + AppSocket::reloadModule($_POST['data-remove'], $table_value); + } + } + + } diff --git a/web/bin/classes/ClassAdmin.php b/web/bin/classes/ClassAdmin.php index 260ecdc..c1dced1 100644 --- a/web/bin/classes/ClassAdmin.php +++ b/web/bin/classes/ClassAdmin.php @@ -1,147 +1,147 @@ -$params['action']($params['value']); - } else { - $this->$params['action'](explode('/', $params['value'])); - } - } - - function entrance($type = 'shop') { - - $type = ($type == 'livreur') ? 'delivery' : $type; - $session_swift = ($type == 'delivery') ? 'livreur' : $type; - $Type = ucfirst($type); - $template_main = "admin_$type"; - # active page - if (empty($_SESSION[$session_swift])) { - // login fragment - $_GET['type'] = ($type == 'delivery') ? 'livreur' : $type; - $this->Fragment = new Fragment(); - $this->Page = new Page(); - if (in_array($session_swift, ['livreur', 'shop','agent'])) { - $this->Page->set_page("application"); - $this->Page->login_multi(['type' => $session_swift]); - } else { - $template_main = "application"; - $this->render($this->Fragment->idae_login_multi(true)); - } - - /*AppSocket::send_cmd('act_script', ['script' => 'post_login_multi', - 'arguments' => $type , - 'options' => []],session_id());*/ - - return; - - } - - switch ($type) { - case "delivery": - case "livreur": - $livreur_private_key = $_SESSION['livreur']; - - $APP_LIVREUR = new IdaeDB('livreur'); - $APP_AFF = new IdaeDB('livreur_affectation'); - - $parameters['var_livreur'] = $arr_livreur = $APP_LIVREUR->findOne(['private_key' => $livreur_private_key], ['_id' => 0]); - $idlivreur = (int)$arr_livreur['idlivreur']; - - $test_aff = $APP_AFF->findOne(["idlivreur" => (int)$idlivreur, 'dateDebutLivreur_affectation' => date('Y-m-d')]); - - $Idae = new Idae('commande'); - $parameters['arr_statut'] = $Idae->liste_statut(['codeCommande_statut' => ['$nin' => ['RESERV']]]);// ['codeCommande_statut'=>['$in'=>['','','']]] - $parameters['html_menu_top'] = $Idae->module('app_gui/app_menu_top'); - AppSocket::send_cmd('act_notify', ['msg' => $type], session_id()); - - AppSocket::send_grantIn(['room' => "livreur_" . $idlivreur]); // room personnelle de type shop_7 - /*if (empty($test_aff['idsecteur'])) die("Aucun secteur");*/ - $idsecteur = (int)$test_aff['idsecteur']; - AppSocket::send_grantIn(['room' => "secteur_" . $idsecteur]); // room personnelle de type shop_7 - - break; - case "shop": - $shop_private_key = $_SESSION['shop']; - - $APP_SHOP = new IdaeDB('shop'); - $BIN = new Bin(); - - $parameters['var_shop'] = $arr_shop = $APP_SHOP->findOne(['private_key' => $shop_private_key], ['_id' => 0]); - $idshop = (int)$arr_shop['idshop']; - $parameters['idshop '] = $idshop; - $parameters['livreur_affect'] = sizeof($BIN->test_livreur_affect($arr_shop['idsecteur'])); - $parameters['livreur_affect_free'] = sizeof($BIN->test_livreur_affect_free($arr_shop['idsecteur'])); - $parameters['commande_shop'] = sizeof($BIN->test_commande_shop($idshop)); - $parameters['commande_shop_wait'] = sizeof($BIN->test_commande_shop_wait($idshop)); - $parameters['commande_shop_livencou'] = sizeof($BIN->test_commande_shop_livencou($idshop)); - - $Idae = new Idae('commande'); - $parameters['html_menu_top'] = $Idae->module('app_gui/app_menu_top'); - $parameters['arr_statut'] = $Idae->liste_statut(['codeCommande_statut' => ['$nin' => ['RESERV']]]);// ['codeCommande_statut'=>['$in'=>['','','']]] - - AppSocket::send_cmd('act_notify', ['msg' => $type], session_id()); - AppSocket::send_grantIn(['room' => "shop_" . $idshop]); // room personnelle de type shop_7 - break; - default: - - $session_key = $_SESSION[$type]; - $name_id_session_key = "id$type"; - $ARR_SESSION = new App($type); - $parameters['var_session'] = $arr_session = $ARR_SESSION->findOne(['private_key' => $session_key], ['_id' => 0]); - $idsession = (int)$arr_session[$name_id_session_key]; - $parameters['var_session']['type'] = $type; - $parameters['var_session']['session_key'] = $session_key; - $parameters['var_session']['Session_key'] = ucfirst($session_key); - $parameters['var_session']['name_id_session_key'] = $name_id_session_key; - $parameters['var_session']['idsession'] = $idsession; - $parameters['var_session']['nom'] = $parameters['var_session']["nom" . $Type]; - $parameters['var_session']['prenom'] = $parameters['var_session']["prenom" . $Type]; - - $Idae = new Idae('commande'); - $parameters['html_menu_top'] = $Idae->module('app_gui/app_menu_top'); - - AppSocket::send_cmd('act_notify', ['msg' => $type], session_id()); - AppSocket::send_grantIn(['room' => $type . "_" . $idsession]); - - $template_main = "application"; - break; - } - - $parameters['html_menu_debug'] = $Idae->module('app_dev/debug_times'); - - # active page - $this->set_page($template_main); - - global $LATTE; - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $tpl_url = ($type == 'agent') ? "idae" : 'pages'; - $LATTE->setAutoRefresh(true); - - $url = APPTPL ."/idae/application"; - $html = $LATTE->renderToString( "$url.html", $parameters); - - $this->render($html); - - } - - } +$params['action']($params['value']); + } else { + $this->$params['action'](explode('/', $params['value'])); + } + } + + function entrance($type = 'shop') { + + $type = ($type == 'livreur') ? 'delivery' : $type; + $session_swift = ($type == 'delivery') ? 'livreur' : $type; + $Type = ucfirst($type); + $template_main = "admin_$type"; + # active page + if (empty($_SESSION[$session_swift])) { + // login fragment + $_GET['type'] = ($type == 'delivery') ? 'livreur' : $type; + $this->Fragment = new Fragment(); + $this->Page = new Page(); + if (in_array($session_swift, ['livreur', 'shop','agent'])) { + $this->Page->set_page("application"); + $this->Page->login_multi(['type' => $session_swift]); + } else { + $template_main = "application"; + $this->render($this->Fragment->idae_login_multi(true)); + } + + /*AppSocket::send_cmd('act_script', ['script' => 'post_login_multi', + 'arguments' => $type , + 'options' => []],session_id());*/ + + return; + + } + + switch ($type) { + case "delivery": + case "livreur": + $livreur_private_key = $_SESSION['livreur']; + + $APP_LIVREUR = new IdaeDB('livreur'); + $APP_AFF = new IdaeDB('livreur_affectation'); + + $parameters['var_livreur'] = $arr_livreur = $APP_LIVREUR->findOne(['private_key' => $livreur_private_key], ['_id' => 0]); + $idlivreur = (int)$arr_livreur['idlivreur']; + + $test_aff = $APP_AFF->findOne(["idlivreur" => (int)$idlivreur, 'dateDebutLivreur_affectation' => date('Y-m-d')]); + + $Idae = new Idae('commande'); + $parameters['arr_statut'] = $Idae->liste_statut(['codeCommande_statut' => ['$nin' => ['RESERV']]]);// ['codeCommande_statut'=>['$in'=>['','','']]] + $parameters['html_menu_top'] = $Idae->module('app_gui/app_menu_top'); + AppSocket::send_cmd('act_notify', ['msg' => $type], session_id()); + + AppSocket::send_grantIn(['room' => "livreur_" . $idlivreur]); // room personnelle de type shop_7 + /*if (empty($test_aff['idsecteur'])) die("Aucun secteur");*/ + $idsecteur = (int)$test_aff['idsecteur']; + AppSocket::send_grantIn(['room' => "secteur_" . $idsecteur]); // room personnelle de type shop_7 + + break; + case "shop": + $shop_private_key = $_SESSION['shop']; + + $APP_SHOP = new IdaeDB('shop'); + $BIN = new Bin(); + + $parameters['var_shop'] = $arr_shop = $APP_SHOP->findOne(['private_key' => $shop_private_key], ['_id' => 0]); + $idshop = (int)$arr_shop['idshop']; + $parameters['idshop '] = $idshop; + $parameters['livreur_affect'] = sizeof($BIN->test_livreur_affect($arr_shop['idsecteur'])); + $parameters['livreur_affect_free'] = sizeof($BIN->test_livreur_affect_free($arr_shop['idsecteur'])); + $parameters['commande_shop'] = sizeof($BIN->test_commande_shop($idshop)); + $parameters['commande_shop_wait'] = sizeof($BIN->test_commande_shop_wait($idshop)); + $parameters['commande_shop_livencou'] = sizeof($BIN->test_commande_shop_livencou($idshop)); + + $Idae = new Idae('commande'); + $parameters['html_menu_top'] = $Idae->module('app_gui/app_menu_top'); + $parameters['arr_statut'] = $Idae->liste_statut(['codeCommande_statut' => ['$nin' => ['RESERV']]]);// ['codeCommande_statut'=>['$in'=>['','','']]] + + AppSocket::send_cmd('act_notify', ['msg' => $type], session_id()); + AppSocket::send_grantIn(['room' => "shop_" . $idshop]); // room personnelle de type shop_7 + break; + default: + + $session_key = $_SESSION[$type]; + $name_id_session_key = "id$type"; + $ARR_SESSION = new App($type); + $parameters['var_session'] = $arr_session = $ARR_SESSION->findOne(['private_key' => $session_key], ['_id' => 0]); + $idsession = (int)$arr_session[$name_id_session_key]; + $parameters['var_session']['type'] = $type; + $parameters['var_session']['session_key'] = $session_key; + $parameters['var_session']['Session_key'] = ucfirst($session_key); + $parameters['var_session']['name_id_session_key'] = $name_id_session_key; + $parameters['var_session']['idsession'] = $idsession; + $parameters['var_session']['nom'] = $parameters['var_session']["nom" . $Type]; + $parameters['var_session']['prenom'] = $parameters['var_session']["prenom" . $Type]; + + $Idae = new Idae('commande'); + $parameters['html_menu_top'] = $Idae->module('app_gui/app_menu_top'); + + AppSocket::send_cmd('act_notify', ['msg' => $type], session_id()); + AppSocket::send_grantIn(['room' => $type . "_" . $idsession]); + + $template_main = "application"; + break; + } + + $parameters['html_menu_debug'] = $Idae->module('app_dev/debug_times'); + + # active page + $this->set_page($template_main); + + global $LATTE; + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $tpl_url = ($type == 'agent') ? "idae" : 'pages'; + $LATTE->setAutoRefresh(true); + + $url = APPTPL ."/idae/application"; + $html = $LATTE->renderToString( "$url.html", $parameters); + + $this->render($html); + + } + + } diff --git a/web/bin/classes/ClassApp.php b/web/bin/classes/ClassApp.php index eb7eaac..d029436 100644 --- a/web/bin/classes/ClassApp.php +++ b/web/bin/classes/ClassApp.php @@ -1,2151 +1,2151 @@ -__construct($table); - } - - /** - * App constructor. - * @deprecated - * - * @param string $table - */ - public function __construct($table = '') { - global $app_conn_nb; - global $PERSIST_CON; - // - if (!defined('MDB_USER')) { - return 'Utilisateur DB non defini'; - } - parent::__construct(); - $this->conn = IdaeConnect::getInstance()->connect(); - - $sitebase_app = MDB_PREFIX . 'sitebase_app'; - $sitebase_sockets = MDB_PREFIX . 'sitebase_sockets'; - - $this->table = $table; - $this->app_conn = $this->conn->$sitebase_app->appscheme; - $this->appscheme = $this->conn->$sitebase_app->appscheme; - $this->appscheme_type = $this->conn->$sitebase_app->appscheme_type; - $this->appscheme_base = $this->conn->$sitebase_app->appscheme_base; - $this->appscheme_field = $this->conn->$sitebase_app->appscheme_field; - $this->appscheme_field_type = $this->conn->$sitebase_app->appscheme_field_type; - $this->appscheme_field_group = $this->conn->$sitebase_app->appscheme_field_group; - $this->appscheme_has_field = $this->conn->$sitebase_app->appscheme_has_field; - $this->appscheme_has_table_field = $this->conn->$sitebase_app->appscheme_has_table_field; - $this->APPCACHE = $this->conn->$sitebase_sockets->data_activity; - - if (!empty($table)) { - $this->app_table_one = $this->app_conn->findOne(['codeAppscheme' => $table]); // si pas reg ? - $this->app_field_name_id = 'id' . $table; - $this->app_field_name_id_type = 'id' . $table . '_type'; - $this->app_field_name_nom = $this->app_table_one['nomAppscheme']; - $this->app_field_name_nom_type = 'nom' . ucfirst($table) . '_type'; - $this->app_field_name_top = 'estTop' . ucfirst($table); - $this->app_field_name_actif = 'estActif' . ucfirst($table); - $this->idappscheme = (int)$this->app_table_one['idappscheme']; - $this->codeAppscheme = $this->app_table_one['codeAppscheme']?? ''; - $this->iconAppscheme = $this->app_table_one['iconAppscheme']?? ''; - $this->colorAppscheme = $this->app_table_one['colorAppscheme'] ?? ''; - $this->nomAppscheme = $this->app_table_one['nomAppscheme']; - $this->codeAppscheme_base = $this->app_table_one['codeAppscheme_base']; - $this->app_table_icon = $this->app_table_one['icon'] ?? ''; - $this->grilleFK = $this->app_table_one['grilleFK'] ?? []; - $this->hasImageScheme = $this->app_table_one['hasImageScheme'] ?? ''; - } - - $this->app_default_fields_add = ['petitNom', - 'nom', - 'bgcolor', - 'code', - 'color', - 'icon', - 'ordre', - 'slug', - 'actif']; - $this->app_default_fields = ['nom' => '', - 'prenom' => '', - 'petitNom' => 'nom court', - 'code' => '', - 'reference' => 'reference', - 'description' => '', - 'quantite' => '', - 'prix' => '', - 'total' => '', - 'atout' => '', - 'valeur' => '', - 'rang' => '', - 'dateCreation' => 'crée le', - 'dateDebut' => 'date debut', - 'dateFin' => 'date de fin', - 'duree' => '', - 'heure' => '', - 'email' => '', - 'telephone' => '', - 'fax' => '', - 'adresse' => '', - 'url' => '', - 'totalHt' => 'total HT', - 'totalTtc' => 'total TTC', - 'totalMarge' => 'total Marge', - 'totalTva' => 'total TVA', - 'ordre' => '', - 'color' => '', - 'image' => '']; - $this->app_default_group_field = ['codification' => '', - 'identification' => '', - 'date' => '', - 'prix' => '', - 'localisation' => '', - 'valeur' => '', - 'texte' => '', - 'image' => '', - 'telephonie' => '', - 'heure' => '', - 'divers' => 'Autres']; - - //$this->make_classes_app(); - } - - public static function getInstance($table = '') { - - if (is_null(self::$_instance)) { - self::$_instance = new App($table); - } - - return self::$_instance; - } - - /** - * @ todo generate Entity, Controller, Repository - * @return bool - */ - function make_classes_app() { - - if (empty($this->table)) {return false;} - if (!is_string($this->table)) {return false;} - $table = $this->table; - $file_name = $table; - $path = APPCLASSES_APP . '/' . BUSINESS . '/' . CUSTOMER . '/' . $table . '/'; - foreach (['app', - 'act', - 'ui', - 'pre_act', - 'post_act'] as $key => $extension) { - $className = $file_name . '_' . $extension; - $path_and_file = $path . $className . '.php'; - // echo "
"; - if (!file_exists($path)) { - mkdir($path, 0777, true); - } - foreach (['Repository','Entity','Controller','Interface'] as $index => $item) { - if (!file_exists($path."/$item")) { - mkdir($path."/$item", 0777, true); - } - - } - if (!file_exists($path_and_file)) { - $monfichier = @fopen($path_and_file, 'a+'); - if (!$monfichier) continue; - $content = $this->write_classes_app($className, $table, $extension); - @fputs($monfichier, $content); - @fclose($monfichier); - } - - } - } - - function write_classes_app($className, $table, $type) { - // $content = file_get_contents(APP_CONFIG_DIR . 'classes_app_models/class_model_' . $type . '.php'); - $content = file_get_contents(APP_CONFIG_DIR . 'class_model.php'); - $content = str_replace('TABLE_CLASS', $table, $content); - $content = str_replace('NAME_CLASS', $className, $content); - - return $content; - } - - function rest($params = ['table', - 'action', - 'vars']) { - // - Helper::dump(func_get_args()); - - if (strpos($params['vars'], '/') === false) { - $value = $params['vars']; - - } else { - $value = explode('/', $params['vars']); - } - $new_value = array_map(function ($node) { - if (strpos($node, ':') === false) { - - return $node; - } - $tmp = explode(':', $node); - - if (strpos($tmp[0], '[]') === true) { - echo "array"; - } - - return [$tmp[0] => $tmp[1]]; - - }, $value); - Helper::dump($new_value); - $app = new App($params['table']); - - if ($params['action'] == 'remove') { - die('verboten'); - } - - $rs = $app->$params['action'](); - - echo json_encode(iterator_to_array($rs)); - // $this->$params['action']($value); - - } - - /** - * @param $table_value - * @param array $vars - * - * @return stdClass - */ - function appobj($table_value = null, $vars = []) { - - $this->obj = new stdClass(); - $this->obj->NAME_ID = 'id' . $this->app_table_one['codeAppscheme']; - $this->obj->NAME_APP = $this->app_table_one['nomAppscheme']; - $this->obj->ICON = $this->app_table_one['iconAppscheme']; - $this->obj->ICON_COLOR = $this->app_table_one['colorAppscheme']; - $this->obj->APP_TABLE = $this->app_table_one; - $this->obj->GRILLE_FK = $this->get_grille_fk(); - $this->obj->HTTP_VARS = $this->translate_vars($vars); - $this->obj->ARR_GROUP_FIELD = $this->get_field_group_list(); - $this->obj->app_default_fields = $this->app_default_fields; - $this->obj->R_FK = $this->get_reverse_grille_fk($this->app_table_one['codeAppscheme'], $table_value); - if (!empty($table_value)) { - $this->obj->ARR = $this->findOne([$this->obj->NAME_ID => (int)$table_value]); - } - - return $this->obj; - } - - function get_grille_fk_grouped($table = '', $vars = []) { - return $this->get_grille_fk($table, ['grouped_scheme' => 1]); - } - - function get_grille_fk_nongrouped($table = '', $vars = []) { - return $this->get_grille_fk($table, ['grouped_scheme' => ['$ne' => 1]]); - } - - /** - * @param string $table - * @param array $vars - * - * @return array - */ - function get_grille_fk($table = '', $vars = []) { - if (empty($table) && !empty($this->table)) { - $grille_fk = $this->grilleFK; - } elseif (empty($table)) { - $arr = $this->app_conn->findOne(array_merge(['codeAppscheme' => $table], $vars)); - $grille_fk = $arr['grilleFK']; - } - $out = []; - if (empty($grille_fk)) { - return []; - } - foreach ($grille_fk as $arr_fk): - $table_fk = $arr_fk['table']; - $index = $arr_fk['ordreTable']; - - $db_fk = $this->app_conn->findOne($vars + ['codeAppscheme' => $table_fk]); - if (!empty($db_fk['codeAppscheme_base'])): - $out[$table_fk] = ['base_fk' => $db_fk['codeAppscheme_base'], - // $out[$index] - 'collection_fk' => $db_fk['codeAppscheme'], - 'nomAppscheme' => $db_fk['nomAppscheme'], - 'codeAppscheme' => $db_fk['codeAppscheme'], - 'iconAppscheme' => $db_fk['iconAppscheme'], - 'colorAppscheme' => $db_fk['colorAppscheme'] ?? '', - 'table_fk' => $table_fk, - 'idtable_fk' => 'id' . $table_fk, - 'nomtable_fk' => 'nom' . ucfirst($table_fk), - 'icon_fk' => $db_fk['icon'] ?? '']; - endif; - endforeach; - - return $out; - } - - function set_grille_fk($fk_table) { - if (empty($this->table)) return false; - $arr['uid'] = uniqid(); - $arr['ordreTable'] = (int)(sizeof($this->get_fk_tables())) + 1; - $arr['table'] = $fk_table; - $test = $this->get_fk_tables(); - if (!in_array($fk_table, $test)) { - // do it - //vardump_async("$this->idappscheme , $this->table => $fk_table",true); - $this->plug('sitebase_app', 'appscheme')->update(['idappscheme' => $this->idappscheme], ['$push' => ['grilleFK' => $arr]]); - } - } - - function translate_vars($arr_vars = []) { - // vars to http ? - $out_vars = []; - foreach ($arr_vars as $name_vars => $value_vars): - $out_vars['vars'][$name_vars] = $value_vars; - endforeach; - - return http_build_query($out_vars); - } - - function get_field_group_list($codeGroupe = '', $qy_has_field = [], $excludedCode = []) { - $out = []; - $vars_code = empty($codeGroupe) ? [] : ['codeAppscheme_field_group' => $codeGroupe]; - $arr_field = $this->appscheme_has_field->distinct('idappscheme_field', ['codeAppscheme_field' => ['$nin' => $excludedCode]] + $qy_has_field + ['idappscheme' => $this->idappscheme]); - $arr_field_2 = $this->appscheme_field->distinct('idappscheme_field_group', ['idappscheme_field' => ['$in' => $arr_field]]); - $rsG = $this->appscheme_field_group->find($vars_code + ['idappscheme_field_group' => ['$in' => $arr_field_2]])->sort(['ordreAppscheme_field_group' => 1]); - $i = 0; - while ($arrg = $rsG->getNext()) { - - $out2 = []; - $out[(int)$i]['group'] = $arrg; - $arr_field_tmp = $this->appscheme_field->distinct('idappscheme_field', ['idappscheme_field_group' => (int)$arrg['idappscheme_field_group']]); - $rstmp_ar = $this->appscheme_has_field->find(['idappscheme' => $this->idappscheme, - 'idappscheme_field' => ['$in' => $arr_field_tmp]])->sort(['ordreAppscheme_has_field' => 1]); - - while ($arrf = $rstmp_ar->getNext()) { - // vardump_async($arrf['ordreAppscheme_has_field']); - $tmp_ar = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrf['idappscheme_field']]); - $out2[] = $tmp_ar; - - } - // $rsF = $this->appscheme_field->find(['idappscheme_field_group' => (int)$arrg['idappscheme_field_group'], 'idappscheme_field' => ['$in' => $arr_field]])->sort(['ordreAppscheme_field' => 1]); - /* while ($arrf = $rsF->getNext()) { - $tmp_ar = $this->appscheme_has_field->findOne(['idappscheme' => $this->idappscheme,'idappscheme_field'=>(int)$arrf['idappscheme_field']]); - $out2[] = $arrf; - }*/ - $out[(int)$i]['field'] = $out2; - $i++; - } - - return $out; - } - - /** - * @param $table $table_value - * @param $table_value - * - * @return array $out - */ - function get_reverse_grille_fk($table, $table_value = '', $add = []) { - $id = 'id' . $table; - $vars = $out = []; - if (!empty($table_value)): - $vars[$id] = (int)$table_value; - endif; - if (empty($add)) { - $rs = $this->app_conn->find(['grilleFK.table' => $table]); - } else { - $rs = $this->app_conn->find($add + ['grilleFK.table' => $table]); - } - - foreach ($rs as $arr): - if (empty($table_value)) { - if (str_find('_ligne', $arr['codeAppscheme_base'])) continue; - $rs_fk = $this->plug($arr['codeAppscheme_base'], $arr['codeAppscheme'])->find(); - } else { - $rs_fk = $this->plug($arr['codeAppscheme_base'], $arr['codeAppscheme'])->find([$id => (int)$table_value]); - } - - $index = $rs_fk->count(); - // - $out[$arr['codeAppscheme']] = $arr + ['count' => $index, - 'table' => $arr['codeAppscheme'], - 'scope' => $arr['codeAppscheme_type'], - 'icon' => $arr['icon'], - 'table_value' => $table_value - /*, 'rs_fk'=>$rs_fk*/]; - endforeach; - - return $out; - } - - /* function plug($base, $table) { - if (empty($table) || empty($base) || !defined('MDB_USER')) { - return 'choisir une base'; - } - // PREFIX HERE POUR BASE - $db = $this->plug_base($base); - $collection = $db->$table; - - return $collection; - } - - function plug_base($base) { - if (empty($base) || !defined('MDB_USER')) { - return 'choisir une base'; - } - // PREFIX HERE POUR BASE - $base = MDB_PREFIX . $base; - $db = $this->conn->$base; - - return $db; - }*/ - - function findOne($vars, $out = []) { - if (empty($this->app_table_one['codeAppscheme_base'])) { - vardump($this->table); - } - if (sizeof($out) == 0) { - $arr = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->findOne($vars); - } else { - $arr = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->findOne($vars, $out); - } - - return $arr; - } - - /** - * @param $table $table_value - * @param $table_value - * - * @return array $out - */ - function get_grille_rfk($table, $table_value = '', $add = []) { - $id = 'id' . $table; - $vars = $out = []; - if (!empty($table_value)): - $vars[$id] = (int)$table_value; - endif; - if (empty($add)) { - $rs = $this->app_conn->find(['grilleFK.table' => $table]); - } else { - $rs = $this->app_conn->find($add + ['grilleFK.table' => $table]); - } - $arr_ty = $this->appscheme->distinct('idappscheme_type', ['grilleFK.table' => $table]); - $rs_ty = $this->appscheme_type->find(['idappscheme_type' => ['$in' => $arr_ty]])->sort(['nomAppscheme_type' => 1]); - - $arr_final = []; - while ($arr_ty = $rs_ty->getNext()) { - $arr_tmp = $arr_out = []; - // - $vars_type = ['idappscheme_type' => (int)$arr_ty['idappscheme_type']]; - - if (empty($add)) { - $rs_det = $this->appscheme->find($vars_type + ['grilleFK.table' => $table]); - } else { - $rs_det = $this->appscheme->find($vars_type + $add + ['grilleFK.table' => $table]); - } - while ($arr_det = $rs_det->getNext()) { - if (empty($table_value)) { - if (str_find('_ligne', $arr_det['codeAppscheme_base'])) continue; - $rs_fk = $this->plug($arr_det['codeAppscheme_base'], $arr_det['codeAppscheme'])->find(); - } else { - $rs_fk = $this->plug($arr_det['codeAppscheme_base'], $arr_det['codeAppscheme'])->find([$id => (int)$table_value]); - } - if ($rs_fk->count() == 0) continue; - $arr_det['count'] = $rs_fk->count(); - $arr_det['table'] = $arr_det['codeAppscheme']; - $arr_tmp['appscheme'][$arr_det['codeAppscheme']] = $arr_det; - } - - if (!empty($arr_tmp['appscheme'])) { - $arr_out = array_merge($arr_ty, $arr_tmp); - $arr_final[] = $arr_out; - } - - } - - return $arr_final; - - } - - function get_table_rfk($table_value = '', $add = []) { - $table = $this->table; - $id = "id$table"; - $vars = $out = []; - if (!empty($table_value)): - $vars[$id] = (int)$table_value; - endif; - - $arr_table_rfk = $this->appscheme->distinct('codeAppscheme', $add + ['grilleFK.table' => $table]); - - return $arr_table_rfk; - } - - /** - * @param $table_value - * @param $vars - */ - function extract_vars($table_value, $vars = []) { - $out['ARR_GROUP_FIELD'] = $this->get_field_group_list(); - $out['NAME_APP'] = $this->app_table_one['nomAppscheme']; - $out['ICON'] = $this->app_table_one['iconAppscheme']; - $out['ICON_COLOR'] = $this->app_table_one['colorAppscheme']; - $out['APP_TABLE'] = $this->app_table_one; - $out['GRILLE_FK'] = $this->get_grille_fk($this->app_table_one['codeAppscheme']); - $out['R_FK'] = $this->get_reverse_grille_fk($this->app_table_one['codeAppscheme'], $table_value); - $out['HTTP_VARS'] = $this->translate_vars($vars); - - return $out; - } - - function set_hist($idagent, $vars) { - - $vars['dateCreationActivity_expl'] = date('Y-m-d'); - $vars['heureCreationActivity_expl'] = date('H:i:s'); - $vars['timeCreationActivity_expl'] = time(); - $vars['idactivity_expl'] = (int)$this->getNext('idactivity_expl'); - $vars['idagent'] = (int)$idagent; - $vars['nomActivity_expl'] = $vars['vars']['table'] . ' ' . $vars['vars']['groupBy']; //.' ' .App::get_full_titre_vars($vars['vars']); - $this->plug('sitebase_base', 'activity_expl')->update(['uid' => $vars['uid']], ['$set' => $vars], ['upsert' => true]); - } - - function getNext($id, $min = 1) { - - if (!empty($min)) { - $test = $this->plug('sitebase_increment', 'auto_increment')->findOne(['_id' => $id]); - if (!empty($test['value'])) { - if ($test['value'] < $min) { - $this->plug('sitebase_increment', 'auto_increment')->update(['_id' => $id], ['value' => (int)$min], ["upsert" => true]); - } - } - } - $this->plug('sitebase_increment', 'auto_increment')->update(['_id' => $id], ['$inc' => ['value' => 1]], ["upsert" => true]); - $ret = $this->plug('sitebase_increment', 'auto_increment')->findOne(['_id' => $id]); - - return (int)$ret['value']; - } - -// - - function set_log($idagent, $table, $table_value, $log_type) { - $round_numerator = 60 * 5; - $rounded_time = (round(time() / $round_numerator) * $round_numerator); - $upd = []; - $upd['codeActivite'] = strtoupper($table) . '_' . strtoupper($log_type); - $upd['timeActivite'] = (int)$rounded_time; - $upd['dateActivite'] = date('Y-m-d', $rounded_time); - $upd['heureActivite'] = date('H:i:s', $rounded_time); - $upd['idagent'] = (int)$idagent; - $upd['table'] = $table; - $upd['table_value'] = (int)$table_value; - // sitebase_pref // agent activite - $this->plug('sitebase_base', 'activity')->update($upd, ['$set' => $upd], ['upsert' => true]); - // nlle table agent_history - $index_upd['idagent'] = (int)$idagent; - $index_upd['codeAgent_history'] = $table; - $index_upd['valeurAgent_history'] = (int)$table_value; - // - $APP_TMP = new App($table); - $ARR_TMP = $APP_TMP->query_one(['id' . $table => (int)$table_value]); - $h_upd['nomAgent_history'] = strtolower($ARR_TMP['nom' . ucfirst($table)]); - $h_upd['timeAgent_history'] = (int)time(); - $h_upd['dateAgent_history'] = date('Y-m-d'); - $h_upd['heureAgent_history'] = date('H:i:s'); - $test = $this->plug('sitebase_pref', 'agent_history')->findOne($index_upd); - if (empty($test['idagent_history'])) { - $index_upd['idagent_history'] = $h_upd['idagent_history'] = (int)App::getNext('idagent_history'); - } - $this->plug('sitebase_pref', 'agent_history')->update($index_upd, ['$set' => $h_upd, - '$inc' => ['quantiteAgent_history' => 1]], ['upsert' => true]); - AppSocket::reloadModule('app/app_gui/app_gui_panel', $table); - } - - function query_one($vars, $fields = []) { - $arr = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->findOne($vars, $fields); - - return $arr; - } - - function get_settings($idagent, $key, $table = '') { - $width_table = empty($table) ? '' : '_' . $table; - $arr = $this->plug('sitebase_pref', 'agent_pref')->findOne(['idagent' => (int)$idagent, - 'codeAgent_pref' => $key . $width_table]); - - return $arr['valeurAgent_pref']; - } - - /** $field_name_raw */ - - function set_settings($idagent, $vars) { - foreach ($vars as $key => $val) { - $out['valeurAgent_pref'] = $val; - $out['codeAgent_pref'] = $key; - $out['idagent'] = (int)$idagent; - - $arr = $this->plug('sitebase_pref', 'agent_pref')->findOne(['idagent' => (int)$idagent, - 'codeAgent_pref' => $key]); - if (empty($arr['idagent_pref'])) { - $out['idagent_pref'] = (int)$this->getNext('idagent_pref'); - } - $this->plug('sitebase_pref', 'agent_pref')->update(['idagent' => (int)$idagent, - 'codeAgent_pref' => $key], ['$set' => $out], ['upsert' => true]); - } - } - - /** $table */ - - function del_settings($idagent, $key, $table = '') { - $width_table = empty($table) ? '' : '_' . $table; - $del = $this->plug('sitebase_pref', 'agent_pref')->remove(['idagent' => (int)$idagent, - 'codeAgent_pref' => $key . $width_table]); - - //$del = $this->plug('sitebase_pref', 'agent_pref')->update(array('idagent' => (int)$idagent), array('$pull' => array('settings.' . $key . $width_table => 1))); - - return $del; - } - - function is_confident_table($table) { - $conf = ['agent_note', - 'todo', - 'tache']; - - return in_array($table, $conf); - } - - function get_array_field_bool() { - $arr = $arrFieldsBool = ['estTop' => ['star', - 'star-o textgris'], - 'estActif' => ['check', - 'square-o textgris'], - 'estVisible' => ['eye-slash', - 'eye textgris']]; - - return $arr; - } - - function scheme($table) { - // return $this->app_conn->findOne($arr_vars); - $base = $this->get_base_from_table($table); - - return $this->conn->$base->$table; - } - - function get_base_from_table($table) { - $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); - - return $arr['codeAppscheme_base']; - } - - function get_one_scheme($arr_vars = []) { - return $this->app_conn->findOne($arr_vars); - } - - function get_table_scheme($table) { - return $this->app_conn->findOne(['codeAppscheme' => $table]); - } - - /** - * @param $field_name_raw - * @param array $ARR - * @param string $field_name - * - * @return string - */ - function cf_output($field_name_raw, $ARR = [], $field_name = '') { - $table = $this->table;; - $Table = ucfirst($table); - $field_name = $field_name ?: $field_name_raw . $Table; - - return $this->draw_field(['field_name' => $field_name, - 'field_name_raw' => $field_name_raw, - 'field_value' => $ARR[$field_name] ?: '']); - } - - /** - * @param $field_name_raw - * - * @return string - */ - function cf_output_icon($field_name_raw) { - $table = $this->table;; - $Table = ucfirst($table); - - $arrF = $this->plug('sitebase_app', 'appscheme_field')->findOne(['codeAppscheme_field' => $field_name_raw]); - $icon = $arrF['iconAppscheme_field']; - - return $value = "";; - } - - /** field_value */ - function draw_field($vars = [], $nude = false) { - $field_name_raw = $vars['field_name_raw']; - $table = $vars['table']; - $Table = ucfirst($table); - $field_name = empty($vars['field_name']) ? $field_name_raw . $Table : $vars['field_name']; - if (is_array($vars['field_value'])) { - if ($vars['field_value'][$field_name]) { - $vars['field_value'] = $vars['field_value'][$field_name]; - } elseif ($vars['field_value']['emailDevis']) { - $vars['field_value'] = $vars['field_value']['emailDevis']; - } else { - return implode(',', $vars['field_value']); - } - - } - $value = $vars['field_value'];//nl2br($vars['field_value']); - // le type - $arrF = $this->plug('sitebase_app', 'appscheme_field')->findOne(['codeAppscheme_field' => $field_name_raw]); - - if (empty($arrF['codeAppscheme_field_type'])) { - // $arrF = $this->appscheme_field->findOne(['codeAppscheme_field' => $field_name_raw]); - // $vars['codeAppscheme_field_type'] = $arr_tmp['codeAppscheme_field_type']; - } - - //if (!empty($value)): - switch (strtolower($arrF['codeAppscheme_field_type'])): - case 'distance': - $value = round($value / 1000, 2) . ' kms'; - break; - case 'minutes': - if (empty($value)) break; - $value = ceil($value / 60) . ' minutes'; - break; - case 'valeur': - $value = (is_int($value)) ? maskNbre($value, 0) : $value; - break; - case 'prix': - if (empty($value)) break; - $value = maskNbre((float)$value, 2) . ' €'; - break; - case 'prix_precis': - if (empty($value)) break; - $value = maskNbre((float)$value, 6) . ' €'; - break; - case 'pourcentage': - $value = (float)$value . ' % '; - break; - case 'date': - if (empty($value)) break; - $value = date_fr($value); - break; - case 'heure': - if (empty($value)) break; - $value = maskHeure($value); - break; - case 'phone': - if (empty($value)) break; - $value = "
" . maskTel($value) . "
"; - break; - case 'textelibre': - if (empty($value)) break; - $value = "
" . nl2br(stripslashes($value)) . "
"; - break; - case 'texteformate': - if (empty($value)) break; - $value = $value; - break; - case 'bool': - $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $field_name_raw]); - $icon = $arr_tmp['iconAppscheme_field']; - $css = empty($value) ? 'textgris' : 'textvert'; - $text = empty($icon) ? ouiNon($value) : ''; - $value = "$text"; - break; - case 'icon': - if (empty($value)) break; - $value = ""; - break; - case 'password': - if (empty($value)) break; - $value = "***********"; - break; - case 'color': - if (empty($value)) break; - $value = ""; - break; - endswitch; - //endif; - if ($nude == false): - $str = "$value "; - else: - $str = "$value"; - endif; - - return $str; - } - - function draw_field_input($vars = [], $var_name = 'vars') { - - $field_name_raw = $vars['field_name_raw']; - $table = $vars['table']; - $value = nl2br($vars['field_value']); - $value = $vars['field_value'];//nl2br($vars['field_value']); - $Table = ucfirst($table); - $field_name = empty($vars['field_name']) ? $field_name_raw . $Table : $vars['field_name']; - $a1 = $this->appscheme_has_field->findOne(['codeAppscheme_has_field' => $field_name]); - $a2 = $this->appscheme_field->findOne(['idappscheme_field' => (int)$a1['idappscheme_field']]); - - // echo $a2['codeAppscheme_field_type']; - // classname // tagg - $tag = "text"; - $type = 'text'; - $attr = ''; - - if (is_array($vars['field_value'])) { - if ($vars['field_value'][$field_name]) { - $vars['field_value'] = $vars['field_value'][$field_name]; - } - if (is_array($vars['field_value'])) { - $value = $vars['field_value'] = implode(',', $vars['field_value']); - } - - } - - switch (strtolower($a2['codeAppscheme_field_type'])): - case "icon": - $attr = 'act_defer mdl="app/app_select_icon_fa" vars="' . http_build_query($vars) . '"'; - $class = "fauxInput"; - $tag = "div"; - break; - case "date": - $class = "validate-date-au"; - $value = $value; - $type = "date"; - break; - case "heure": - $type = "time"; - $class = "heure inputSmall"; - break; - case "email": - $class = "email"; - $type = 'email'; - break; - case "identification": - $class = "inputLarge"; - break; - case "codification": - $class = "inputSmall"; - break; - case "localisation": - $class = "inputLarge"; - break; - case "bool": - $class = "inputLarge"; - $tag = 'checkbox'; - break; - case "textelibre": - //$value = br2nl(strip_tags($value)); - $value = br2nl($value); - $class = "inputLarge"; - $tag = 'textarea'; - break; - case "texteformate": - //$value = br2nl(strip_tags($value)); - $value = br2nl($value); - $class = "inputLarge"; - $tag = 'textarea'; - $attr = 'ext_mce_textarea'; - break; - case "color": - $class = "inputTiny"; - $type = 'color'; - if (empty($value)) $value = '_'; - break; - case "valeur": - $class = "inputTiny"; - break; - case "texte": - $class = "inputLarge"; - break; - case "prix_precis": - $value = maskNbre((float)$value, 6); - $class = "inputSmall"; - break; - case "prix": - $value = maskNbre((float)$value, 2); - $class = "inputSmall"; - break; - case "password": - $class = "inputMedium"; - $type = 'password'; - break; - case 'phone': - $value = maskTel($value); - break; - default: - $class = ""; - $type = 'text'; - break; - endswitch; - $required = empty($a1['required']) ? '' : 'required="required"'; - $required_hash = empty($a1['required']) ? '' : ' * '; - switch ($tag): - case 'div': - $str = '
' . $value . '
'; - break; - case 'textarea': - $str = ''; - break; - case 'checkbox': - $str = chkSch($field_name, $value); - break; - default: - $placeholder = 'placeholder="' . $a2['nomAppscheme_field'] . '"'; - $str = ''; - break; - endswitch; - - return $required_hash . $str; - } - - /** - * Test si table a colonne agent - * @return bool - */ - function has_agent() { - $TEST_AGENT = array_search('agent', array_column($this->get_grille_fk($this->table), 'table_fk')); - - return ($TEST_AGENT !== false); - } - - public function has_field_fk($table) { - $arr_test = array_search($table, array_column($this->get_grille_fk(), 'table_fk')); - - return ($arr_test === false) ? false : true; - } - - function get_table_field_list() { - $out = []; - $rsG = $this->appscheme_has_table_field->find(['idappscheme' => (int)$this->idappscheme]); - // idappscheme_link - $a = []; - while ($arrg = $rsG->getNext()) : - $test = $this->appscheme->findOne(['idappscheme' => (int)$arrg['idappscheme_link']]); - $a['nomAppscheme'] = $test['nomAppscheme']; - $a['codeAppscheme'] = $test['codeAppscheme']; - $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); - $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; - $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; - $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; - $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; - - $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($a['nomAppscheme']); - $a['field_name_raw'] = $test['codeAppscheme_field']; - $out[$a['field_name']] = $a; - endwhile; - - return $out; - } - - function vars_to_titre($arr_vars = []) { - - $out_vars = []; - $APP_SCH = new App('appscheme'); - $APP = new App('appscheme_has_field'); - if (!empty($arr_vars['vars'])) { - $arr_vars += $arr_vars['vars']; - unset($arr_vars['vars']); - } - foreach ($arr_vars as $name_vars => $value_vars): - $ARR = $APP->findOne(['codeAppscheme_has_field' => $name_vars]); - if ($ARR['_id'] != ''): - $out_vars[] = $ARR['nomAppscheme_field'] . ' ' . $ARR['nomAppscheme'] . ' : ' . $value_vars; - else: - $table = str_replace('id', '', $name_vars); - $ARR = $APP_SCH->findOne(['codeAppscheme' => $table]); - if ($ARR['_id'] != ''): - $APP_TMP = new App($table); - $ARR_TMP = $APP_TMP->findOne([$name_vars => (int)$value_vars]); - if (empty($ARR_TMP['nom' . ucfirst($table)])) continue; - $out_vars[] = ' ' . $ARR['nomAppscheme'] . ' : ' . $ARR_TMP['nom' . ucfirst($table)]; - endif; - endif; - - endforeach; - $out = implode('', $out_vars); - if (!empty($arr_vars['groupBy'])) $out .= ' par ' . $arr_vars['groupBy']; - if (!empty($arr_vars['sortBy'])) $out .= ' tri par' . $arr_vars['sortBy']; - if (!empty($arr_vars['search'])) $out .= ' Recherche : "' . $arr_vars['search'] . '"'; - - return $out; - } - - function get_titre_vars($arr_vars = []) { - // vars to http ? - $out_vars = []; - foreach ($arr_vars as $name_vars => $value_vars): - // table = namevars - id - $table = str_replace('id', '', $name_vars); - $nom = 'nom' . ucfirst($table); - $base = $this->get_base_from_table($table); - if (empty($table) || empty($base)) continue; - $arr = $this->plug($base, $table)->findOne([$name_vars => (int)$value_vars]); - $out_vars[] = $arr[$nom]; - endforeach; - $out = implode(' ; ', $out_vars); - if (!empty($arr_vars['groupBy'])) $out .= ' par ' . $arr_vars['groupBy']; - if (!empty($arr_vars['sortBy'])) $out .= ' tri par' . $arr_vars['sortBy']; - - return $out; - } - - /* function plug_fs($base) { - // PREFIX HERE POUR BASE - $db = $this->plug_base($base); - - return $db->getGridFS(); - }*/ - - function update_inc($vars, $field = '') { - $table = $this->app_table_one['codeAppscheme']; - - if (empty($field)) $field = 'nombreVue' . ucfirst($table); - // - $this->plug($this->app_table_one['codeAppscheme_base'], $table)->update($vars, ['$inc' => [$field => 1]], ["upsert" => true]); - - } - - function readNext($id) { - $arr = $this->plug('sitebase_increment', 'auto_increment')->findOne(['_id' => $id]); - - return (int)$arr['value']; - } - - function setNext($id, $value) { - $this->plug('sitebase_increment', 'auto_increment')->update(['_id' => $id], ['value' => (int)$value], ["upsert" => true]); - - return $value; - } - - function resetNext($id) { - $this->plug('sitebase_increment', 'auto_increment')->remove(['_id' => $id]); - } - - function distinct($groupBy, $vars = [], $limit = 200, $mode = 'full', $field = '', $sort_field = ['ordre', - 1]) { - if (empty($field)) $field = 'id' . $groupBy; - // table sur laquelle on bosse - $dist = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme']); - if (sizeof($vars) != 0) { - $first_arr_dist = $dist->distinct($field, $vars); - } else { - $first_arr_dist = $dist->distinct($field); - } - - if (empty($first_arr_dist)) $first_arr_dist = []; - - // ! $groupbBy : nom de la table - $base = $this->get_base_from_table($groupBy); - if (empty($base)) { - $base = "sitebase_base"; - } - // - if ($mode == 'full'): - - $rs_dist = $this->plug($base, $groupBy)->find(['id' . $groupBy => ['$in' => $first_arr_dist]])->sort([$sort_field[0] . ucfirst($groupBy) => $sort_field[1]])->limit($limit); - - return $rs_dist; - endif; - - return $first_arr_dist; - } - - function distinct_rs($vars_dist) { - // $groupBy_table, $vars = ['1' => '1'], $limit = 250, $mode = 'full', $field = '', $sort_field = ['nom', 1] - - $groupBy_table = $vars_dist['groupBy_table']; - $vars = empty($vars_dist['vars']) ? [] : $vars_dist['vars']; - $limit = empty($vars_dist['limit']) ? 250 : $vars_dist['limit']; - $field = empty($vars_dist['field']) ? '' : $vars_dist['field']; - $sort_field = empty($vars_dist['sort_field']) ? ['nom', - 1] : $vars_dist['sort_field']; - - if (empty($field)) $field = 'id' . $groupBy_table; - $idgroupBy_table = 'id' . $groupBy_table; - $arr_collect_rs = []; - $arr_collect = []; - $arr_collect_field = []; - $tmp_iddistinct = []; - - # tri sur table principale $this ou $table_group_by - if ($this->has_field($sort_field[0] . ucfirst($this->table))) { - $sort_on = $sort_field[0] . ucfirst($this->table); - } else { - $sort_on = $sort_field[0]; - } - - // echo "on collecte $field et tri sur " . $this->app_table_one['codeAppscheme'] . ' ' . $sort_field[0] . '
'; - $base_rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme']); - $basedist = new App($groupBy_table); - // sort field peut etre count +1 ou count -1 - - if ($sort_field[0] != 'count') { - $rs_basedist = $base_rs->find($vars, ['_id' => 0])->limit(3000)->sort([$sort_on => $sort_field[1]]); - } else - $rs_basedist = $base_rs->find($vars, ['_id' => 0])->limit(3000)->sort(['nom' . ucfirst($this->table) => 1]); - - # boucle dans liste triée - - while ($arr_basedist = $rs_basedist->getNext()) { - // - # collecter ids - # sauf si déja collecter - - $arr_collect_field[$arr_basedist[$field]][] = $arr_basedist[$this->app_field_name_id]; - if (empty($arr_basedist[$idgroupBy_table])) continue; - // if (empty($arr_basedist[$field])) continue; - if (array_key_exists($arr_basedist[$field], $arr_collect)) continue; - - # table de groupby - $arr_dist = $basedist->findOne([$idgroupBy_table => (int)$arr_basedist[$idgroupBy_table]], ['_id' => 0]); - if (empty($arr_dist)) continue; - $arr_collect[$arr_basedist[$field]] = $arr_basedist[$field]; - # charge - $arr_collect_rs[$arr_basedist[$field]] = $arr_dist + $arr_basedist + ['nomAppscheme' => $groupBy_table, - 'count' => 0, - 'groupBy' => $groupBy_table, - $field => $arr_basedist[$field], - $this->app_field_name_id => (int)$arr_basedist[$this->app_field_name_id], - $sort_field[0] => $arr_basedist[$sort_field[0] . ucfirst($this->table)]]; - - $tmp_iddistinct[] = (int)$arr_basedist[$this->app_field_name_id];; - $rs_base_rs_tmp = $base_rs->find($vars + [$idgroupBy_table => (int)$arr_basedist[$idgroupBy_table]], ['_id' => 0]); - $rs_base_rs_count = $rs_base_rs_tmp->count(); - $arr_collect_rs[$arr_basedist[$field]]['count'] = $rs_base_rs_count; - // - if ($sort_field[0] != 'count') if (sizeof($arr_collect_rs) == $limit) break; - } - if ($sort_field[0] == 'count') { - usort($arr_collect_rs, function ($a, $b) { - return (int)$a['count'] < (int)$b['count']; - }); - $arr_collect_rs = array_slice($arr_collect_rs, 0, $limit - 1); - } else { - global $sort_vars; - $sort_vars = $sort_on; - usort($arr_collect_rs, function ($a, $b) { - global $sort_vars; - - return (int)$a[$sort_vars] > (int)$b[$sort_vars]; - }); - $arr_collect_rs = array_slice($arr_collect_rs, 0, $limit - 1); - } - - return $arr_collect_rs; - - } - - function groupBy() { - - } - - # cds - - function has_field($field) { - if (is_array($field)) { - foreach ($field as $key => $value) { - $arr_test = $this->appscheme_has_field->findOne(['idappscheme' => (int)$this->idappscheme, - 'codeAppscheme_field' => $value]); - if (!empty($arr_test['idappscheme'])) return true; - } - - return false; - } - $arr_test = $this->appscheme_has_field->findOne(['idappscheme' => (int)$this->idappscheme, - 'codeAppscheme_field' => $field]); - - return (!empty($arr_test['idappscheme'])); - } - - function get_full_titre_vars($arr_vars = []) { - // vars to http ? - $out_vars = []; - foreach ($arr_vars as $name_vars => $value_vars): - // table = namevars - id - $table = str_replace('id', '', $name_vars); - $nom = 'nom' . ucfirst($table); - $base = $this->get_base_from_table($table); - $arr = $this->plug($base, $table)->findOne([$name_vars => (int)$value_vars]); - $out_vars[] = ucfirst($table) . ' ' . $arr[$nom]; - endforeach; - - return implode(' ; ', $out_vars); - } - - function get_fk_tables($table = null) { - if (empty($table)) $table = $this->table; - $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); - $grille_fk = $arr['grilleFK']; - $out = []; - if (empty($grille_fk)) { - return []; - } - foreach ($grille_fk as $arr_fk): - $table_fk = $arr_fk['table']; - $index = $arr_fk['ordreTable']; - - $db_fk = $this->app_conn->findOne(['codeAppscheme' => $table_fk]); - if (!empty($db_fk['codeAppscheme_base'])): - $out[$index] = $table_fk; - endif; - endforeach; - ksort($out); - - return $out; - } - - function get_fk_id_tables($table) { - $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); - $grille_fk = $arr['grilleFK']; - $out = []; - if (empty($grille_fk)) { - return []; - } - foreach ($grille_fk as $arr_fk): - $table_fk = $arr_fk['table']; - $index = $arr_fk['ordreTable']; - - $db_fk = $this->app_conn->findOne(['codeAppscheme' => $table_fk]); - if (!empty($db_fk['codeAppscheme_base'])): - $out['id' . $table_fk] = 'id' . $table_fk; - endif; - endforeach; - ksort($out); - - return $out; - } - - function get_display_fields($table = '') { - $APP_TABLE = $this->app_table_one; - $Table = ucfirst($table); - $default_model = []; - $DEFAULT_FIELDS = $this->app_default_fields; - - foreach ($DEFAULT_FIELDS as $key_df => $value_df) { - $Key = ucfirst($key_df); - $Name = empty($value_df) ? $key_df : $value_df; - - if (!empty($APP_TABLE['has' . ucfirst($Key) . 'Scheme'])): - $default_model[$key_df] = ['field_name' => $key_df . $Table, - 'field_name_raw' => $key_df, - 'title' => idioma($Name)]; - if ($key_df == 'adresse'): - // $default_model[$key_df.'2'] = array( 'field_name' => 'adresse2' . $Table , 'field_name_raw' => 'adresse2' , 'title' => idioma('..') ); - //$default_model['codePostal'] = array( 'field_name' => 'codePostal' . $Table , 'field_name_raw' => 'codePostal' , 'title' => idioma('code postal') ); - //$default_model['ville'] = array( 'field_name' => 'ville' . $Table , 'field_name_raw' => 'ville' , 'title' => idioma('ville') ); - endif; - endif; - } - - return $default_model; - } - - function get_grille_count($table) { - $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); - $grilleCount = empty($arr['grilleCount']) ? [] : $arr['grilleCount']; - - return $grilleCount; - } - - function get_grille($table) { - $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); - $grille_fk = $arr['grille']; - $out = []; - if (empty($grille_fk)) { - return []; - } - foreach ($grille_fk as $arr_fk): - $table_fk = $arr_fk['table']; - $index = $arr_fk['ordreTable']; - - $db_fk = $this->app_conn->findOne(['codeAppscheme' => $table_fk]); - if (!empty($db_fk['codeAppscheme_base'])): - $out[$index] = ['base_grille' => $db_fk['codeAppscheme_base'], - 'collection_grille' => $db_fk['codeAppscheme'], - 'table_grille' => $table_fk, - 'idtable_grille' => 'id' . $table_fk, - 'nomtable_grille' => 'nom' . ucfirst($table_fk), - 'icon_grille' => $db_fk['icon']]; - endif; - endforeach; - ksort($out); - - return $out; - } - - function get_schemes($arr_vars = [], $page = 0, $rppage = 250) { - return $this->app_conn->find($arr_vars)->sort(['nomAppscheme' => 1])->skip($page * $rppage)->limit($rppage); - } - - function get_http_mdl($mdl, $vars = [], $value = '', $attributes = '') { - // http_post_data() - $fields = ['name' => 'mike', - 'pass' => 'se_ret']; - $files = [['name' => 'uimg', - 'type' => 'image/jpeg', - 'file' => './profile.jpg',]]; - - $response = http_post_fields("http://www.example.com/", $fields, $files); - - return $response; - } - - function consolidate_app_scheme($table) { - - $APP_GROUPE = new App('agent_groupe'); - $APP_DROIT = new App('agent_groupe_droit'); - $APP_BASE = new App('appscheme_base'); - $APP_SCH = new App('appscheme'); - $APP_SCH_FIELD = new App('appscheme_field'); - $APP_SCH_HAS = new App('appscheme_has_field'); - $APP_SCH_HAS_TABLE = new App('appscheme_has_table_field'); - $APP_CONSOLIDATE = new App($table); - - $ARR = $APP_SCH->findOne(['codeAppscheme' => $table]); - $idappscheme = (int)$ARR['idappscheme']; - if (empty($idappscheme)) { - - $ARR = $APP_SCH->findOne(['collection' => $table]); - if (!empty($ARR['collection'])) { - // echo "
non déclarée fallback collection"; - $idappscheme = $APP_SCH->create_update(['collection' => $table], ['codeAppscheme' => $table, - 'nomAppscheme' => $table]); - $APP_SCH->consolidate_app_scheme($table); - } - - return; - } - - $arr_main = $APP_SCH_HAS_TABLE->distinct_all('idappscheme_field', ['idappscheme' => $idappscheme]); - $arr_main_2 = $APP_SCH_HAS->distinct_all('idappscheme_field', ['idappscheme' => $idappscheme]); - - if (sizeof($arr_main) != 0 && sizeof($arr_main_2) != 0) { - $diff = array_values(array_diff($arr_main, $arr_main_2)); - - if (sizeof($diff) != 0) { - $APP_SCH_HAS_TABLE->remove(['idappscheme' => $idappscheme, - 'idappscheme_field' => ['$in' => $diff]]); - } - } - - $ARR_GR = $APP_GROUPE->findOne(['codeAgent_groupe' => 'ADMIN']); - $ARR_FIELD_NOM = $APP_SCH_FIELD->findOne(['codeAppscheme_field' => 'nom']); - $IDFIELD_NOM = (int)$ARR_FIELD_NOM['idappscheme_field']; - - if (!empty($ARR_GR['idagent_groupe'])) { - $APP_DROIT->create_update(['idagent_groupe' => (int)$ARR_GR['idagent_groupe'], - 'idappscheme' => $idappscheme], ['C' => true, - 'R' => true, - 'U' => true, - 'D' => true, - 'L' => true]); - } - if (empty($ARR['codeAppscheme_base']) && !empty($ARR['base'])) { - $idappscheme_base = $APP_BASE->create_update(['codeAppscheme_base' => $ARR['base']], ['nomAppscheme_base' => $ARR['base']]); - } - if (empty($ARR['iconAppscheme']) && !empty($ARR['icon'])) { - $APP_SCH->update(['idappscheme' => $idappscheme], ['iconAppscheme' => $ARR['icon']]); - } - // - $arr_has = ['statut', - 'type', - 'categorie', - 'group', - 'groupe']; - - $GRILLEFK = $APP_CONSOLIDATE->get_grille_fk(); - foreach ($arr_has as $key => $value): - $Value = ucfirst($value); - $_table = $table . '_' . $value; - - if (!empty((int)$ARR['has' . $Value . 'Scheme']) && empty($GRILLEFK[$_table]) && !empty($ARR['codeAppscheme_base'])): - $this->init_scheme($ARR['codeAppscheme_base'], $_table); - // put it in grilleFK - $APP_CONSOLIDATE->set_grille_fk($_table); - endif; - $test = strpos($table, "_$value"); - if (strpos($table, "_$value") !== false && (empty($ARR['is' . $Value . 'Scheme']) || empty($ARR['grouped_scheme']))): - $APP_SCH->update(['idappscheme' => $idappscheme], ['is' . $Value . 'Scheme' => 1, - 'grouped_scheme' => 1]); - endif; - endforeach; - - $testSF = $APP_SCH_HAS->find(['idappscheme' => $idappscheme]); - $arrSF = $APP_SCH_HAS->findOne(['idappscheme' => $idappscheme, - 'idappscheme_field' => $IDFIELD_NOM]); - - if (empty($arrSF['idappscheme_field']) && $testSF->count() == 0) { - // echo "
champ nom par defaut vide"; - $ins = ['codeAppscheme_has_field' => 'nom' . ucfirst($table), - 'codeAppscheme_field' => 'nom']; - $ins['nomAppscheme_has_field'] = $ARR_FIELD_NOM['nomAppscheme_field'] . ' ' . $ARR['nomAppscheme']; - $ins['codeAppscheme_has_field'] = $ARR_FIELD_NOM['codeAppscheme_field'] . ucfirst($table); - $ins['in_mini_fiche'] = 1; - - $idappscheme_has_field = $APP_SCH_HAS->create_update(['idappscheme' => $idappscheme, - 'idappscheme_field' => (int)$IDFIELD_NOM], $ins); - $APP_SCH_FIELD->consolidate_scheme($idappscheme_has_field); - } - $testSF = $APP_SCH_HAS_TABLE->find(['idappscheme' => $idappscheme]); - $arrSF = $APP_SCH_HAS_TABLE->findOne(['idappscheme' => $idappscheme, - 'idappscheme_link' => $idappscheme, - 'idappscheme_field' => $IDFIELD_NOM]); - if (empty($arrSF['codeAppscheme_field']) && $testSF->count() == 0) { - // echo "
champ nom personnalisé vide"; - $ins = ['idappscheme' => $idappscheme, - 'idappscheme_link' => $idappscheme, - 'idappscheme_field' => $IDFIELD_NOM]; - $ins['nomAppscheme_has_table_field'] = $ARR_FIELD_NOM['nomAppscheme_field'] . ' ' . $ARR['nomAppscheme']; - $ins['codeAppscheme_has_table_field'] = $ARR_FIELD_NOM['codeAppscheme_field'] . ucfirst($table); - $ins['idappscheme_field'] = (int)$ARR_FIELD_NOM['idappscheme_field']; - - $idappscheme_has_table_field = $APP_SCH_HAS_TABLE->create_update(['idappscheme' => $idappscheme, - 'idappscheme_link' => $idappscheme], $ins); - $APP_SCH_HAS_TABLE->consolidate_scheme($idappscheme_has_table_field); - } - - } - - function create_update($vars, $fields = []) { - if (empty($vars)) return false; - $table = $this->app_table_one['codeAppscheme']; - $test = $this->find($vars); - $count = count($test->toArray()); - - /*if ($count == 0): - if (empty($vars['id' . $table])) { - $id = (int)$this->getNext('id' . $table); - $fields['id' . $table] = $id; - } - $fields = array_merge($vars, $fields); - $id = $this->insert($fields); - else: - $arr_c = $test->getNext(); - $id = (int)$arr_c['id' . $table]; - $fields = array_merge($vars, $fields); - $this->update(['id' . $table => $id], $fields); - endif;*/ - - //return (int)$id; - return null; - } - - function find($vars = [], $proj = []) { - - if (empty($this->app_table_one['codeAppscheme_base'])) { - vardump($this->table); - } - // echo '
'.$this->table.' - '.($this->app_table_one['codeAppscheme_base'].' - '. $this->app_table_one['codeAppscheme']); - if (sizeof($proj) == 0) { - $rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->find($vars); - } else { - $rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->find($vars, $proj); - } - - return $rs; - } - - function insert($vars = []) { - if (empty($vars[$this->app_field_name_id])): - $vars[$this->app_field_name_id] = (int)$this->getNext($this->app_field_name_id); - endif; - $rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->insert($vars); - - //appSOcket::send_cmd('act_add_data', $g_vars); - $this->consolidate_scheme($vars[$this->app_field_name_id]); - - return (int)$vars[$this->app_field_name_id]; - } - - function consolidate_scheme($table_value = '') { // nom et codetype, grille_fk - // table sur laquelle on bosse - $name_id = $this->app_field_name_id; - $name_table = $this->app_table_one['codeAppscheme']; - $Name_table = ucfirst($name_table); - $GRILLE_FK = $this->get_grille_fk(); - $col = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme']); - $arr_vars = (empty($table_value)) ? [] : [$name_id => $table_value]; - $rs = $col->find($arr_vars); - // table_has_field ? - // - while ($arr = $rs->getNext()): - $arr_new = []; - $value_id = (int)$arr[$name_id]; - // DATES debut et fin => t(ime) - foreach ([null, - 'Creation', - 'Debut', - 'Fin'] as $k => $TYPE_DATE) { - $suffix_field = $TYPE_DATE . $Name_table; - $to_time = strtotime($arr['date' . $suffix_field]); - if (!empty($arr['date' . $suffix_field])): - if (($arr['time' . $suffix_field]) != $to_time) { - //$arr_new['time' . $suffix_field] = $to_time; - $arr_new['isoDate' . $suffix_field] = new MongoDate($to_time); - } - endif; - } - // - - if (!empty($arr['color' . $Name_table]) && empty($arr['bgcolor' . $Name_table]) && $arr['color' . $Name_table] != $arr['bgcolor' . $Name_table]): - - endif; - - if ($this->has_field('slug')) { - if (empty($arr['slug' . $Name_table]) && !empty($arr['nom' . $Name_table])) { - $arr_new['slug' . $Name_table] = format_uri($arr['nom' . $Name_table]); - } - } - // FKS : prendre nom et code => appscheme_has_table_field - - foreach ($GRILLE_FK as $field): - $id_fk = $field['idtable_fk']; - if (empty($arr[$id_fk])) continue; - $arr_lnk = $this->appscheme->findOne(['codeAppscheme' => $field['table_fk']]); - $rs_fields = $this->appscheme_has_table_field->find(['idappscheme' => $this->idappscheme, - 'idappscheme_link' => (int)$arr_lnk['idappscheme']]); - - // echo $rs_fields->count(); - $arrq = $this->plug($field['base_fk'], $field['table_fk'])->findOne([$id_fk => (int)$arr[$id_fk]]); - if (empty($arrq)) continue; - foreach ($rs_fields as $arr_fields) { - if ($arr[$arr_fields['codeAppscheme_field'] . ucfirst($field['table_fk'])] == $arrq[$arr_fields['codeAppscheme_field'] . ucfirst($field['table_fk'])]) continue; - $arr_new[$arr_fields['codeAppscheme_field'] . ucfirst($field['table_fk'])] = $arrq[$arr_fields['codeAppscheme_field'] . ucfirst($field['table_fk'])]; - } - // - foreach ($this->app_default_fields_add as $pfield_name) { - $full_field_name = $pfield_name . ucfirst($field['table_fk']); - if (array_key_exists($full_field_name, $arrq)) { - if ($arr[$full_field_name] !== $arrq[$full_field_name]) { - $arr_new[$full_field_name] = $arrq[$full_field_name]; - } - } - } - - endforeach; - - // TYPE STATUT - $arr_has = ['statut', - 'type', - 'categorie', - 'groupe']; - foreach ($arr_has as $key => $statut_type): - $Statut_type = ucfirst($statut_type); - $name_table_type = $name_table . '_' . $statut_type; - $Name_table_type = ucfirst($name_table_type); - $name_table_type_id = 'id' . $name_table_type; - $_nom = 'nom' . $name_table_type; - // - if (!empty($this->app_table_one['has' . $Statut_type . 'Scheme']) && !empty($arr[$name_table_type_id])): - $APP_TYPE = new App($name_table_type); - $arr_tmp = $APP_TYPE->findOne([$name_table_type_id => (int)$arr[$name_table_type_id]]) || []; - - foreach ($this->app_default_fields_add as $pfield_name) { - if (array_key_exists($pfield_name . $Name_table_type, $arr_tmp)) { - if ($arr_tmp[$pfield_name . $Name_table_type] !== $arr[$pfield_name . $Name_table_type]) { - $arr_new[$pfield_name . $Name_table_type] = $arr_tmp[$pfield_name . $Name_table_type]; - } - } - } - - endif; - - endforeach; -// - - // partie metier - if ($name_table == 'appscheme' && !empty($arr['codeAppscheme'])): - $this->consolidate_app_scheme($arr['codeAppscheme']); - endif; - if ($name_table == 'contrat'): - if (!empty($arr['idclient'])): - $APP_TMP = new App('client'); - $rs_test = $col->find(['idclient' => (int)$arr['idclient']])->sort(['dateFinContrat' => 1]); - $arr_test = $rs_test->getNext(); - $arr_cl = $APP_TMP->findOne(['idclient' => (int)$arr['idclient']]); - - if ($arr_cl['dateFinClient'] != $arr_test['dateFinContrat']) $APP_TMP->update(['idclient' => (int)$arr['idclient']], ['dateFinClient' => $arr_test['dateFinContrat']]); - endif; - endif; - if ($name_table == 'conge'): - $new_value = $arr['nomAgent'] . ' ' . strtolower($arr['codeConge_type']) . ' ' . fonctionsProduction::moisDate_fr($arr['dateDebutConge']); - if ($arr['nom' . $Name_table] != $new_value) { - $arr_new['nom' . $Name_table] = $new_value; - } - endif; - if ($name_table == 'ressource'): - $new_value = $arr['quantite' . $Name_table] . ' * ' . $arr['nomProduit'] . ' - ' . $arr['nomProspect'] . $arr['nomClient']; - if ($arr['nom' . $Name_table] != $new_value) { - $arr_new['nom' . $Name_table] = $new_value; - }; - endif; - if ($name_table == 'opportunite_ligne'): - $new_value = $arr['quantite' . $Name_table] . ' * ' . $arr['nomProduit']; - if ($arr['nom' . $Name_table] != $new_value) { - $arr_new['nom' . $Name_table] = $new_value; - }; - endif; - - if ($name_table == 'commande'): - $new_value = date('dmy') . auto_code($arr['codeClient']) . auto_code($arr['codeShop']); - if ($arr['code' . $Name_table] != $new_value) { - // $arr_new['code' . $Name_table] = $new_value; - }; - endif; - - if (empty($arr['code' . $Name_table]) && empty($arr_new['code' . $Name_table])): - $arr_new['code' . $Name_table] = auto_code($arr['nom' . $Name_table]); - endif; - if (empty($arr['nom' . $Name_table]) && empty($arr_new['nom' . $Name_table])): - foreach ($GRILLE_FK as $field): - $id_fk = $field['idtable_fk']; - if (empty($arr[$id_fk])) continue; - // - $dsp_name = $arr['nom' . ucfirst($field['table_fk'])]; - // - $arr_new['nom' . $Name_table] .= strtolower($dsp_name) . ' '; - endforeach; - endif; - if (empty($arr['nom' . $Name_table]) && empty($arr_new['nom' . $Name_table])): - if (!empty($APP_TABLE['hasTypeScheme'])): - // $arr_new['nom' . $Name_table] = $arr['nom' . $Name_table.'_type']; - endif; - // $arr_new['nom' . $Name_table] .= substr(strip_tags($arr['code' . $Name_table]),0,5) ; - if (!empty($APP_TABLE['hasDateScheme']) && !empty($arr['dateDebut' . $Name_table])): - $arr_new['nom' . $Name_table] .= ' ' . date_fr($arr['dateDebut' . $Name_table]); - endif; - // $arr_new['nom' . $Name_table] .= substr(strip_tags($arr['description' . $Name_table]),0,10); - endif; - if (sizeof($arr_new) != 0) { - $arr_new ['updated_fields'] = $arr_new; // log ??? - // versioning - $arr_new['dateModification' . $Name_table] = date('Y-m-d'); - $arr_new['heureModification' . $Name_table] = date('H:i:s'); - $arr_new['timeModification' . $Name_table] = time(); - - $col->update([$name_id => $value_id], ['$set' => $arr_new], ['upsert' => true]); - } - if ($rs->count() == 1) { - return $arr_new; - } - - endwhile; - } - - function update($vars, $fields = [], $upsert = true) { - $table = $this->app_table_one['codeAppscheme']; - $table_value = (int)$vars[$this->app_field_name_id]; - // anciennes valeurs - if (empty($table_value)) { - echo "probleme de mise à jour"; - - //vardump_async("$table sans value en update"); - - return; - } - $arr_one_before = $this->findOne([$this->app_field_name_id => $table_value]); - // differences avec anciennes valeurs - $arr_inter = array_diff_assoc($fields, (array)$arr_one_before); - if (sizeof($arr_inter) == 0) { - // AppSocket::send_cmd('act_notify', ['msg' => 'Mise à jour inutile'], session_id()); - - return; - } - // on garde la différence - $fields = $arr_inter; - // UPDATE !!! - $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->update($vars, ['$set' => $fields], ['upsert' => $upsert]); - $this->consolidate_scheme($table_value); - // - $arr_one_after = $this->findOne([$this->app_field_name_id => $table_value]); - - $updated_fields_real = array_diff_assoc((array)$arr_one_after, (array)$arr_one_before); - $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->update($vars, ['$set' => ['updated_fields' => $updated_fields_real]], ['upsert' => $upsert]); - - // AppSocket::send_cmd('act_notify',['msg'=>json_encode($updated_fields_real,JSON_PRETTY_PRINT),'options'=>['sticky'=>true]],session_id()); - - $update_diff_cast = []; - foreach ($updated_fields_real as $k => $v): - $exp['field_name'] = $k; - $exp['field_value'] = $v; - //if($v==$vars[$k] || empty($vars[$k])) continue; - $update_diff_cast[$k] = App::cast_field_all($exp, true); // new_vars deviendra vars - endforeach; - - AppSocket::send_cmd('act_upd_data', ['table' => $table, - 'table_value' => $table_value, - 'new_vars' => $update_diff_cast]); - - // log - $R_FK = $this->get_reverse_grille_fk($this->app_table_one['codeAppscheme'], (int)$vars[$this->app_field_name_id]); - // - if (!empty($fields['nom' . ucfirst($table)])): - foreach ($R_FK as $arr_fk): - $value_rfk = $arr_fk['table_value']; - $table_rfk = $arr_fk['table']; - $vars_rfk['vars'] = ['id' . $table => $table_value]; - $vars_rfk['table'] = $table_rfk; - $vars_rfk['table_value'] = $value_rfk; - $count = $arr_fk['count']; - - if (!empty($count)): - $APPCONV = new App($table_rfk); - $sd_vars = ['id' . $table => $table_value]; - $fields_fk = ['nom' . ucfirst($table) => $fields['nom' . ucfirst($table)]]; - $APPCONV->update($sd_vars, $fields_fk); - - endif; - endforeach; - endif; - - return $update_diff_cast; - } - - function cast_field_all($vars = [], $nude = false) { // json_data_table ! - $field_name = $vars['field_name']; - - if (is_array($vars['field_value'])) { - - return $vars['field_value']; - } - $value = $vars['field_value']; - - if (empty($vars['codeAppscheme_field_type'])) { - $arr_tmp = $this->appscheme_has_field->findOne(['codeAppscheme_has_field' => $field_name]); - $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $arr_tmp['codeAppscheme_field']]); - $vars['codeAppscheme_field_type'] = $arr_tmp['codeAppscheme_field_type']; - } - - switch ($vars['codeAppscheme_field_type']): - case 'distance': - $value = round($value / 1000, 2) . ' kms'; - break; - case 'minutes': - if (empty($value)) break; - $value = ceil($value / 60) . ' minutes '; - break; - case 'bool': - $arr_field = $this->appscheme_has_field->findOne(['codeAppscheme_has_field' => $field_name]); - $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $arr_field['codeAppscheme_field']]); - $icon = $arr_tmp['iconAppscheme_field']; - $css = empty($value) ? 'textgris' : 'textvert'; - $text = empty($icon) ? ouiNon($value) : ouiNon($value); - $value = " $text"; - break; - case 'valeur': - $value = $value; - break; - case 'prix': - $value = maskNbre($value, 2) . ' €'; - break; - case 'prix_precis': - $value = maskNbre((float)$value, 6) . ' €'; - break; - case 'pourcentage': - $value = (float)$value . ' %'; - break; - case 'date': - $value = date_fr($value); - break; - case 'heure': - $value = maskHeure($value); - break; - case 'phone': - $value = maskTel($value); - break; - case 'icon': - $value = ""; - break; - case 'color': - $value = ""; - break; - case 'textelibre': - $value = nl2br(stripslashes($value)); - break; - endswitch; - $str = "$value"; - - return $str; - } - - function distinct_all($groupBy, $vars = [], $limit = 200, $mode = 'full') { - - // table sur laquelle on bosse - $dist = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme']); - if (sizeof($vars) != 0) { - $first_arr_dist = $dist->distinct($groupBy, $vars); - } else { - $first_arr_dist = $dist->distinct($groupBy); - } - - return $first_arr_dist; - } - - function remove($vars = []) { - if (sizeof($vars) == 0) return; - $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->remove($vars); - } - - function init_scheme($base, $table, $options = [], $force = false) { - if (empty($table) || empty($base)) return false; - $test_base = $this->appscheme_base->findOne(['codeAppscheme_base' => $base]); - $test = $this->appscheme->findOne(['codeAppscheme' => $table]); - if (empty($test_base['idappscheme_base'])) { - $ins['idappscheme_base'] = $this->getNext('idappscheme_base'); - $ins['codeAppscheme_base'] = $base; - $ins['nomAppscheme_base'] = $base; - $this->appscheme_base->insert($ins); - - } else { - $ins['idappscheme_base'] = (int)$test_base['idappscheme_base']; - $ins['codeAppscheme_base'] = $base; - $ins['nomAppscheme_base'] = $test_base['nomAppscheme_base']; - } - if (empty($test['idappscheme'])) { - $ins['idappscheme'] = $this->getNext('idappscheme'); - } elseif ($force == true) { - - $ins['idappscheme'] = (int)$test['idappscheme']; - unset($ins['_id']); - } else { - return; - } - - $ins['codeAppscheme'] = $table; - $ins['nomAppscheme'] = $table; - if (!empty($options['has'])) { - foreach ($options['has'] as $key => $value) { - $ins['has' . ucfirst($value) . 'Scheme'] = 1; - } - unset($options['has']); - } - if (!empty($options['has'])) { - foreach ($options['has'] as $key => $value) { - $ins['has' . ucfirst($value) . ucfirst($table)] = 1; - } - unset($options['has']); - } - if (!empty($options['fields'])) { - foreach ($options['fields'] as $key => $value) { - $ARRF = $this->appscheme_field->findOne(['codeAppscheme_field' => $value]); - if (!empty($ARRF['idappscheme_field'])) $arr_field[] = (int)$ARRF['idappscheme_field']; else { - $APPF = new App('appscheme_field'); - $arr_field[] = $APPF->create_update(['codeAppscheme_field' => $value], ['nomAppscheme_field' => $value]); - } - } - unset($options['fields']); - } - if (!empty($options['grilleFK'])) { - $ARRFK = []; - foreach ($options['grilleFK'] as $key => $value) { - $ARRFK [(int)$key] = ['table' => $value, - 'ordreTable' => (int)$key, - 'uid' => uniqid()]; - } - $ins['grilleFK'] = $ARRFK; - unset($options['grilleFK']); - } - $ins = array_filter($ins); - $this->appscheme->update(['idappscheme' => $ins['idappscheme']], ['$set' => $ins], ['upsert' => 1]); - - $APP_TMP = new App('appscheme'); - $APP_TMP->consolidate_scheme($ins['idappscheme']); - if (!empty($arr_field)) { - $APP_SCH_HAS = new App('appscheme_has_field'); - foreach ($arr_field as $key => $value) { - $id = (int)$value; - $idschas = $APP_SCH_HAS->create_update(['idappscheme' => $ins['idappscheme'], - 'idappscheme_field' => $id]); - $APP_SCH_HAS->consolidate_scheme($idschas); - } - } - - return new App($table); - } - - function update_native($vars, $fields = [], $upsert = true) { - $table = $this->app_table_one['codeAppscheme']; - if (empty($vars[$this->app_field_name_id]) && empty($vars['_id'])) { - if (empty($table_value)) { - // vardump_async("$table sans value en update"); - //return; - } - } - $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->update($vars, ['$set' => $fields], ['upsert' => $upsert, - 'multi' => 1]); - - } - - /** - * field list + grille fk - * - * @param array $in - * - * @return array - */ - function get_field_list_all($in = []) { - $out = []; - if (!empty($in)) $DIST = $this->appscheme_field->distinct('idappscheme_field', $in); - if (!empty($in)) $DIST_2 = $this->appscheme_has_field->distinct('idappscheme_field'); - if (empty($DIST)) return $out; - $DIST_all = array_merge($DIST, $DIST_2); - $DIST_all = (!empty($DIST_all)) ? ['idappscheme_field' => ['$in' => $DIST_all]] : []; - - $rsG = $this->appscheme_has_field->find($DIST_all + ['idappscheme' => (int)$this->idappscheme]); - // $rsG = $this->appscheme_field->find( ['idappscheme_field' => ['$in' => $arr_field]]); - $a = []; - while ($arrg = $rsG->getNext()) : - $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); - $a['iconAppscheme_field'] = $test['iconAppscheme_field']; - $a['nomAppscheme_field'] = $test['nomAppscheme_field']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field']; - $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; - $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; - $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; - $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); - $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); - $a['field_name_raw'] = $test['codeAppscheme_field']; - $out[$a['field_name']] = $a; - endwhile; - $a = []; - foreach ($this->grilleFK as $keyFK => $fieldFK) { - $table_fk = $fieldFK['table']; - $rsG = $this->appscheme_has_field->find(['codeAppscheme' => $table_fk]); - - while ($arrg = $rsG->getNext()) : - $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); - $a['iconAppscheme_field'] = $test['iconAppscheme_field']; - $a['nomAppscheme_field'] = $test['nomAppscheme_field']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field']; - $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; - $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; - $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; - $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); - $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); - $a['field_name_raw'] = $test['codeAppscheme_field']; - $out[$a['field_name']] = $a; - endwhile; - } - - return $out; - } - - /** - * @param array $in - * - * @return array - */ - function get_field_list($in = []) { - $out = $DIST = $DIST_2 = []; - if (!empty($in)) $DIST = $this->appscheme_field->distinct('idappscheme_field', $in); - if (!empty($in)) $DIST_2 = $this->appscheme_has_field->distinct('idappscheme_field'); - $DIST_all = array_merge($DIST, $DIST_2); - $DIST_all = (!empty($DIST_all)) ? ['idappscheme_field' => ['$in' => $DIST_all]] : []; - $rsG = $this->appscheme_has_field->find($DIST + ['idappscheme' => (int)$this->idappscheme]); - // $rsG = $this->appscheme_field->find( ['idappscheme_field' => ['$in' => $arr_field]]); - $a = []; - while ($arrg = $rsG->getNext()) : - $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); - $a['iconAppscheme_field'] = $test['iconAppscheme_field']; - $a['nomAppscheme_field'] = $test['nomAppscheme_field']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field']; - $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; - $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; - $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; - $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); - $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); - $a['field_name_raw'] = $test['codeAppscheme_field']; - $out[$a['field_name']] = $a; - endwhile; - - $rsG = $this->appscheme_has_table_field->find($DIST + ['idappscheme' => (int)$this->idappscheme]); - // idappscheme_link - $a = []; - while ($arrg = $rsG->getNext()) : - $test = $this->appscheme->findOne(['idappscheme' => (int)$arrg['idappscheme_link']]); - $a['nomAppscheme'] = $test['nomAppscheme']; - $a['codeAppscheme'] = $test['codeAppscheme']; - $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); - $a['iconAppscheme_field'] = $test['iconAppscheme_field']; - $a['nomAppscheme_field'] = $test['nomAppscheme_field']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field']; - $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; - $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; - $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; - $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; - - $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($a['codeAppscheme']); - $a['field_name_raw'] = $test['codeAppscheme_field']; - $out[$a['field_name']] = $a; - endwhile; - - return $out; - } - - /** - * @param array $vars - * @param bool $nude - */ - function cast_field($vars = [], $nude = false) { // json_data_table ! - $field_name = $vars['field_name']; - $field_name_raw = $vars['field_name_raw']; - if (is_array($vars['field_value'])) { - - return $vars['field_value']; - } - $value = $vars['field_value'];//nl2br($vars['field_value']); - - if (str_find($field_name, 'date')) { - $value = date_fr($value); - } - if (str_find($field_name, 'nbre')) { - $value = maskNbre($value); - } - if (str_find($field_name, 'prix')) { - // $value = maskNbre($value); - } - if (str_find($field_name, 'telephone')) { - $value = maskTel($value); - } - if (str_find($field_name, 'mobile')) { - $value = maskTel($value); - } - if (str_find($field_name, 'duree')) { - $value = (float)$value; - } - if (str_find($field_name, 'code')) { - - } - if (str_find($field_name, 'color')) { - $vars['codeAppscheme_field_type'] = 'color'; - } - if (str_find($field_name, 'icon')) { - $vars['codeAppscheme_field_type'] = 'icon'; - } - if (str_find($field_name, 'actif')) { - $vars['codeAppscheme_field_type'] = 'bool'; - } - if (empty($vars['codeAppscheme_field_type'])) { - $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $field_name_raw]); - $vars['codeAppscheme_field_type'] = $arr_tmp['codeAppscheme_field_type']; - } - switch ($vars['codeAppscheme_field_type']): - case 'distance': - $value = round($value / 1000, 2) . ' kms'; - break; - case 'minutes': - if (empty($value)) break; - $value = ceil($value / 60); - break; - case 'bool': - $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $field_name_raw]); - $icon = $arr_tmp['iconAppscheme_field']; - $css = empty($value) ? 'textgris' : ''; - $text = empty($icon) ? ouiNon($value) : ''; - $value = ""; - break; - case 'valeur': - $value = $value; - break; - case 'prix': - $value = maskNbre($value, 2) . ' €'; - break; - case 'prix_precis': - $value = maskNbre((float)$value, 6) . ' €'; - break; - case 'pourcentage': - $value = (float)$value . ' %'; - break; - case 'date': - $value = date_fr($value); - break; - case 'heure': - $value = maskHeure($value); - break; - case 'phone': - $value = maskTel($value); - break; - case 'icon': - $value = ""; - break; - case 'color': - $value = ""; - break; - case 'textelibre': - $value = nl2br(stripslashes($value)); - break; - endswitch; - $str = "$value"; - - return $str; - } - - function query($vars = [], $page = 0, $rppage = 40, $fields = []) { - if (empty($rppage)) { - $rppage = 15; - } - if (empty($this->app_table_one['codeAppscheme_base'])) { - die(' [' . $this->table . '-' . $this->app_table_one['codeAppscheme_base'] . '-' . $this->app_table_one['codeAppscheme'] . ']'); - exit; - } - $rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->find($vars, $fields); - $totcount = $rs->count(); - $rs->sort([$this->app_field_name_top => -1, - $this->app_field_name_nom => 1]); - $rs->skip($page * $rppage)->limit($rppage); - - return $rs; - } - - function get_field_list_raw($in = []) { - $out = []; - if (!empty($in)) $DIST = $this->appscheme_field->distinct('idappscheme_field', $in); - $DIST = (!empty($DIST)) ? ['idappscheme_field' => ['$in' => $DIST]] : []; - - $rsG = $this->appscheme_has_field->find($DIST + ['idappscheme' => (int)$this->idappscheme]); - // $rsG = $this->appscheme_field->find( ['idappscheme_field' => ['$in' => $arr_field]]); - $a = []; - while ($arrg = $rsG->getNext()) : - $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); - $a['iconAppscheme_field'] = $test['iconAppscheme_field']; - $a['nomAppscheme_field'] = $test['nomAppscheme_field']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field']; - $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; - $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; - $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; - $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; - $a['codeAppscheme_field'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); - $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); - $a['field_name_raw'] = $test['codeAppscheme_field']; - $out[$a['field_name']] = $a; - endwhile; - - return $out; - } - } +__construct($table); + } + + /** + * App constructor. + * @deprecated + * + * @param string $table + */ + public function __construct($table = '') { + global $app_conn_nb; + global $PERSIST_CON; + // + if (!defined('MDB_USER')) { + return 'Utilisateur DB non defini'; + } + parent::__construct(); + $this->conn = IdaeConnect::getInstance()->connect(); + + $sitebase_app = MDB_PREFIX . 'sitebase_app'; + $sitebase_sockets = MDB_PREFIX . 'sitebase_sockets'; + + $this->table = $table; + $this->app_conn = $this->conn->$sitebase_app->appscheme; + $this->appscheme = $this->conn->$sitebase_app->appscheme; + $this->appscheme_type = $this->conn->$sitebase_app->appscheme_type; + $this->appscheme_base = $this->conn->$sitebase_app->appscheme_base; + $this->appscheme_field = $this->conn->$sitebase_app->appscheme_field; + $this->appscheme_field_type = $this->conn->$sitebase_app->appscheme_field_type; + $this->appscheme_field_group = $this->conn->$sitebase_app->appscheme_field_group; + $this->appscheme_has_field = $this->conn->$sitebase_app->appscheme_has_field; + $this->appscheme_has_table_field = $this->conn->$sitebase_app->appscheme_has_table_field; + $this->APPCACHE = $this->conn->$sitebase_sockets->data_activity; + + if (!empty($table)) { + $this->app_table_one = $this->app_conn->findOne(['codeAppscheme' => $table]); // si pas reg ? + $this->app_field_name_id = 'id' . $table; + $this->app_field_name_id_type = 'id' . $table . '_type'; + $this->app_field_name_nom = $this->app_table_one['nomAppscheme']; + $this->app_field_name_nom_type = 'nom' . ucfirst($table) . '_type'; + $this->app_field_name_top = 'estTop' . ucfirst($table); + $this->app_field_name_actif = 'estActif' . ucfirst($table); + $this->idappscheme = (int)$this->app_table_one['idappscheme']; + $this->codeAppscheme = $this->app_table_one['codeAppscheme']?? ''; + $this->iconAppscheme = $this->app_table_one['iconAppscheme']?? ''; + $this->colorAppscheme = $this->app_table_one['colorAppscheme'] ?? ''; + $this->nomAppscheme = $this->app_table_one['nomAppscheme']; + $this->codeAppscheme_base = $this->app_table_one['codeAppscheme_base']; + $this->app_table_icon = $this->app_table_one['icon'] ?? ''; + $this->grilleFK = $this->app_table_one['grilleFK'] ?? []; + $this->hasImageScheme = $this->app_table_one['hasImageScheme'] ?? ''; + } + + $this->app_default_fields_add = ['petitNom', + 'nom', + 'bgcolor', + 'code', + 'color', + 'icon', + 'ordre', + 'slug', + 'actif']; + $this->app_default_fields = ['nom' => '', + 'prenom' => '', + 'petitNom' => 'nom court', + 'code' => '', + 'reference' => 'reference', + 'description' => '', + 'quantite' => '', + 'prix' => '', + 'total' => '', + 'atout' => '', + 'valeur' => '', + 'rang' => '', + 'dateCreation' => 'crée le', + 'dateDebut' => 'date debut', + 'dateFin' => 'date de fin', + 'duree' => '', + 'heure' => '', + 'email' => '', + 'telephone' => '', + 'fax' => '', + 'adresse' => '', + 'url' => '', + 'totalHt' => 'total HT', + 'totalTtc' => 'total TTC', + 'totalMarge' => 'total Marge', + 'totalTva' => 'total TVA', + 'ordre' => '', + 'color' => '', + 'image' => '']; + $this->app_default_group_field = ['codification' => '', + 'identification' => '', + 'date' => '', + 'prix' => '', + 'localisation' => '', + 'valeur' => '', + 'texte' => '', + 'image' => '', + 'telephonie' => '', + 'heure' => '', + 'divers' => 'Autres']; + + //$this->make_classes_app(); + } + + public static function getInstance($table = '') { + + if (is_null(self::$_instance)) { + self::$_instance = new App($table); + } + + return self::$_instance; + } + + /** + * @ todo generate Entity, Controller, Repository + * @return bool + */ + function make_classes_app() { + + if (empty($this->table)) {return false;} + if (!is_string($this->table)) {return false;} + $table = $this->table; + $file_name = $table; + $path = APPCLASSES_APP . '/' . BUSINESS . '/' . CUSTOMER . '/' . $table . '/'; + foreach (['app', + 'act', + 'ui', + 'pre_act', + 'post_act'] as $key => $extension) { + $className = $file_name . '_' . $extension; + $path_and_file = $path . $className . '.php'; + // echo "
"; + if (!file_exists($path)) { + mkdir($path, 0777, true); + } + foreach (['Repository','Entity','Controller','Interface'] as $index => $item) { + if (!file_exists($path."/$item")) { + mkdir($path."/$item", 0777, true); + } + + } + if (!file_exists($path_and_file)) { + $monfichier = @fopen($path_and_file, 'a+'); + if (!$monfichier) continue; + $content = $this->write_classes_app($className, $table, $extension); + @fputs($monfichier, $content); + @fclose($monfichier); + } + + } + } + + function write_classes_app($className, $table, $type) { + // $content = file_get_contents(APP_CONFIG_DIR . 'classes_app_models/class_model_' . $type . '.php'); + $content = file_get_contents(APP_CONFIG_DIR . 'class_model.php'); + $content = str_replace('TABLE_CLASS', $table, $content); + $content = str_replace('NAME_CLASS', $className, $content); + + return $content; + } + + function rest($params = ['table', + 'action', + 'vars']) { + // + Helper::dump(func_get_args()); + + if (strpos($params['vars'], '/') === false) { + $value = $params['vars']; + + } else { + $value = explode('/', $params['vars']); + } + $new_value = array_map(function ($node) { + if (strpos($node, ':') === false) { + + return $node; + } + $tmp = explode(':', $node); + + if (strpos($tmp[0], '[]') === true) { + echo "array"; + } + + return [$tmp[0] => $tmp[1]]; + + }, $value); + Helper::dump($new_value); + $app = new App($params['table']); + + if ($params['action'] == 'remove') { + die('verboten'); + } + + $rs = $app->$params['action'](); + + echo json_encode(iterator_to_array($rs)); + // $this->$params['action']($value); + + } + + /** + * @param $table_value + * @param array $vars + * + * @return stdClass + */ + function appobj($table_value = null, $vars = []) { + + $this->obj = new stdClass(); + $this->obj->NAME_ID = 'id' . $this->app_table_one['codeAppscheme']; + $this->obj->NAME_APP = $this->app_table_one['nomAppscheme']; + $this->obj->ICON = $this->app_table_one['iconAppscheme']; + $this->obj->ICON_COLOR = $this->app_table_one['colorAppscheme']; + $this->obj->APP_TABLE = $this->app_table_one; + $this->obj->GRILLE_FK = $this->get_grille_fk(); + $this->obj->HTTP_VARS = $this->translate_vars($vars); + $this->obj->ARR_GROUP_FIELD = $this->get_field_group_list(); + $this->obj->app_default_fields = $this->app_default_fields; + $this->obj->R_FK = $this->get_reverse_grille_fk($this->app_table_one['codeAppscheme'], $table_value); + if (!empty($table_value)) { + $this->obj->ARR = $this->findOne([$this->obj->NAME_ID => (int)$table_value]); + } + + return $this->obj; + } + + function get_grille_fk_grouped($table = '', $vars = []) { + return $this->get_grille_fk($table, ['grouped_scheme' => 1]); + } + + function get_grille_fk_nongrouped($table = '', $vars = []) { + return $this->get_grille_fk($table, ['grouped_scheme' => ['$ne' => 1]]); + } + + /** + * @param string $table + * @param array $vars + * + * @return array + */ + function get_grille_fk($table = '', $vars = []) { + if (empty($table) && !empty($this->table)) { + $grille_fk = $this->grilleFK; + } elseif (empty($table)) { + $arr = $this->app_conn->findOne(array_merge(['codeAppscheme' => $table], $vars)); + $grille_fk = $arr['grilleFK']; + } + $out = []; + if (empty($grille_fk)) { + return []; + } + foreach ($grille_fk as $arr_fk): + $table_fk = $arr_fk['table']; + $index = $arr_fk['ordreTable']; + + $db_fk = $this->app_conn->findOne($vars + ['codeAppscheme' => $table_fk]); + if (!empty($db_fk['codeAppscheme_base'])): + $out[$table_fk] = ['base_fk' => $db_fk['codeAppscheme_base'], + // $out[$index] + 'collection_fk' => $db_fk['codeAppscheme'], + 'nomAppscheme' => $db_fk['nomAppscheme'], + 'codeAppscheme' => $db_fk['codeAppscheme'], + 'iconAppscheme' => $db_fk['iconAppscheme'], + 'colorAppscheme' => $db_fk['colorAppscheme'] ?? '', + 'table_fk' => $table_fk, + 'idtable_fk' => 'id' . $table_fk, + 'nomtable_fk' => 'nom' . ucfirst($table_fk), + 'icon_fk' => $db_fk['icon'] ?? '']; + endif; + endforeach; + + return $out; + } + + function set_grille_fk($fk_table) { + if (empty($this->table)) return false; + $arr['uid'] = uniqid(); + $arr['ordreTable'] = (int)(sizeof($this->get_fk_tables())) + 1; + $arr['table'] = $fk_table; + $test = $this->get_fk_tables(); + if (!in_array($fk_table, $test)) { + // do it + //vardump_async("$this->idappscheme , $this->table => $fk_table",true); + $this->plug('sitebase_app', 'appscheme')->update(['idappscheme' => $this->idappscheme], ['$push' => ['grilleFK' => $arr]]); + } + } + + function translate_vars($arr_vars = []) { + // vars to http ? + $out_vars = []; + foreach ($arr_vars as $name_vars => $value_vars): + $out_vars['vars'][$name_vars] = $value_vars; + endforeach; + + return http_build_query($out_vars); + } + + function get_field_group_list($codeGroupe = '', $qy_has_field = [], $excludedCode = []) { + $out = []; + $vars_code = empty($codeGroupe) ? [] : ['codeAppscheme_field_group' => $codeGroupe]; + $arr_field = $this->appscheme_has_field->distinct('idappscheme_field', ['codeAppscheme_field' => ['$nin' => $excludedCode]] + $qy_has_field + ['idappscheme' => $this->idappscheme]); + $arr_field_2 = $this->appscheme_field->distinct('idappscheme_field_group', ['idappscheme_field' => ['$in' => $arr_field]]); + $rsG = $this->appscheme_field_group->find($vars_code + ['idappscheme_field_group' => ['$in' => $arr_field_2]])->sort(['ordreAppscheme_field_group' => 1]); + $i = 0; + while ($arrg = $rsG->getNext()) { + + $out2 = []; + $out[(int)$i]['group'] = $arrg; + $arr_field_tmp = $this->appscheme_field->distinct('idappscheme_field', ['idappscheme_field_group' => (int)$arrg['idappscheme_field_group']]); + $rstmp_ar = $this->appscheme_has_field->find(['idappscheme' => $this->idappscheme, + 'idappscheme_field' => ['$in' => $arr_field_tmp]])->sort(['ordreAppscheme_has_field' => 1]); + + while ($arrf = $rstmp_ar->getNext()) { + // vardump_async($arrf['ordreAppscheme_has_field']); + $tmp_ar = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrf['idappscheme_field']]); + $out2[] = $tmp_ar; + + } + // $rsF = $this->appscheme_field->find(['idappscheme_field_group' => (int)$arrg['idappscheme_field_group'], 'idappscheme_field' => ['$in' => $arr_field]])->sort(['ordreAppscheme_field' => 1]); + /* while ($arrf = $rsF->getNext()) { + $tmp_ar = $this->appscheme_has_field->findOne(['idappscheme' => $this->idappscheme,'idappscheme_field'=>(int)$arrf['idappscheme_field']]); + $out2[] = $arrf; + }*/ + $out[(int)$i]['field'] = $out2; + $i++; + } + + return $out; + } + + /** + * @param $table $table_value + * @param $table_value + * + * @return array $out + */ + function get_reverse_grille_fk($table, $table_value = '', $add = []) { + $id = 'id' . $table; + $vars = $out = []; + if (!empty($table_value)): + $vars[$id] = (int)$table_value; + endif; + if (empty($add)) { + $rs = $this->app_conn->find(['grilleFK.table' => $table]); + } else { + $rs = $this->app_conn->find($add + ['grilleFK.table' => $table]); + } + + foreach ($rs as $arr): + if (empty($table_value)) { + if (str_find('_ligne', $arr['codeAppscheme_base'])) continue; + $rs_fk = $this->plug($arr['codeAppscheme_base'], $arr['codeAppscheme'])->find(); + } else { + $rs_fk = $this->plug($arr['codeAppscheme_base'], $arr['codeAppscheme'])->find([$id => (int)$table_value]); + } + + $index = $rs_fk->count(); + // + $out[$arr['codeAppscheme']] = $arr + ['count' => $index, + 'table' => $arr['codeAppscheme'], + 'scope' => $arr['codeAppscheme_type'], + 'icon' => $arr['icon'], + 'table_value' => $table_value + /*, 'rs_fk'=>$rs_fk*/]; + endforeach; + + return $out; + } + + /* function plug($base, $table) { + if (empty($table) || empty($base) || !defined('MDB_USER')) { + return 'choisir une base'; + } + // PREFIX HERE POUR BASE + $db = $this->plug_base($base); + $collection = $db->$table; + + return $collection; + } + + function plug_base($base) { + if (empty($base) || !defined('MDB_USER')) { + return 'choisir une base'; + } + // PREFIX HERE POUR BASE + $base = MDB_PREFIX . $base; + $db = $this->conn->$base; + + return $db; + }*/ + + function findOne($vars, $out = []) { + if (empty($this->app_table_one['codeAppscheme_base'])) { + vardump($this->table); + } + if (sizeof($out) == 0) { + $arr = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->findOne($vars); + } else { + $arr = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->findOne($vars, $out); + } + + return $arr; + } + + /** + * @param $table $table_value + * @param $table_value + * + * @return array $out + */ + function get_grille_rfk($table, $table_value = '', $add = []) { + $id = 'id' . $table; + $vars = $out = []; + if (!empty($table_value)): + $vars[$id] = (int)$table_value; + endif; + if (empty($add)) { + $rs = $this->app_conn->find(['grilleFK.table' => $table]); + } else { + $rs = $this->app_conn->find($add + ['grilleFK.table' => $table]); + } + $arr_ty = $this->appscheme->distinct('idappscheme_type', ['grilleFK.table' => $table]); + $rs_ty = $this->appscheme_type->find(['idappscheme_type' => ['$in' => $arr_ty]])->sort(['nomAppscheme_type' => 1]); + + $arr_final = []; + while ($arr_ty = $rs_ty->getNext()) { + $arr_tmp = $arr_out = []; + // + $vars_type = ['idappscheme_type' => (int)$arr_ty['idappscheme_type']]; + + if (empty($add)) { + $rs_det = $this->appscheme->find($vars_type + ['grilleFK.table' => $table]); + } else { + $rs_det = $this->appscheme->find($vars_type + $add + ['grilleFK.table' => $table]); + } + while ($arr_det = $rs_det->getNext()) { + if (empty($table_value)) { + if (str_find('_ligne', $arr_det['codeAppscheme_base'])) continue; + $rs_fk = $this->plug($arr_det['codeAppscheme_base'], $arr_det['codeAppscheme'])->find(); + } else { + $rs_fk = $this->plug($arr_det['codeAppscheme_base'], $arr_det['codeAppscheme'])->find([$id => (int)$table_value]); + } + if ($rs_fk->count() == 0) continue; + $arr_det['count'] = $rs_fk->count(); + $arr_det['table'] = $arr_det['codeAppscheme']; + $arr_tmp['appscheme'][$arr_det['codeAppscheme']] = $arr_det; + } + + if (!empty($arr_tmp['appscheme'])) { + $arr_out = array_merge($arr_ty, $arr_tmp); + $arr_final[] = $arr_out; + } + + } + + return $arr_final; + + } + + function get_table_rfk($table_value = '', $add = []) { + $table = $this->table; + $id = "id$table"; + $vars = $out = []; + if (!empty($table_value)): + $vars[$id] = (int)$table_value; + endif; + + $arr_table_rfk = $this->appscheme->distinct('codeAppscheme', $add + ['grilleFK.table' => $table]); + + return $arr_table_rfk; + } + + /** + * @param $table_value + * @param $vars + */ + function extract_vars($table_value, $vars = []) { + $out['ARR_GROUP_FIELD'] = $this->get_field_group_list(); + $out['NAME_APP'] = $this->app_table_one['nomAppscheme']; + $out['ICON'] = $this->app_table_one['iconAppscheme']; + $out['ICON_COLOR'] = $this->app_table_one['colorAppscheme']; + $out['APP_TABLE'] = $this->app_table_one; + $out['GRILLE_FK'] = $this->get_grille_fk($this->app_table_one['codeAppscheme']); + $out['R_FK'] = $this->get_reverse_grille_fk($this->app_table_one['codeAppscheme'], $table_value); + $out['HTTP_VARS'] = $this->translate_vars($vars); + + return $out; + } + + function set_hist($idagent, $vars) { + + $vars['dateCreationActivity_expl'] = date('Y-m-d'); + $vars['heureCreationActivity_expl'] = date('H:i:s'); + $vars['timeCreationActivity_expl'] = time(); + $vars['idactivity_expl'] = (int)$this->getNext('idactivity_expl'); + $vars['idagent'] = (int)$idagent; + $vars['nomActivity_expl'] = $vars['vars']['table'] . ' ' . $vars['vars']['groupBy']; //.' ' .App::get_full_titre_vars($vars['vars']); + $this->plug('sitebase_base', 'activity_expl')->update(['uid' => $vars['uid']], ['$set' => $vars], ['upsert' => true]); + } + + function getNext($id, $min = 1) { + + if (!empty($min)) { + $test = $this->plug('sitebase_increment', 'auto_increment')->findOne(['_id' => $id]); + if (!empty($test['value'])) { + if ($test['value'] < $min) { + $this->plug('sitebase_increment', 'auto_increment')->update(['_id' => $id], ['value' => (int)$min], ["upsert" => true]); + } + } + } + $this->plug('sitebase_increment', 'auto_increment')->update(['_id' => $id], ['$inc' => ['value' => 1]], ["upsert" => true]); + $ret = $this->plug('sitebase_increment', 'auto_increment')->findOne(['_id' => $id]); + + return (int)$ret['value']; + } + +// + + function set_log($idagent, $table, $table_value, $log_type) { + $round_numerator = 60 * 5; + $rounded_time = (round(time() / $round_numerator) * $round_numerator); + $upd = []; + $upd['codeActivite'] = strtoupper($table) . '_' . strtoupper($log_type); + $upd['timeActivite'] = (int)$rounded_time; + $upd['dateActivite'] = date('Y-m-d', $rounded_time); + $upd['heureActivite'] = date('H:i:s', $rounded_time); + $upd['idagent'] = (int)$idagent; + $upd['table'] = $table; + $upd['table_value'] = (int)$table_value; + // sitebase_pref // agent activite + $this->plug('sitebase_base', 'activity')->update($upd, ['$set' => $upd], ['upsert' => true]); + // nlle table agent_history + $index_upd['idagent'] = (int)$idagent; + $index_upd['codeAgent_history'] = $table; + $index_upd['valeurAgent_history'] = (int)$table_value; + // + $APP_TMP = new App($table); + $ARR_TMP = $APP_TMP->query_one(['id' . $table => (int)$table_value]); + $h_upd['nomAgent_history'] = strtolower($ARR_TMP['nom' . ucfirst($table)]); + $h_upd['timeAgent_history'] = (int)time(); + $h_upd['dateAgent_history'] = date('Y-m-d'); + $h_upd['heureAgent_history'] = date('H:i:s'); + $test = $this->plug('sitebase_pref', 'agent_history')->findOne($index_upd); + if (empty($test['idagent_history'])) { + $index_upd['idagent_history'] = $h_upd['idagent_history'] = (int)App::getNext('idagent_history'); + } + $this->plug('sitebase_pref', 'agent_history')->update($index_upd, ['$set' => $h_upd, + '$inc' => ['quantiteAgent_history' => 1]], ['upsert' => true]); + AppSocket::reloadModule('app/app_gui/app_gui_panel', $table); + } + + function query_one($vars, $fields = []) { + $arr = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->findOne($vars, $fields); + + return $arr; + } + + function get_settings($idagent, $key, $table = '') { + $width_table = empty($table) ? '' : '_' . $table; + $arr = $this->plug('sitebase_pref', 'agent_pref')->findOne(['idagent' => (int)$idagent, + 'codeAgent_pref' => $key . $width_table]); + + return $arr['valeurAgent_pref']; + } + + /** $field_name_raw */ + + function set_settings($idagent, $vars) { + foreach ($vars as $key => $val) { + $out['valeurAgent_pref'] = $val; + $out['codeAgent_pref'] = $key; + $out['idagent'] = (int)$idagent; + + $arr = $this->plug('sitebase_pref', 'agent_pref')->findOne(['idagent' => (int)$idagent, + 'codeAgent_pref' => $key]); + if (empty($arr['idagent_pref'])) { + $out['idagent_pref'] = (int)$this->getNext('idagent_pref'); + } + $this->plug('sitebase_pref', 'agent_pref')->update(['idagent' => (int)$idagent, + 'codeAgent_pref' => $key], ['$set' => $out], ['upsert' => true]); + } + } + + /** $table */ + + function del_settings($idagent, $key, $table = '') { + $width_table = empty($table) ? '' : '_' . $table; + $del = $this->plug('sitebase_pref', 'agent_pref')->remove(['idagent' => (int)$idagent, + 'codeAgent_pref' => $key . $width_table]); + + //$del = $this->plug('sitebase_pref', 'agent_pref')->update(array('idagent' => (int)$idagent), array('$pull' => array('settings.' . $key . $width_table => 1))); + + return $del; + } + + function is_confident_table($table) { + $conf = ['agent_note', + 'todo', + 'tache']; + + return in_array($table, $conf); + } + + function get_array_field_bool() { + $arr = $arrFieldsBool = ['estTop' => ['star', + 'star-o textgris'], + 'estActif' => ['check', + 'square-o textgris'], + 'estVisible' => ['eye-slash', + 'eye textgris']]; + + return $arr; + } + + function scheme($table) { + // return $this->app_conn->findOne($arr_vars); + $base = $this->get_base_from_table($table); + + return $this->conn->$base->$table; + } + + function get_base_from_table($table) { + $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); + + return $arr['codeAppscheme_base']; + } + + function get_one_scheme($arr_vars = []) { + return $this->app_conn->findOne($arr_vars); + } + + function get_table_scheme($table) { + return $this->app_conn->findOne(['codeAppscheme' => $table]); + } + + /** + * @param $field_name_raw + * @param array $ARR + * @param string $field_name + * + * @return string + */ + function cf_output($field_name_raw, $ARR = [], $field_name = '') { + $table = $this->table;; + $Table = ucfirst($table); + $field_name = $field_name ?: $field_name_raw . $Table; + + return $this->draw_field(['field_name' => $field_name, + 'field_name_raw' => $field_name_raw, + 'field_value' => $ARR[$field_name] ?: '']); + } + + /** + * @param $field_name_raw + * + * @return string + */ + function cf_output_icon($field_name_raw) { + $table = $this->table;; + $Table = ucfirst($table); + + $arrF = $this->plug('sitebase_app', 'appscheme_field')->findOne(['codeAppscheme_field' => $field_name_raw]); + $icon = $arrF['iconAppscheme_field']; + + return $value = "";; + } + + /** field_value */ + function draw_field($vars = [], $nude = false) { + $field_name_raw = $vars['field_name_raw']; + $table = $vars['table']; + $Table = ucfirst($table); + $field_name = empty($vars['field_name']) ? $field_name_raw . $Table : $vars['field_name']; + if (is_array($vars['field_value'])) { + if ($vars['field_value'][$field_name]) { + $vars['field_value'] = $vars['field_value'][$field_name]; + } elseif ($vars['field_value']['emailDevis']) { + $vars['field_value'] = $vars['field_value']['emailDevis']; + } else { + return implode(',', $vars['field_value']); + } + + } + $value = $vars['field_value'];//nl2br($vars['field_value']); + // le type + $arrF = $this->plug('sitebase_app', 'appscheme_field')->findOne(['codeAppscheme_field' => $field_name_raw]); + + if (empty($arrF['codeAppscheme_field_type'])) { + // $arrF = $this->appscheme_field->findOne(['codeAppscheme_field' => $field_name_raw]); + // $vars['codeAppscheme_field_type'] = $arr_tmp['codeAppscheme_field_type']; + } + + //if (!empty($value)): + switch (strtolower($arrF['codeAppscheme_field_type'])): + case 'distance': + $value = round($value / 1000, 2) . ' kms'; + break; + case 'minutes': + if (empty($value)) break; + $value = ceil($value / 60) . ' minutes'; + break; + case 'valeur': + $value = (is_int($value)) ? maskNbre($value, 0) : $value; + break; + case 'prix': + if (empty($value)) break; + $value = maskNbre((float)$value, 2) . ' €'; + break; + case 'prix_precis': + if (empty($value)) break; + $value = maskNbre((float)$value, 6) . ' €'; + break; + case 'pourcentage': + $value = (float)$value . ' % '; + break; + case 'date': + if (empty($value)) break; + $value = date_fr($value); + break; + case 'heure': + if (empty($value)) break; + $value = maskHeure($value); + break; + case 'phone': + if (empty($value)) break; + $value = "
" . maskTel($value) . "
"; + break; + case 'textelibre': + if (empty($value)) break; + $value = "
" . nl2br(stripslashes($value)) . "
"; + break; + case 'texteformate': + if (empty($value)) break; + $value = $value; + break; + case 'bool': + $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $field_name_raw]); + $icon = $arr_tmp['iconAppscheme_field']; + $css = empty($value) ? 'textgris' : 'textvert'; + $text = empty($icon) ? ouiNon($value) : ''; + $value = "$text"; + break; + case 'icon': + if (empty($value)) break; + $value = ""; + break; + case 'password': + if (empty($value)) break; + $value = "***********"; + break; + case 'color': + if (empty($value)) break; + $value = ""; + break; + endswitch; + //endif; + if ($nude == false): + $str = "$value "; + else: + $str = "$value"; + endif; + + return $str; + } + + function draw_field_input($vars = [], $var_name = 'vars') { + + $field_name_raw = $vars['field_name_raw']; + $table = $vars['table']; + $value = nl2br($vars['field_value']); + $value = $vars['field_value'];//nl2br($vars['field_value']); + $Table = ucfirst($table); + $field_name = empty($vars['field_name']) ? $field_name_raw . $Table : $vars['field_name']; + $a1 = $this->appscheme_has_field->findOne(['codeAppscheme_has_field' => $field_name]); + $a2 = $this->appscheme_field->findOne(['idappscheme_field' => (int)$a1['idappscheme_field']]); + + // echo $a2['codeAppscheme_field_type']; + // classname // tagg + $tag = "text"; + $type = 'text'; + $attr = ''; + + if (is_array($vars['field_value'])) { + if ($vars['field_value'][$field_name]) { + $vars['field_value'] = $vars['field_value'][$field_name]; + } + if (is_array($vars['field_value'])) { + $value = $vars['field_value'] = implode(',', $vars['field_value']); + } + + } + + switch (strtolower($a2['codeAppscheme_field_type'])): + case "icon": + $attr = 'act_defer mdl="app/app_select_icon_fa" vars="' . http_build_query($vars) . '"'; + $class = "fauxInput"; + $tag = "div"; + break; + case "date": + $class = "validate-date-au"; + $value = $value; + $type = "date"; + break; + case "heure": + $type = "time"; + $class = "heure inputSmall"; + break; + case "email": + $class = "email"; + $type = 'email'; + break; + case "identification": + $class = "inputLarge"; + break; + case "codification": + $class = "inputSmall"; + break; + case "localisation": + $class = "inputLarge"; + break; + case "bool": + $class = "inputLarge"; + $tag = 'checkbox'; + break; + case "textelibre": + //$value = br2nl(strip_tags($value)); + $value = br2nl($value); + $class = "inputLarge"; + $tag = 'textarea'; + break; + case "texteformate": + //$value = br2nl(strip_tags($value)); + $value = br2nl($value); + $class = "inputLarge"; + $tag = 'textarea'; + $attr = 'ext_mce_textarea'; + break; + case "color": + $class = "inputTiny"; + $type = 'color'; + if (empty($value)) $value = '_'; + break; + case "valeur": + $class = "inputTiny"; + break; + case "texte": + $class = "inputLarge"; + break; + case "prix_precis": + $value = maskNbre((float)$value, 6); + $class = "inputSmall"; + break; + case "prix": + $value = maskNbre((float)$value, 2); + $class = "inputSmall"; + break; + case "password": + $class = "inputMedium"; + $type = 'password'; + break; + case 'phone': + $value = maskTel($value); + break; + default: + $class = ""; + $type = 'text'; + break; + endswitch; + $required = empty($a1['required']) ? '' : 'required="required"'; + $required_hash = empty($a1['required']) ? '' : ' * '; + switch ($tag): + case 'div': + $str = '
' . $value . '
'; + break; + case 'textarea': + $str = ''; + break; + case 'checkbox': + $str = chkSch($field_name, $value); + break; + default: + $placeholder = 'placeholder="' . $a2['nomAppscheme_field'] . '"'; + $str = ''; + break; + endswitch; + + return $required_hash . $str; + } + + /** + * Test si table a colonne agent + * @return bool + */ + function has_agent() { + $TEST_AGENT = array_search('agent', array_column($this->get_grille_fk($this->table), 'table_fk')); + + return ($TEST_AGENT !== false); + } + + public function has_field_fk($table) { + $arr_test = array_search($table, array_column($this->get_grille_fk(), 'table_fk')); + + return ($arr_test === false) ? false : true; + } + + function get_table_field_list() { + $out = []; + $rsG = $this->appscheme_has_table_field->find(['idappscheme' => (int)$this->idappscheme]); + // idappscheme_link + $a = []; + while ($arrg = $rsG->getNext()) : + $test = $this->appscheme->findOne(['idappscheme' => (int)$arrg['idappscheme_link']]); + $a['nomAppscheme'] = $test['nomAppscheme']; + $a['codeAppscheme'] = $test['codeAppscheme']; + $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); + $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; + $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; + $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; + $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; + + $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($a['nomAppscheme']); + $a['field_name_raw'] = $test['codeAppscheme_field']; + $out[$a['field_name']] = $a; + endwhile; + + return $out; + } + + function vars_to_titre($arr_vars = []) { + + $out_vars = []; + $APP_SCH = new App('appscheme'); + $APP = new App('appscheme_has_field'); + if (!empty($arr_vars['vars'])) { + $arr_vars += $arr_vars['vars']; + unset($arr_vars['vars']); + } + foreach ($arr_vars as $name_vars => $value_vars): + $ARR = $APP->findOne(['codeAppscheme_has_field' => $name_vars]); + if ($ARR['_id'] != ''): + $out_vars[] = $ARR['nomAppscheme_field'] . ' ' . $ARR['nomAppscheme'] . ' : ' . $value_vars; + else: + $table = str_replace('id', '', $name_vars); + $ARR = $APP_SCH->findOne(['codeAppscheme' => $table]); + if ($ARR['_id'] != ''): + $APP_TMP = new App($table); + $ARR_TMP = $APP_TMP->findOne([$name_vars => (int)$value_vars]); + if (empty($ARR_TMP['nom' . ucfirst($table)])) continue; + $out_vars[] = ' ' . $ARR['nomAppscheme'] . ' : ' . $ARR_TMP['nom' . ucfirst($table)]; + endif; + endif; + + endforeach; + $out = implode('', $out_vars); + if (!empty($arr_vars['groupBy'])) $out .= ' par ' . $arr_vars['groupBy']; + if (!empty($arr_vars['sortBy'])) $out .= ' tri par' . $arr_vars['sortBy']; + if (!empty($arr_vars['search'])) $out .= ' Recherche : "' . $arr_vars['search'] . '"'; + + return $out; + } + + function get_titre_vars($arr_vars = []) { + // vars to http ? + $out_vars = []; + foreach ($arr_vars as $name_vars => $value_vars): + // table = namevars - id + $table = str_replace('id', '', $name_vars); + $nom = 'nom' . ucfirst($table); + $base = $this->get_base_from_table($table); + if (empty($table) || empty($base)) continue; + $arr = $this->plug($base, $table)->findOne([$name_vars => (int)$value_vars]); + $out_vars[] = $arr[$nom]; + endforeach; + $out = implode(' ; ', $out_vars); + if (!empty($arr_vars['groupBy'])) $out .= ' par ' . $arr_vars['groupBy']; + if (!empty($arr_vars['sortBy'])) $out .= ' tri par' . $arr_vars['sortBy']; + + return $out; + } + + /* function plug_fs($base) { + // PREFIX HERE POUR BASE + $db = $this->plug_base($base); + + return $db->getGridFS(); + }*/ + + function update_inc($vars, $field = '') { + $table = $this->app_table_one['codeAppscheme']; + + if (empty($field)) $field = 'nombreVue' . ucfirst($table); + // + $this->plug($this->app_table_one['codeAppscheme_base'], $table)->update($vars, ['$inc' => [$field => 1]], ["upsert" => true]); + + } + + function readNext($id) { + $arr = $this->plug('sitebase_increment', 'auto_increment')->findOne(['_id' => $id]); + + return (int)$arr['value']; + } + + function setNext($id, $value) { + $this->plug('sitebase_increment', 'auto_increment')->update(['_id' => $id], ['value' => (int)$value], ["upsert" => true]); + + return $value; + } + + function resetNext($id) { + $this->plug('sitebase_increment', 'auto_increment')->remove(['_id' => $id]); + } + + function distinct($groupBy, $vars = [], $limit = 200, $mode = 'full', $field = '', $sort_field = ['ordre', + 1]) { + if (empty($field)) $field = 'id' . $groupBy; + // table sur laquelle on bosse + $dist = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme']); + if (sizeof($vars) != 0) { + $first_arr_dist = $dist->distinct($field, $vars); + } else { + $first_arr_dist = $dist->distinct($field); + } + + if (empty($first_arr_dist)) $first_arr_dist = []; + + // ! $groupbBy : nom de la table + $base = $this->get_base_from_table($groupBy); + if (empty($base)) { + $base = "sitebase_base"; + } + // + if ($mode == 'full'): + + $rs_dist = $this->plug($base, $groupBy)->find(['id' . $groupBy => ['$in' => $first_arr_dist]])->sort([$sort_field[0] . ucfirst($groupBy) => $sort_field[1]])->limit($limit); + + return $rs_dist; + endif; + + return $first_arr_dist; + } + + function distinct_rs($vars_dist) { + // $groupBy_table, $vars = ['1' => '1'], $limit = 250, $mode = 'full', $field = '', $sort_field = ['nom', 1] + + $groupBy_table = $vars_dist['groupBy_table']; + $vars = empty($vars_dist['vars']) ? [] : $vars_dist['vars']; + $limit = empty($vars_dist['limit']) ? 250 : $vars_dist['limit']; + $field = empty($vars_dist['field']) ? '' : $vars_dist['field']; + $sort_field = empty($vars_dist['sort_field']) ? ['nom', + 1] : $vars_dist['sort_field']; + + if (empty($field)) $field = 'id' . $groupBy_table; + $idgroupBy_table = 'id' . $groupBy_table; + $arr_collect_rs = []; + $arr_collect = []; + $arr_collect_field = []; + $tmp_iddistinct = []; + + # tri sur table principale $this ou $table_group_by + if ($this->has_field($sort_field[0] . ucfirst($this->table))) { + $sort_on = $sort_field[0] . ucfirst($this->table); + } else { + $sort_on = $sort_field[0]; + } + + // echo "on collecte $field et tri sur " . $this->app_table_one['codeAppscheme'] . ' ' . $sort_field[0] . '
'; + $base_rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme']); + $basedist = new App($groupBy_table); + // sort field peut etre count +1 ou count -1 + + if ($sort_field[0] != 'count') { + $rs_basedist = $base_rs->find($vars, ['_id' => 0])->limit(3000)->sort([$sort_on => $sort_field[1]]); + } else + $rs_basedist = $base_rs->find($vars, ['_id' => 0])->limit(3000)->sort(['nom' . ucfirst($this->table) => 1]); + + # boucle dans liste triée + + while ($arr_basedist = $rs_basedist->getNext()) { + // + # collecter ids + # sauf si déja collecter + + $arr_collect_field[$arr_basedist[$field]][] = $arr_basedist[$this->app_field_name_id]; + if (empty($arr_basedist[$idgroupBy_table])) continue; + // if (empty($arr_basedist[$field])) continue; + if (array_key_exists($arr_basedist[$field], $arr_collect)) continue; + + # table de groupby + $arr_dist = $basedist->findOne([$idgroupBy_table => (int)$arr_basedist[$idgroupBy_table]], ['_id' => 0]); + if (empty($arr_dist)) continue; + $arr_collect[$arr_basedist[$field]] = $arr_basedist[$field]; + # charge + $arr_collect_rs[$arr_basedist[$field]] = $arr_dist + $arr_basedist + ['nomAppscheme' => $groupBy_table, + 'count' => 0, + 'groupBy' => $groupBy_table, + $field => $arr_basedist[$field], + $this->app_field_name_id => (int)$arr_basedist[$this->app_field_name_id], + $sort_field[0] => $arr_basedist[$sort_field[0] . ucfirst($this->table)]]; + + $tmp_iddistinct[] = (int)$arr_basedist[$this->app_field_name_id];; + $rs_base_rs_tmp = $base_rs->find($vars + [$idgroupBy_table => (int)$arr_basedist[$idgroupBy_table]], ['_id' => 0]); + $rs_base_rs_count = $rs_base_rs_tmp->count(); + $arr_collect_rs[$arr_basedist[$field]]['count'] = $rs_base_rs_count; + // + if ($sort_field[0] != 'count') if (sizeof($arr_collect_rs) == $limit) break; + } + if ($sort_field[0] == 'count') { + usort($arr_collect_rs, function ($a, $b) { + return (int)$a['count'] < (int)$b['count']; + }); + $arr_collect_rs = array_slice($arr_collect_rs, 0, $limit - 1); + } else { + global $sort_vars; + $sort_vars = $sort_on; + usort($arr_collect_rs, function ($a, $b) { + global $sort_vars; + + return (int)$a[$sort_vars] > (int)$b[$sort_vars]; + }); + $arr_collect_rs = array_slice($arr_collect_rs, 0, $limit - 1); + } + + return $arr_collect_rs; + + } + + function groupBy() { + + } + + # cds + + function has_field($field) { + if (is_array($field)) { + foreach ($field as $key => $value) { + $arr_test = $this->appscheme_has_field->findOne(['idappscheme' => (int)$this->idappscheme, + 'codeAppscheme_field' => $value]); + if (!empty($arr_test['idappscheme'])) return true; + } + + return false; + } + $arr_test = $this->appscheme_has_field->findOne(['idappscheme' => (int)$this->idappscheme, + 'codeAppscheme_field' => $field]); + + return (!empty($arr_test['idappscheme'])); + } + + function get_full_titre_vars($arr_vars = []) { + // vars to http ? + $out_vars = []; + foreach ($arr_vars as $name_vars => $value_vars): + // table = namevars - id + $table = str_replace('id', '', $name_vars); + $nom = 'nom' . ucfirst($table); + $base = $this->get_base_from_table($table); + $arr = $this->plug($base, $table)->findOne([$name_vars => (int)$value_vars]); + $out_vars[] = ucfirst($table) . ' ' . $arr[$nom]; + endforeach; + + return implode(' ; ', $out_vars); + } + + function get_fk_tables($table = null) { + if (empty($table)) $table = $this->table; + $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); + $grille_fk = $arr['grilleFK']; + $out = []; + if (empty($grille_fk)) { + return []; + } + foreach ($grille_fk as $arr_fk): + $table_fk = $arr_fk['table']; + $index = $arr_fk['ordreTable']; + + $db_fk = $this->app_conn->findOne(['codeAppscheme' => $table_fk]); + if (!empty($db_fk['codeAppscheme_base'])): + $out[$index] = $table_fk; + endif; + endforeach; + ksort($out); + + return $out; + } + + function get_fk_id_tables($table) { + $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); + $grille_fk = $arr['grilleFK']; + $out = []; + if (empty($grille_fk)) { + return []; + } + foreach ($grille_fk as $arr_fk): + $table_fk = $arr_fk['table']; + $index = $arr_fk['ordreTable']; + + $db_fk = $this->app_conn->findOne(['codeAppscheme' => $table_fk]); + if (!empty($db_fk['codeAppscheme_base'])): + $out['id' . $table_fk] = 'id' . $table_fk; + endif; + endforeach; + ksort($out); + + return $out; + } + + function get_display_fields($table = '') { + $APP_TABLE = $this->app_table_one; + $Table = ucfirst($table); + $default_model = []; + $DEFAULT_FIELDS = $this->app_default_fields; + + foreach ($DEFAULT_FIELDS as $key_df => $value_df) { + $Key = ucfirst($key_df); + $Name = empty($value_df) ? $key_df : $value_df; + + if (!empty($APP_TABLE['has' . ucfirst($Key) . 'Scheme'])): + $default_model[$key_df] = ['field_name' => $key_df . $Table, + 'field_name_raw' => $key_df, + 'title' => idioma($Name)]; + if ($key_df == 'adresse'): + // $default_model[$key_df.'2'] = array( 'field_name' => 'adresse2' . $Table , 'field_name_raw' => 'adresse2' , 'title' => idioma('..') ); + //$default_model['codePostal'] = array( 'field_name' => 'codePostal' . $Table , 'field_name_raw' => 'codePostal' , 'title' => idioma('code postal') ); + //$default_model['ville'] = array( 'field_name' => 'ville' . $Table , 'field_name_raw' => 'ville' , 'title' => idioma('ville') ); + endif; + endif; + } + + return $default_model; + } + + function get_grille_count($table) { + $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); + $grilleCount = empty($arr['grilleCount']) ? [] : $arr['grilleCount']; + + return $grilleCount; + } + + function get_grille($table) { + $arr = $this->app_conn->findOne(['codeAppscheme' => $table]); + $grille_fk = $arr['grille']; + $out = []; + if (empty($grille_fk)) { + return []; + } + foreach ($grille_fk as $arr_fk): + $table_fk = $arr_fk['table']; + $index = $arr_fk['ordreTable']; + + $db_fk = $this->app_conn->findOne(['codeAppscheme' => $table_fk]); + if (!empty($db_fk['codeAppscheme_base'])): + $out[$index] = ['base_grille' => $db_fk['codeAppscheme_base'], + 'collection_grille' => $db_fk['codeAppscheme'], + 'table_grille' => $table_fk, + 'idtable_grille' => 'id' . $table_fk, + 'nomtable_grille' => 'nom' . ucfirst($table_fk), + 'icon_grille' => $db_fk['icon']]; + endif; + endforeach; + ksort($out); + + return $out; + } + + function get_schemes($arr_vars = [], $page = 0, $rppage = 250) { + return $this->app_conn->find($arr_vars)->sort(['nomAppscheme' => 1])->skip($page * $rppage)->limit($rppage); + } + + function get_http_mdl($mdl, $vars = [], $value = '', $attributes = '') { + // http_post_data() + $fields = ['name' => 'mike', + 'pass' => 'se_ret']; + $files = [['name' => 'uimg', + 'type' => 'image/jpeg', + 'file' => './profile.jpg',]]; + + $response = http_post_fields("http://www.example.com/", $fields, $files); + + return $response; + } + + function consolidate_app_scheme($table) { + + $APP_GROUPE = new App('agent_groupe'); + $APP_DROIT = new App('agent_groupe_droit'); + $APP_BASE = new App('appscheme_base'); + $APP_SCH = new App('appscheme'); + $APP_SCH_FIELD = new App('appscheme_field'); + $APP_SCH_HAS = new App('appscheme_has_field'); + $APP_SCH_HAS_TABLE = new App('appscheme_has_table_field'); + $APP_CONSOLIDATE = new App($table); + + $ARR = $APP_SCH->findOne(['codeAppscheme' => $table]); + $idappscheme = (int)$ARR['idappscheme']; + if (empty($idappscheme)) { + + $ARR = $APP_SCH->findOne(['collection' => $table]); + if (!empty($ARR['collection'])) { + // echo "
non déclarée fallback collection"; + $idappscheme = $APP_SCH->create_update(['collection' => $table], ['codeAppscheme' => $table, + 'nomAppscheme' => $table]); + $APP_SCH->consolidate_app_scheme($table); + } + + return; + } + + $arr_main = $APP_SCH_HAS_TABLE->distinct_all('idappscheme_field', ['idappscheme' => $idappscheme]); + $arr_main_2 = $APP_SCH_HAS->distinct_all('idappscheme_field', ['idappscheme' => $idappscheme]); + + if (sizeof($arr_main) != 0 && sizeof($arr_main_2) != 0) { + $diff = array_values(array_diff($arr_main, $arr_main_2)); + + if (sizeof($diff) != 0) { + $APP_SCH_HAS_TABLE->remove(['idappscheme' => $idappscheme, + 'idappscheme_field' => ['$in' => $diff]]); + } + } + + $ARR_GR = $APP_GROUPE->findOne(['codeAgent_groupe' => 'ADMIN']); + $ARR_FIELD_NOM = $APP_SCH_FIELD->findOne(['codeAppscheme_field' => 'nom']); + $IDFIELD_NOM = (int)$ARR_FIELD_NOM['idappscheme_field']; + + if (!empty($ARR_GR['idagent_groupe'])) { + $APP_DROIT->create_update(['idagent_groupe' => (int)$ARR_GR['idagent_groupe'], + 'idappscheme' => $idappscheme], ['C' => true, + 'R' => true, + 'U' => true, + 'D' => true, + 'L' => true]); + } + if (empty($ARR['codeAppscheme_base']) && !empty($ARR['base'])) { + $idappscheme_base = $APP_BASE->create_update(['codeAppscheme_base' => $ARR['base']], ['nomAppscheme_base' => $ARR['base']]); + } + if (empty($ARR['iconAppscheme']) && !empty($ARR['icon'])) { + $APP_SCH->update(['idappscheme' => $idappscheme], ['iconAppscheme' => $ARR['icon']]); + } + // + $arr_has = ['statut', + 'type', + 'categorie', + 'group', + 'groupe']; + + $GRILLEFK = $APP_CONSOLIDATE->get_grille_fk(); + foreach ($arr_has as $key => $value): + $Value = ucfirst($value); + $_table = $table . '_' . $value; + + if (!empty((int)$ARR['has' . $Value . 'Scheme']) && empty($GRILLEFK[$_table]) && !empty($ARR['codeAppscheme_base'])): + $this->init_scheme($ARR['codeAppscheme_base'], $_table); + // put it in grilleFK + $APP_CONSOLIDATE->set_grille_fk($_table); + endif; + $test = strpos($table, "_$value"); + if (strpos($table, "_$value") !== false && (empty($ARR['is' . $Value . 'Scheme']) || empty($ARR['grouped_scheme']))): + $APP_SCH->update(['idappscheme' => $idappscheme], ['is' . $Value . 'Scheme' => 1, + 'grouped_scheme' => 1]); + endif; + endforeach; + + $testSF = $APP_SCH_HAS->find(['idappscheme' => $idappscheme]); + $arrSF = $APP_SCH_HAS->findOne(['idappscheme' => $idappscheme, + 'idappscheme_field' => $IDFIELD_NOM]); + + if (empty($arrSF['idappscheme_field']) && $testSF->count() == 0) { + // echo "
champ nom par defaut vide"; + $ins = ['codeAppscheme_has_field' => 'nom' . ucfirst($table), + 'codeAppscheme_field' => 'nom']; + $ins['nomAppscheme_has_field'] = $ARR_FIELD_NOM['nomAppscheme_field'] . ' ' . $ARR['nomAppscheme']; + $ins['codeAppscheme_has_field'] = $ARR_FIELD_NOM['codeAppscheme_field'] . ucfirst($table); + $ins['in_mini_fiche'] = 1; + + $idappscheme_has_field = $APP_SCH_HAS->create_update(['idappscheme' => $idappscheme, + 'idappscheme_field' => (int)$IDFIELD_NOM], $ins); + $APP_SCH_FIELD->consolidate_scheme($idappscheme_has_field); + } + $testSF = $APP_SCH_HAS_TABLE->find(['idappscheme' => $idappscheme]); + $arrSF = $APP_SCH_HAS_TABLE->findOne(['idappscheme' => $idappscheme, + 'idappscheme_link' => $idappscheme, + 'idappscheme_field' => $IDFIELD_NOM]); + if (empty($arrSF['codeAppscheme_field']) && $testSF->count() == 0) { + // echo "
champ nom personnalisé vide"; + $ins = ['idappscheme' => $idappscheme, + 'idappscheme_link' => $idappscheme, + 'idappscheme_field' => $IDFIELD_NOM]; + $ins['nomAppscheme_has_table_field'] = $ARR_FIELD_NOM['nomAppscheme_field'] . ' ' . $ARR['nomAppscheme']; + $ins['codeAppscheme_has_table_field'] = $ARR_FIELD_NOM['codeAppscheme_field'] . ucfirst($table); + $ins['idappscheme_field'] = (int)$ARR_FIELD_NOM['idappscheme_field']; + + $idappscheme_has_table_field = $APP_SCH_HAS_TABLE->create_update(['idappscheme' => $idappscheme, + 'idappscheme_link' => $idappscheme], $ins); + $APP_SCH_HAS_TABLE->consolidate_scheme($idappscheme_has_table_field); + } + + } + + function create_update($vars, $fields = []) { + if (empty($vars)) return false; + $table = $this->app_table_one['codeAppscheme']; + $test = $this->find($vars); + $count = count($test->toArray()); + + /*if ($count == 0): + if (empty($vars['id' . $table])) { + $id = (int)$this->getNext('id' . $table); + $fields['id' . $table] = $id; + } + $fields = array_merge($vars, $fields); + $id = $this->insert($fields); + else: + $arr_c = $test->getNext(); + $id = (int)$arr_c['id' . $table]; + $fields = array_merge($vars, $fields); + $this->update(['id' . $table => $id], $fields); + endif;*/ + + //return (int)$id; + return null; + } + + function find($vars = [], $proj = []) { + + if (empty($this->app_table_one['codeAppscheme_base'])) { + vardump($this->table); + } + // echo '
'.$this->table.' - '.($this->app_table_one['codeAppscheme_base'].' - '. $this->app_table_one['codeAppscheme']); + if (sizeof($proj) == 0) { + $rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->find($vars); + } else { + $rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->find($vars, $proj); + } + + return $rs; + } + + function insert($vars = []) { + if (empty($vars[$this->app_field_name_id])): + $vars[$this->app_field_name_id] = (int)$this->getNext($this->app_field_name_id); + endif; + $rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->insert($vars); + + //appSOcket::send_cmd('act_add_data', $g_vars); + $this->consolidate_scheme($vars[$this->app_field_name_id]); + + return (int)$vars[$this->app_field_name_id]; + } + + function consolidate_scheme($table_value = '') { // nom et codetype, grille_fk + // table sur laquelle on bosse + $name_id = $this->app_field_name_id; + $name_table = $this->app_table_one['codeAppscheme']; + $Name_table = ucfirst($name_table); + $GRILLE_FK = $this->get_grille_fk(); + $col = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme']); + $arr_vars = (empty($table_value)) ? [] : [$name_id => $table_value]; + $rs = $col->find($arr_vars); + // table_has_field ? + // + while ($arr = $rs->getNext()): + $arr_new = []; + $value_id = (int)$arr[$name_id]; + // DATES debut et fin => t(ime) + foreach ([null, + 'Creation', + 'Debut', + 'Fin'] as $k => $TYPE_DATE) { + $suffix_field = $TYPE_DATE . $Name_table; + $to_time = strtotime($arr['date' . $suffix_field]); + if (!empty($arr['date' . $suffix_field])): + if (($arr['time' . $suffix_field]) != $to_time) { + //$arr_new['time' . $suffix_field] = $to_time; + $arr_new['isoDate' . $suffix_field] = new MongoDate($to_time); + } + endif; + } + // + + if (!empty($arr['color' . $Name_table]) && empty($arr['bgcolor' . $Name_table]) && $arr['color' . $Name_table] != $arr['bgcolor' . $Name_table]): + + endif; + + if ($this->has_field('slug')) { + if (empty($arr['slug' . $Name_table]) && !empty($arr['nom' . $Name_table])) { + $arr_new['slug' . $Name_table] = format_uri($arr['nom' . $Name_table]); + } + } + // FKS : prendre nom et code => appscheme_has_table_field + + foreach ($GRILLE_FK as $field): + $id_fk = $field['idtable_fk']; + if (empty($arr[$id_fk])) continue; + $arr_lnk = $this->appscheme->findOne(['codeAppscheme' => $field['table_fk']]); + $rs_fields = $this->appscheme_has_table_field->find(['idappscheme' => $this->idappscheme, + 'idappscheme_link' => (int)$arr_lnk['idappscheme']]); + + // echo $rs_fields->count(); + $arrq = $this->plug($field['base_fk'], $field['table_fk'])->findOne([$id_fk => (int)$arr[$id_fk]]); + if (empty($arrq)) continue; + foreach ($rs_fields as $arr_fields) { + if ($arr[$arr_fields['codeAppscheme_field'] . ucfirst($field['table_fk'])] == $arrq[$arr_fields['codeAppscheme_field'] . ucfirst($field['table_fk'])]) continue; + $arr_new[$arr_fields['codeAppscheme_field'] . ucfirst($field['table_fk'])] = $arrq[$arr_fields['codeAppscheme_field'] . ucfirst($field['table_fk'])]; + } + // + foreach ($this->app_default_fields_add as $pfield_name) { + $full_field_name = $pfield_name . ucfirst($field['table_fk']); + if (array_key_exists($full_field_name, $arrq)) { + if ($arr[$full_field_name] !== $arrq[$full_field_name]) { + $arr_new[$full_field_name] = $arrq[$full_field_name]; + } + } + } + + endforeach; + + // TYPE STATUT + $arr_has = ['statut', + 'type', + 'categorie', + 'groupe']; + foreach ($arr_has as $key => $statut_type): + $Statut_type = ucfirst($statut_type); + $name_table_type = $name_table . '_' . $statut_type; + $Name_table_type = ucfirst($name_table_type); + $name_table_type_id = 'id' . $name_table_type; + $_nom = 'nom' . $name_table_type; + // + if (!empty($this->app_table_one['has' . $Statut_type . 'Scheme']) && !empty($arr[$name_table_type_id])): + $APP_TYPE = new App($name_table_type); + $arr_tmp = $APP_TYPE->findOne([$name_table_type_id => (int)$arr[$name_table_type_id]]) || []; + + foreach ($this->app_default_fields_add as $pfield_name) { + if (array_key_exists($pfield_name . $Name_table_type, $arr_tmp)) { + if ($arr_tmp[$pfield_name . $Name_table_type] !== $arr[$pfield_name . $Name_table_type]) { + $arr_new[$pfield_name . $Name_table_type] = $arr_tmp[$pfield_name . $Name_table_type]; + } + } + } + + endif; + + endforeach; +// + + // partie metier + if ($name_table == 'appscheme' && !empty($arr['codeAppscheme'])): + $this->consolidate_app_scheme($arr['codeAppscheme']); + endif; + if ($name_table == 'contrat'): + if (!empty($arr['idclient'])): + $APP_TMP = new App('client'); + $rs_test = $col->find(['idclient' => (int)$arr['idclient']])->sort(['dateFinContrat' => 1]); + $arr_test = $rs_test->getNext(); + $arr_cl = $APP_TMP->findOne(['idclient' => (int)$arr['idclient']]); + + if ($arr_cl['dateFinClient'] != $arr_test['dateFinContrat']) $APP_TMP->update(['idclient' => (int)$arr['idclient']], ['dateFinClient' => $arr_test['dateFinContrat']]); + endif; + endif; + if ($name_table == 'conge'): + $new_value = $arr['nomAgent'] . ' ' . strtolower($arr['codeConge_type']) . ' ' . fonctionsProduction::moisDate_fr($arr['dateDebutConge']); + if ($arr['nom' . $Name_table] != $new_value) { + $arr_new['nom' . $Name_table] = $new_value; + } + endif; + if ($name_table == 'ressource'): + $new_value = $arr['quantite' . $Name_table] . ' * ' . $arr['nomProduit'] . ' - ' . $arr['nomProspect'] . $arr['nomClient']; + if ($arr['nom' . $Name_table] != $new_value) { + $arr_new['nom' . $Name_table] = $new_value; + }; + endif; + if ($name_table == 'opportunite_ligne'): + $new_value = $arr['quantite' . $Name_table] . ' * ' . $arr['nomProduit']; + if ($arr['nom' . $Name_table] != $new_value) { + $arr_new['nom' . $Name_table] = $new_value; + }; + endif; + + if ($name_table == 'commande'): + $new_value = date('dmy') . auto_code($arr['codeClient']) . auto_code($arr['codeShop']); + if ($arr['code' . $Name_table] != $new_value) { + // $arr_new['code' . $Name_table] = $new_value; + }; + endif; + + if (empty($arr['code' . $Name_table]) && empty($arr_new['code' . $Name_table])): + $arr_new['code' . $Name_table] = auto_code($arr['nom' . $Name_table]); + endif; + if (empty($arr['nom' . $Name_table]) && empty($arr_new['nom' . $Name_table])): + foreach ($GRILLE_FK as $field): + $id_fk = $field['idtable_fk']; + if (empty($arr[$id_fk])) continue; + // + $dsp_name = $arr['nom' . ucfirst($field['table_fk'])]; + // + $arr_new['nom' . $Name_table] .= strtolower($dsp_name) . ' '; + endforeach; + endif; + if (empty($arr['nom' . $Name_table]) && empty($arr_new['nom' . $Name_table])): + if (!empty($APP_TABLE['hasTypeScheme'])): + // $arr_new['nom' . $Name_table] = $arr['nom' . $Name_table.'_type']; + endif; + // $arr_new['nom' . $Name_table] .= substr(strip_tags($arr['code' . $Name_table]),0,5) ; + if (!empty($APP_TABLE['hasDateScheme']) && !empty($arr['dateDebut' . $Name_table])): + $arr_new['nom' . $Name_table] .= ' ' . date_fr($arr['dateDebut' . $Name_table]); + endif; + // $arr_new['nom' . $Name_table] .= substr(strip_tags($arr['description' . $Name_table]),0,10); + endif; + if (sizeof($arr_new) != 0) { + $arr_new ['updated_fields'] = $arr_new; // log ??? + // versioning + $arr_new['dateModification' . $Name_table] = date('Y-m-d'); + $arr_new['heureModification' . $Name_table] = date('H:i:s'); + $arr_new['timeModification' . $Name_table] = time(); + + $col->update([$name_id => $value_id], ['$set' => $arr_new], ['upsert' => true]); + } + if ($rs->count() == 1) { + return $arr_new; + } + + endwhile; + } + + function update($vars, $fields = [], $upsert = true) { + $table = $this->app_table_one['codeAppscheme']; + $table_value = (int)$vars[$this->app_field_name_id]; + // anciennes valeurs + if (empty($table_value)) { + echo "probleme de mise à jour"; + + //vardump_async("$table sans value en update"); + + return; + } + $arr_one_before = $this->findOne([$this->app_field_name_id => $table_value]); + // differences avec anciennes valeurs + $arr_inter = array_diff_assoc($fields, (array)$arr_one_before); + if (sizeof($arr_inter) == 0) { + // AppSocket::send_cmd('act_notify', ['msg' => 'Mise à jour inutile'], session_id()); + + return; + } + // on garde la différence + $fields = $arr_inter; + // UPDATE !!! + $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->update($vars, ['$set' => $fields], ['upsert' => $upsert]); + $this->consolidate_scheme($table_value); + // + $arr_one_after = $this->findOne([$this->app_field_name_id => $table_value]); + + $updated_fields_real = array_diff_assoc((array)$arr_one_after, (array)$arr_one_before); + $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->update($vars, ['$set' => ['updated_fields' => $updated_fields_real]], ['upsert' => $upsert]); + + // AppSocket::send_cmd('act_notify',['msg'=>json_encode($updated_fields_real,JSON_PRETTY_PRINT),'options'=>['sticky'=>true]],session_id()); + + $update_diff_cast = []; + foreach ($updated_fields_real as $k => $v): + $exp['field_name'] = $k; + $exp['field_value'] = $v; + //if($v==$vars[$k] || empty($vars[$k])) continue; + $update_diff_cast[$k] = App::cast_field_all($exp, true); // new_vars deviendra vars + endforeach; + + AppSocket::send_cmd('act_upd_data', ['table' => $table, + 'table_value' => $table_value, + 'new_vars' => $update_diff_cast]); + + // log + $R_FK = $this->get_reverse_grille_fk($this->app_table_one['codeAppscheme'], (int)$vars[$this->app_field_name_id]); + // + if (!empty($fields['nom' . ucfirst($table)])): + foreach ($R_FK as $arr_fk): + $value_rfk = $arr_fk['table_value']; + $table_rfk = $arr_fk['table']; + $vars_rfk['vars'] = ['id' . $table => $table_value]; + $vars_rfk['table'] = $table_rfk; + $vars_rfk['table_value'] = $value_rfk; + $count = $arr_fk['count']; + + if (!empty($count)): + $APPCONV = new App($table_rfk); + $sd_vars = ['id' . $table => $table_value]; + $fields_fk = ['nom' . ucfirst($table) => $fields['nom' . ucfirst($table)]]; + $APPCONV->update($sd_vars, $fields_fk); + + endif; + endforeach; + endif; + + return $update_diff_cast; + } + + function cast_field_all($vars = [], $nude = false) { // json_data_table ! + $field_name = $vars['field_name']; + + if (is_array($vars['field_value'])) { + + return $vars['field_value']; + } + $value = $vars['field_value']; + + if (empty($vars['codeAppscheme_field_type'])) { + $arr_tmp = $this->appscheme_has_field->findOne(['codeAppscheme_has_field' => $field_name]); + $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $arr_tmp['codeAppscheme_field']]); + $vars['codeAppscheme_field_type'] = $arr_tmp['codeAppscheme_field_type']; + } + + switch ($vars['codeAppscheme_field_type']): + case 'distance': + $value = round($value / 1000, 2) . ' kms'; + break; + case 'minutes': + if (empty($value)) break; + $value = ceil($value / 60) . ' minutes '; + break; + case 'bool': + $arr_field = $this->appscheme_has_field->findOne(['codeAppscheme_has_field' => $field_name]); + $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $arr_field['codeAppscheme_field']]); + $icon = $arr_tmp['iconAppscheme_field']; + $css = empty($value) ? 'textgris' : 'textvert'; + $text = empty($icon) ? ouiNon($value) : ouiNon($value); + $value = " $text"; + break; + case 'valeur': + $value = $value; + break; + case 'prix': + $value = maskNbre($value, 2) . ' €'; + break; + case 'prix_precis': + $value = maskNbre((float)$value, 6) . ' €'; + break; + case 'pourcentage': + $value = (float)$value . ' %'; + break; + case 'date': + $value = date_fr($value); + break; + case 'heure': + $value = maskHeure($value); + break; + case 'phone': + $value = maskTel($value); + break; + case 'icon': + $value = ""; + break; + case 'color': + $value = ""; + break; + case 'textelibre': + $value = nl2br(stripslashes($value)); + break; + endswitch; + $str = "$value"; + + return $str; + } + + function distinct_all($groupBy, $vars = [], $limit = 200, $mode = 'full') { + + // table sur laquelle on bosse + $dist = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme']); + if (sizeof($vars) != 0) { + $first_arr_dist = $dist->distinct($groupBy, $vars); + } else { + $first_arr_dist = $dist->distinct($groupBy); + } + + return $first_arr_dist; + } + + function remove($vars = []) { + if (sizeof($vars) == 0) return; + $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->remove($vars); + } + + function init_scheme($base, $table, $options = [], $force = false) { + if (empty($table) || empty($base)) return false; + $test_base = $this->appscheme_base->findOne(['codeAppscheme_base' => $base]); + $test = $this->appscheme->findOne(['codeAppscheme' => $table]); + if (empty($test_base['idappscheme_base'])) { + $ins['idappscheme_base'] = $this->getNext('idappscheme_base'); + $ins['codeAppscheme_base'] = $base; + $ins['nomAppscheme_base'] = $base; + $this->appscheme_base->insert($ins); + + } else { + $ins['idappscheme_base'] = (int)$test_base['idappscheme_base']; + $ins['codeAppscheme_base'] = $base; + $ins['nomAppscheme_base'] = $test_base['nomAppscheme_base']; + } + if (empty($test['idappscheme'])) { + $ins['idappscheme'] = $this->getNext('idappscheme'); + } elseif ($force == true) { + + $ins['idappscheme'] = (int)$test['idappscheme']; + unset($ins['_id']); + } else { + return; + } + + $ins['codeAppscheme'] = $table; + $ins['nomAppscheme'] = $table; + if (!empty($options['has'])) { + foreach ($options['has'] as $key => $value) { + $ins['has' . ucfirst($value) . 'Scheme'] = 1; + } + unset($options['has']); + } + if (!empty($options['has'])) { + foreach ($options['has'] as $key => $value) { + $ins['has' . ucfirst($value) . ucfirst($table)] = 1; + } + unset($options['has']); + } + if (!empty($options['fields'])) { + foreach ($options['fields'] as $key => $value) { + $ARRF = $this->appscheme_field->findOne(['codeAppscheme_field' => $value]); + if (!empty($ARRF['idappscheme_field'])) $arr_field[] = (int)$ARRF['idappscheme_field']; else { + $APPF = new App('appscheme_field'); + $arr_field[] = $APPF->create_update(['codeAppscheme_field' => $value], ['nomAppscheme_field' => $value]); + } + } + unset($options['fields']); + } + if (!empty($options['grilleFK'])) { + $ARRFK = []; + foreach ($options['grilleFK'] as $key => $value) { + $ARRFK [(int)$key] = ['table' => $value, + 'ordreTable' => (int)$key, + 'uid' => uniqid()]; + } + $ins['grilleFK'] = $ARRFK; + unset($options['grilleFK']); + } + $ins = array_filter($ins); + $this->appscheme->update(['idappscheme' => $ins['idappscheme']], ['$set' => $ins], ['upsert' => 1]); + + $APP_TMP = new App('appscheme'); + $APP_TMP->consolidate_scheme($ins['idappscheme']); + if (!empty($arr_field)) { + $APP_SCH_HAS = new App('appscheme_has_field'); + foreach ($arr_field as $key => $value) { + $id = (int)$value; + $idschas = $APP_SCH_HAS->create_update(['idappscheme' => $ins['idappscheme'], + 'idappscheme_field' => $id]); + $APP_SCH_HAS->consolidate_scheme($idschas); + } + } + + return new App($table); + } + + function update_native($vars, $fields = [], $upsert = true) { + $table = $this->app_table_one['codeAppscheme']; + if (empty($vars[$this->app_field_name_id]) && empty($vars['_id'])) { + if (empty($table_value)) { + // vardump_async("$table sans value en update"); + //return; + } + } + $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->update($vars, ['$set' => $fields], ['upsert' => $upsert, + 'multi' => 1]); + + } + + /** + * field list + grille fk + * + * @param array $in + * + * @return array + */ + function get_field_list_all($in = []) { + $out = []; + if (!empty($in)) $DIST = $this->appscheme_field->distinct('idappscheme_field', $in); + if (!empty($in)) $DIST_2 = $this->appscheme_has_field->distinct('idappscheme_field'); + if (empty($DIST)) return $out; + $DIST_all = array_merge($DIST, $DIST_2); + $DIST_all = (!empty($DIST_all)) ? ['idappscheme_field' => ['$in' => $DIST_all]] : []; + + $rsG = $this->appscheme_has_field->find($DIST_all + ['idappscheme' => (int)$this->idappscheme]); + // $rsG = $this->appscheme_field->find( ['idappscheme_field' => ['$in' => $arr_field]]); + $a = []; + while ($arrg = $rsG->getNext()) : + $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); + $a['iconAppscheme_field'] = $test['iconAppscheme_field']; + $a['nomAppscheme_field'] = $test['nomAppscheme_field']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field']; + $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; + $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; + $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; + $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); + $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); + $a['field_name_raw'] = $test['codeAppscheme_field']; + $out[$a['field_name']] = $a; + endwhile; + $a = []; + foreach ($this->grilleFK as $keyFK => $fieldFK) { + $table_fk = $fieldFK['table']; + $rsG = $this->appscheme_has_field->find(['codeAppscheme' => $table_fk]); + + while ($arrg = $rsG->getNext()) : + $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); + $a['iconAppscheme_field'] = $test['iconAppscheme_field']; + $a['nomAppscheme_field'] = $test['nomAppscheme_field']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field']; + $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; + $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; + $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; + $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); + $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); + $a['field_name_raw'] = $test['codeAppscheme_field']; + $out[$a['field_name']] = $a; + endwhile; + } + + return $out; + } + + /** + * @param array $in + * + * @return array + */ + function get_field_list($in = []) { + $out = $DIST = $DIST_2 = []; + if (!empty($in)) $DIST = $this->appscheme_field->distinct('idappscheme_field', $in); + if (!empty($in)) $DIST_2 = $this->appscheme_has_field->distinct('idappscheme_field'); + $DIST_all = array_merge($DIST, $DIST_2); + $DIST_all = (!empty($DIST_all)) ? ['idappscheme_field' => ['$in' => $DIST_all]] : []; + $rsG = $this->appscheme_has_field->find($DIST + ['idappscheme' => (int)$this->idappscheme]); + // $rsG = $this->appscheme_field->find( ['idappscheme_field' => ['$in' => $arr_field]]); + $a = []; + while ($arrg = $rsG->getNext()) : + $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); + $a['iconAppscheme_field'] = $test['iconAppscheme_field']; + $a['nomAppscheme_field'] = $test['nomAppscheme_field']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field']; + $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; + $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; + $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; + $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); + $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); + $a['field_name_raw'] = $test['codeAppscheme_field']; + $out[$a['field_name']] = $a; + endwhile; + + $rsG = $this->appscheme_has_table_field->find($DIST + ['idappscheme' => (int)$this->idappscheme]); + // idappscheme_link + $a = []; + while ($arrg = $rsG->getNext()) : + $test = $this->appscheme->findOne(['idappscheme' => (int)$arrg['idappscheme_link']]); + $a['nomAppscheme'] = $test['nomAppscheme']; + $a['codeAppscheme'] = $test['codeAppscheme']; + $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); + $a['iconAppscheme_field'] = $test['iconAppscheme_field']; + $a['nomAppscheme_field'] = $test['nomAppscheme_field']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field']; + $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; + $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; + $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; + $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; + + $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($a['codeAppscheme']); + $a['field_name_raw'] = $test['codeAppscheme_field']; + $out[$a['field_name']] = $a; + endwhile; + + return $out; + } + + /** + * @param array $vars + * @param bool $nude + */ + function cast_field($vars = [], $nude = false) { // json_data_table ! + $field_name = $vars['field_name']; + $field_name_raw = $vars['field_name_raw']; + if (is_array($vars['field_value'])) { + + return $vars['field_value']; + } + $value = $vars['field_value'];//nl2br($vars['field_value']); + + if (str_find($field_name, 'date')) { + $value = date_fr($value); + } + if (str_find($field_name, 'nbre')) { + $value = maskNbre($value); + } + if (str_find($field_name, 'prix')) { + // $value = maskNbre($value); + } + if (str_find($field_name, 'telephone')) { + $value = maskTel($value); + } + if (str_find($field_name, 'mobile')) { + $value = maskTel($value); + } + if (str_find($field_name, 'duree')) { + $value = (float)$value; + } + if (str_find($field_name, 'code')) { + + } + if (str_find($field_name, 'color')) { + $vars['codeAppscheme_field_type'] = 'color'; + } + if (str_find($field_name, 'icon')) { + $vars['codeAppscheme_field_type'] = 'icon'; + } + if (str_find($field_name, 'actif')) { + $vars['codeAppscheme_field_type'] = 'bool'; + } + if (empty($vars['codeAppscheme_field_type'])) { + $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $field_name_raw]); + $vars['codeAppscheme_field_type'] = $arr_tmp['codeAppscheme_field_type']; + } + switch ($vars['codeAppscheme_field_type']): + case 'distance': + $value = round($value / 1000, 2) . ' kms'; + break; + case 'minutes': + if (empty($value)) break; + $value = ceil($value / 60); + break; + case 'bool': + $arr_tmp = $this->appscheme_field->findOne(['codeAppscheme_field' => $field_name_raw]); + $icon = $arr_tmp['iconAppscheme_field']; + $css = empty($value) ? 'textgris' : ''; + $text = empty($icon) ? ouiNon($value) : ''; + $value = ""; + break; + case 'valeur': + $value = $value; + break; + case 'prix': + $value = maskNbre($value, 2) . ' €'; + break; + case 'prix_precis': + $value = maskNbre((float)$value, 6) . ' €'; + break; + case 'pourcentage': + $value = (float)$value . ' %'; + break; + case 'date': + $value = date_fr($value); + break; + case 'heure': + $value = maskHeure($value); + break; + case 'phone': + $value = maskTel($value); + break; + case 'icon': + $value = ""; + break; + case 'color': + $value = ""; + break; + case 'textelibre': + $value = nl2br(stripslashes($value)); + break; + endswitch; + $str = "$value"; + + return $str; + } + + function query($vars = [], $page = 0, $rppage = 40, $fields = []) { + if (empty($rppage)) { + $rppage = 15; + } + if (empty($this->app_table_one['codeAppscheme_base'])) { + die(' [' . $this->table . '-' . $this->app_table_one['codeAppscheme_base'] . '-' . $this->app_table_one['codeAppscheme'] . ']'); + exit; + } + $rs = $this->plug($this->app_table_one['codeAppscheme_base'], $this->app_table_one['codeAppscheme'])->find($vars, $fields); + $totcount = $rs->count(); + $rs->sort([$this->app_field_name_top => -1, + $this->app_field_name_nom => 1]); + $rs->skip($page * $rppage)->limit($rppage); + + return $rs; + } + + function get_field_list_raw($in = []) { + $out = []; + if (!empty($in)) $DIST = $this->appscheme_field->distinct('idappscheme_field', $in); + $DIST = (!empty($DIST)) ? ['idappscheme_field' => ['$in' => $DIST]] : []; + + $rsG = $this->appscheme_has_field->find($DIST + ['idappscheme' => (int)$this->idappscheme]); + // $rsG = $this->appscheme_field->find( ['idappscheme_field' => ['$in' => $arr_field]]); + $a = []; + while ($arrg = $rsG->getNext()) : + $test = $this->appscheme_field->findOne(['idappscheme_field' => (int)$arrg['idappscheme_field']]); + $a['iconAppscheme_field'] = $test['iconAppscheme_field']; + $a['nomAppscheme_field'] = $test['nomAppscheme_field']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field']; + $a['nomAppscheme_field_type'] = $test['nomAppscheme_field_type']; + $a['codeAppscheme_field_type'] = $test['codeAppscheme_field_type']; + $a['nomAppscheme_field_group'] = $test['nomAppscheme_field_group']; + $a['codeAppscheme_field_group'] = $test['codeAppscheme_field_group']; + $a['codeAppscheme_field'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); + $a['field_name'] = $test['codeAppscheme_field'] . ucfirst($arrg['codeAppscheme']); + $a['field_name_raw'] = $test['codeAppscheme_field']; + $out[$a['field_name']] = $a; + endwhile; + + return $out; + } + } diff --git a/web/bin/classes/ClassAppCharges.php b/web/bin/classes/ClassAppCharges.php index 7118034..f243ba2 100644 --- a/web/bin/classes/ClassAppCharges.php +++ b/web/bin/classes/ClassAppCharges.php @@ -1,44 +1,44 @@ - $total_commande_client, - 'total_livraison_commande' => $total_livraison_commande, - 'margeCommande_facture' => round($gain, 3), - 'totalCommande_facture' => round($toshare, 3), - 'partShopCommande_facture' => round($toshare_shop, 3), - 'partLivreurCommande_facture' => round($toshare_agent, 3)]; - - return $return; - - } - + $total_commande_client, + 'total_livraison_commande' => $total_livraison_commande, + 'margeCommande_facture' => round($gain, 3), + 'totalCommande_facture' => round($toshare, 3), + 'partShopCommande_facture' => round($toshare_shop, 3), + 'partLivreurCommande_facture' => round($toshare_agent, 3)]; + + return $return; + + } + } \ No newline at end of file diff --git a/web/bin/classes/ClassAppLink.php b/web/bin/classes/ClassAppLink.php index 45de053..2091396 100644 --- a/web/bin/classes/ClassAppLink.php +++ b/web/bin/classes/ClassAppLink.php @@ -1,117 +1,117 @@ - $table, - 'table_value' => $table_value, - 'vars' => array_filter($vars)]); - - return http_build_query($out); - } - - private static function build_link($mdl, $uri) { - - return "idae/module/$mdl/$uri";//encrypt_url("$mdl/$uri"); - } + $table, + 'table_value' => $table_value, + 'vars' => array_filter($vars)]); + + return http_build_query($out); + } + + private static function build_link($mdl, $uri) { + + return "idae/module/$mdl/$uri";//encrypt_url("$mdl/$uri"); + } } \ No newline at end of file diff --git a/web/bin/classes/ClassAppMail.php b/web/bin/classes/ClassAppMail.php index 9556ee2..954d29c 100644 --- a/web/bin/classes/ClassAppMail.php +++ b/web/bin/classes/ClassAppMail.php @@ -1,81 +1,81 @@ -body = 'body'; - $this->body_strip = strip_tags($this->body); - $this->subject = 'subject'; - $this->sender_email = SMTPUSER; - $this->destinataire_email = null; - $this->destinataire_name = 'Mydde'; - } - - function set_subject($body) { - $this->subject = $body; - } - function set_body($body) { - $this->body = $body; - $this->body_strip = strip_tags($body); - } - - function set_sender_email($body) { - $this->sender_email = $body; - } - - function set_destinataire_email($destinataire_email) { - $this->destinataire_email = $destinataire_email; - } - function set_destinataire_name($body) { - $this->destinataire_name = $body; - } - function sendMail() { - include_once(APPCLASSES . 'ClassSMTP.php'); - - $mail = new PHPMailer(); - - $mail->IsSMTP(); - $mail->IsHTML(); - $mail->WordWrap = 50; - $mail->SMTPDebug = 0; - $mail->SMTPAuth = true; - $mail->SMTPOptions = [ // PREPROD ? - 'ssl' => [ - 'verify_peer' => false, - 'verify_peer_name' => false, - 'allow_self_signed' => true - ] - ]; - $mail->CharSet = 'UTF-8'; - $mail->Hostname = SMTPDOMAIN; - $mail->Helo = SMTPDOMAIN; - $mail->Host = SMTPHOST; - $mail->Username = SMTPUSER; - $mail->Password = SMTPPASS; - $mail->SetFrom(SMTPUSER, 'postmaster tac-tac'); - // $mail->AddReplyTo($_POST['emailFrom'] , $_POST['emailFromName']); - $mail->Subject = $this->subject; - $mail->AltBody = strip_tags($this->body); - $this->destinataire_email; - $mail->AddAddress($this->destinataire_email, $this->destinataire_name); - - $mail->MsgHTML($this->body); - - if (!$mail->Send()) { - AppSocket::send_cmd('act_notify', ['msg' => 'Erreur envoi email'], session_id()); - - return false; - } else { - return true; - } - } +body = 'body'; + $this->body_strip = strip_tags($this->body); + $this->subject = 'subject'; + $this->sender_email = SMTPUSER; + $this->destinataire_email = null; + $this->destinataire_name = 'Mydde'; + } + + function set_subject($body) { + $this->subject = $body; + } + function set_body($body) { + $this->body = $body; + $this->body_strip = strip_tags($body); + } + + function set_sender_email($body) { + $this->sender_email = $body; + } + + function set_destinataire_email($destinataire_email) { + $this->destinataire_email = $destinataire_email; + } + function set_destinataire_name($body) { + $this->destinataire_name = $body; + } + function sendMail() { + include_once(APPCLASSES . 'ClassSMTP.php'); + + $mail = new PHPMailer(); + + $mail->IsSMTP(); + $mail->IsHTML(); + $mail->WordWrap = 50; + $mail->SMTPDebug = 0; + $mail->SMTPAuth = true; + $mail->SMTPOptions = [ // PREPROD ? + 'ssl' => [ + 'verify_peer' => false, + 'verify_peer_name' => false, + 'allow_self_signed' => true + ] + ]; + $mail->CharSet = 'UTF-8'; + $mail->Hostname = SMTPDOMAIN; + $mail->Helo = SMTPDOMAIN; + $mail->Host = SMTPHOST; + $mail->Username = SMTPUSER; + $mail->Password = SMTPPASS; + $mail->SetFrom(SMTPUSER, 'postmaster tac-tac'); + // $mail->AddReplyTo($_POST['emailFrom'] , $_POST['emailFromName']); + $mail->Subject = $this->subject; + $mail->AltBody = strip_tags($this->body); + $this->destinataire_email; + $mail->AddAddress($this->destinataire_email, $this->destinataire_name); + + $mail->MsgHTML($this->body); + + if (!$mail->Send()) { + AppSocket::send_cmd('act_notify', ['msg' => 'Erreur envoi email'], session_id()); + + return false; + } else { + return true; + } + } } \ No newline at end of file diff --git a/web/bin/classes/ClassAppSite.php b/web/bin/classes/ClassAppSite.php index ba253e1..d6be81a 100644 --- a/web/bin/classes/ClassAppSite.php +++ b/web/bin/classes/ClassAppSite.php @@ -1,191 +1,191 @@ - $size): - // if(!empty($this->app_table_one['hasImage'.$size.'Scheme'])){ } - $out['image_' . $table . '_' . $size] = $this->imgSrc($table . '-' . $size . '-' . $value_id); - - endforeach; - - return $out; - } - - static function imgSrc($image_name) { - - $APP = new App(); - $raw_image_name = $image_name; - $file_extension = strtolower(substr(strrchr($image_name, '.'), 1)); - if (empty($file_extension)) { - $image_name .= '.jpg'; - }; - $type = empty($reflect) ? 'jpg' : 'png'; - - $grid = $APP->plug_base('sitebase_image')->getGridFs(); - // - $image = $grid->findOne(['filename' => $image_name]); - if (empty($image)) { - $image = $grid->findOne(['filename' => $raw_image_name]); - } - $dir = $image->file['metadata']['tag'] . '/'; // tag = table - $file = $image->file; - - switch ($file['metadata']['contentType']) { - case "image/jpeg": - $ext = 'jpg'; - break; - case "image/jpg": - $ext = 'jpg'; - break; - case "image/gif": - $ext = 'gif'; - break; - case "image/png": - $ext = 'png'; - break; - default: - $ext = 'jpg'; - break; - } - - // echo FLATTENIMGDIR . $dir; - - $image_file = FLATTENIMGDIR . $dir . $image_name; - $image_http_file = FLATTENIMGHTTP . $dir . $image_name; - - if (!file_exists(FLATTENIMGDIR)) { - mkdir(FLATTENIMGDIR); - } - if (!file_exists(FLATTENIMGDIR . $dir)) { - mkdir(FLATTENIMGDIR . $dir); - } - if (empty($image) && !file_exists($image_file)) { - // echo "ok 3 "; - return ''; - - return empty($image) . " but not found $image_file";// HTTPIMAGES."blank.png?f=".$image_http_file; - - } - if (!empty($image) || !file_exists($image_file)) { - // on écrit image - $file = $image->file; - $sdir = $image->file['metadata']['tag']; - if (is_array($sdir)) { - $sdir = $sdir[0]; - } - - $dir = FLATTENIMGDIR . $sdir . '/'; - if (!file_exists($dir) && !empty($file['length'])) { - mkdir($dir, 0777); - } - if (file_exists($dir) && !empty($file['length']) && !empty($file['chunkSize'])): - - if (file_exists($dir . $image_name)) { - $length = $image->file['length']; - $filesize = filesize($dir . $image_name); - - if ($length == $filesize): - return $image_http_file; - else: - //@chmod($dir , 777); - $image->write($dir . $image_name); - - return $image_http_file; - endif; - } - if (!file_exists($dir . $image_name)) { - - $image->write($dir . $image_name); - - return $image_http_file; - } - endif; - - } - if (file_exists($image_file)) { - return $image_http_file; - - } - - return $image_name; - } - - public function render($html = '', $parameters = []) { - global $LATTE; - - $parameters['route'] = $html; - $parameters['site_page'] = $this->site_page; - $parameters['meta_tile'] = $this->get_meta_title(); - $parameters['meta_description'] = $this->get_meta_description(); - - $Fragment = new Fragment(); - $parameters['menu_bar'] = $Fragment->menu_bar(true); - $parameters['html_footer'] = $Fragment->footer(true); - // $LATTE->setAutoRefresh(true); - $LATTE->setAutoRefresh(false); - if ($this->site_page == 'application') { - echo $html = $LATTE->renderToString(APPTPL . 'idae/body.html', $parameters); - } else { - echo $html = $LATTE->renderToString(APPTPL . 'body.html', $parameters); - } - } - - function get_meta_title() { - $meta_tile = ''; - switch ($this->site_page): - case 'index': - $meta_tile = 'tac-tac city votre service de livraison preféré'; - break; - case 'shop': - $meta_tile = 'tac-tac city restaurant'; - break; - - endswitch; - - return empty($this->meta_title) ? $meta_tile : $this->meta_title; - } - - function set_meta_title($meta_title = '') { - $this->meta_title = $meta_title; - } - - function get_meta_description() { - return $this->meta_description; - } - - function set_meta_description($meta_title = '') { - $this->meta_description = $meta_title; - } - - function set_page($site_page = '') { - $this->site_page = $_SESSION['site_page'] = $site_page; - } - - function get_page() { - return $_SESSION['site_page']; - } + $size): + // if(!empty($this->app_table_one['hasImage'.$size.'Scheme'])){ } + $out['image_' . $table . '_' . $size] = $this->imgSrc($table . '-' . $size . '-' . $value_id); + + endforeach; + + return $out; + } + + static function imgSrc($image_name) { + + $APP = new App(); + $raw_image_name = $image_name; + $file_extension = strtolower(substr(strrchr($image_name, '.'), 1)); + if (empty($file_extension)) { + $image_name .= '.jpg'; + }; + $type = empty($reflect) ? 'jpg' : 'png'; + + $grid = $APP->plug_base('sitebase_image')->getGridFs(); + // + $image = $grid->findOne(['filename' => $image_name]); + if (empty($image)) { + $image = $grid->findOne(['filename' => $raw_image_name]); + } + $dir = $image->file['metadata']['tag'] . '/'; // tag = table + $file = $image->file; + + switch ($file['metadata']['contentType']) { + case "image/jpeg": + $ext = 'jpg'; + break; + case "image/jpg": + $ext = 'jpg'; + break; + case "image/gif": + $ext = 'gif'; + break; + case "image/png": + $ext = 'png'; + break; + default: + $ext = 'jpg'; + break; + } + + // echo FLATTENIMGDIR . $dir; + + $image_file = FLATTENIMGDIR . $dir . $image_name; + $image_http_file = FLATTENIMGHTTP . $dir . $image_name; + + if (!file_exists(FLATTENIMGDIR)) { + mkdir(FLATTENIMGDIR); + } + if (!file_exists(FLATTENIMGDIR . $dir)) { + mkdir(FLATTENIMGDIR . $dir); + } + if (empty($image) && !file_exists($image_file)) { + // echo "ok 3 "; + return ''; + + return empty($image) . " but not found $image_file";// HTTPIMAGES."blank.png?f=".$image_http_file; + + } + if (!empty($image) || !file_exists($image_file)) { + // on écrit image + $file = $image->file; + $sdir = $image->file['metadata']['tag']; + if (is_array($sdir)) { + $sdir = $sdir[0]; + } + + $dir = FLATTENIMGDIR . $sdir . '/'; + if (!file_exists($dir) && !empty($file['length'])) { + mkdir($dir, 0777); + } + if (file_exists($dir) && !empty($file['length']) && !empty($file['chunkSize'])): + + if (file_exists($dir . $image_name)) { + $length = $image->file['length']; + $filesize = filesize($dir . $image_name); + + if ($length == $filesize): + return $image_http_file; + else: + //@chmod($dir , 777); + $image->write($dir . $image_name); + + return $image_http_file; + endif; + } + if (!file_exists($dir . $image_name)) { + + $image->write($dir . $image_name); + + return $image_http_file; + } + endif; + + } + if (file_exists($image_file)) { + return $image_http_file; + + } + + return $image_name; + } + + public function render($html = '', $parameters = []) { + global $LATTE; + + $parameters['route'] = $html; + $parameters['site_page'] = $this->site_page; + $parameters['meta_tile'] = $this->get_meta_title(); + $parameters['meta_description'] = $this->get_meta_description(); + + $Fragment = new Fragment(); + $parameters['menu_bar'] = $Fragment->menu_bar(true); + $parameters['html_footer'] = $Fragment->footer(true); + // $LATTE->setAutoRefresh(true); + $LATTE->setAutoRefresh(false); + if ($this->site_page == 'application') { + echo $html = $LATTE->renderToString(APPTPL . 'idae/body.html', $parameters); + } else { + echo $html = $LATTE->renderToString(APPTPL . 'body.html', $parameters); + } + } + + function get_meta_title() { + $meta_tile = ''; + switch ($this->site_page): + case 'index': + $meta_tile = 'tac-tac city votre service de livraison preféré'; + break; + case 'shop': + $meta_tile = 'tac-tac city restaurant'; + break; + + endswitch; + + return empty($this->meta_title) ? $meta_tile : $this->meta_title; + } + + function set_meta_title($meta_title = '') { + $this->meta_title = $meta_title; + } + + function get_meta_description() { + return $this->meta_description; + } + + function set_meta_description($meta_title = '') { + $this->meta_description = $meta_title; + } + + function set_page($site_page = '') { + $this->site_page = $_SESSION['site_page'] = $site_page; + } + + function get_page() { + return $_SESSION['site_page']; + } } \ No newline at end of file diff --git a/web/bin/classes/ClassAppSocket.php b/web/bin/classes/ClassAppSocket.php index bc85079..5769751 100644 --- a/web/bin/classes/ClassAppSocket.php +++ b/web/bin/classes/ClassAppSocket.php @@ -1,425 +1,425 @@ -" : ""; // title='$module=$value' - $end = ($moduleTag != 'none') ? "" : ""; - - ob_start(); - $final = ''; - $final .= $start; - if (file_exists(APPMDL . '/' . $module . '.php')) { - - if (empty($array['defer'])) { - if (empty($array['emptyModule'])) { - $tempPost = $_POST; - $_POST = $arrQuery; - // $_POST['MODULE'] = $module; - include(APPMDL . '/' . $module . '.php'); - $_POST = $tempPost; - //$final .= AppSocket::doCurl(HTTPMDL . $module . '.php' , $array); - } - } else { - // echo('scripo'); - - } - } else { - // $final .= "missing" . APPMDL . '/' . $module . '.php'; - } - $final .= $end; - - $final = ob_get_contents(); - $final = $start . $final . $end; - ob_end_clean(); - - return trim($final); - - } - - static function reloadModule($module, $value='*', $vars = [],$room = null) { - $arrjson = ['timeStamp' => (int)time(), 'module' => $module, 'value' => $value,'room'=>$room]; - if (sizeof($vars) != 0) { - $arrjson['vars'] = $vars; - } - - AppSocket::send_cmd('act_reload_module',$arrjson,$room); - //return $dozat; - } - static function reloadMdlTest($module, $value='*', $vars = [],$room = null) { - - $arrjson = ['timeStamp' => (int)time(), 'mdl_test' => $module, 'value' => $value,'room'=>$room]; - if (sizeof($vars) != 0) { - $arrjson['vars'] = $vars; - } - - AppSocket::send_cmd('act_reload_module',$arrjson,$room); - //return $dozat; - } - - function doCurl($module, $array = []) { - /*$ckfile = COOKIE_PATH . "cookie.txt"; - $fp = fopen($ckfile, "w"); - fclose($fp);*/ - $array['iscurlmdl'] = '1'; - $strcookie = session_name() . "=" . session_id() . "; path=" . session_save_path(); - // session_write_close(); - $curl = curl_init(); - curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($array)); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($curl, CURLOPT_COOKIESESSION, TRUE); - curl_setopt($curl, CURLOPT_HEADER, 0); - // curl_setopt($curl, CURLOPT_HTTPHEADER,array("Expect:")); - /*curl_setopt($curl , CURLOPT_COOKIEFILE , $ckfile); - curl_setopt($curl , CURLOPT_COOKIEJAR , $ckfile);*/ - curl_setopt($curl, CURLOPT_COOKIE, $strcookie); - curl_setopt($curl, CURLOPT_URL, $module); // - curl_setopt($curl, CURLOPT_POST, 1); - $page = curl_exec($curl); - if ($page === false) { - // trigger_error('Erreur curl : ' . curl_error($curl) . ' ' . $module, E_USER_WARNING); - } - // curl_close($curl); - - //unlink($ckfile); - return ($page); - } - - static function run($mdl, $vars = [], $room = '') { - - $arrjson = ['mdl' => $mdl]; - if (sizeof($vars) != 0) { - $arrjson['vars'] = $vars; - } - if (!empty($room)) { - $arrjson['OWN'] = $room; - } - - AppSocket::doPost(HTTPHOSTNOPORT . ':' . SOCKETIO_PORT . '/run', $arrjson); - } - - static function doPost($url, $vars = []) { - - $crlf = "\r\n"; - $parts = parse_url($url); - $cookie_str = session_name() . "=" . session_id(). "; path=" . session_save_path(); - - // - // $fp = fsockopen('ssl://'.$parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30); - $fp = fsockopen($_SERVER['HTTP_HOST'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30); - - $vars['DOCUMENTDOMAIN'] = DOCUMENTDOMAIN; - $vars['PHPSESSID'] = session_id(); - $query = http_build_query($vars); - - - if (!$fp) { - - // AppSocket::send_cmd('act_notify', ['msg' => 'ERREUR ' . $errstr . ' $errno ' . $errno, session_id()]); - - return false; - } else { - $out = "POST " . $parts['path'] . " HTTP/1.1" . $crlf; - $out .= "Host: ". $parts['scheme'].'://'. $parts['host'].':'.$parts['port'] . $crlf; - $out .= "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0" . $crlf; - $out .= "Origin: ".HTTPHOST."" . $crlf; - $out .= "Content-Type: application/x-www-form-urlencoded" . $crlf; - $out .= "Content-Length: " . strlen($query) . $crlf; - $out .= "Connection: Close" . $crlf; - $out .= $crlf; - - if (isset($query)) { - $out .= $query; - } - if (!empty($cookie_str)) { - $out .= 'Cookie: ' . substr($cookie_str, 0, -2) . $crlf; - } - - fwrite($fp, $out); - fclose($fp); - - return true; - } - } - - static function send_cmd($cmd, $vars = [], $room = '') { - $arrjson = ['timeStamp' => (int)time(), 'cmd' => $cmd]; - // - if (sizeof($vars) != 0) { - $arrjson['vars'] = $vars; - } - // - if (!empty($room)) { - $arrjson['OWN'] = $room; - } - // - - AppSocket::doPost(SOCKETIO_HOST . ':' . SOCKETIO_PORT . '/postReload', $arrjson); - - } - static function send_grantIn( $vars = [], $room = '') { - $arrjson = ['timeStamp' => (int)time(), 'vars' => $vars]; - // - - // - if (!empty($room)) { - $arrjson['OWN'] = $room; - } - // - - AppSocket::doPost(SOCKETIO_HOST . ':' . SOCKETIO_PORT . '/postGrantIn', $arrjson); - - } - - - static function runSocketModule($mdl, $vars = [], $room = '') { - $arrjson = ['timeStamp' => (int)time(), 'mdl' => $mdl, 'PHPSESSID' => session_id()]; - if (sizeof($vars) != 0) { - $arrjson['vars'] = $vars; - } - if (!empty($room)) { - $arrjson['OWN'] = $room; - } - - AppSocket::doPost(HTTPMDL . $mdl . '.php', $vars); - } - - static function runModule($mdl, $vars = [], $room = '') { - $arrjson = ['timeStamp' => (int)time(), 'mdl' => $mdl, 'PHPSESSID' => session_id()]; - if (sizeof($vars) != 0) { - $arrjson['vars'] = $vars; - } - if (!empty($room)) { - $arrjson['OWN'] = $room; - } - - $arrjson['str_cookie'] = session_name() . "=" . session_id() . "; path=" . session_save_path(); - AppSocket::doPost(HTTPHOSTNOPORT . ':' . SOCKETIO_PORT . '/runModule', $arrjson); - } - - function _construct() { - - } - - function wrapIt($content) { - $start = ($moduleTag != 'none') ? "<$moduleTag $attributes class='cf_module $className' mdl='$module' vars='$theQuery' value='$value'>" : ""; - $end = ($moduleTag != 'none') ? "" : ""; - - return $start . $content . $end; - } - - function doInclude($module, $MDLPOST = []) { - $MDLPOST; - // - $moduleid = AppSocket::getModuleId($module, $MDLPOST); - // - $needCache = AppSocket::testNeedCache($module, $MDLPOST); - // - if ($needCache === true): - $dsp = AppSocket::getCache($module, $MDLPOST); - else: - ob_start(); - include(APPMDL . '/' . $module . '.php'); - $dsp = ob_get_contents(); - ob_end_clean(); - AppSocket::writeCache($module, $MDLPOST, $dsp); - endif; - - return $dsp; - } - - function getModuleId($module, $theQuery) { - unset($theQuery['cacheTime']); - unset($theQuery['cacheOn']); - unset($theQuery['mdl']); - unset($theQuery['scope']); - unset($theQuery['moduleTag']); - unset($theQuery['className']); - unset($theQuery['HTTP_REFERER']); - unset($theQuery['REMOTE_ADDR']); - unset($theQuery['load_time']); - unset($theQuery['session_id']); - unset($theQuery['time']); - ksort($theQuery); - - $add = http_build_query($theQuery); - $moduleid = md5($module . $add); - - return $moduleid; - } - - function testNeedCache($module, $theQuery) { - // - $moduleid = AppSocket::getModuleId($module, $theQuery); - // - // - $timecache = (defined(CACHETIME)) ? 43200 : CACHETIME; - $timecache = (!empty($theQuery['cacheTime'])) ? $theQuery['cacheTime'] : $timecache; - $timecache = (defined(CACHETIME)) ? CACHETIME : $timecache; - // - $maxAge = time() - $timecache; - // - $APP = new App(); - $conBase = $APP->plug_base('sitebase_cache'); - $gridBase = $conBase->getGridFs(); - // - $testBase = $gridBase->find(['filename' => $moduleid . '.html'])->count(); - if ($testBase == 0) { - return false; - } - // - $testBase = $gridBase->find(['time' => ['$lte' => (int)$maxAge], 'filename' => $moduleid . '.html'])->count(); - if ($testBase > 1) { - return true; - } - - return false; - } - - function getCache($module, $theQuery) { - $APP = new App(); - $conBase = $APP->plug_base('sitebase_cache'); - $gridBase = $conBase->getGridFs(); - // - $moduleid = AppSocket::getModuleId($module, $theQuery); - // - $testBase = $gridBase->findOne(['filename' => $moduleid . '.html']); - - return $testBase->getBytes(); - } - - function writeCache($module, $array, $final) { - // - $moduleid = AppSocket::getModuleId($module, $array); - // - $APP = new App(); - $conBase = $APP->plug_base('sitebase_cache'); - $Fs = $conBase->getGridFS(); - // - $Fs->remove(['filename' => $moduleid . '.html']); - // - $pattern = '/(?:(?<=\>)|(?<=\/\>))(\s+)(?=\<\/?)/'; - $newfinal = preg_replace($pattern, "", $final); - - $obj = ['filename' => $moduleid . '.html', 'time' => (int)time(), "module" => $module, 'date' => new MongoDate(), 'uploadDate' => new MongoDate()]; - $obj['metadata'] = $array; - // - $Fs->storeBytes($newfinal, $obj); - } - - function urlCache($dsp, $url) { - if (!AppSocket::testCacheUrl($url)): - // AppSocket::setCacheUrl($dsp, $url); - - return $dsp; - endif; - } - - function testCacheUrl($url) { - // - $timecache = (defined(CACHETIME)) ? 43200 : CACHETIME; - $timecache = (!empty($theQuery['cacheTime'])) ? $theQuery['cacheTime'] : $timecache; - $timecache = (defined(CACHETIME)) ? CACHETIME : $timecache; - // - $maxAge = time() - $timecache; - // - $APP = new App(); - $conBase = $APP->plug_base('sitebase_cache'); - $gridBase = $conBase->getGridFs(); - // - $testBase = $gridBase->findOne(['filename' => $url]); - // - $obj = $testBase->file; - if (empty($obj['filename']) || $obj['time'] < $maxAge) { - return false; - } - $oldDate = $obj['time']; - $curDate = time(); - $diff = $curDate - $oldDate; - - if ($timecache > $diff) { - return true; - } - - return false; - } - - function dropCache() { - $APP = new App(); - $conBase = $APP->plug_base('sitebase_cache'); - $conBase->drop(); - } - - function getCacheUrl($url) { - $APP = new App(); - $conBase = $APP->plug_base('sitebase_cache'); - $gridBase = $conBase->getGridFs(); - // - $testBase = $gridBase->findOne(['filename' => $url]); - - return $testBase->getBytes(); - } - - function setCacheUrl($dsp, $url) { - $APP = new App(); - $conBase = $APP->plug_base('sitebase_cache'); - - $Fs = $conBase->getGridFS(); - // - $Fs->remove(['filename' => $url]); - - $obj = ['filename' => $url, 'time' => time(), 'date' => date('Y-m-d')]; - // - $Fs->storeBytes($dsp, $obj); - } - - function cleanModuleVars($module, $theQuery) { - unset($theQuery['cacheTime']); - unset($theQuery['cacheOn']); - unset($theQuery['mdl']); - unset($theQuery['scope']); - unset($theQuery['moduleTag']); - unset($theQuery['className']); - unset($theQuery['HTTP_REFERER']); - unset($theQuery['REMOTE_ADDR']); - unset($theQuery['load_time']); - unset($theQuery['session_id']); - unset($theQuery['time']); - ksort($theQuery); - - $add = http_build_query($theQuery); - $moduleid = md5($module . $add); - - return $moduleid; - } - } - -?> +" : ""; // title='$module=$value' + $end = ($moduleTag != 'none') ? "" : ""; + + ob_start(); + $final = ''; + $final .= $start; + if (file_exists(APPMDL . '/' . $module . '.php')) { + + if (empty($array['defer'])) { + if (empty($array['emptyModule'])) { + $tempPost = $_POST; + $_POST = $arrQuery; + // $_POST['MODULE'] = $module; + include(APPMDL . '/' . $module . '.php'); + $_POST = $tempPost; + //$final .= AppSocket::doCurl(HTTPMDL . $module . '.php' , $array); + } + } else { + // echo('scripo'); + + } + } else { + // $final .= "missing" . APPMDL . '/' . $module . '.php'; + } + $final .= $end; + + $final = ob_get_contents(); + $final = $start . $final . $end; + ob_end_clean(); + + return trim($final); + + } + + static function reloadModule($module, $value='*', $vars = [],$room = null) { + $arrjson = ['timeStamp' => (int)time(), 'module' => $module, 'value' => $value,'room'=>$room]; + if (sizeof($vars) != 0) { + $arrjson['vars'] = $vars; + } + + AppSocket::send_cmd('act_reload_module',$arrjson,$room); + //return $dozat; + } + static function reloadMdlTest($module, $value='*', $vars = [],$room = null) { + + $arrjson = ['timeStamp' => (int)time(), 'mdl_test' => $module, 'value' => $value,'room'=>$room]; + if (sizeof($vars) != 0) { + $arrjson['vars'] = $vars; + } + + AppSocket::send_cmd('act_reload_module',$arrjson,$room); + //return $dozat; + } + + function doCurl($module, $array = []) { + /*$ckfile = COOKIE_PATH . "cookie.txt"; + $fp = fopen($ckfile, "w"); + fclose($fp);*/ + $array['iscurlmdl'] = '1'; + $strcookie = session_name() . "=" . session_id() . "; path=" . session_save_path(); + // session_write_close(); + $curl = curl_init(); + curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($array)); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($curl, CURLOPT_COOKIESESSION, TRUE); + curl_setopt($curl, CURLOPT_HEADER, 0); + // curl_setopt($curl, CURLOPT_HTTPHEADER,array("Expect:")); + /*curl_setopt($curl , CURLOPT_COOKIEFILE , $ckfile); + curl_setopt($curl , CURLOPT_COOKIEJAR , $ckfile);*/ + curl_setopt($curl, CURLOPT_COOKIE, $strcookie); + curl_setopt($curl, CURLOPT_URL, $module); // + curl_setopt($curl, CURLOPT_POST, 1); + $page = curl_exec($curl); + if ($page === false) { + // trigger_error('Erreur curl : ' . curl_error($curl) . ' ' . $module, E_USER_WARNING); + } + // curl_close($curl); + + //unlink($ckfile); + return ($page); + } + + static function run($mdl, $vars = [], $room = '') { + + $arrjson = ['mdl' => $mdl]; + if (sizeof($vars) != 0) { + $arrjson['vars'] = $vars; + } + if (!empty($room)) { + $arrjson['OWN'] = $room; + } + + AppSocket::doPost(HTTPHOSTNOPORT . ':' . SOCKETIO_PORT . '/run', $arrjson); + } + + static function doPost($url, $vars = []) { + + $crlf = "\r\n"; + $parts = parse_url($url); + $cookie_str = session_name() . "=" . session_id(). "; path=" . session_save_path(); + + // + // $fp = fsockopen('ssl://'.$parts['host'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30); + $fp = fsockopen($_SERVER['HTTP_HOST'], isset($parts['port']) ? $parts['port'] : 80, $errno, $errstr, 30); + + $vars['DOCUMENTDOMAIN'] = DOCUMENTDOMAIN; + $vars['PHPSESSID'] = session_id(); + $query = http_build_query($vars); + + + if (!$fp) { + + // AppSocket::send_cmd('act_notify', ['msg' => 'ERREUR ' . $errstr . ' $errno ' . $errno, session_id()]); + + return false; + } else { + $out = "POST " . $parts['path'] . " HTTP/1.1" . $crlf; + $out .= "Host: ". $parts['scheme'].'://'. $parts['host'].':'.$parts['port'] . $crlf; + $out .= "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0" . $crlf; + $out .= "Origin: ".HTTPHOST."" . $crlf; + $out .= "Content-Type: application/x-www-form-urlencoded" . $crlf; + $out .= "Content-Length: " . strlen($query) . $crlf; + $out .= "Connection: Close" . $crlf; + $out .= $crlf; + + if (isset($query)) { + $out .= $query; + } + if (!empty($cookie_str)) { + $out .= 'Cookie: ' . substr($cookie_str, 0, -2) . $crlf; + } + + fwrite($fp, $out); + fclose($fp); + + return true; + } + } + + static function send_cmd($cmd, $vars = [], $room = '') { + $arrjson = ['timeStamp' => (int)time(), 'cmd' => $cmd]; + // + if (sizeof($vars) != 0) { + $arrjson['vars'] = $vars; + } + // + if (!empty($room)) { + $arrjson['OWN'] = $room; + } + // + + AppSocket::doPost(SOCKETIO_HOST . ':' . SOCKETIO_PORT . '/postReload', $arrjson); + + } + static function send_grantIn( $vars = [], $room = '') { + $arrjson = ['timeStamp' => (int)time(), 'vars' => $vars]; + // + + // + if (!empty($room)) { + $arrjson['OWN'] = $room; + } + // + + AppSocket::doPost(SOCKETIO_HOST . ':' . SOCKETIO_PORT . '/postGrantIn', $arrjson); + + } + + + static function runSocketModule($mdl, $vars = [], $room = '') { + $arrjson = ['timeStamp' => (int)time(), 'mdl' => $mdl, 'PHPSESSID' => session_id()]; + if (sizeof($vars) != 0) { + $arrjson['vars'] = $vars; + } + if (!empty($room)) { + $arrjson['OWN'] = $room; + } + + AppSocket::doPost(HTTPMDL . $mdl . '.php', $vars); + } + + static function runModule($mdl, $vars = [], $room = '') { + $arrjson = ['timeStamp' => (int)time(), 'mdl' => $mdl, 'PHPSESSID' => session_id()]; + if (sizeof($vars) != 0) { + $arrjson['vars'] = $vars; + } + if (!empty($room)) { + $arrjson['OWN'] = $room; + } + + $arrjson['str_cookie'] = session_name() . "=" . session_id() . "; path=" . session_save_path(); + AppSocket::doPost(HTTPHOSTNOPORT . ':' . SOCKETIO_PORT . '/runModule', $arrjson); + } + + function _construct() { + + } + + function wrapIt($content) { + $start = ($moduleTag != 'none') ? "<$moduleTag $attributes class='cf_module $className' mdl='$module' vars='$theQuery' value='$value'>" : ""; + $end = ($moduleTag != 'none') ? "" : ""; + + return $start . $content . $end; + } + + function doInclude($module, $MDLPOST = []) { + $MDLPOST; + // + $moduleid = AppSocket::getModuleId($module, $MDLPOST); + // + $needCache = AppSocket::testNeedCache($module, $MDLPOST); + // + if ($needCache === true): + $dsp = AppSocket::getCache($module, $MDLPOST); + else: + ob_start(); + include(APPMDL . '/' . $module . '.php'); + $dsp = ob_get_contents(); + ob_end_clean(); + AppSocket::writeCache($module, $MDLPOST, $dsp); + endif; + + return $dsp; + } + + function getModuleId($module, $theQuery) { + unset($theQuery['cacheTime']); + unset($theQuery['cacheOn']); + unset($theQuery['mdl']); + unset($theQuery['scope']); + unset($theQuery['moduleTag']); + unset($theQuery['className']); + unset($theQuery['HTTP_REFERER']); + unset($theQuery['REMOTE_ADDR']); + unset($theQuery['load_time']); + unset($theQuery['session_id']); + unset($theQuery['time']); + ksort($theQuery); + + $add = http_build_query($theQuery); + $moduleid = md5($module . $add); + + return $moduleid; + } + + function testNeedCache($module, $theQuery) { + // + $moduleid = AppSocket::getModuleId($module, $theQuery); + // + // + $timecache = (defined(CACHETIME)) ? 43200 : CACHETIME; + $timecache = (!empty($theQuery['cacheTime'])) ? $theQuery['cacheTime'] : $timecache; + $timecache = (defined(CACHETIME)) ? CACHETIME : $timecache; + // + $maxAge = time() - $timecache; + // + $APP = new App(); + $conBase = $APP->plug_base('sitebase_cache'); + $gridBase = $conBase->getGridFs(); + // + $testBase = $gridBase->find(['filename' => $moduleid . '.html'])->count(); + if ($testBase == 0) { + return false; + } + // + $testBase = $gridBase->find(['time' => ['$lte' => (int)$maxAge], 'filename' => $moduleid . '.html'])->count(); + if ($testBase > 1) { + return true; + } + + return false; + } + + function getCache($module, $theQuery) { + $APP = new App(); + $conBase = $APP->plug_base('sitebase_cache'); + $gridBase = $conBase->getGridFs(); + // + $moduleid = AppSocket::getModuleId($module, $theQuery); + // + $testBase = $gridBase->findOne(['filename' => $moduleid . '.html']); + + return $testBase->getBytes(); + } + + function writeCache($module, $array, $final) { + // + $moduleid = AppSocket::getModuleId($module, $array); + // + $APP = new App(); + $conBase = $APP->plug_base('sitebase_cache'); + $Fs = $conBase->getGridFS(); + // + $Fs->remove(['filename' => $moduleid . '.html']); + // + $pattern = '/(?:(?<=\>)|(?<=\/\>))(\s+)(?=\<\/?)/'; + $newfinal = preg_replace($pattern, "", $final); + + $obj = ['filename' => $moduleid . '.html', 'time' => (int)time(), "module" => $module, 'date' => new MongoDate(), 'uploadDate' => new MongoDate()]; + $obj['metadata'] = $array; + // + $Fs->storeBytes($newfinal, $obj); + } + + function urlCache($dsp, $url) { + if (!AppSocket::testCacheUrl($url)): + // AppSocket::setCacheUrl($dsp, $url); + + return $dsp; + endif; + } + + function testCacheUrl($url) { + // + $timecache = (defined(CACHETIME)) ? 43200 : CACHETIME; + $timecache = (!empty($theQuery['cacheTime'])) ? $theQuery['cacheTime'] : $timecache; + $timecache = (defined(CACHETIME)) ? CACHETIME : $timecache; + // + $maxAge = time() - $timecache; + // + $APP = new App(); + $conBase = $APP->plug_base('sitebase_cache'); + $gridBase = $conBase->getGridFs(); + // + $testBase = $gridBase->findOne(['filename' => $url]); + // + $obj = $testBase->file; + if (empty($obj['filename']) || $obj['time'] < $maxAge) { + return false; + } + $oldDate = $obj['time']; + $curDate = time(); + $diff = $curDate - $oldDate; + + if ($timecache > $diff) { + return true; + } + + return false; + } + + function dropCache() { + $APP = new App(); + $conBase = $APP->plug_base('sitebase_cache'); + $conBase->drop(); + } + + function getCacheUrl($url) { + $APP = new App(); + $conBase = $APP->plug_base('sitebase_cache'); + $gridBase = $conBase->getGridFs(); + // + $testBase = $gridBase->findOne(['filename' => $url]); + + return $testBase->getBytes(); + } + + function setCacheUrl($dsp, $url) { + $APP = new App(); + $conBase = $APP->plug_base('sitebase_cache'); + + $Fs = $conBase->getGridFS(); + // + $Fs->remove(['filename' => $url]); + + $obj = ['filename' => $url, 'time' => time(), 'date' => date('Y-m-d')]; + // + $Fs->storeBytes($dsp, $obj); + } + + function cleanModuleVars($module, $theQuery) { + unset($theQuery['cacheTime']); + unset($theQuery['cacheOn']); + unset($theQuery['mdl']); + unset($theQuery['scope']); + unset($theQuery['moduleTag']); + unset($theQuery['className']); + unset($theQuery['HTTP_REFERER']); + unset($theQuery['REMOTE_ADDR']); + unset($theQuery['load_time']); + unset($theQuery['session_id']); + unset($theQuery['time']); + ksort($theQuery); + + $add = http_build_query($theQuery); + $moduleid = md5($module . $add); + + return $moduleid; + } + } + +?> diff --git a/web/bin/classes/ClassBin.php b/web/bin/classes/ClassBin.php index a9901ac..13858bc 100644 --- a/web/bin/classes/ClassBin.php +++ b/web/bin/classes/ClassBin.php @@ -1,790 +1,790 @@ -distinct_all('idcommande_statut', ['codeCommande_statut' => ['$in' => ['RESERV', - 'RUN']]]); - $vars_qy_liv['idsecteur'] = (int)$idsecteur; - $vars_qy_liv['dateCommande'] = $day; - $vars_qy_liv['idcommande_statut'] = ['$in' => $ARR_STATUT]; - // - $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); - // - $arr_test_affect = $this->test_livreur_affect($idsecteur); - $arr_idlivreur_affect = array_column(array_values($arr_test_affect), 'idlivreur'); - $arr_idlivreur = array_values(array_intersect($arr_idlivreur_affect, $arr_test_affect_free)); - - $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_idlivreur], - 'actifLivreur' => 1]); - - // - return iterator_to_array($rs_test_affect); - - } - - function test_livreur_proposal_free($idsecteur, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $APP_LIVREUR = new App('livreur'); - - $idsecteur = (int)$idsecteur; - - $day = date('Y-m-d'); - - $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); - $vars_qy_liv['idsecteur'] = $idsecteur; - $vars_qy_liv['dateCommande'] = $day; - $vars_qy_liv['idcommande_statut'] = ['$nin' => [(int)$ARR_STATUT['idcommande_statut']]]; - // - $arr_test_affect = $this->test_livreur_affect($idsecteur); - $arr_idlivreur = array_column(array_values($arr_test_affect), 'idlivreur'); - // les livreurs en commandes ou en proposal sont à exclure - $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); - // - $arr_idlivreur = array_values(array_diff($arr_idlivreur, $arr_test_affect_free)); - - $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_idlivreur], - 'actifLivreur' => 1]); - - // - return iterator_to_array($rs_test_affect); - - } - - function test_livreur_is_affected($idlivreur, $date_time = null) { - $APP_LIV = new App('livreur'); - $APP_LIV_AFFECT = new App('livreur_affectation'); - - $day = date('Y-m-d', $date_time ?: time()); - - $now = date('H:i:s', $date_time ?: time()); - - $vars_qy_liv['heureDebutLivreur_affectation'] = ['$lte' => $now]; - $vars_qy_liv['heureFinLivreur_affectation'] = ['$gte' => $now]; - $vars_qy_liv['idlivreur'] = $idlivreur; - $vars_qy_liv['dateDebutLivreur_affectation'] = $day; - $vars_qy_liv['actifLivreur_affectation'] = 1; - - $vars_liv = []; // livreurs actifs ! - $vars_liv['idlivreur'] = (int)$idlivreur; - $vars_liv['actifLivreur'] = 1; - $LIV_IN = $APP_LIV->distinct_all('idlivreur', $vars_liv); - - $vars_qy_liv['idlivreur'] = ['$in' => $LIV_IN]; - - $rs_test_affect = $APP_LIV_AFFECT->find($vars_qy_liv, ['_id' => 0]); - - return iterator_to_array($rs_test_affect); - - } - - function test_livreur_is_free($idlivreur, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $APP_LIVREUR = new App('livreur'); - - $day = date('Y-m-d'); - - $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); - $vars_qy_liv['idlivreur'] = $idlivreur; - $vars_qy_liv['dateCommande'] = $day; - $vars_qy_liv['idcommande_statut'] = ['$nin' => [(int)$ARR_STATUT['idcommande_statut']]]; - - $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); - $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_test_affect_free], - 'actifLivreur' => 1]); - - return iterator_to_array($rs_test_affect); - - } - - function test_livreur_affect_free($idsecteur, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $APP_LIVREUR = new App('livreur'); - - $idsecteur = (int)$idsecteur; - - $day = date('Y-m-d'); - - $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); - $vars_qy_liv['idsecteur'] = $idsecteur; - $vars_qy_liv['dateCommande'] = $day; - $vars_qy_liv['idcommande_statut'] = ['$nin' => [(int)$ARR_STATUT['idcommande_statut']]]; - // - $arr_test_affect = $this->test_livreur_affect($idsecteur); - $arr_idlivreur = array_column(array_values($arr_test_affect), 'idlivreur'); - // les livreurs en commandes sont à exclure - $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); - // - $arr_idlivreur = array_values(array_diff($arr_idlivreur, $arr_test_affect_free)); - - $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_idlivreur], - 'actifLivreur' => 1]); - - // - return iterator_to_array($rs_test_affect); - - } - - function test_commande_shop_time($idshop, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $day = date('Y-m-d'); - $now = date('H:i:s'); - - $rs_test_commande_shop = $APP_COMMANDE->find(['idshop' => $idshop, - 'dateCommande' => $day], ['_id' => 0]); - - return iterator_to_array($rs_test_commande_shop); - - } - - function test_commande_shop($idshop, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $day = date('Y-m-d'); - $now = date('H:i:s'); - - $rs_test_commande_shop = $APP_COMMANDE->find(['idshop' => $idshop, - 'dateCommande' => $day], ['_id' => 0]); - - return iterator_to_array($rs_test_commande_shop); - - } - - function test_commande_shop_wait($idshop, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $day = date('Y-m-d'); - $now = date('H:i:s'); - - $rs_test_commande_shop = $APP_COMMANDE->find(['idlivreur' => ['$in' => [null, - 0, - '']], - 'codeCommande_statut' => ['$ne' => 'END'], - 'idshop' => (int)$idshop, - 'dateCommande' => $day], ['_id' => 0]); - - return iterator_to_array($rs_test_commande_shop); - - } - - function get_elapsed_minutes_arr_for_commande($idcommande) { - $table = 'commande'; - $idcommande = (int)$idcommande; - $APP_COMMANDE = new App($table); - - $ARR = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - if (empty($ARR['idcommande'])) return false; - - $NOW = time(); - // - switch ($ARR['codeCommande_statut']) { - case 'START': - case 'RESERV': - case 'RUN': - $start_time = ($ARR['timeDebutPreparationCommande'] > $NOW) ? $NOW : $ARR['timeDebutPreparationCommande']; - $to_time = ($ARR['timeDebutPreparationCommande'] > $NOW) ? $ARR['timeDebutPreparationCommande'] : $ARR['timeFinPreparationCommande']; - - $max = $to_time - $start_time; - $value_progress = $NOW - $start_time; - break; - case 'PREFIN': - case 'LIVENCOU': - case 'END': - $start_time = $ARR['timeFinPreparationCommande']; - $to_time = $ARR['timeLivraisonCommande']; - - $max = $to_time - $start_time; - $value_progress = $NOW - $start_time; - break; - default: - $start_time = ($ARR['timeDebutPreparationCommande'] > $NOW) ? $NOW : $ARR['timeDebutPreparationCommande']; - $to_time = ($ARR['timeDebutPreparationCommande'] > $NOW) ? $ARR['timeDebutPreparationCommande'] : $ARR['timeFinPreparationCommande']; - - $max = $to_time - $start_time; - $value_progress = $NOW - $start_time; - break; - } - - $arr_dates = ['start_time' => $start_time, - 'to_time' => $to_time, - 'max' => $max, - 'value_progress' => $value_progress]; - - return $arr_dates; - } - - function get_elapsed_secondes_arr_for_commande($idcommande) { - if (!$idcommande) return false; - - $table = 'commande'; - $idcommande = (int)$idcommande; - $APP_COMMANDE = new App($table); - - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - if (empty($arr_commande['idcommande'])) return false; - - $NOW_TIME = time(); - $NOW = date('H:i:s', $NOW_TIME); - // $attentePreparationCommande - $datetime1 = new DateTime($NOW); - $datetime2 = new DateTime($arr_commande['heureFinPreparationCommande']); - $interval = $datetime1->diff($datetime2); - $elapsed_secondes_preparation = $interval->format('%R%s'); - $elapsed_minutes_preparation = $interval->format('%R%i'); - $elapsed_secondes_preparation = $elapsed_secondes_preparation + ($elapsed_minutes_preparation * 60); - - $datetime1 = new DateTime($NOW); - $datetime2 = new DateTime($arr_commande['heureLivraisonCommande']); - $interval = $datetime1->diff($datetime2); - $elapsed_minutes_livraison = $interval->format('%R%i'); - $elapsed_secondes_livraison = $interval->format('%R%s'); - $elapsed_secondes_livraison = $elapsed_secondes_livraison + ($elapsed_minutes_livraison * 60); - - $datetime1 = new DateTime($NOW); - $datetime2 = new DateTime($arr_commande['heureLivraisonCommande']); - $interval = $datetime1->diff($datetime2); - $elapsed_secondes_commande = $interval->format('%R%s'); - $elapsed_minutes_commande = $interval->format('%R%i'); - $elapsed_secondes_commande = $elapsed_secondes_commande + ($elapsed_minutes_commande * 60); - - return ['elapsed_minutes_preparation' => $elapsed_minutes_preparation, - 'elapsed_secondes_preparation' => $elapsed_secondes_preparation, - 'elapsed_minutes_livraison' => $elapsed_minutes_livraison, - 'elapsed_secondes_livraison' => $elapsed_secondes_livraison, - 'elapsed_minutes_commande' => $elapsed_minutes_commande, - 'elapsed_secondes_commande' => $elapsed_secondes_commande, - 'remaining_minutes_preparation' => TIME_PREPARATION_COMMANDE - $elapsed_minutes_preparation, - 'remaining_secondes_preparation' => (TIME_PREPARATION_COMMANDE * 60) - $elapsed_secondes_preparation, - 'remaining_minutes_livraison' => TEMPS_LIVRAISON_COMMANDE - $elapsed_minutes_livraison, - 'remaining_secondes_livraison' => (TEMPS_LIVRAISON_COMMANDE * 60) - $elapsed_secondes_livraison, - 'remaining_minutes_commande' => DUREE_REALISATION_COMMANDE - $elapsed_minutes_commande, - 'remaining_secondes_commande' => (DUREE_REALISATION_COMMANDE * 60) - $elapsed_secondes_commande]; - } - - function get_next_commande_secteur($idsecteur) { - $APP_COMMANDE = new App('commande'); - - $rs_commande = $APP_COMMANDE->find(['idsecteur' => (int)$idsecteur, - 'idlivreur' => ['$in' => [0, - null, - '']]])->sort(['timeFinPreparationCommande' => 1]); - $arr_commande = $rs_commande->getNext(); - - return (int)$arr_commande['idcommande']; - } - - function fetch_estimation_wait_time_fields($idshop) { - - $LAST_COMMANDE = CommandeQueue::shop_commande_queue_last($idshop); - - $return_field['attentePreparationCommande'] = $LAST_COMMANDE['attentePreparationCommande']; - $return_field['heureDebutPreparationCommande'] = $LAST_COMMANDE['heureDebutPreparationCommande']; - $return_field['timeDebutPreparationCommande'] = $LAST_COMMANDE['timeDebutPreparationCommande']; - $return_field['heureFinPreparationCommande'] = $LAST_COMMANDE['heureFinPreparationCommande']; - $return_field['timeFinPreparationCommande'] = $LAST_COMMANDE['timeFinPreparationCommande']; - $return_field['heureLivraisonCommande'] = $LAST_COMMANDE['heureLivraisonCommande']; - $return_field['timeLivraisonCommande'] = $LAST_COMMANDE['timeLivraisonCommande']; - - return $return_field; - } - - static function get_shop_shift_current($idshop) { - - $APP_SH_J = new IdaeDB('shop_jours'); - $APP_SH_J_SHIFT = new IdaeDB('shop_jours_shift'); - - $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; - $NOW = date('H:i:00'); - - $arr_sh_j = $APP_SH_J->findOne(['idshop' => (int)$idshop, - 'ordreJours' => $index_jour]); - - $return = $APP_SH_J_SHIFT->findOne(['idshop' => $idshop, - 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], - 'actifShop_jours_shift' => 1, - 'heureDebutShop_jours_shift' => ['$lte' => $NOW], - 'heureFinShop_jours_shift' => ['$gte' => $NOW]]); - - return $return; - } - - static function get_shop_secteur_shift_current($idsecteur) { - - $APP_SH = new IdaeDB('shop'); - $APP_SH_J = new IdaeDB('shop_jours'); - $APP_SH_J_SHIFT = new IdaeDB('shop_jours_shift'); - - $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; - $NOW = date('H:i:00'); - - $arr_sh_j = $APP_SH_J->distinct('idshop', ['actifShop_jours' => 1, 'ordreJours' => $index_jour]); - $arr_sh_j_shift = $APP_SH_J_SHIFT->distinct('idshop', ['idshop' => ['$in' => $arr_sh_j], - 'actifShop_jours_shift' => 1, - 'heureDebutShop_jours_shift' => ['$lte' => $NOW], - 'heureFinShop_jours_shift' => ['$gte' => $NOW]]); - - $rs_sh = $APP_SH->find(['idsecteur' => $idsecteur, 'idshop' => ['$in' => $arr_sh_j_shift]], ['_id' => 0]); - - return $rs_sh; - } - - function getCommande_queue_periods($idcommande) { - $DB_COMMANDE = new IdaeDB('commande'); - $ARR_COMMANDE = $DB_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - $idshop = (int)$ARR_COMMANDE['idshop']; - $ordreCommande = (int)$ARR_COMMANDE['ordreCommande']; - - $timeCommande = time(); - - $seconde_preparation_commande = TIME_PREPARATION_COMMANDE * 60; - $seconde_livraison_commande = TEMPS_LIVRAISON_COMMANDE * 60; - $multi_before_secondes = ($ordreCommande - 1) * $seconde_preparation_commande; - $timeDebutPreparationCommande = $timeCommande + $multi_before_secondes; - $timeFinPreparationCommande = $timeDebutPreparationCommande + $seconde_preparation_commande; - $timeFinLivraisonCommande = $timeFinPreparationCommande + $seconde_livraison_commande; - - $return_field['timeDebutPreparationCommande'] = $timeDebutPreparationCommande; - $return_field['heureDebutPreparationCommande'] = date('H:i:00', $timeDebutPreparationCommande); - $return_field['timeFinPreparationCommande'] = $timeFinPreparationCommande; - $return_field['heureFinPreparationCommande'] = date('H:i:00', $timeFinPreparationCommande); - $return_field['timeFinLivraisonCommande'] = $timeFinLivraisonCommande; - $return_field['heureFinLivraisonCommande'] = date('H:i:00', $timeFinLivraisonCommande); - - return $return_field; - } - - function get_update_estimation_wait_time_fields($idshop) { - $BIN = new Bin(); - $APP_SHOP = new IdaeDB('shop'); - $APP_SH_J = new IdaeDB('shop_jours'); - $APP_SH_J_SHIFT = new IdaeDB('shop_jours_shift'); - - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $idsecteur = (int)$ARR_SHOP['idsecteur']; - - $arr_commande_wait = $BIN->shop_commande_queue($idshop); - $arr_secteur_wait = $BIN->secteur_commande_queue($idsecteur); - $arr_secteur_wait_all = $BIN->secteur_commande_queue_all($idsecteur); - $arr_liv_free = $BIN->test_livreur_affect_free($idsecteur); - // - $nb_liv_free = sizeof($arr_liv_free); - $nb_commande_wait = sizeof($arr_commande_wait); - $nb_secteur_wait_all = sizeof($arr_secteur_wait_all); - - $timeCommande = time(); - $multi_before = ($nb_liv_free > sizeof($arr_secteur_wait)) ? 0 : ceil($nb_secteur_wait_all - $nb_liv_free); - $multi_before_secondes = $multi_before * TIME_PREPARATION_COMMANDE; - - $attentePreparationCommande = $nb_commande_wait + 1; - // fin de préparation - $time_prep = ((TIME_PREPARATION_COMMANDE * 60) * $attentePreparationCommande) + ((int)$ARR_SHOP['tempsAttenteShop'] * 60); - - // début de préparation - $timeDebutPreparationCommande = $timeCommande + $time_prep - (TIME_PREPARATION_COMMANDE * 60); - $heureDebutPreparationCommande = date('H:i:00', $timeDebutPreparationCommande); - - $heureFinPreparationCommande = date('H:i:00', $timeCommande + $time_prep); - $timeFinPreparationCommande = $timeCommande + $time_prep; - - // si nombre de livreurs free < nombre commandes START,RESERV,RUN du secteur ! alors normal, sinon date de fin derniere commande - // on prend la date théorique de la derniere commande de la queue active ? => $arr_secteur_wait_all - $multi = ceil($nb_secteur_wait_all - $nb_liv_free); - // si une commande 30 mn sinon 20 min ? a voir - $last_commande_to_liv = $arr_secteur_wait_all[$multi]['timeLivraisonCommande']; - $auto_commande_to_liv = $timeFinPreparationCommande + ((TEMPS_LIVRAISON_COMMANDE * 60)); - if ($auto_commande_to_liv < $last_commande_to_liv - (TEMPS_LIVRAISON_COMMANDE * 60 * 2)) { - $timeLivraisonCommande = $last_commande_to_liv + (TEMPS_LIVRAISON_COMMANDE * 60 * 2); - } else { - $timeLivraisonCommande = $auto_commande_to_liv; - } - $heureLivraisonCommande = date('H:i:00', $timeLivraisonCommande); - - /*$arr_upd['slotCommande'] = 'R' . CommandeQueue::shop_actual_slot($idcommande);*/ - $return_field['rangCommande'] = $attentePreparationCommande ?: ''; - $return_field['attentePreparationCommande'] = $attentePreparationCommande ?: ''; - $return_field['heureDebutPreparationCommande'] = $heureDebutPreparationCommande ?: ''; - $return_field['timeDebutPreparationCommande'] = $timeDebutPreparationCommande ?: ''; - $return_field['heureFinPreparationCommande'] = $heureFinPreparationCommande ?: ''; - $return_field['timeFinPreparationCommande'] = $timeFinPreparationCommande ?: ''; - $return_field['heureLivraisonCommande'] = $heureLivraisonCommande ?: ''; - $return_field['timeLivraisonCommande'] = $timeLivraisonCommande ?: ''; - - return $return_field; - } - - function get_estimation_wait_time_fields($idshop) { - $BIN = new Bin(); - $APP_SHOP = new App('shop'); - $APP_SH_J = new App('shop_jours'); - $APP_SH_J_SHIFT = new App('shop_jours_shift'); - - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $idsecteur = (int)$ARR_SHOP['idsecteur']; - - $duree_realisationCommande = DUREE_REALISATION_COMMANDE;// de la prise de commande à la livraison, en minutes - $time_preparation_commande = TIME_PREPARATION_COMMANDE; - $temps_livraison = TEMPS_LIVRAISON_COMMANDE; - - $arr_commande_wait = $BIN->shop_commande_queue($idshop); - $arr_secteur_wait = $BIN->secteur_commande_queue($idsecteur); - $arr_secteur_wait_all = $BIN->secteur_commande_queue_all($idsecteur); - $arr_liv_free = $BIN->test_livreur_affect_free($idsecteur); - - if (sizeof($arr_commande_wait) > 4) { - - } - - $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; - $NOW = date('H:i:s'); - - $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, - 'ordreJours' => $index_jour]); - $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, - 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], - 'actifShop_jours_shift' => 1, - 'heureDebutShop_jours_shift' => ['$lte' => $NOW], - 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); - if (sizeof($arr_sh_shift) != 0) { - $return_field['idshop_jours_shift'] = (int)$arr_sh_shift[0]['idshop_jours_shift']; - } else { - - } - - $nb_liv_free = sizeof($arr_liv_free); - $nb_commande_wait = sizeof($arr_commande_wait); - $nb_secteur_wait_all = sizeof($arr_secteur_wait_all); - - $timeCommande = time(); - $multi_before = ($nb_liv_free > sizeof($arr_secteur_wait)) ? 0 : ceil($nb_secteur_wait_all - $nb_liv_free); - $multi_before_secondes = $multi_before * TIME_PREPARATION_COMMANDE; - - $attentePreparationCommande = $nb_commande_wait + 1; - // fin de préparation - $time_prep = ((TIME_PREPARATION_COMMANDE * 60) * $attentePreparationCommande) + ((int)$ARR_SHOP['tempsAttenteShop'] * 60); - - // début de préparation - $timeDebutPreparationCommande = $timeCommande + $time_prep - (TIME_PREPARATION_COMMANDE * 60); - $heureDebutPreparationCommande = date('H:i:00', $timeDebutPreparationCommande); - - $heureFinPreparationCommande = date('H:i:00', $timeCommande + $time_prep); - $timeFinPreparationCommande = $timeCommande + $time_prep; - - // si nombre de livreurs free < nombre commandes START,RESERV,RUN du secteur ! alors normal, sinon date de fin derniere commande - if ($nb_liv_free >= sizeof($arr_secteur_wait)) { - $timeLivraisonCommande = $timeFinPreparationCommande + (($temps_livraison * 60));// * $attentePreparationCommande - $heureLivraisonCommande = date('H:i:00', $timeLivraisonCommande); - - } else { - // on prend la date théorique de la derniere commande de la queue active ? => $arr_secteur_wait_all - $multi = ceil($nb_secteur_wait_all - $nb_liv_free); - // si une commande 30 mn sinon 20 min ? a voir - $last_commande_to_liv = $arr_secteur_wait_all[$multi]['timeLivraisonCommande']; - $auto_commande_to_liv = $timeFinPreparationCommande + (($temps_livraison * 60)); - if ($auto_commande_to_liv < $last_commande_to_liv - ($temps_livraison * 60 * 2)) { - $timeLivraisonCommande = $last_commande_to_liv + ($temps_livraison * 60 * 2); - } else { - $timeLivraisonCommande = $auto_commande_to_liv; - } - $heureLivraisonCommande = date('H:i:00', $timeLivraisonCommande); - } - - $return_field['attentePreparationCommande'] = $attentePreparationCommande ?: ''; - $return_field['heureDebutPreparationCommande'] = $heureDebutPreparationCommande ?: ''; - $return_field['timeDebutPreparationCommande'] = $timeDebutPreparationCommande ?: ''; - $return_field['heureFinPreparationCommande'] = $heureFinPreparationCommande ?: ''; - $return_field['timeFinPreparationCommande'] = $timeFinPreparationCommande ?: ''; - $return_field['heureLivraisonCommande'] = $heureLivraisonCommande ?: ''; - $return_field['timeLivraisonCommande'] = $timeLivraisonCommande ?: ''; - - return $return_field; - } - - function get_value_wait_time_shop_secteur($idshop) { - $time_livraison = $this->get_wait_time_shop_secteur($idshop); - $secondeLivraison = $time_livraison - time(); // en secondes - $heures = (int)($secondeLivraison / 3600); - $minutes = (int)(($secondeLivraison % 3600) / 60); - $str_hours = empty($heures) ? '' : $heures . ' hr'; - $str_hours .= ($heures > 1) ? 's' : ''; - - $str_minutes = ($minutes == 0) ? '' : ' ' . $minutes . ' mn'; - - return $tempsLivraison = $str_hours . $str_minutes; - } - - function get_wait_time_shop_secteur($idshop) { - if (empty($idshop)) { - return false; - } - $duree_realisationCommande = DUREE_REALISATION_COMMANDE;// de la prise de commande à la livraison, en minutes - $time_preparation_commande = TIME_PREPARATION_COMMANDE; - $temps_livraison = TEMPS_LIVRAISON_COMMANDE; - - $APP_COMMANDE = new App('commande'); - $APP_SHOP = new App('shop'); - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $idsecteur = (int)$ARR_SHOP['idsecteur']; - $arr_liv_free = $this->test_livreur_affect_free($idsecteur); - - $return_field = $this->get_estimation_wait_time_fields($idshop); - - // si nombre de livreurs < nombre de commandes en cours... - $nb_liv_free = sizeof($arr_liv_free); - //$secteur_commande_nonfree_count = CommandeQueue::secteur_commande_nonfree_count($idsecteur); - $secteur_commande_nonfree_count = CommandeQueue::secteur_commande_queue_count($idsecteur); - - $timeFinPreparationCommande = $return_field['timeFinPreparationCommande']; - $timeLivraisonCommande = $return_field['timeLivraisonCommande']; - - // si commande engagées dans autre shops - - if ($nb_liv_free <= $secteur_commande_nonfree_count) { - $plus = CommandeQueue::secteur_shop_other_commande_non_prefin_count($idshop); - $timeLivraisonCommande = $timeFinPreparationCommande + ($plus * ($temps_livraison * 60));// * $attentePreparationCommande - $heureLivraisonCommande = date('H:i:00', $timeLivraisonCommande); - } - - return $timeLivraisonCommande; - } - - /** - * @deprecated move to CommandeQueue::shop_commande_queue_list - * - * @param $idshop - * @param string $day - * @param string $now - * - * @return array - */ - function shop_commande_queue($idshop, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $day = date('Y-m-d'); - $now = date('H:i:s'); - - $rs_test_commande_shop = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['PREFIN', - 'LIVENCOU', - 'END']], - 'idshop' => (int)$idshop, - 'dateCommande' => $day], ['_id' => 0])->sort(['timeLivraisonCommande' => 1]); - - return iterator_to_array($rs_test_commande_shop); - - } - - function secteur_commande_free_queue($idsecteur) { - $APP_COMMANDE = new App('commande'); - $day = date('Y-m-d'); - - $rs_test_commande_secteur = $APP_COMMANDE->find(['idlivreur' => ['$in' => ['', - 0, - null]], - 'idsecteur' => (int)$idsecteur, - 'dateCommande' => $day], ['_id' => 0])->sort(['rangCommande' => 1, 'slotCommande' => 1, 'heureCommande' => 1]); - - return iterator_to_array($rs_test_commande_secteur); - - } - - /** - * @deprecated CommandeQueue::secteur_commande_nonfree_list($idsecteur) - * - * @param $idsecteur - * @param string $day - * @param string $now - * - * @return array - */ - function secteur_commande_queue($idsecteur, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $day = date('Y-m-d'); - $now = date('H:i:s'); - - $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['PREFIN', - 'LIVENCOU', - 'END']], - 'idsecteur' => (int)$idsecteur, - 'dateCommande' => $day], ['_id' => 0])->sort(['heureCommande' => 1]); - - return iterator_to_array($rs_test_commande_secteur); - - } - - function secteur_commande_queue_all($idsecteur, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $day = date('Y-m-d'); - $now = date('H:i:s'); - - $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['END']], - 'idsecteur' => (int)$idsecteur, - 'dateCommande' => $day], ['_id' => 0])->sort(['heureCommande' => 1]); - - return iterator_to_array($rs_test_commande_secteur); - - } - - function test_commande_shop_livencou($idshop, $day = '', $now = '') { - $APP_COMMANDE = new App('commande'); - $day = date('Y-m-d'); - $now = date('H:i:s'); - - $rs_test_commande_shop = $APP_COMMANDE->find(['codeCommande_statut' => 'LIVENCOU', - 'idshop' => $idshop, - 'dateCommande' => $day], ['_id' => 0]); - - return iterator_to_array($rs_test_commande_shop); - - } - - static function test_shop_open($idshop) { - // Shop - $NOW = date('H:i:s'); - $APP_SHOP = new App('shop'); - $APP_SH_J = new App('shop_jours'); - $APP_SH_J_SHIFT = new App('shop_jours_shift'); - - $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; - - $arr_shop = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $idshop = (int)$arr_shop['idshop']; - - $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, - 'ordreJours' => $index_jour]); - $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, - 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], - 'actifShop_jours_shift' => 1, - 'heureDebutShop_jours_shift' => ['$lte' => $NOW], - 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); - if (sizeof($arr_sh_shift) != 0 && $arr_shop['actifShop'] == 1) { - $parameters['heureDebutShop_jours_shift'] = maskHeure($arr_sh_shift[0]['heureDebutShop_jours_shift']); - $parameters['heureFinShop_jours_shift'] = maskHeure($arr_sh_shift[0]['heureFinShop_jours_shift']); - - return true; - } else { - return false; - } - } - - /** - * @param array $array_vars - * - * @return array - * @throws \MongoConnectionException - * @throws \MongoCursorException - * @throws \MongoCursorTimeoutException - */ - function test_delivery_reserv($array_vars = []) { - global $LATTE; - - $idcommande = (int)$array_vars['idcommande']; - $idlivreur = (int)$array_vars['idlivreur']; - - $APP_COMMANDE = new App("commande"); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $APP_LIVREUR = new App('livreur'); - - $arr_livreur = $APP_LIVREUR->findOne(['idlivreur' => $idlivreur]); - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - - $idshop = (int)$arr_commande['idshop']; - $idsecteur = (int)$arr_commande['idsecteur']; - - $room_livreur = "livreur_$idlivreur"; - - $commande_non_prefin = CommandeQueue::shop_has_other_commandefree_non_prefin_list($idshop, $idcommande); - $commande_non_prefin_count = $commande_non_prefin->count(); - if ($commande_non_prefin_count != 0) { - $arr_test_first = array_values(iterator_to_array($commande_non_prefin))[0]; - - return ['err' => 1, - 'msg' => 'Merci de prendre la premiere commande disponible ' . $arr_test_first['referenceCommande']]; - } - - if (empty($arr_commande['idlivreur'])) { - // nombre de commandes en cours !! - $max_commande = 1; - $test_max_commande = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), - 'idlivreur' => $idlivreur, - 'codeCommande_statut' => ['$nin' => ['END']]]); - - /*$test_max_commande_before = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), - 'idsecteur' => $idsecteur, - 'idlivreur' => ['$in' => ['', - null, - 0]], - 'codeCommande_statut' => ['$nin' => ['END']]])->sort(['timeFinPreparationCommande' => 1]);*/ - - // - //$arr_test_first = $test_max_commande_before->getNext(); - /* Helper::dump($test_max_commande->count()); - Helper::dump($arr_test_first);*/ - - //if ($arr_test_first['idcommande'] != $idcommande) { - // NotifySite::notify_modal('Merci de prendre la premiere commande disponible '.$arr_test_first['referenceCommande'], 'error', null, $room_livreur); - - /*return ['err' => 1, - 'msg' => 'Merci de prendre la premiere commande disponible ' . $arr_test_first['referenceCommande']];*/ - //} - if ($test_max_commande->count() >= $max_commande) { - // NotifySite::notify_idae('trop de commandes ou commande en cours', 'alert', null, $room_livreur); - - return ['err' => 1, - 'msg' => 'trop de commandes ou commande actuellement en cours']; - } - $insert_field = []; - // statut + livreur - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'RESERV']); - if ((int)$arr_commande['ordreCommande_statut'] < (int)$arr_commande_statut['ordreCommande_statut']) { - // statut "reserv" seulement si pas deja avancée - $insert_field['idcommande_statut'] = (int)$arr_commande_statut['idcommande_statut']; - $insert_field['ordreCommande_statut'] = (int)$arr_commande_statut['ordreCommande_statut']; - $insert_field['codeCommande_statut'] = 'RESERV'; - - } - $insert_field['idlivreur'] = $idlivreur; - $insert_field['timeFinPreparationCommande']; - - return ['err' => 0, - 'idcommande' => $idcommande]; - - } else { - $msg = "Un livreur est déja affecté à cette commande"; - - return ['err' => 1, - 'msg' => $msg]; - } - } - } +distinct_all('idcommande_statut', ['codeCommande_statut' => ['$in' => ['RESERV', + 'RUN']]]); + $vars_qy_liv['idsecteur'] = (int)$idsecteur; + $vars_qy_liv['dateCommande'] = $day; + $vars_qy_liv['idcommande_statut'] = ['$in' => $ARR_STATUT]; + // + $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); + // + $arr_test_affect = $this->test_livreur_affect($idsecteur); + $arr_idlivreur_affect = array_column(array_values($arr_test_affect), 'idlivreur'); + $arr_idlivreur = array_values(array_intersect($arr_idlivreur_affect, $arr_test_affect_free)); + + $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_idlivreur], + 'actifLivreur' => 1]); + + // + return iterator_to_array($rs_test_affect); + + } + + function test_livreur_proposal_free($idsecteur, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $APP_LIVREUR = new App('livreur'); + + $idsecteur = (int)$idsecteur; + + $day = date('Y-m-d'); + + $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); + $vars_qy_liv['idsecteur'] = $idsecteur; + $vars_qy_liv['dateCommande'] = $day; + $vars_qy_liv['idcommande_statut'] = ['$nin' => [(int)$ARR_STATUT['idcommande_statut']]]; + // + $arr_test_affect = $this->test_livreur_affect($idsecteur); + $arr_idlivreur = array_column(array_values($arr_test_affect), 'idlivreur'); + // les livreurs en commandes ou en proposal sont à exclure + $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); + // + $arr_idlivreur = array_values(array_diff($arr_idlivreur, $arr_test_affect_free)); + + $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_idlivreur], + 'actifLivreur' => 1]); + + // + return iterator_to_array($rs_test_affect); + + } + + function test_livreur_is_affected($idlivreur, $date_time = null) { + $APP_LIV = new App('livreur'); + $APP_LIV_AFFECT = new App('livreur_affectation'); + + $day = date('Y-m-d', $date_time ?: time()); + + $now = date('H:i:s', $date_time ?: time()); + + $vars_qy_liv['heureDebutLivreur_affectation'] = ['$lte' => $now]; + $vars_qy_liv['heureFinLivreur_affectation'] = ['$gte' => $now]; + $vars_qy_liv['idlivreur'] = $idlivreur; + $vars_qy_liv['dateDebutLivreur_affectation'] = $day; + $vars_qy_liv['actifLivreur_affectation'] = 1; + + $vars_liv = []; // livreurs actifs ! + $vars_liv['idlivreur'] = (int)$idlivreur; + $vars_liv['actifLivreur'] = 1; + $LIV_IN = $APP_LIV->distinct_all('idlivreur', $vars_liv); + + $vars_qy_liv['idlivreur'] = ['$in' => $LIV_IN]; + + $rs_test_affect = $APP_LIV_AFFECT->find($vars_qy_liv, ['_id' => 0]); + + return iterator_to_array($rs_test_affect); + + } + + function test_livreur_is_free($idlivreur, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $APP_LIVREUR = new App('livreur'); + + $day = date('Y-m-d'); + + $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); + $vars_qy_liv['idlivreur'] = $idlivreur; + $vars_qy_liv['dateCommande'] = $day; + $vars_qy_liv['idcommande_statut'] = ['$nin' => [(int)$ARR_STATUT['idcommande_statut']]]; + + $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); + $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_test_affect_free], + 'actifLivreur' => 1]); + + return iterator_to_array($rs_test_affect); + + } + + function test_livreur_affect_free($idsecteur, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $APP_LIVREUR = new App('livreur'); + + $idsecteur = (int)$idsecteur; + + $day = date('Y-m-d'); + + $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); + $vars_qy_liv['idsecteur'] = $idsecteur; + $vars_qy_liv['dateCommande'] = $day; + $vars_qy_liv['idcommande_statut'] = ['$nin' => [(int)$ARR_STATUT['idcommande_statut']]]; + // + $arr_test_affect = $this->test_livreur_affect($idsecteur); + $arr_idlivreur = array_column(array_values($arr_test_affect), 'idlivreur'); + // les livreurs en commandes sont à exclure + $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); + // + $arr_idlivreur = array_values(array_diff($arr_idlivreur, $arr_test_affect_free)); + + $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_idlivreur], + 'actifLivreur' => 1]); + + // + return iterator_to_array($rs_test_affect); + + } + + function test_commande_shop_time($idshop, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $day = date('Y-m-d'); + $now = date('H:i:s'); + + $rs_test_commande_shop = $APP_COMMANDE->find(['idshop' => $idshop, + 'dateCommande' => $day], ['_id' => 0]); + + return iterator_to_array($rs_test_commande_shop); + + } + + function test_commande_shop($idshop, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $day = date('Y-m-d'); + $now = date('H:i:s'); + + $rs_test_commande_shop = $APP_COMMANDE->find(['idshop' => $idshop, + 'dateCommande' => $day], ['_id' => 0]); + + return iterator_to_array($rs_test_commande_shop); + + } + + function test_commande_shop_wait($idshop, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $day = date('Y-m-d'); + $now = date('H:i:s'); + + $rs_test_commande_shop = $APP_COMMANDE->find(['idlivreur' => ['$in' => [null, + 0, + '']], + 'codeCommande_statut' => ['$ne' => 'END'], + 'idshop' => (int)$idshop, + 'dateCommande' => $day], ['_id' => 0]); + + return iterator_to_array($rs_test_commande_shop); + + } + + function get_elapsed_minutes_arr_for_commande($idcommande) { + $table = 'commande'; + $idcommande = (int)$idcommande; + $APP_COMMANDE = new App($table); + + $ARR = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + if (empty($ARR['idcommande'])) return false; + + $NOW = time(); + // + switch ($ARR['codeCommande_statut']) { + case 'START': + case 'RESERV': + case 'RUN': + $start_time = ($ARR['timeDebutPreparationCommande'] > $NOW) ? $NOW : $ARR['timeDebutPreparationCommande']; + $to_time = ($ARR['timeDebutPreparationCommande'] > $NOW) ? $ARR['timeDebutPreparationCommande'] : $ARR['timeFinPreparationCommande']; + + $max = $to_time - $start_time; + $value_progress = $NOW - $start_time; + break; + case 'PREFIN': + case 'LIVENCOU': + case 'END': + $start_time = $ARR['timeFinPreparationCommande']; + $to_time = $ARR['timeLivraisonCommande']; + + $max = $to_time - $start_time; + $value_progress = $NOW - $start_time; + break; + default: + $start_time = ($ARR['timeDebutPreparationCommande'] > $NOW) ? $NOW : $ARR['timeDebutPreparationCommande']; + $to_time = ($ARR['timeDebutPreparationCommande'] > $NOW) ? $ARR['timeDebutPreparationCommande'] : $ARR['timeFinPreparationCommande']; + + $max = $to_time - $start_time; + $value_progress = $NOW - $start_time; + break; + } + + $arr_dates = ['start_time' => $start_time, + 'to_time' => $to_time, + 'max' => $max, + 'value_progress' => $value_progress]; + + return $arr_dates; + } + + function get_elapsed_secondes_arr_for_commande($idcommande) { + if (!$idcommande) return false; + + $table = 'commande'; + $idcommande = (int)$idcommande; + $APP_COMMANDE = new App($table); + + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + if (empty($arr_commande['idcommande'])) return false; + + $NOW_TIME = time(); + $NOW = date('H:i:s', $NOW_TIME); + // $attentePreparationCommande + $datetime1 = new DateTime($NOW); + $datetime2 = new DateTime($arr_commande['heureFinPreparationCommande']); + $interval = $datetime1->diff($datetime2); + $elapsed_secondes_preparation = $interval->format('%R%s'); + $elapsed_minutes_preparation = $interval->format('%R%i'); + $elapsed_secondes_preparation = $elapsed_secondes_preparation + ($elapsed_minutes_preparation * 60); + + $datetime1 = new DateTime($NOW); + $datetime2 = new DateTime($arr_commande['heureLivraisonCommande']); + $interval = $datetime1->diff($datetime2); + $elapsed_minutes_livraison = $interval->format('%R%i'); + $elapsed_secondes_livraison = $interval->format('%R%s'); + $elapsed_secondes_livraison = $elapsed_secondes_livraison + ($elapsed_minutes_livraison * 60); + + $datetime1 = new DateTime($NOW); + $datetime2 = new DateTime($arr_commande['heureLivraisonCommande']); + $interval = $datetime1->diff($datetime2); + $elapsed_secondes_commande = $interval->format('%R%s'); + $elapsed_minutes_commande = $interval->format('%R%i'); + $elapsed_secondes_commande = $elapsed_secondes_commande + ($elapsed_minutes_commande * 60); + + return ['elapsed_minutes_preparation' => $elapsed_minutes_preparation, + 'elapsed_secondes_preparation' => $elapsed_secondes_preparation, + 'elapsed_minutes_livraison' => $elapsed_minutes_livraison, + 'elapsed_secondes_livraison' => $elapsed_secondes_livraison, + 'elapsed_minutes_commande' => $elapsed_minutes_commande, + 'elapsed_secondes_commande' => $elapsed_secondes_commande, + 'remaining_minutes_preparation' => TIME_PREPARATION_COMMANDE - $elapsed_minutes_preparation, + 'remaining_secondes_preparation' => (TIME_PREPARATION_COMMANDE * 60) - $elapsed_secondes_preparation, + 'remaining_minutes_livraison' => TEMPS_LIVRAISON_COMMANDE - $elapsed_minutes_livraison, + 'remaining_secondes_livraison' => (TEMPS_LIVRAISON_COMMANDE * 60) - $elapsed_secondes_livraison, + 'remaining_minutes_commande' => DUREE_REALISATION_COMMANDE - $elapsed_minutes_commande, + 'remaining_secondes_commande' => (DUREE_REALISATION_COMMANDE * 60) - $elapsed_secondes_commande]; + } + + function get_next_commande_secteur($idsecteur) { + $APP_COMMANDE = new App('commande'); + + $rs_commande = $APP_COMMANDE->find(['idsecteur' => (int)$idsecteur, + 'idlivreur' => ['$in' => [0, + null, + '']]])->sort(['timeFinPreparationCommande' => 1]); + $arr_commande = $rs_commande->getNext(); + + return (int)$arr_commande['idcommande']; + } + + function fetch_estimation_wait_time_fields($idshop) { + + $LAST_COMMANDE = CommandeQueue::shop_commande_queue_last($idshop); + + $return_field['attentePreparationCommande'] = $LAST_COMMANDE['attentePreparationCommande']; + $return_field['heureDebutPreparationCommande'] = $LAST_COMMANDE['heureDebutPreparationCommande']; + $return_field['timeDebutPreparationCommande'] = $LAST_COMMANDE['timeDebutPreparationCommande']; + $return_field['heureFinPreparationCommande'] = $LAST_COMMANDE['heureFinPreparationCommande']; + $return_field['timeFinPreparationCommande'] = $LAST_COMMANDE['timeFinPreparationCommande']; + $return_field['heureLivraisonCommande'] = $LAST_COMMANDE['heureLivraisonCommande']; + $return_field['timeLivraisonCommande'] = $LAST_COMMANDE['timeLivraisonCommande']; + + return $return_field; + } + + static function get_shop_shift_current($idshop) { + + $APP_SH_J = new IdaeDB('shop_jours'); + $APP_SH_J_SHIFT = new IdaeDB('shop_jours_shift'); + + $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; + $NOW = date('H:i:00'); + + $arr_sh_j = $APP_SH_J->findOne(['idshop' => (int)$idshop, + 'ordreJours' => $index_jour]); + + $return = $APP_SH_J_SHIFT->findOne(['idshop' => $idshop, + 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], + 'actifShop_jours_shift' => 1, + 'heureDebutShop_jours_shift' => ['$lte' => $NOW], + 'heureFinShop_jours_shift' => ['$gte' => $NOW]]); + + return $return; + } + + static function get_shop_secteur_shift_current($idsecteur) { + + $APP_SH = new IdaeDB('shop'); + $APP_SH_J = new IdaeDB('shop_jours'); + $APP_SH_J_SHIFT = new IdaeDB('shop_jours_shift'); + + $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; + $NOW = date('H:i:00'); + + $arr_sh_j = $APP_SH_J->distinct('idshop', ['actifShop_jours' => 1, 'ordreJours' => $index_jour]); + $arr_sh_j_shift = $APP_SH_J_SHIFT->distinct('idshop', ['idshop' => ['$in' => $arr_sh_j], + 'actifShop_jours_shift' => 1, + 'heureDebutShop_jours_shift' => ['$lte' => $NOW], + 'heureFinShop_jours_shift' => ['$gte' => $NOW]]); + + $rs_sh = $APP_SH->find(['idsecteur' => $idsecteur, 'idshop' => ['$in' => $arr_sh_j_shift]], ['_id' => 0]); + + return $rs_sh; + } + + function getCommande_queue_periods($idcommande) { + $DB_COMMANDE = new IdaeDB('commande'); + $ARR_COMMANDE = $DB_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + $idshop = (int)$ARR_COMMANDE['idshop']; + $ordreCommande = (int)$ARR_COMMANDE['ordreCommande']; + + $timeCommande = time(); + + $seconde_preparation_commande = TIME_PREPARATION_COMMANDE * 60; + $seconde_livraison_commande = TEMPS_LIVRAISON_COMMANDE * 60; + $multi_before_secondes = ($ordreCommande - 1) * $seconde_preparation_commande; + $timeDebutPreparationCommande = $timeCommande + $multi_before_secondes; + $timeFinPreparationCommande = $timeDebutPreparationCommande + $seconde_preparation_commande; + $timeFinLivraisonCommande = $timeFinPreparationCommande + $seconde_livraison_commande; + + $return_field['timeDebutPreparationCommande'] = $timeDebutPreparationCommande; + $return_field['heureDebutPreparationCommande'] = date('H:i:00', $timeDebutPreparationCommande); + $return_field['timeFinPreparationCommande'] = $timeFinPreparationCommande; + $return_field['heureFinPreparationCommande'] = date('H:i:00', $timeFinPreparationCommande); + $return_field['timeFinLivraisonCommande'] = $timeFinLivraisonCommande; + $return_field['heureFinLivraisonCommande'] = date('H:i:00', $timeFinLivraisonCommande); + + return $return_field; + } + + function get_update_estimation_wait_time_fields($idshop) { + $BIN = new Bin(); + $APP_SHOP = new IdaeDB('shop'); + $APP_SH_J = new IdaeDB('shop_jours'); + $APP_SH_J_SHIFT = new IdaeDB('shop_jours_shift'); + + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $idsecteur = (int)$ARR_SHOP['idsecteur']; + + $arr_commande_wait = $BIN->shop_commande_queue($idshop); + $arr_secteur_wait = $BIN->secteur_commande_queue($idsecteur); + $arr_secteur_wait_all = $BIN->secteur_commande_queue_all($idsecteur); + $arr_liv_free = $BIN->test_livreur_affect_free($idsecteur); + // + $nb_liv_free = sizeof($arr_liv_free); + $nb_commande_wait = sizeof($arr_commande_wait); + $nb_secteur_wait_all = sizeof($arr_secteur_wait_all); + + $timeCommande = time(); + $multi_before = ($nb_liv_free > sizeof($arr_secteur_wait)) ? 0 : ceil($nb_secteur_wait_all - $nb_liv_free); + $multi_before_secondes = $multi_before * TIME_PREPARATION_COMMANDE; + + $attentePreparationCommande = $nb_commande_wait + 1; + // fin de préparation + $time_prep = ((TIME_PREPARATION_COMMANDE * 60) * $attentePreparationCommande) + ((int)$ARR_SHOP['tempsAttenteShop'] * 60); + + // début de préparation + $timeDebutPreparationCommande = $timeCommande + $time_prep - (TIME_PREPARATION_COMMANDE * 60); + $heureDebutPreparationCommande = date('H:i:00', $timeDebutPreparationCommande); + + $heureFinPreparationCommande = date('H:i:00', $timeCommande + $time_prep); + $timeFinPreparationCommande = $timeCommande + $time_prep; + + // si nombre de livreurs free < nombre commandes START,RESERV,RUN du secteur ! alors normal, sinon date de fin derniere commande + // on prend la date théorique de la derniere commande de la queue active ? => $arr_secteur_wait_all + $multi = ceil($nb_secteur_wait_all - $nb_liv_free); + // si une commande 30 mn sinon 20 min ? a voir + $last_commande_to_liv = $arr_secteur_wait_all[$multi]['timeLivraisonCommande']; + $auto_commande_to_liv = $timeFinPreparationCommande + ((TEMPS_LIVRAISON_COMMANDE * 60)); + if ($auto_commande_to_liv < $last_commande_to_liv - (TEMPS_LIVRAISON_COMMANDE * 60 * 2)) { + $timeLivraisonCommande = $last_commande_to_liv + (TEMPS_LIVRAISON_COMMANDE * 60 * 2); + } else { + $timeLivraisonCommande = $auto_commande_to_liv; + } + $heureLivraisonCommande = date('H:i:00', $timeLivraisonCommande); + + /*$arr_upd['slotCommande'] = 'R' . CommandeQueue::shop_actual_slot($idcommande);*/ + $return_field['rangCommande'] = $attentePreparationCommande ?: ''; + $return_field['attentePreparationCommande'] = $attentePreparationCommande ?: ''; + $return_field['heureDebutPreparationCommande'] = $heureDebutPreparationCommande ?: ''; + $return_field['timeDebutPreparationCommande'] = $timeDebutPreparationCommande ?: ''; + $return_field['heureFinPreparationCommande'] = $heureFinPreparationCommande ?: ''; + $return_field['timeFinPreparationCommande'] = $timeFinPreparationCommande ?: ''; + $return_field['heureLivraisonCommande'] = $heureLivraisonCommande ?: ''; + $return_field['timeLivraisonCommande'] = $timeLivraisonCommande ?: ''; + + return $return_field; + } + + function get_estimation_wait_time_fields($idshop) { + $BIN = new Bin(); + $APP_SHOP = new App('shop'); + $APP_SH_J = new App('shop_jours'); + $APP_SH_J_SHIFT = new App('shop_jours_shift'); + + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $idsecteur = (int)$ARR_SHOP['idsecteur']; + + $duree_realisationCommande = DUREE_REALISATION_COMMANDE;// de la prise de commande à la livraison, en minutes + $time_preparation_commande = TIME_PREPARATION_COMMANDE; + $temps_livraison = TEMPS_LIVRAISON_COMMANDE; + + $arr_commande_wait = $BIN->shop_commande_queue($idshop); + $arr_secteur_wait = $BIN->secteur_commande_queue($idsecteur); + $arr_secteur_wait_all = $BIN->secteur_commande_queue_all($idsecteur); + $arr_liv_free = $BIN->test_livreur_affect_free($idsecteur); + + if (sizeof($arr_commande_wait) > 4) { + + } + + $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; + $NOW = date('H:i:s'); + + $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, + 'ordreJours' => $index_jour]); + $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, + 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], + 'actifShop_jours_shift' => 1, + 'heureDebutShop_jours_shift' => ['$lte' => $NOW], + 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); + if (sizeof($arr_sh_shift) != 0) { + $return_field['idshop_jours_shift'] = (int)$arr_sh_shift[0]['idshop_jours_shift']; + } else { + + } + + $nb_liv_free = sizeof($arr_liv_free); + $nb_commande_wait = sizeof($arr_commande_wait); + $nb_secteur_wait_all = sizeof($arr_secteur_wait_all); + + $timeCommande = time(); + $multi_before = ($nb_liv_free > sizeof($arr_secteur_wait)) ? 0 : ceil($nb_secteur_wait_all - $nb_liv_free); + $multi_before_secondes = $multi_before * TIME_PREPARATION_COMMANDE; + + $attentePreparationCommande = $nb_commande_wait + 1; + // fin de préparation + $time_prep = ((TIME_PREPARATION_COMMANDE * 60) * $attentePreparationCommande) + ((int)$ARR_SHOP['tempsAttenteShop'] * 60); + + // début de préparation + $timeDebutPreparationCommande = $timeCommande + $time_prep - (TIME_PREPARATION_COMMANDE * 60); + $heureDebutPreparationCommande = date('H:i:00', $timeDebutPreparationCommande); + + $heureFinPreparationCommande = date('H:i:00', $timeCommande + $time_prep); + $timeFinPreparationCommande = $timeCommande + $time_prep; + + // si nombre de livreurs free < nombre commandes START,RESERV,RUN du secteur ! alors normal, sinon date de fin derniere commande + if ($nb_liv_free >= sizeof($arr_secteur_wait)) { + $timeLivraisonCommande = $timeFinPreparationCommande + (($temps_livraison * 60));// * $attentePreparationCommande + $heureLivraisonCommande = date('H:i:00', $timeLivraisonCommande); + + } else { + // on prend la date théorique de la derniere commande de la queue active ? => $arr_secteur_wait_all + $multi = ceil($nb_secteur_wait_all - $nb_liv_free); + // si une commande 30 mn sinon 20 min ? a voir + $last_commande_to_liv = $arr_secteur_wait_all[$multi]['timeLivraisonCommande']; + $auto_commande_to_liv = $timeFinPreparationCommande + (($temps_livraison * 60)); + if ($auto_commande_to_liv < $last_commande_to_liv - ($temps_livraison * 60 * 2)) { + $timeLivraisonCommande = $last_commande_to_liv + ($temps_livraison * 60 * 2); + } else { + $timeLivraisonCommande = $auto_commande_to_liv; + } + $heureLivraisonCommande = date('H:i:00', $timeLivraisonCommande); + } + + $return_field['attentePreparationCommande'] = $attentePreparationCommande ?: ''; + $return_field['heureDebutPreparationCommande'] = $heureDebutPreparationCommande ?: ''; + $return_field['timeDebutPreparationCommande'] = $timeDebutPreparationCommande ?: ''; + $return_field['heureFinPreparationCommande'] = $heureFinPreparationCommande ?: ''; + $return_field['timeFinPreparationCommande'] = $timeFinPreparationCommande ?: ''; + $return_field['heureLivraisonCommande'] = $heureLivraisonCommande ?: ''; + $return_field['timeLivraisonCommande'] = $timeLivraisonCommande ?: ''; + + return $return_field; + } + + function get_value_wait_time_shop_secteur($idshop) { + $time_livraison = $this->get_wait_time_shop_secteur($idshop); + $secondeLivraison = $time_livraison - time(); // en secondes + $heures = (int)($secondeLivraison / 3600); + $minutes = (int)(($secondeLivraison % 3600) / 60); + $str_hours = empty($heures) ? '' : $heures . ' hr'; + $str_hours .= ($heures > 1) ? 's' : ''; + + $str_minutes = ($minutes == 0) ? '' : ' ' . $minutes . ' mn'; + + return $tempsLivraison = $str_hours . $str_minutes; + } + + function get_wait_time_shop_secteur($idshop) { + if (empty($idshop)) { + return false; + } + $duree_realisationCommande = DUREE_REALISATION_COMMANDE;// de la prise de commande à la livraison, en minutes + $time_preparation_commande = TIME_PREPARATION_COMMANDE; + $temps_livraison = TEMPS_LIVRAISON_COMMANDE; + + $APP_COMMANDE = new App('commande'); + $APP_SHOP = new App('shop'); + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $idsecteur = (int)$ARR_SHOP['idsecteur']; + $arr_liv_free = $this->test_livreur_affect_free($idsecteur); + + $return_field = $this->get_estimation_wait_time_fields($idshop); + + // si nombre de livreurs < nombre de commandes en cours... + $nb_liv_free = sizeof($arr_liv_free); + //$secteur_commande_nonfree_count = CommandeQueue::secteur_commande_nonfree_count($idsecteur); + $secteur_commande_nonfree_count = CommandeQueue::secteur_commande_queue_count($idsecteur); + + $timeFinPreparationCommande = $return_field['timeFinPreparationCommande']; + $timeLivraisonCommande = $return_field['timeLivraisonCommande']; + + // si commande engagées dans autre shops + + if ($nb_liv_free <= $secteur_commande_nonfree_count) { + $plus = CommandeQueue::secteur_shop_other_commande_non_prefin_count($idshop); + $timeLivraisonCommande = $timeFinPreparationCommande + ($plus * ($temps_livraison * 60));// * $attentePreparationCommande + $heureLivraisonCommande = date('H:i:00', $timeLivraisonCommande); + } + + return $timeLivraisonCommande; + } + + /** + * @deprecated move to CommandeQueue::shop_commande_queue_list + * + * @param $idshop + * @param string $day + * @param string $now + * + * @return array + */ + function shop_commande_queue($idshop, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $day = date('Y-m-d'); + $now = date('H:i:s'); + + $rs_test_commande_shop = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['PREFIN', + 'LIVENCOU', + 'END']], + 'idshop' => (int)$idshop, + 'dateCommande' => $day], ['_id' => 0])->sort(['timeLivraisonCommande' => 1]); + + return iterator_to_array($rs_test_commande_shop); + + } + + function secteur_commande_free_queue($idsecteur) { + $APP_COMMANDE = new App('commande'); + $day = date('Y-m-d'); + + $rs_test_commande_secteur = $APP_COMMANDE->find(['idlivreur' => ['$in' => ['', + 0, + null]], + 'idsecteur' => (int)$idsecteur, + 'dateCommande' => $day], ['_id' => 0])->sort(['rangCommande' => 1, 'slotCommande' => 1, 'heureCommande' => 1]); + + return iterator_to_array($rs_test_commande_secteur); + + } + + /** + * @deprecated CommandeQueue::secteur_commande_nonfree_list($idsecteur) + * + * @param $idsecteur + * @param string $day + * @param string $now + * + * @return array + */ + function secteur_commande_queue($idsecteur, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $day = date('Y-m-d'); + $now = date('H:i:s'); + + $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['PREFIN', + 'LIVENCOU', + 'END']], + 'idsecteur' => (int)$idsecteur, + 'dateCommande' => $day], ['_id' => 0])->sort(['heureCommande' => 1]); + + return iterator_to_array($rs_test_commande_secteur); + + } + + function secteur_commande_queue_all($idsecteur, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $day = date('Y-m-d'); + $now = date('H:i:s'); + + $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['END']], + 'idsecteur' => (int)$idsecteur, + 'dateCommande' => $day], ['_id' => 0])->sort(['heureCommande' => 1]); + + return iterator_to_array($rs_test_commande_secteur); + + } + + function test_commande_shop_livencou($idshop, $day = '', $now = '') { + $APP_COMMANDE = new App('commande'); + $day = date('Y-m-d'); + $now = date('H:i:s'); + + $rs_test_commande_shop = $APP_COMMANDE->find(['codeCommande_statut' => 'LIVENCOU', + 'idshop' => $idshop, + 'dateCommande' => $day], ['_id' => 0]); + + return iterator_to_array($rs_test_commande_shop); + + } + + static function test_shop_open($idshop) { + // Shop + $NOW = date('H:i:s'); + $APP_SHOP = new App('shop'); + $APP_SH_J = new App('shop_jours'); + $APP_SH_J_SHIFT = new App('shop_jours_shift'); + + $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; + + $arr_shop = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $idshop = (int)$arr_shop['idshop']; + + $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, + 'ordreJours' => $index_jour]); + $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, + 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], + 'actifShop_jours_shift' => 1, + 'heureDebutShop_jours_shift' => ['$lte' => $NOW], + 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); + if (sizeof($arr_sh_shift) != 0 && $arr_shop['actifShop'] == 1) { + $parameters['heureDebutShop_jours_shift'] = maskHeure($arr_sh_shift[0]['heureDebutShop_jours_shift']); + $parameters['heureFinShop_jours_shift'] = maskHeure($arr_sh_shift[0]['heureFinShop_jours_shift']); + + return true; + } else { + return false; + } + } + + /** + * @param array $array_vars + * + * @return array + * @throws \MongoConnectionException + * @throws \MongoCursorException + * @throws \MongoCursorTimeoutException + */ + function test_delivery_reserv($array_vars = []) { + global $LATTE; + + $idcommande = (int)$array_vars['idcommande']; + $idlivreur = (int)$array_vars['idlivreur']; + + $APP_COMMANDE = new App("commande"); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $APP_LIVREUR = new App('livreur'); + + $arr_livreur = $APP_LIVREUR->findOne(['idlivreur' => $idlivreur]); + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + + $idshop = (int)$arr_commande['idshop']; + $idsecteur = (int)$arr_commande['idsecteur']; + + $room_livreur = "livreur_$idlivreur"; + + $commande_non_prefin = CommandeQueue::shop_has_other_commandefree_non_prefin_list($idshop, $idcommande); + $commande_non_prefin_count = $commande_non_prefin->count(); + if ($commande_non_prefin_count != 0) { + $arr_test_first = array_values(iterator_to_array($commande_non_prefin))[0]; + + return ['err' => 1, + 'msg' => 'Merci de prendre la premiere commande disponible ' . $arr_test_first['referenceCommande']]; + } + + if (empty($arr_commande['idlivreur'])) { + // nombre de commandes en cours !! + $max_commande = 1; + $test_max_commande = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), + 'idlivreur' => $idlivreur, + 'codeCommande_statut' => ['$nin' => ['END']]]); + + /*$test_max_commande_before = $APP_COMMANDE->find(['dateCommande' => date('Y-m-d'), + 'idsecteur' => $idsecteur, + 'idlivreur' => ['$in' => ['', + null, + 0]], + 'codeCommande_statut' => ['$nin' => ['END']]])->sort(['timeFinPreparationCommande' => 1]);*/ + + // + //$arr_test_first = $test_max_commande_before->getNext(); + /* Helper::dump($test_max_commande->count()); + Helper::dump($arr_test_first);*/ + + //if ($arr_test_first['idcommande'] != $idcommande) { + // NotifySite::notify_modal('Merci de prendre la premiere commande disponible '.$arr_test_first['referenceCommande'], 'error', null, $room_livreur); + + /*return ['err' => 1, + 'msg' => 'Merci de prendre la premiere commande disponible ' . $arr_test_first['referenceCommande']];*/ + //} + if ($test_max_commande->count() >= $max_commande) { + // NotifySite::notify_idae('trop de commandes ou commande en cours', 'alert', null, $room_livreur); + + return ['err' => 1, + 'msg' => 'trop de commandes ou commande actuellement en cours']; + } + $insert_field = []; + // statut + livreur + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'RESERV']); + if ((int)$arr_commande['ordreCommande_statut'] < (int)$arr_commande_statut['ordreCommande_statut']) { + // statut "reserv" seulement si pas deja avancée + $insert_field['idcommande_statut'] = (int)$arr_commande_statut['idcommande_statut']; + $insert_field['ordreCommande_statut'] = (int)$arr_commande_statut['ordreCommande_statut']; + $insert_field['codeCommande_statut'] = 'RESERV'; + + } + $insert_field['idlivreur'] = $idlivreur; + $insert_field['timeFinPreparationCommande']; + + return ['err' => 0, + 'idcommande' => $idcommande]; + + } else { + $msg = "Un livreur est déja affecté à cette commande"; + + return ['err' => 1, + 'msg' => $msg]; + } + } + } diff --git a/web/bin/classes/ClassCart.php b/web/bin/classes/ClassCart.php index 00df5f7..b093adb 100644 --- a/web/bin/classes/ClassCart.php +++ b/web/bin/classes/ClassCart.php @@ -1,404 +1,404 @@ -APP_CART = new App('cart'); - $this->APP_PROD = new App('produit'); - $this->APP_PROD_CAT = new App('produit_categorie'); - $this->APP_SHOP = new App('shop'); - - $this->cart_id = empty($cart_sess) ? session_id() : $cart_sess; - $this->cart_room = 'client_' . $this->cart_id; - $this->init_cart(); - $this->cart_arr = $this->get_cart(); - - # join socket pour publication - AppSocket::send_grantIn(['room' => $this->cart_room]); // room personnelle de type shop_7 - } - - function get_cart() { - $var_cart = $this->APP_CART->findOne(['cart_id' => $this->cart_id], ['_id' => 0]); - - //$this->idshop = $var_cart['idshop']; - //$this->idsecteur = $var_cart['idsecteur']; - //$this->cart_lines = $var_cart['cart_lines']; - //$this->cart_adresse = $var_cart['cart_adresse']; - - return $var_cart; - } - - function do_action($params = ['action', - 'value']) { - // - if (strpos($params['value'], '/') === false) { - $this->$params['action']($params['value']); - } else { - $this->$params['action'](explode('/', $params['value'])); - } - - } - - function update_meta($arr_meta = []) { - $post = (sizeof($arr_meta) == 0) ? $_POST : $arr_meta; - Helper::dump($post); - foreach ($post as $key => $value) { - Helper::dump($value); - - if (in_array($key, $this->cart_allowed_keys) && !empty($value)) { - $this->$value = $post[$value]; - } - $this->update_cart(); - } - } - - private function init_cart() { - $var_cart = $this->APP_CART->findOne(['cart_id' => $this->cart_id]); - if (empty($var_cart['cart_id'])) $this->APP_CART->insert(['cart_id' => $this->cart_id, - 'nomCart' => $this->cart_id, - 'init_time' => time(), - 'cart_adresse' => [], - 'cart_lines' => []]); - - } - - function init_adress() { - $this->empty_cart('all'); - /*$this->cart_adresse = $_POST['cart_adresse']; - $this->idsecteur = (int)$_POST['idsecteur']; - $this->idshop = null;*/ - - $this->APP_CART->update_native(['cart_id' => $this->cart_id], ['init_time' => time(), - 'cart_adresse' => $_POST['cart_adresse'], - 'idsecteur' => (int)$_POST['idsecteur'], - 'idshop' => null, - 'cart_lines' => []]); - - } - - function validate_cart() { - $err = 0; - $json_msg = ['err' => $err, - 'msg' => '', - 'data_html' => '']; - $cart_arr = $this->get_cart(); - if (!Bin::test_shop_open((int)$cart_arr['idshop'])) { - NotifySite::notify_modal("Le restaurant est actuellement fermé !!", 'alert', [], $this->cart_room); - $err = 1; - } - if ($cart_arr['idsecteur'] != $cart_arr['shop']['idsecteur']) { - NotifySite::notify_modal("Vous n'êtes pas situé sur le bon secteur !!", 'alert', [], $this->cart_room); - $err = 1; - } - $BIN = new Bin(); - $nb_commande_wait = CommandeQueue::shop_commande_queue_count($cart_arr['idshop']);// $BIN->shop_commande_queue((int)$cart_arr['idshop']); - - if ($nb_commande_wait > NB_MAX_COMMANDE_SHOP) { - NotifySite::notify_modal("Ce restaurant a trop de commandes en cours", 'alert', [], $this->cart_room); - $err = 1; - } - - $json_msg = ['err' => $err, - 'msg' => '', - 'data_html' => '']; - - echo json_encode($json_msg, JSON_FORCE_OBJECT); - } - - function reload_cart() { - $cart_arr = $this->APP_CART->findOne(['cart_id' => $this->cart_id], ['_id' => 0]); - $cart_arr = json_decode(json_encode($cart_arr, JSON_FORCE_OBJECT), false); - } - - function update_cart() { - - //$this->reload_cart(); - $cart_arr = $this->get_cart(); - $tot = 0; - $tot_vol = 0; - $duree = 0; - // - $insert_fields = []; - $insert_fields['last_time'] = time(); - if (!empty($cart_arr['cart_lines'])) { - foreach ($cart_arr['cart_lines'] as $key => $value) { - $tot += $value['total']; - $tot_vol += (float)$value['id']['volumeProduit'] * $value['qte']; - if ($value['id']['duree_realisationProduit'] > $duree) $duree = $value['id']['duree_realisationProduit']; - } - // $insert_fields['cart_lines'] = $this->cart_lines; - - } - // pas glop - if ($tot == 0) { - $final_total = 0; - $final_sstotal = 0; - } else if ($tot < 15) { - $final_total = $tot + 6; - $final_sstotal = 6; - } else if ($tot < 35) { - $final_total = $tot + 3; - $final_sstotal = 3; - } else { - $final_total = $tot; - $final_sstotal = 0; - } - $insert_fields['cart_total'] = (float)$final_total; - $insert_fields['cart_sous_total'] = (float)$final_sstotal; - $insert_fields['cart_total_volume'] = $tot_vol; - $insert_fields['cart_total_time'] = 30;//$duree; - //$insert_fields['cart_adresse'] = $this->cart_adresse; - //$insert_fields['idsecteur'] = (int)$this->idsecteur; - // - $this->APP_CART->update_native(['cart_id' => $this->cart_id], $insert_fields); - /*if ($insert_fields['cart_total_volume'] > 10 && $cart_arr['cart_total_volume'] < $insert_fields['cart_total_volume']) { - - AppSocket::send_cmd('act_script', ['script' => 'cart_notify', - 'arguments' => ['msg' => 'enregistrement impossible, volume dépassé', - 'type' => 'error'], - 'options' => ['sticky' => 1]], $this->cart_id); - } else { - - }*/ - $this->json_export(); - } - - function update_native($insert_fields) { - $this->APP_CART->update_native(['cart_id' => $this->cart_id], $insert_fields); - } - - function json_export() { - $cart = json_encode($this->get_cart()); - - AppSocket::send_cmd('act_script', ['script' => 'cart_update_json', - 'arguments' => $cart, - 'options' => []], $this->cart_id); - // echo $cart; - } - - function set_adresse($arr_meta = []) { - if (!isset($arr_meta)) return false; - $this->cart_adresse = $arr_meta; - $this->update_native(['cart_adresse' => $arr_meta]); - } - - function delete_adresse() { - $this->set_adresse([]); - /*$this->cart_adresse = []; - $this->update_native(['cart_id'=>$this->cart_id],['cart_adresse'=> []]);*/ - } - - function add_item($item_id) { - # produit - $cart_arr = $this->get_cart(); - $item = $this->get_produit((int)$item_id); - $arr_shop = $this->get_shop((int)$item['idshop']); - $cart_lines = $cart_arr['cart_lines']; - if (empty($arr_shop['actifShop'])) { - AppSocket::send_cmd('act_notify', ['msg' => "Ce restaurant est fermé !!"], $this->cart_room); - - return; - } - if (!Bin::test_shop_open((int)$item['idshop'])) { - NotifySite::notify_modal("Le restaurant est actuellement fermé !!", 'alert', [], $this->cart_room); - - return; - } - if (empty($cart_arr['idsecteur'])) { - NotifySite::notify_modal("Merci de choisir votre adresse", 'alert', [], $this->cart_room); - - return; - } - # verif - if (empty($cart_arr['idshop']) && !empty($arr_shop['idshop'])) { - $this->APP_CART->update_native(['cart_id' => $this->cart_id], ['idshop' => (int)$item['idshop'], - 'idsecteur' => (int)$arr_shop['idsecteur'], - 'shop' => $arr_shop]); - } else { - if ($cart_arr['idshop'] != $arr_shop['idshop']) { - # reset cart to default ! - $this->APP_CART->update_native(['cart_id' => $this->cart_id], ['idshop' => (int)$item['idshop'], - 'idsecteur' => (int)$arr_shop['idsecteur'], - 'shop' => $arr_shop]); - $this->empty_cart('all'); - } - } - $tes1 = $cart_arr['idsecteur']; - $test2 = $arr_shop['idsecteur']; - - if ($tes1 != $test2) { - NotifySite::notify_modal("Vous n'êtes pas situé sur le bon secteur !!", 'alert', [], $this->cart_room); - - return; - } - if (!empty($cart_arr['idshop']) && $cart_arr['idshop'] != $arr_shop['idshop']) { - NotifySite::notify_modal("Vous n'êtes pas situé sur le bon restaurant", 'alert', [], $this->cart_room); - - return; - } - - $volumeProduit = (float)$item ['volumeProduit']; - - if ($cart_arr['cart_total_volume'] + $volumeProduit > 100) { - $this->json_export(); - AppSocket::send_cmd('act_script', ['script' => 'cart_notify', - 'arguments' => ['msg' => 'enregistrement impossible, volume dépassé', - 'type' => 'error'], - 'options' => ['sticky' => 1]], $this->cart_id); - - return false; - } - if (!empty($cart_lines["prod_$item_id"]['id']) && !empty($cart_lines["prod_$item_id"]['qte'])) { - $cart_lines["prod_$item_id"]['qte']++; - $cart_lines["prod_$item_id"]['total'] = $cart_lines["prod_$item_id"]['qte'] * $item['prix_siteProduit']; - } else { - $cart_lines["prod_$item_id"]['id'] = $item; - $cart_lines["prod_$item_id"]['qte'] = 1; - $cart_lines["prod_$item_id"]['total'] = $item['prix_siteProduit']; - $cart_lines["prod_$item_id"]['idshop'] = (int)$item['idshop']; - } - - $this->update_native(['cart_lines' => $cart_lines]); - $this->update_cart(); - $this->json_export(); - } - - function get_produit($id) { - $allowed_c = ['idshop' => 1, - 'idproduit' => 1, - 'idproduit_categorie' => 1, - 'nomProduit' => 1, - 'codeProduit' => 1, - 'prixProduit' => 1, - 'prix_siteProduit' => 1, - 'volumeProduit' => 1, - 'duree_realisationProduit' => 1, - '_id' => 0]; - $allowed_p_c = ['idproduit_categorie' => 1, - 'ordreProduit_categorie' => 1, - 'codeProduit_categorie' => 1, - '_id' => 0]; - - $arr = $this->APP_PROD->findOne(['idproduit' => (int)$id], $allowed_c); - $arr_cat = $this->APP_PROD_CAT->findOne(['idproduit_categorie' => (int)$arr['idproduit_categorie']], $allowed_p_c); - - return array_merge($arr, $arr_cat); - - } - - function get_shop($id) { - $allowed_c = ['idshop' => 1, - 'nomShop' => 1, - 'codeShop' => 1, - 'slugShop' => 1, - 'idsecteur' => 1, - 'slugSecteur' => 1, - 'actifShop' => 1, - '_id' => 0]; - $arr = $this->APP_SHOP->findOne(['idshop' => (int)$id], $allowed_c);; - unset($arr['_id']); - - return $arr; - } - - function set_shop($idshop) { - if (empty($idshop)) return false; - $this->update_native(['idshop' => (int)$idshop]); - } - - function set_secteur($idsecteur) { - if (empty($idsecteur)) return false; - $this->update_native(['idsecteur' => (int)$idsecteur]); - } - - function empty_cart($all = 'none') { - if ($all !== 'all') return; - $this->cart_lines = []; - $this->update_native(['cart_lines' => $this->cart_lines]); - $this->update_cart(); - } - - function cart_edit_line() { - if (empty($_REQUEST['cart_line_key'])) return false; - - $cart_line_key = $_REQUEST['cart_line_key']; - - $arr_cart = $this->get_cart(); - $cart_lines = $arr_cart['cart_lines']; - $cart_line = $cart_lines[$cart_line_key]; - if (isset($_REQUEST['cart_line_description'])) { - $cart_lines[$cart_line_key]['description'] = $_REQUEST['cart_line_description']; - $this->update_native(['cart_lines' => $cart_lines]); - $this->update_cart(); - } - } - - /** - * need prod_id and qte - * - * @param array $vars - * - * @return bool - */ - function update_cart_line($vars = ['prod_id' => 'test', - 'qte']) { - $arr_cart = $this->get_cart(); - $cart_lines = $arr_cart['cart_lines']; - if ($vars[1] == 0) { - unset($cart_lines[$vars[0]]); - } else { - //$this->add_item($vars[1]); - $cart_lines[$vars[0]]['qte'] = $vars[1]; - $cart_lines[$vars[0]]['total'] = number_format($cart_lines[$vars[0]]['id']['prix_siteProduit'] * $vars[1], 2, '.', ' '); - - } - $tot = 0; - $tot_vol = 0; - foreach ($cart_lines as $key => $value) { - $tot += $value['total']; - $tot_vol += (float)$value['id']['volumeProduit'] * $value['qte']; - } - - if ($tot_vol > 10) { - AppSocket::send_cmd('act_script', ['script' => 'cart_notify', - 'arguments' => ['msg' => 'enregistrement impossible, volume dépassé', - 'type' => 'error'], - 'options' => ['sticky' => 1]], $this->cart_id); - - return false; - } - $this->update_native(['cart_lines' => $cart_lines]); - $this->update_cart(); - } - - function remove_item() { - $this->update_cart(); - } - - function calcul_total() { - - } +APP_CART = new App('cart'); + $this->APP_PROD = new App('produit'); + $this->APP_PROD_CAT = new App('produit_categorie'); + $this->APP_SHOP = new App('shop'); + + $this->cart_id = empty($cart_sess) ? session_id() : $cart_sess; + $this->cart_room = 'client_' . $this->cart_id; + $this->init_cart(); + $this->cart_arr = $this->get_cart(); + + # join socket pour publication + AppSocket::send_grantIn(['room' => $this->cart_room]); // room personnelle de type shop_7 + } + + function get_cart() { + $var_cart = $this->APP_CART->findOne(['cart_id' => $this->cart_id], ['_id' => 0]); + + //$this->idshop = $var_cart['idshop']; + //$this->idsecteur = $var_cart['idsecteur']; + //$this->cart_lines = $var_cart['cart_lines']; + //$this->cart_adresse = $var_cart['cart_adresse']; + + return $var_cart; + } + + function do_action($params = ['action', + 'value']) { + // + if (strpos($params['value'], '/') === false) { + $this->$params['action']($params['value']); + } else { + $this->$params['action'](explode('/', $params['value'])); + } + + } + + function update_meta($arr_meta = []) { + $post = (sizeof($arr_meta) == 0) ? $_POST : $arr_meta; + Helper::dump($post); + foreach ($post as $key => $value) { + Helper::dump($value); + + if (in_array($key, $this->cart_allowed_keys) && !empty($value)) { + $this->$value = $post[$value]; + } + $this->update_cart(); + } + } + + private function init_cart() { + $var_cart = $this->APP_CART->findOne(['cart_id' => $this->cart_id]); + if (empty($var_cart['cart_id'])) $this->APP_CART->insert(['cart_id' => $this->cart_id, + 'nomCart' => $this->cart_id, + 'init_time' => time(), + 'cart_adresse' => [], + 'cart_lines' => []]); + + } + + function init_adress() { + $this->empty_cart('all'); + /*$this->cart_adresse = $_POST['cart_adresse']; + $this->idsecteur = (int)$_POST['idsecteur']; + $this->idshop = null;*/ + + $this->APP_CART->update_native(['cart_id' => $this->cart_id], ['init_time' => time(), + 'cart_adresse' => $_POST['cart_adresse'], + 'idsecteur' => (int)$_POST['idsecteur'], + 'idshop' => null, + 'cart_lines' => []]); + + } + + function validate_cart() { + $err = 0; + $json_msg = ['err' => $err, + 'msg' => '', + 'data_html' => '']; + $cart_arr = $this->get_cart(); + if (!Bin::test_shop_open((int)$cart_arr['idshop'])) { + NotifySite::notify_modal("Le restaurant est actuellement fermé !!", 'alert', [], $this->cart_room); + $err = 1; + } + if ($cart_arr['idsecteur'] != $cart_arr['shop']['idsecteur']) { + NotifySite::notify_modal("Vous n'êtes pas situé sur le bon secteur !!", 'alert', [], $this->cart_room); + $err = 1; + } + $BIN = new Bin(); + $nb_commande_wait = CommandeQueue::shop_commande_queue_count($cart_arr['idshop']);// $BIN->shop_commande_queue((int)$cart_arr['idshop']); + + if ($nb_commande_wait > NB_MAX_COMMANDE_SHOP) { + NotifySite::notify_modal("Ce restaurant a trop de commandes en cours", 'alert', [], $this->cart_room); + $err = 1; + } + + $json_msg = ['err' => $err, + 'msg' => '', + 'data_html' => '']; + + echo json_encode($json_msg, JSON_FORCE_OBJECT); + } + + function reload_cart() { + $cart_arr = $this->APP_CART->findOne(['cart_id' => $this->cart_id], ['_id' => 0]); + $cart_arr = json_decode(json_encode($cart_arr, JSON_FORCE_OBJECT), false); + } + + function update_cart() { + + //$this->reload_cart(); + $cart_arr = $this->get_cart(); + $tot = 0; + $tot_vol = 0; + $duree = 0; + // + $insert_fields = []; + $insert_fields['last_time'] = time(); + if (!empty($cart_arr['cart_lines'])) { + foreach ($cart_arr['cart_lines'] as $key => $value) { + $tot += $value['total']; + $tot_vol += (float)$value['id']['volumeProduit'] * $value['qte']; + if ($value['id']['duree_realisationProduit'] > $duree) $duree = $value['id']['duree_realisationProduit']; + } + // $insert_fields['cart_lines'] = $this->cart_lines; + + } + // pas glop + if ($tot == 0) { + $final_total = 0; + $final_sstotal = 0; + } else if ($tot < 15) { + $final_total = $tot + 6; + $final_sstotal = 6; + } else if ($tot < 35) { + $final_total = $tot + 3; + $final_sstotal = 3; + } else { + $final_total = $tot; + $final_sstotal = 0; + } + $insert_fields['cart_total'] = (float)$final_total; + $insert_fields['cart_sous_total'] = (float)$final_sstotal; + $insert_fields['cart_total_volume'] = $tot_vol; + $insert_fields['cart_total_time'] = 30;//$duree; + //$insert_fields['cart_adresse'] = $this->cart_adresse; + //$insert_fields['idsecteur'] = (int)$this->idsecteur; + // + $this->APP_CART->update_native(['cart_id' => $this->cart_id], $insert_fields); + /*if ($insert_fields['cart_total_volume'] > 10 && $cart_arr['cart_total_volume'] < $insert_fields['cart_total_volume']) { + + AppSocket::send_cmd('act_script', ['script' => 'cart_notify', + 'arguments' => ['msg' => 'enregistrement impossible, volume dépassé', + 'type' => 'error'], + 'options' => ['sticky' => 1]], $this->cart_id); + } else { + + }*/ + $this->json_export(); + } + + function update_native($insert_fields) { + $this->APP_CART->update_native(['cart_id' => $this->cart_id], $insert_fields); + } + + function json_export() { + $cart = json_encode($this->get_cart()); + + AppSocket::send_cmd('act_script', ['script' => 'cart_update_json', + 'arguments' => $cart, + 'options' => []], $this->cart_id); + // echo $cart; + } + + function set_adresse($arr_meta = []) { + if (!isset($arr_meta)) return false; + $this->cart_adresse = $arr_meta; + $this->update_native(['cart_adresse' => $arr_meta]); + } + + function delete_adresse() { + $this->set_adresse([]); + /*$this->cart_adresse = []; + $this->update_native(['cart_id'=>$this->cart_id],['cart_adresse'=> []]);*/ + } + + function add_item($item_id) { + # produit + $cart_arr = $this->get_cart(); + $item = $this->get_produit((int)$item_id); + $arr_shop = $this->get_shop((int)$item['idshop']); + $cart_lines = $cart_arr['cart_lines']; + if (empty($arr_shop['actifShop'])) { + AppSocket::send_cmd('act_notify', ['msg' => "Ce restaurant est fermé !!"], $this->cart_room); + + return; + } + if (!Bin::test_shop_open((int)$item['idshop'])) { + NotifySite::notify_modal("Le restaurant est actuellement fermé !!", 'alert', [], $this->cart_room); + + return; + } + if (empty($cart_arr['idsecteur'])) { + NotifySite::notify_modal("Merci de choisir votre adresse", 'alert', [], $this->cart_room); + + return; + } + # verif + if (empty($cart_arr['idshop']) && !empty($arr_shop['idshop'])) { + $this->APP_CART->update_native(['cart_id' => $this->cart_id], ['idshop' => (int)$item['idshop'], + 'idsecteur' => (int)$arr_shop['idsecteur'], + 'shop' => $arr_shop]); + } else { + if ($cart_arr['idshop'] != $arr_shop['idshop']) { + # reset cart to default ! + $this->APP_CART->update_native(['cart_id' => $this->cart_id], ['idshop' => (int)$item['idshop'], + 'idsecteur' => (int)$arr_shop['idsecteur'], + 'shop' => $arr_shop]); + $this->empty_cart('all'); + } + } + $tes1 = $cart_arr['idsecteur']; + $test2 = $arr_shop['idsecteur']; + + if ($tes1 != $test2) { + NotifySite::notify_modal("Vous n'êtes pas situé sur le bon secteur !!", 'alert', [], $this->cart_room); + + return; + } + if (!empty($cart_arr['idshop']) && $cart_arr['idshop'] != $arr_shop['idshop']) { + NotifySite::notify_modal("Vous n'êtes pas situé sur le bon restaurant", 'alert', [], $this->cart_room); + + return; + } + + $volumeProduit = (float)$item ['volumeProduit']; + + if ($cart_arr['cart_total_volume'] + $volumeProduit > 100) { + $this->json_export(); + AppSocket::send_cmd('act_script', ['script' => 'cart_notify', + 'arguments' => ['msg' => 'enregistrement impossible, volume dépassé', + 'type' => 'error'], + 'options' => ['sticky' => 1]], $this->cart_id); + + return false; + } + if (!empty($cart_lines["prod_$item_id"]['id']) && !empty($cart_lines["prod_$item_id"]['qte'])) { + $cart_lines["prod_$item_id"]['qte']++; + $cart_lines["prod_$item_id"]['total'] = $cart_lines["prod_$item_id"]['qte'] * $item['prix_siteProduit']; + } else { + $cart_lines["prod_$item_id"]['id'] = $item; + $cart_lines["prod_$item_id"]['qte'] = 1; + $cart_lines["prod_$item_id"]['total'] = $item['prix_siteProduit']; + $cart_lines["prod_$item_id"]['idshop'] = (int)$item['idshop']; + } + + $this->update_native(['cart_lines' => $cart_lines]); + $this->update_cart(); + $this->json_export(); + } + + function get_produit($id) { + $allowed_c = ['idshop' => 1, + 'idproduit' => 1, + 'idproduit_categorie' => 1, + 'nomProduit' => 1, + 'codeProduit' => 1, + 'prixProduit' => 1, + 'prix_siteProduit' => 1, + 'volumeProduit' => 1, + 'duree_realisationProduit' => 1, + '_id' => 0]; + $allowed_p_c = ['idproduit_categorie' => 1, + 'ordreProduit_categorie' => 1, + 'codeProduit_categorie' => 1, + '_id' => 0]; + + $arr = $this->APP_PROD->findOne(['idproduit' => (int)$id], $allowed_c); + $arr_cat = $this->APP_PROD_CAT->findOne(['idproduit_categorie' => (int)$arr['idproduit_categorie']], $allowed_p_c); + + return array_merge($arr, $arr_cat); + + } + + function get_shop($id) { + $allowed_c = ['idshop' => 1, + 'nomShop' => 1, + 'codeShop' => 1, + 'slugShop' => 1, + 'idsecteur' => 1, + 'slugSecteur' => 1, + 'actifShop' => 1, + '_id' => 0]; + $arr = $this->APP_SHOP->findOne(['idshop' => (int)$id], $allowed_c);; + unset($arr['_id']); + + return $arr; + } + + function set_shop($idshop) { + if (empty($idshop)) return false; + $this->update_native(['idshop' => (int)$idshop]); + } + + function set_secteur($idsecteur) { + if (empty($idsecteur)) return false; + $this->update_native(['idsecteur' => (int)$idsecteur]); + } + + function empty_cart($all = 'none') { + if ($all !== 'all') return; + $this->cart_lines = []; + $this->update_native(['cart_lines' => $this->cart_lines]); + $this->update_cart(); + } + + function cart_edit_line() { + if (empty($_REQUEST['cart_line_key'])) return false; + + $cart_line_key = $_REQUEST['cart_line_key']; + + $arr_cart = $this->get_cart(); + $cart_lines = $arr_cart['cart_lines']; + $cart_line = $cart_lines[$cart_line_key]; + if (isset($_REQUEST['cart_line_description'])) { + $cart_lines[$cart_line_key]['description'] = $_REQUEST['cart_line_description']; + $this->update_native(['cart_lines' => $cart_lines]); + $this->update_cart(); + } + } + + /** + * need prod_id and qte + * + * @param array $vars + * + * @return bool + */ + function update_cart_line($vars = ['prod_id' => 'test', + 'qte']) { + $arr_cart = $this->get_cart(); + $cart_lines = $arr_cart['cart_lines']; + if ($vars[1] == 0) { + unset($cart_lines[$vars[0]]); + } else { + //$this->add_item($vars[1]); + $cart_lines[$vars[0]]['qte'] = $vars[1]; + $cart_lines[$vars[0]]['total'] = number_format($cart_lines[$vars[0]]['id']['prix_siteProduit'] * $vars[1], 2, '.', ' '); + + } + $tot = 0; + $tot_vol = 0; + foreach ($cart_lines as $key => $value) { + $tot += $value['total']; + $tot_vol += (float)$value['id']['volumeProduit'] * $value['qte']; + } + + if ($tot_vol > 10) { + AppSocket::send_cmd('act_script', ['script' => 'cart_notify', + 'arguments' => ['msg' => 'enregistrement impossible, volume dépassé', + 'type' => 'error'], + 'options' => ['sticky' => 1]], $this->cart_id); + + return false; + } + $this->update_native(['cart_lines' => $cart_lines]); + $this->update_cart(); + } + + function remove_item() { + $this->update_cart(); + } + + function calcul_total() { + + } } \ No newline at end of file diff --git a/web/bin/classes/ClassCartLivraison.php b/web/bin/classes/ClassCartLivraison.php index 82115fe..d5a2e03 100644 --- a/web/bin/classes/ClassCartLivraison.php +++ b/web/bin/classes/ClassCartLivraison.php @@ -1,179 +1,179 @@ -APP_CART_LIVRAISON = new App('cart_livraison'); - - $this->cart_id = empty($cart_sess)? session_id() : $cart_sess; - // - $this->cart_arr = $this->get_cart(); - - } - - function get_cart() { - - $var_cart = $this->APP_CART_LIVRAISON->findOne(['cart_id' => $this->cart_id]); - if (empty($var_cart['cart_id'])) $this->APP_CART_LIVRAISON->insert(['cart_id' => $this->cart_id, 'nomCart' => $this->cart_id, 'init_time' => time(), 'cart_adresse' => [], 'cart_lines' => []]); - $var_cart = $this->APP_CART_LIVRAISON->findOne(['cart_id' => $this->cart_id], ['_id' => 0]); - - $this->cart_lines = $var_cart['cart_lines']; - $this->cart_adresse = $var_cart['cart_adresse']; - - $this->cart_arr = $var_cart; - - return $var_cart; - } - - function do_action($params = ['action', 'value']) { - // - - if (strpos($params['value'], '/') === false) { - $this->$params['action']($params['value']); - } else { - $this->$params['action'](explode('/', $params['value'])); - } - - } - - function update_meta($arr_meta=[]) { - $post = (sizeof($arr_meta)==0)? $_POST : $arr_meta; - foreach ($_POST as $key => $value) { - if (in_array($key, $this->cart_allowed_keys)) { - $this->$key = $value; - } - $this->update_cart(); - } - // Helper::dump($this->get_cart()); - // Helper::dump([array_keys($arr_meta)[0] , array_values($arr_meta)[0]]); - // $this->array_keys($arr_meta)[0] = array_values($arr_meta)[0]; - } - - function update_cart() { - - $tot = 0; - $tot_vol = 0; - $duree = 0; - foreach ($this->cart_lines as $key => $value) { - $tot += $value['total']; - $tot_vol += (float)$value['id']['volumeProduit'] * $value['qte']; - if ($value['id']['duree_realisationProduit'] > $duree) $duree = $value['id']['duree_realisationProduit']; - } - // - $insert_fields = []; - $insert_fields['last_time'] = time(); - $insert_fields['cart_lines'] = $this->cart_lines; - $insert_fields['cart_total'] = $tot; - $insert_fields['cart_total_volume'] = $tot_vol; - $insert_fields['cart_total_time'] = $duree; - $insert_fields['cart_adresse'] = $this->cart_adresse; - // - if ($insert_fields['cart_total_volume'] > 100 && $this->cart_arr['cart_total_volume'] < $insert_fields['cart_total_volume']) { - AppSocket::send_cmd('act_script', ['script' => 'cart_notify', - 'arguments' => ['msg' => 'enregistrement impossible, volume dépassé', 'type' => 'error'], - 'options' => []], $this->cart_id); - } else { - $this->APP_CART_LIVRAISON->update(['cart_id' => $this->cart_id], $insert_fields); - } - // - $this->json_export(); - /*AppSocket::run('act_run', ['route' => 'demo/dump/apoil:vert/aussi:rouge', - 'method' => 'POST', - 'delay' => 10, - 'vars' => ['idoine' => 'red']]);*/ - } - - function json_export() { - $cart = json_encode($this->get_cart()); - AppSocket::send_cmd('act_script', ['script' => 'cart_update_json', - 'arguments' => $cart, - 'options' => []], $this->cart_id); - // echo $cart; - } - - function delete_adresse() { - $this->cart_adresse = []; - $this->update_cart(); - } - - function add_item($item_id) { - # produit - $item = $this->get_produit($item_id); - $arr_shop = $this->get_shop((int)$item['idshop']); - - # verif - if (empty($this->cart_arr['idshop']) && !empty($arr_shop['idshop'])) { - $this->APP_CART_LIVRAISON->update(['cart_id' => $this->cart_id], ['idshop' => (int)$item['idshop'], 'idsecteur' => (int)$arr_shop['idsecteur'], 'shop' => $arr_shop]); - } else { - - } - - if (!empty($this->cart_lines["prod_$item_id"]['id']) && !empty($this->cart_lines["prod_$item_id"]['qte'])) { - $this->cart_lines["prod_$item_id"]['qte']++; - $this->cart_lines["prod_$item_id"]['total'] = $this->cart_lines["prod_$item_id"]['qte'] * $item['prix_siteProduit']; - } else { - $this->cart_lines["prod_$item_id"]['id'] = $item; - $this->cart_lines["prod_$item_id"]['qte'] = 1; - $this->cart_lines["prod_$item_id"]['total'] = $item['prix_siteProduit']; - $this->cart_lines["prod_$item_id"]['idshop'] = (int)$item['idshop']; - } - - $this->update_cart(); - } - - function get_produit() { - return ''; - - } - - function get_shop($id) { - $allowed_c = ['idshop' => 1, 'nomShop' => 1, 'codeShop' => 1, 'slugShop' => 1, 'idsecteur' => 1, '_id' => 0]; - $arr = $this->APP_SHOP->findOne(['idshop' => (int)$id], $allowed_c);; - unset($arr['_id']); - - return $arr; - - } - - function update_cart_line($vars = ['prod_id' => 'test', 'qte']) { - - if ($vars[1] == 0) { - unset($this->cart_lines[$vars[0]]); - } else { - $this->cart_lines[$vars[0]]['qte'] = $vars[1]; - $this->cart_lines[$vars[0]]['total'] = number_format($this->cart_lines[$vars[0]]['id']['prix_siteProduit'] * $vars[1], 2, '.', ' '); - - } - - $this->update_cart(); - } - - function remove_item() { - $this->update_cart(); - } - - function calcul_total() { - - } - - function empty_cart($all = 'none') { - if ($all !== 'all') return; - $this->cart_lines = []; - $this->update_cart(); - } +APP_CART_LIVRAISON = new App('cart_livraison'); + + $this->cart_id = empty($cart_sess)? session_id() : $cart_sess; + // + $this->cart_arr = $this->get_cart(); + + } + + function get_cart() { + + $var_cart = $this->APP_CART_LIVRAISON->findOne(['cart_id' => $this->cart_id]); + if (empty($var_cart['cart_id'])) $this->APP_CART_LIVRAISON->insert(['cart_id' => $this->cart_id, 'nomCart' => $this->cart_id, 'init_time' => time(), 'cart_adresse' => [], 'cart_lines' => []]); + $var_cart = $this->APP_CART_LIVRAISON->findOne(['cart_id' => $this->cart_id], ['_id' => 0]); + + $this->cart_lines = $var_cart['cart_lines']; + $this->cart_adresse = $var_cart['cart_adresse']; + + $this->cart_arr = $var_cart; + + return $var_cart; + } + + function do_action($params = ['action', 'value']) { + // + + if (strpos($params['value'], '/') === false) { + $this->$params['action']($params['value']); + } else { + $this->$params['action'](explode('/', $params['value'])); + } + + } + + function update_meta($arr_meta=[]) { + $post = (sizeof($arr_meta)==0)? $_POST : $arr_meta; + foreach ($_POST as $key => $value) { + if (in_array($key, $this->cart_allowed_keys)) { + $this->$key = $value; + } + $this->update_cart(); + } + // Helper::dump($this->get_cart()); + // Helper::dump([array_keys($arr_meta)[0] , array_values($arr_meta)[0]]); + // $this->array_keys($arr_meta)[0] = array_values($arr_meta)[0]; + } + + function update_cart() { + + $tot = 0; + $tot_vol = 0; + $duree = 0; + foreach ($this->cart_lines as $key => $value) { + $tot += $value['total']; + $tot_vol += (float)$value['id']['volumeProduit'] * $value['qte']; + if ($value['id']['duree_realisationProduit'] > $duree) $duree = $value['id']['duree_realisationProduit']; + } + // + $insert_fields = []; + $insert_fields['last_time'] = time(); + $insert_fields['cart_lines'] = $this->cart_lines; + $insert_fields['cart_total'] = $tot; + $insert_fields['cart_total_volume'] = $tot_vol; + $insert_fields['cart_total_time'] = $duree; + $insert_fields['cart_adresse'] = $this->cart_adresse; + // + if ($insert_fields['cart_total_volume'] > 100 && $this->cart_arr['cart_total_volume'] < $insert_fields['cart_total_volume']) { + AppSocket::send_cmd('act_script', ['script' => 'cart_notify', + 'arguments' => ['msg' => 'enregistrement impossible, volume dépassé', 'type' => 'error'], + 'options' => []], $this->cart_id); + } else { + $this->APP_CART_LIVRAISON->update(['cart_id' => $this->cart_id], $insert_fields); + } + // + $this->json_export(); + /*AppSocket::run('act_run', ['route' => 'demo/dump/apoil:vert/aussi:rouge', + 'method' => 'POST', + 'delay' => 10, + 'vars' => ['idoine' => 'red']]);*/ + } + + function json_export() { + $cart = json_encode($this->get_cart()); + AppSocket::send_cmd('act_script', ['script' => 'cart_update_json', + 'arguments' => $cart, + 'options' => []], $this->cart_id); + // echo $cart; + } + + function delete_adresse() { + $this->cart_adresse = []; + $this->update_cart(); + } + + function add_item($item_id) { + # produit + $item = $this->get_produit($item_id); + $arr_shop = $this->get_shop((int)$item['idshop']); + + # verif + if (empty($this->cart_arr['idshop']) && !empty($arr_shop['idshop'])) { + $this->APP_CART_LIVRAISON->update(['cart_id' => $this->cart_id], ['idshop' => (int)$item['idshop'], 'idsecteur' => (int)$arr_shop['idsecteur'], 'shop' => $arr_shop]); + } else { + + } + + if (!empty($this->cart_lines["prod_$item_id"]['id']) && !empty($this->cart_lines["prod_$item_id"]['qte'])) { + $this->cart_lines["prod_$item_id"]['qte']++; + $this->cart_lines["prod_$item_id"]['total'] = $this->cart_lines["prod_$item_id"]['qte'] * $item['prix_siteProduit']; + } else { + $this->cart_lines["prod_$item_id"]['id'] = $item; + $this->cart_lines["prod_$item_id"]['qte'] = 1; + $this->cart_lines["prod_$item_id"]['total'] = $item['prix_siteProduit']; + $this->cart_lines["prod_$item_id"]['idshop'] = (int)$item['idshop']; + } + + $this->update_cart(); + } + + function get_produit() { + return ''; + + } + + function get_shop($id) { + $allowed_c = ['idshop' => 1, 'nomShop' => 1, 'codeShop' => 1, 'slugShop' => 1, 'idsecteur' => 1, '_id' => 0]; + $arr = $this->APP_SHOP->findOne(['idshop' => (int)$id], $allowed_c);; + unset($arr['_id']); + + return $arr; + + } + + function update_cart_line($vars = ['prod_id' => 'test', 'qte']) { + + if ($vars[1] == 0) { + unset($this->cart_lines[$vars[0]]); + } else { + $this->cart_lines[$vars[0]]['qte'] = $vars[1]; + $this->cart_lines[$vars[0]]['total'] = number_format($this->cart_lines[$vars[0]]['id']['prix_siteProduit'] * $vars[1], 2, '.', ' '); + + } + + $this->update_cart(); + } + + function remove_item() { + $this->update_cart(); + } + + function calcul_total() { + + } + + function empty_cart($all = 'none') { + if ($all !== 'all') return; + $this->cart_lines = []; + $this->update_cart(); + } } \ No newline at end of file diff --git a/web/bin/classes/ClassCommandeProposition.php b/web/bin/classes/ClassCommandeProposition.php index fc9babe..9d69d9e 100644 --- a/web/bin/classes/ClassCommandeProposition.php +++ b/web/bin/classes/ClassCommandeProposition.php @@ -1,41 +1,41 @@ -findOne(['idcommande' => (int)$idcommande]); - - $TEST_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->find(['idlivreur' => (int)$idlivreur, - 'idsecteur' => (int)$ARR_COMMANDE['idsecteur'], - 'livreur_take' => ['$ne' => (int)$idlivreur], - 'dateCommande_proposition' => date('Y-m-d'), - 'endedCommande_proposition' => ['$ne' => 1], - 'timeFinPreparationCommande_proposition' => ['$lt' => $ARR_COMMANDE['timeFinPreparationCommande']], - 'actifCommande_proposition' => 1])->sort(['timeFinPreparationCommande_proposition' => 1]); - - return iterator_to_array($TEST_COMMANDE_PROPOSITION); - } - - static public function livreur_last_commande_seen_still_active($idlivreur) { - - $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); - - $arr_find = ['dateCommande_proposition' => date('Y-m-d'), - 'idlivreur' => (int)$idlivreur, - 'actifCommande_proposition' => 1, - 'vuCommande_proposition' => 1,]; - - $ARR_COMMANDE = $APP_COMMANDE_PROPOSITION->findOne($arr_find); - - return $ARR_COMMANDE; - } +findOne(['idcommande' => (int)$idcommande]); + + $TEST_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->find(['idlivreur' => (int)$idlivreur, + 'idsecteur' => (int)$ARR_COMMANDE['idsecteur'], + 'livreur_take' => ['$ne' => (int)$idlivreur], + 'dateCommande_proposition' => date('Y-m-d'), + 'endedCommande_proposition' => ['$ne' => 1], + 'timeFinPreparationCommande_proposition' => ['$lt' => $ARR_COMMANDE['timeFinPreparationCommande']], + 'actifCommande_proposition' => 1])->sort(['timeFinPreparationCommande_proposition' => 1]); + + return iterator_to_array($TEST_COMMANDE_PROPOSITION); + } + + static public function livreur_last_commande_seen_still_active($idlivreur) { + + $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); + + $arr_find = ['dateCommande_proposition' => date('Y-m-d'), + 'idlivreur' => (int)$idlivreur, + 'actifCommande_proposition' => 1, + 'vuCommande_proposition' => 1,]; + + $ARR_COMMANDE = $APP_COMMANDE_PROPOSITION->findOne($arr_find); + + return $ARR_COMMANDE; + } } \ No newline at end of file diff --git a/web/bin/classes/ClassCommandeQueue.php b/web/bin/classes/ClassCommandeQueue.php index a752e03..6f0409c 100644 --- a/web/bin/classes/ClassCommandeQueue.php +++ b/web/bin/classes/ClassCommandeQueue.php @@ -1,507 +1,507 @@ - 1, 'heureCommande' => 1, 'slotCommande' => 1]; - const sort_from_last_slot = ['rangCommande' => -1, 'heureCommande' => -1, 'slotCommande' => -1]; - - const sort_from_first_commande = ['rangCommande' => 1, 'heureCommande' => 1]; - const sort_from_last_commande = ['rangCommande' => -1, 'heureCommande' => -1]; - - static function secteur_commande_queue_ended_count($idsecteur) { - return self::secteur_commande_queue_ended_list($idsecteur)->count(); - } - - static function secteur_commande_queue_ended_list($idsecteur) { - $APP_COMMANDE = new IdaeDB('commande'); - $day = date('Y-m-d'); - - $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$in' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day]); - $rs_test_commande_secteur->sort(self::sort_from_first_slot); - - return $rs_test_commande_secteur; - } - - static function secteur_commande_queue_count($idsecteur) { - return self::secteur_commande_queue_list($idsecteur)->count(); - } - - static function secteur_commande_queue_list($idsecteur) { - $APP_COMMANDE = new IdaeDB('commande'); - $day = date('Y-m-d'); - - $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); - - return $rs_test_commande_secteur; - } - - static function secteur_commande_queue_list_last($idsecteur) { - return self::secteur_commande_queue_list($idsecteur)->sort(['slotCommande' => -1, 'rangCommande' => -1])->getNext(); - } - - static function secteur_commande_free_count($idsecteur, $day = '', $now = '') { - return sizeof(self::secteur_commande_free_list($idsecteur)); - } - - static function secteur_commande_free_list($idsecteur, $day = '', $now = '') { - $APP_COMMANDE = new IdaeDB('commande'); - $day = date('Y-m-d'); - - $rs_test_commande_secteur = $APP_COMMANDE->find(['idlivreur' => ['$in' => ['', 0, null]], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['slotCommande' => 1, 'rangCommande' => 1, 'heureCommande' => 1]); - - return iterator_to_array($rs_test_commande_secteur); - } - - static function secteur_commande_nonfree_count($idsecteur) { - return sizeof((self::secteur_commande_nonfree_list($idsecteur))); - } - - static function secteur_commande_nonfree_list($idsecteur, $day = '', $now = '') { - $APP_COMMANDE = new App('secteur'); - $day = date('Y-m-d'); - - $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['PREFIN', 'LIVENCOU', 'END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['slotCommande' => 1, 'rangCommande' => 1, 'heureCommande' => 1]); - - return iterator_to_array($rs_test_commande_secteur); - } - - /** - * @param $idsecteur - * @param null $idlivreur - * - * @return int - */ - static function secteur_has_livreur_count($idsecteur, $idlivreur = null) { - return sizeof(self::secteur_has_livreur_list($idsecteur, $idlivreur)); - } - - /** - * @param $idsecteur - * @param null $idlivreur - * - * @return array - */ - static function secteur_has_livreur_list($idsecteur, $idlivreur = null) { - - $APP_LIV = new IdaeDB('livreur'); - $APP_LIV_AFFECT = new IdaeDB('livreur_affectation'); - $idsecteur = (int)$idsecteur; - - $time_test_against = time() - (TIME_PREPARATION_COMMANDE + TEMPS_LIVRAISON_COMMANDE) * 60; - $day = date('Y-m-d'); - $now = date('H:i:s'); - - $vars_qy_liv['heureDebutLivreur_affectation'] = ['$lte' => $now]; - $vars_qy_liv['heureFinLivreur_affectation'] = ['$gte' => $now]; - $vars_qy_liv['idsecteur'] = $idsecteur; - $vars_qy_liv['dateDebutLivreur_affectation'] = $day; - $vars_qy_liv['actifLivreur_affectation'] = 1; - - $vars_liv = []; // livreurs actifs ! - if ($idlivreur) { - $vars_liv['idlivreur'] = $idlivreur; - } - $vars_liv['idsecteur'] = $idsecteur; - $vars_liv['actifLivreur'] = 1; - $LIV_IN = $APP_LIV->distinct('idlivreur', $vars_liv); - $vars_qy_liv['idlivreur'] = ['$in' => $LIV_IN]; - - $rs_test_affect = $APP_LIV_AFFECT->find($vars_qy_liv); - - return iterator_to_array($rs_test_affect); - } - - static function secteur_has_livreur_free($idsecteur) { - return (self::secteur_has_livreur_free_list($idsecteur)->count() == 0); - } - - static function secteur_has_livreur_free_count($idsecteur) { - return self::secteur_has_livreur_free_list($idsecteur)->count(); - } - - /** - * Livreurs actifs, n'ayant aucune commande en cours - * - * @param $idsecteur - * @param string $day - * @param string $now - * - * @return MongoCursor - */ - static function secteur_has_livreur_free_list($idsecteur, $day = '', $now = '') { - $APP_COMMANDE = new IdaeDB('commande'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $APP_LIVREUR = new App('livreur'); - $BIN = new Bin(); - - $idsecteur = (int)$idsecteur; - - $day = date('Y-m-d'); - - $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); - $livreur_secteur['idsecteur'] = $idsecteur; - $livreur_secteur['dateCommande'] = $day; - $livreur_secteur['idcommande_statut'] = ['$nin' => [(int)$ARR_STATUT['idcommande_statut']]]; - // livreur FREE - $arr_test_affect_free = $APP_COMMANDE->distinct('idlivreur', $livreur_secteur); - - $arr_secteur_liv = CommandeQueue::secteur_has_livreur_list($idsecteur); - //$arr_test_affect = $BIN->test_livreur_affect($idsecteur); - $arr_test_affect = array_column(array_values($arr_secteur_liv), 'idlivreur'); - - // - $arr_idlivreur = array_values(array_diff($arr_test_affect, $arr_test_affect_free)); - - $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_idlivreur], 'actifLivreur' => 1]); - - return $rs_test_affect; - - } - - static function secteur_has_livreur_waiting($idsecteur, $day = '') { - return (self::secteur_has_livreur_waiting_list($idsecteur)->count() == 0); - } - - static function secteur_has_livreur_waiting_count($idsecteur, $day = '') { - return self::secteur_has_livreur_waiting_list($idsecteur)->count(); - } - - static function secteur_has_livreur_waiting_list($idsecteur, $day = '') { - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $APP_LIVREUR = new App('livreur'); - - $day = date('Y-m-d'); - - $arr_test_affect = CommandeQueue::secteur_has_livreur_list((int)$idsecteur); - $arr_idlivreur = array_column(array_values($arr_test_affect), 'idlivreur'); - - $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => ['$in' => ['START', 'RESERV', 'RUN']]]); - $vars_qy_liv['idsecteur'] = (int)$idsecteur; - $vars_qy_liv['dateCommande'] = $day; - $vars_qy_liv['idcommande_statut'] = ['$in' => [(int)$ARR_STATUT['idcommande_statut']]]; - $vars_qy_liv['idlivreur']['$nin'] = ['', 0, null]; - $vars_qy_liv['idlivreur']['$in'] = $arr_idlivreur; - - $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); - $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_test_affect_free]]); - - return $rs_test_affect; - - } - - /** - * get other commands ( same secteur ) other shops - * - * @param $idshop - * - * @return bool - */ - static public function secteur_shop_other_commande_non_prefin($idshop) { - return (self::secteur_shop_other_commande_non_prefin_list($idshop)->count() == 0); - } - - /** - * get other commands ( same secteur ) other shops - * - * @param $idshop - * - * @return int - */ - static public function secteur_shop_other_commande_non_prefin_count($idshop) { - return self::secteur_shop_other_commande_non_prefin_list($idshop)->count(); - } - - /** - * get other commands ( same secteur ) other shops - * - * @param $idshop - * - * @return MongoCursor - */ - static public function secteur_shop_other_commande_non_prefin_list($idshop) { - $APP_COMMANDE = new App("commande"); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $day = date('Y-m-d'); - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); - - $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], - 'idshop' => ['$ne' => (int)$idshop], - 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); - - return $rs_test_commande_shop; - } - - static public function shop_has_other_commande_non_prefin($idshop, $idcommande) { - return (self::shop_has_other_commande_non_prefin_list($idshop, $idcommande)->count() != 0); - } - - static public function shop_has_other_commande_non_prefin_count($idshop, $idcommande) { - return self::shop_has_other_commande_non_prefin_list($idshop, $idcommande)->count(); - } - - static public function shop_has_other_commande_non_prefin_list($idshop, $idcommande) { - $APP_COMMANDE = new App("commande"); - $APP_COMMANDE_STATUT = new App('commande_statut'); - - $day = date('Y-m-d'); - - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); - - $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], - 'idcommande' => ['$ne' => (int)$idcommande], - 'idshop' => (int)$idshop, - 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); - - return $rs_test_commande_shop; - - } - - static public function shop_has_other_commandefree_non_prefin_list($idshop, $idcommande) { - $APP_COMMANDE = new App("commande"); - $APP_COMMANDE_STATUT = new App('commande_statut'); - - $day = date('Y-m-d'); - - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - - $arr_commande_statut = $APP_COMMANDE_STATUT->distinct_all('idcommande_statut', ['codeCommande_statut' => ['$in' => ['START', 'RESERV', 'RUN']]]); - - $rs_test_commande_shop = $APP_COMMANDE->find(['idcommande_statut' => ['$in' => $arr_commande_statut], - 'idcommande' => ['$ne' => (int)$idcommande], - 'idlivreur' => ['$in' => ['', 0, null]], - 'idshop' => (int)$idshop, - 'heureCommande' => ['$lt' => $arr_commande['heureCommande']], - 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); - - return $rs_test_commande_shop; - } - - static public function shop_has_other_commandefree_non_prefin($idshop, $idcommande) { - return (self::shop_has_other_commandefree_non_prefin_list($idshop, $idcommande)->count() == 0); - } - - static public function shop_has_other_commandefree_non_prefin_count($idshop, $idcommande) { - return self::shop_has_other_commandefree_non_prefin_list($idshop, $idcommande)->count(); - } - - /** - * @param $idshop - * - * @return \MongoCursor - * @throws \MongoCursorException - */ - static public function shop_commande_queue_list($idshop) { - $APP_COMMANDE = new IdaeDB('commande'); - $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); - $day = date('Y-m-d'); - - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); - - $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); - - return $rs_test_commande_shop; - } - - static public function shop_commande_queue_count($idshop) { - return self::shop_commande_queue_list($idshop)->count(); - } - - static public function shop_commande_queue_undelivered_list($idshop) { - $APP_COMMANDE = new IdaeDB('commande'); - $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); - $day = date('Y-m-d'); - - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); - - $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1, 'slotCommande' => 1]); - - return $rs_test_commande_shop; - } - - static public function shop_commande_queue_undelivered_count($idshop) { - return self::shop_commande_queue_undelivered_list($idshop)->count(); - } - - static public function shop_commande_queue_undelivered_last_list($idshop) { - $APP_COMMANDE = new IdaeDB('commande'); - $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); - $day = date('Y-m-d'); - - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); - - $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['rangCommande' => -1, 'heureCommande' => -1, 'slotCommande' => -1]); - - return $rs_test_commande_shop; - } - - static public function shop_commande_queue_undelivered_last_elemnt($idshop) { - return self::shop_commande_queue_undelivered_last_list($idshop)->getNext(); - } - - /** - * @param $idshop - * - * @return \MongoCursor - * @throws \MongoCursorException - */ - static public function shop_commande_queue_shift_list($idshop) { - $APP_COMMANDE = new IdaeDB('commande'); - $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); - $day = date('Y-m-d'); - $arr_shift = Bin::get_shop_shift_current($idshop); - $arr_shift_vars = ['heureCommande' => ['$gte' => $arr_shift['heureDebutShop_jours_shift'], '$lte' => $arr_shift['heureFinShop_jours_shift']]]; - - $rs_test_commande_shop = $APP_COMMANDE->find($arr_shift_vars + ['idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); - - return $rs_test_commande_shop; - } - - /** - * @param $idshop - * - * @return bool - * @throws \MongoCursorException - */ - static public function shop_commande_queue_shift($idshop) { - return (self::shop_commande_queue_shift_count($idshop) == 0); - } - - /** - * @param $idshop - * - * @return int - * @throws \MongoCursorException - */ - static public function shop_commande_queue_shift_count($idshop) { - return self::shop_commande_queue_shift_list($idshop)->count(); - } - - static public function shop_commande_queue_last($idshop) { - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $day = date('Y-m-d'); - - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); - - $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['heureCommande' => -1, 'rangCommande' => -1]); - - return $rs_test_commande_shop->getNext(); - } - - /** - * shop actual slot is rang commande !!! shop_actual_slot - * - * @param $idcommande - * - * @return int - */ - static public function shop_actual_slot($idcommande) { - $APP_COMMANDE = new App('commande'); - $APP_SHOP = new App('shop'); - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - - $idshop = $arr_commande['idshop']; - $arr_shop = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $list_secteur = CommandeQueue::secteur_commande_queue_list($arr_shop['idsecteur']); - $list_shop = CommandeQueue::shop_commande_queue_last($idshop); - $secteur_queue_count = CommandeQueue::secteur_shop_other_commande_non_prefin($idshop); - $nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($arr_shop['idsecteur']); - - $arr_list = iterator_to_array($list_secteur); - $adadou = array_column($arr_list, 'rangCommande'); - $ADADA = array_count_values($adadou); - - ksort($ADADA); - - $rangCommande = $arr_commande['rangCommande']; - $taille = $ADADA[$rangCommande]; - $taille_int = (int)str_replace('S', '', $rangCommande); - - return $taille_int; - - $i = 0; - if (empty($rangCommande)) { - $i = 0; - foreach ($ADADA as $index => $nb) { - ++$i; - if ($nb >= $nb_livreur_disp && $i != sizeof($ADADA)) { - continue; - } - $rang = (int)str_replace('S', '', $index); - - $rangCommande = $rang; - } - - } else { - $taille = $ADADA[$rangCommande]; - $taille_int = (int)str_replace('S', '', $rangCommande); - - if (empty($taille)) { - $i = 0; - - foreach ($ADADA as $index => $nb) { - ++$i; - if ($nb >= $nb_livreur_disp && $i != sizeof($ADADA)) { - continue; - } - $rang = (int)str_replace('S', '', $index); - $rangCommande = $rang; - } - } else { - $rangCommande = $taille_int; - } - } - - return $rangCommande; - - } - - static public function shop_next_slot($idshop) { - - $APP_SHOP = new IdaeDB('shop'); - $arr_shop = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $a_nomShop = $arr_shop['nomShop']; - $list_shop = CommandeQueue::shop_commande_queue_last($idshop); - $list_secteur = CommandeQueue::secteur_commande_queue_list($arr_shop['idsecteur']); // last before shop - $nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($arr_shop['idsecteur']); - - $arr_list = iterator_to_array($list_secteur); - $adadou = array_column($arr_list, 'slotCommande'); - $ADADA = array_count_values($adadou); - - ksort($ADADA, SORT_STRING); - - $rangCommande_str = $list_shop['slotCommande'] ?: 'R0'; - $rangCommande = (int)str_replace('R', '', $rangCommande_str); - - $taille = $ADADA[$rangCommande_str]; - - $i = 0; - - $calculated = $rangCommande + 1 ; - - foreach ($ADADA as $index => $nb) { - ++$i; - - $rangSecteur = (int)str_replace('R', '', $index); // rang actuel secteur ADADA - $rangSecteur_nb = $ADADA[$index]; - - if ($rangSecteur <= $rangCommande) { - continue; - } - - $calculated = ++$rangSecteur_nb; - } - - return "$calculated"; - - } - } + 1, 'heureCommande' => 1, 'slotCommande' => 1]; + const sort_from_last_slot = ['rangCommande' => -1, 'heureCommande' => -1, 'slotCommande' => -1]; + + const sort_from_first_commande = ['rangCommande' => 1, 'heureCommande' => 1]; + const sort_from_last_commande = ['rangCommande' => -1, 'heureCommande' => -1]; + + static function secteur_commande_queue_ended_count($idsecteur) { + return self::secteur_commande_queue_ended_list($idsecteur)->count(); + } + + static function secteur_commande_queue_ended_list($idsecteur) { + $APP_COMMANDE = new IdaeDB('commande'); + $day = date('Y-m-d'); + + $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$in' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day]); + $rs_test_commande_secteur->sort(self::sort_from_first_slot); + + return $rs_test_commande_secteur; + } + + static function secteur_commande_queue_count($idsecteur) { + return self::secteur_commande_queue_list($idsecteur)->count(); + } + + static function secteur_commande_queue_list($idsecteur) { + $APP_COMMANDE = new IdaeDB('commande'); + $day = date('Y-m-d'); + + $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); + + return $rs_test_commande_secteur; + } + + static function secteur_commande_queue_list_last($idsecteur) { + return self::secteur_commande_queue_list($idsecteur)->sort(['slotCommande' => -1, 'rangCommande' => -1])->getNext(); + } + + static function secteur_commande_free_count($idsecteur, $day = '', $now = '') { + return sizeof(self::secteur_commande_free_list($idsecteur)); + } + + static function secteur_commande_free_list($idsecteur, $day = '', $now = '') { + $APP_COMMANDE = new IdaeDB('commande'); + $day = date('Y-m-d'); + + $rs_test_commande_secteur = $APP_COMMANDE->find(['idlivreur' => ['$in' => ['', 0, null]], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['slotCommande' => 1, 'rangCommande' => 1, 'heureCommande' => 1]); + + return iterator_to_array($rs_test_commande_secteur); + } + + static function secteur_commande_nonfree_count($idsecteur) { + return sizeof((self::secteur_commande_nonfree_list($idsecteur))); + } + + static function secteur_commande_nonfree_list($idsecteur, $day = '', $now = '') { + $APP_COMMANDE = new App('secteur'); + $day = date('Y-m-d'); + + $rs_test_commande_secteur = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['PREFIN', 'LIVENCOU', 'END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['slotCommande' => 1, 'rangCommande' => 1, 'heureCommande' => 1]); + + return iterator_to_array($rs_test_commande_secteur); + } + + /** + * @param $idsecteur + * @param null $idlivreur + * + * @return int + */ + static function secteur_has_livreur_count($idsecteur, $idlivreur = null) { + return sizeof(self::secteur_has_livreur_list($idsecteur, $idlivreur)); + } + + /** + * @param $idsecteur + * @param null $idlivreur + * + * @return array + */ + static function secteur_has_livreur_list($idsecteur, $idlivreur = null) { + + $APP_LIV = new IdaeDB('livreur'); + $APP_LIV_AFFECT = new IdaeDB('livreur_affectation'); + $idsecteur = (int)$idsecteur; + + $time_test_against = time() - (TIME_PREPARATION_COMMANDE + TEMPS_LIVRAISON_COMMANDE) * 60; + $day = date('Y-m-d'); + $now = date('H:i:s'); + + $vars_qy_liv['heureDebutLivreur_affectation'] = ['$lte' => $now]; + $vars_qy_liv['heureFinLivreur_affectation'] = ['$gte' => $now]; + $vars_qy_liv['idsecteur'] = $idsecteur; + $vars_qy_liv['dateDebutLivreur_affectation'] = $day; + $vars_qy_liv['actifLivreur_affectation'] = 1; + + $vars_liv = []; // livreurs actifs ! + if ($idlivreur) { + $vars_liv['idlivreur'] = $idlivreur; + } + $vars_liv['idsecteur'] = $idsecteur; + $vars_liv['actifLivreur'] = 1; + $LIV_IN = $APP_LIV->distinct('idlivreur', $vars_liv); + $vars_qy_liv['idlivreur'] = ['$in' => $LIV_IN]; + + $rs_test_affect = $APP_LIV_AFFECT->find($vars_qy_liv); + + return iterator_to_array($rs_test_affect); + } + + static function secteur_has_livreur_free($idsecteur) { + return (self::secteur_has_livreur_free_list($idsecteur)->count() == 0); + } + + static function secteur_has_livreur_free_count($idsecteur) { + return self::secteur_has_livreur_free_list($idsecteur)->count(); + } + + /** + * Livreurs actifs, n'ayant aucune commande en cours + * + * @param $idsecteur + * @param string $day + * @param string $now + * + * @return MongoCursor + */ + static function secteur_has_livreur_free_list($idsecteur, $day = '', $now = '') { + $APP_COMMANDE = new IdaeDB('commande'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $APP_LIVREUR = new App('livreur'); + $BIN = new Bin(); + + $idsecteur = (int)$idsecteur; + + $day = date('Y-m-d'); + + $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); + $livreur_secteur['idsecteur'] = $idsecteur; + $livreur_secteur['dateCommande'] = $day; + $livreur_secteur['idcommande_statut'] = ['$nin' => [(int)$ARR_STATUT['idcommande_statut']]]; + // livreur FREE + $arr_test_affect_free = $APP_COMMANDE->distinct('idlivreur', $livreur_secteur); + + $arr_secteur_liv = CommandeQueue::secteur_has_livreur_list($idsecteur); + //$arr_test_affect = $BIN->test_livreur_affect($idsecteur); + $arr_test_affect = array_column(array_values($arr_secteur_liv), 'idlivreur'); + + // + $arr_idlivreur = array_values(array_diff($arr_test_affect, $arr_test_affect_free)); + + $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_idlivreur], 'actifLivreur' => 1]); + + return $rs_test_affect; + + } + + static function secteur_has_livreur_waiting($idsecteur, $day = '') { + return (self::secteur_has_livreur_waiting_list($idsecteur)->count() == 0); + } + + static function secteur_has_livreur_waiting_count($idsecteur, $day = '') { + return self::secteur_has_livreur_waiting_list($idsecteur)->count(); + } + + static function secteur_has_livreur_waiting_list($idsecteur, $day = '') { + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $APP_LIVREUR = new App('livreur'); + + $day = date('Y-m-d'); + + $arr_test_affect = CommandeQueue::secteur_has_livreur_list((int)$idsecteur); + $arr_idlivreur = array_column(array_values($arr_test_affect), 'idlivreur'); + + $ARR_STATUT = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => ['$in' => ['START', 'RESERV', 'RUN']]]); + $vars_qy_liv['idsecteur'] = (int)$idsecteur; + $vars_qy_liv['dateCommande'] = $day; + $vars_qy_liv['idcommande_statut'] = ['$in' => [(int)$ARR_STATUT['idcommande_statut']]]; + $vars_qy_liv['idlivreur']['$nin'] = ['', 0, null]; + $vars_qy_liv['idlivreur']['$in'] = $arr_idlivreur; + + $arr_test_affect_free = $APP_COMMANDE->distinct_all('idlivreur', $vars_qy_liv); + $rs_test_affect = $APP_LIVREUR->find(['idlivreur' => ['$in' => $arr_test_affect_free]]); + + return $rs_test_affect; + + } + + /** + * get other commands ( same secteur ) other shops + * + * @param $idshop + * + * @return bool + */ + static public function secteur_shop_other_commande_non_prefin($idshop) { + return (self::secteur_shop_other_commande_non_prefin_list($idshop)->count() == 0); + } + + /** + * get other commands ( same secteur ) other shops + * + * @param $idshop + * + * @return int + */ + static public function secteur_shop_other_commande_non_prefin_count($idshop) { + return self::secteur_shop_other_commande_non_prefin_list($idshop)->count(); + } + + /** + * get other commands ( same secteur ) other shops + * + * @param $idshop + * + * @return MongoCursor + */ + static public function secteur_shop_other_commande_non_prefin_list($idshop) { + $APP_COMMANDE = new App("commande"); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $day = date('Y-m-d'); + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); + + $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], + 'idshop' => ['$ne' => (int)$idshop], + 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); + + return $rs_test_commande_shop; + } + + static public function shop_has_other_commande_non_prefin($idshop, $idcommande) { + return (self::shop_has_other_commande_non_prefin_list($idshop, $idcommande)->count() != 0); + } + + static public function shop_has_other_commande_non_prefin_count($idshop, $idcommande) { + return self::shop_has_other_commande_non_prefin_list($idshop, $idcommande)->count(); + } + + static public function shop_has_other_commande_non_prefin_list($idshop, $idcommande) { + $APP_COMMANDE = new App("commande"); + $APP_COMMANDE_STATUT = new App('commande_statut'); + + $day = date('Y-m-d'); + + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); + + $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], + 'idcommande' => ['$ne' => (int)$idcommande], + 'idshop' => (int)$idshop, + 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); + + return $rs_test_commande_shop; + + } + + static public function shop_has_other_commandefree_non_prefin_list($idshop, $idcommande) { + $APP_COMMANDE = new App("commande"); + $APP_COMMANDE_STATUT = new App('commande_statut'); + + $day = date('Y-m-d'); + + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + + $arr_commande_statut = $APP_COMMANDE_STATUT->distinct_all('idcommande_statut', ['codeCommande_statut' => ['$in' => ['START', 'RESERV', 'RUN']]]); + + $rs_test_commande_shop = $APP_COMMANDE->find(['idcommande_statut' => ['$in' => $arr_commande_statut], + 'idcommande' => ['$ne' => (int)$idcommande], + 'idlivreur' => ['$in' => ['', 0, null]], + 'idshop' => (int)$idshop, + 'heureCommande' => ['$lt' => $arr_commande['heureCommande']], + 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); + + return $rs_test_commande_shop; + } + + static public function shop_has_other_commandefree_non_prefin($idshop, $idcommande) { + return (self::shop_has_other_commandefree_non_prefin_list($idshop, $idcommande)->count() == 0); + } + + static public function shop_has_other_commandefree_non_prefin_count($idshop, $idcommande) { + return self::shop_has_other_commandefree_non_prefin_list($idshop, $idcommande)->count(); + } + + /** + * @param $idshop + * + * @return \MongoCursor + * @throws \MongoCursorException + */ + static public function shop_commande_queue_list($idshop) { + $APP_COMMANDE = new IdaeDB('commande'); + $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); + $day = date('Y-m-d'); + + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); + + $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); + + return $rs_test_commande_shop; + } + + static public function shop_commande_queue_count($idshop) { + return self::shop_commande_queue_list($idshop)->count(); + } + + static public function shop_commande_queue_undelivered_list($idshop) { + $APP_COMMANDE = new IdaeDB('commande'); + $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); + $day = date('Y-m-d'); + + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); + + $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1, 'slotCommande' => 1]); + + return $rs_test_commande_shop; + } + + static public function shop_commande_queue_undelivered_count($idshop) { + return self::shop_commande_queue_undelivered_list($idshop)->count(); + } + + static public function shop_commande_queue_undelivered_last_list($idshop) { + $APP_COMMANDE = new IdaeDB('commande'); + $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); + $day = date('Y-m-d'); + + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); + + $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['rangCommande' => -1, 'heureCommande' => -1, 'slotCommande' => -1]); + + return $rs_test_commande_shop; + } + + static public function shop_commande_queue_undelivered_last_elemnt($idshop) { + return self::shop_commande_queue_undelivered_last_list($idshop)->getNext(); + } + + /** + * @param $idshop + * + * @return \MongoCursor + * @throws \MongoCursorException + */ + static public function shop_commande_queue_shift_list($idshop) { + $APP_COMMANDE = new IdaeDB('commande'); + $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); + $day = date('Y-m-d'); + $arr_shift = Bin::get_shop_shift_current($idshop); + $arr_shift_vars = ['heureCommande' => ['$gte' => $arr_shift['heureDebutShop_jours_shift'], '$lte' => $arr_shift['heureFinShop_jours_shift']]]; + + $rs_test_commande_shop = $APP_COMMANDE->find($arr_shift_vars + ['idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['rangCommande' => 1, 'heureCommande' => 1]); + + return $rs_test_commande_shop; + } + + /** + * @param $idshop + * + * @return bool + * @throws \MongoCursorException + */ + static public function shop_commande_queue_shift($idshop) { + return (self::shop_commande_queue_shift_count($idshop) == 0); + } + + /** + * @param $idshop + * + * @return int + * @throws \MongoCursorException + */ + static public function shop_commande_queue_shift_count($idshop) { + return self::shop_commande_queue_shift_list($idshop)->count(); + } + + static public function shop_commande_queue_last($idshop) { + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $day = date('Y-m-d'); + + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); + + $rs_test_commande_shop = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['heureCommande' => -1, 'rangCommande' => -1]); + + return $rs_test_commande_shop->getNext(); + } + + /** + * shop actual slot is rang commande !!! shop_actual_slot + * + * @param $idcommande + * + * @return int + */ + static public function shop_actual_slot($idcommande) { + $APP_COMMANDE = new App('commande'); + $APP_SHOP = new App('shop'); + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + + $idshop = $arr_commande['idshop']; + $arr_shop = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $list_secteur = CommandeQueue::secteur_commande_queue_list($arr_shop['idsecteur']); + $list_shop = CommandeQueue::shop_commande_queue_last($idshop); + $secteur_queue_count = CommandeQueue::secteur_shop_other_commande_non_prefin($idshop); + $nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($arr_shop['idsecteur']); + + $arr_list = iterator_to_array($list_secteur); + $adadou = array_column($arr_list, 'rangCommande'); + $ADADA = array_count_values($adadou); + + ksort($ADADA); + + $rangCommande = $arr_commande['rangCommande']; + $taille = $ADADA[$rangCommande]; + $taille_int = (int)str_replace('S', '', $rangCommande); + + return $taille_int; + + $i = 0; + if (empty($rangCommande)) { + $i = 0; + foreach ($ADADA as $index => $nb) { + ++$i; + if ($nb >= $nb_livreur_disp && $i != sizeof($ADADA)) { + continue; + } + $rang = (int)str_replace('S', '', $index); + + $rangCommande = $rang; + } + + } else { + $taille = $ADADA[$rangCommande]; + $taille_int = (int)str_replace('S', '', $rangCommande); + + if (empty($taille)) { + $i = 0; + + foreach ($ADADA as $index => $nb) { + ++$i; + if ($nb >= $nb_livreur_disp && $i != sizeof($ADADA)) { + continue; + } + $rang = (int)str_replace('S', '', $index); + $rangCommande = $rang; + } + } else { + $rangCommande = $taille_int; + } + } + + return $rangCommande; + + } + + static public function shop_next_slot($idshop) { + + $APP_SHOP = new IdaeDB('shop'); + $arr_shop = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $a_nomShop = $arr_shop['nomShop']; + $list_shop = CommandeQueue::shop_commande_queue_last($idshop); + $list_secteur = CommandeQueue::secteur_commande_queue_list($arr_shop['idsecteur']); // last before shop + $nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($arr_shop['idsecteur']); + + $arr_list = iterator_to_array($list_secteur); + $adadou = array_column($arr_list, 'slotCommande'); + $ADADA = array_count_values($adadou); + + ksort($ADADA, SORT_STRING); + + $rangCommande_str = $list_shop['slotCommande'] ?: 'R0'; + $rangCommande = (int)str_replace('R', '', $rangCommande_str); + + $taille = $ADADA[$rangCommande_str]; + + $i = 0; + + $calculated = $rangCommande + 1 ; + + foreach ($ADADA as $index => $nb) { + ++$i; + + $rangSecteur = (int)str_replace('R', '', $index); // rang actuel secteur ADADA + $rangSecteur_nb = $ADADA[$index]; + + if ($rangSecteur <= $rangCommande) { + continue; + } + + $calculated = ++$rangSecteur_nb; + } + + return "$calculated"; + + } + } diff --git a/web/bin/classes/ClassCommandeQueueConsole.php b/web/bin/classes/ClassCommandeQueueConsole.php index 996ae31..689ab22 100644 --- a/web/bin/classes/ClassCommandeQueueConsole.php +++ b/web/bin/classes/ClassCommandeQueueConsole.php @@ -1,102 +1,102 @@ -findOne(['idshop' => $idshop]); - $idsecteur = $RS['idsecteur']; - - $credentials = ['idsecteur' => $idsecteur, 'idshop' => $idshop, 'soncole' => 'site']; - $CommandeQueueTime = new CommandeQueueTime(); - $data['console_shop'] = $CommandeQueueTime->set_credentials($credentials)->get_times_shop($idshop); - $CommandeQueueTime = new CommandeQueueTime(); - $data ['console_secteur_livreur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur_livreur($idsecteur); - - - - return (object)$data; - } - - static public function consoleShop($idshop) { - - $DB = new IdaeDB('shop'); - $RS = $DB->findOne(['idshop' => $idshop]); - $idsecteur = $RS['idsecteur']; - - $data = []; - $credentials = ['idsecteur' => $idsecteur, 'idshop' => $idshop]; - $CommandeQueueTime = new CommandeQueueTime(); - $data['console_secteur_livreur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur_livreur($idsecteur); - $CommandeQueueTime = new CommandeQueueTime(); - $data ['console_secteur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur($idsecteur); - $CommandeQueueTime = new CommandeQueueTime(); - $data['console_shop'] = $CommandeQueueTime->set_credentials($credentials)->get_times_shop($idshop); - - return (object)$data; - } - - static private function array_flatten($arr) { - $arr = array_values($arr); - while (list($k, $v) = each($arr)) { - if (is_array($v)) { - array_splice($arr, $k, 1, $v); - next($arr); - } - } - - return $arr; - } - - static public function consoleLivreur($idlivreur) { - - $DB = new IdaeDB('livreur'); - $RS = $DB->findOne(['idlivreur' => (int)$idlivreur]); - $idsecteur = (int)$RS['idsecteur']; - - $data = []; - $CommandeQueueTime = new CommandeQueueTime(); - $credentials = ['idsecteur' => $idsecteur, 'idlivreur' => $idlivreur]; - $data['console_secteur_livreur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur_livreur($idsecteur); - $CommandeQueueTime = new CommandeQueueTime(); - $data ['console_secteur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur($idsecteur); - - return (object)$data; - } - - /** - * @return $this|object \CommandeQueueTime[] - */ - static public function get_times_config() { - - - $SELF = new IdaeDB('secteur'); - $ARR_SELF = $SELF->findOne(['slugSecteur' => 'saint-malo']); - - $idsecteur = $ARR_SELF['idsecteur']; - $data = []; - $CommandeQueueTime = new CommandeQueueTime(); - $data ['get_times_secteur'] = $CommandeQueueTime->set_credentials(['idsecteur' => $idsecteur])->get_times_secteur($idsecteur); - $CommandeQueueTime = new CommandeQueueTime(); - $data['get_times_secteur_livreur'] = $CommandeQueueTime->set_credentials(['idsecteur' => $idsecteur])->get_times_secteur_livreur($idsecteur); - - return (object)$data; - } - - } - +findOne(['idshop' => $idshop]); + $idsecteur = $RS['idsecteur']; + + $credentials = ['idsecteur' => $idsecteur, 'idshop' => $idshop, 'soncole' => 'site']; + $CommandeQueueTime = new CommandeQueueTime(); + $data['console_shop'] = $CommandeQueueTime->set_credentials($credentials)->get_times_shop($idshop); + $CommandeQueueTime = new CommandeQueueTime(); + $data ['console_secteur_livreur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur_livreur($idsecteur); + + + + return (object)$data; + } + + static public function consoleShop($idshop) { + + $DB = new IdaeDB('shop'); + $RS = $DB->findOne(['idshop' => $idshop]); + $idsecteur = $RS['idsecteur']; + + $data = []; + $credentials = ['idsecteur' => $idsecteur, 'idshop' => $idshop]; + $CommandeQueueTime = new CommandeQueueTime(); + $data['console_secteur_livreur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur_livreur($idsecteur); + $CommandeQueueTime = new CommandeQueueTime(); + $data ['console_secteur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur($idsecteur); + $CommandeQueueTime = new CommandeQueueTime(); + $data['console_shop'] = $CommandeQueueTime->set_credentials($credentials)->get_times_shop($idshop); + + return (object)$data; + } + + static private function array_flatten($arr) { + $arr = array_values($arr); + while (list($k, $v) = each($arr)) { + if (is_array($v)) { + array_splice($arr, $k, 1, $v); + next($arr); + } + } + + return $arr; + } + + static public function consoleLivreur($idlivreur) { + + $DB = new IdaeDB('livreur'); + $RS = $DB->findOne(['idlivreur' => (int)$idlivreur]); + $idsecteur = (int)$RS['idsecteur']; + + $data = []; + $CommandeQueueTime = new CommandeQueueTime(); + $credentials = ['idsecteur' => $idsecteur, 'idlivreur' => $idlivreur]; + $data['console_secteur_livreur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur_livreur($idsecteur); + $CommandeQueueTime = new CommandeQueueTime(); + $data ['console_secteur'] = $CommandeQueueTime->set_credentials($credentials)->get_times_secteur($idsecteur); + + return (object)$data; + } + + /** + * @return $this|object \CommandeQueueTime[] + */ + static public function get_times_config() { + + + $SELF = new IdaeDB('secteur'); + $ARR_SELF = $SELF->findOne(['slugSecteur' => 'saint-malo']); + + $idsecteur = $ARR_SELF['idsecteur']; + $data = []; + $CommandeQueueTime = new CommandeQueueTime(); + $data ['get_times_secteur'] = $CommandeQueueTime->set_credentials(['idsecteur' => $idsecteur])->get_times_secteur($idsecteur); + $CommandeQueueTime = new CommandeQueueTime(); + $data['get_times_secteur_livreur'] = $CommandeQueueTime->set_credentials(['idsecteur' => $idsecteur])->get_times_secteur_livreur($idsecteur); + + return (object)$data; + } + + } + diff --git a/web/bin/classes/ClassCommandeQueueTime.php b/web/bin/classes/ClassCommandeQueueTime.php index 09ae184..c2a34b7 100644 --- a/web/bin/classes/ClassCommandeQueueTime.php +++ b/web/bin/classes/ClassCommandeQueueTime.php @@ -1,123 +1,123 @@ -current = CommandeQueueTimeFabric::get_times_config(); - - return $this; - } - - public function get_times_secteur_livreur($idsecteur) { - - - $this->current = CommandeQueueTimeFabric::get_times_secteur_livreur($idsecteur); - - return $this; - } - - public function get_times_shop($idshop) { - - $this->current = CommandeQueueTimeFabric::get_times_shop($idshop); - - return $this; - } - - /** - * @param $idsecteur - * - * @return \CommandeQueueTime $this - */ - public function get_times_secteur($idsecteur) { - - - $this->current = CommandeQueueTimeFabric::get_times_secteur($idsecteur); - - return $this; - } - - public function update() { - - $credential_out = $this->get_credentialsSelector(); - - $arr_cmd = []; - - foreach ($this->current as $index => $item) { - $selector = "[data-wait_debug=$index]$credential_out"; - $selector_value = $item; - - array_push($arr_cmd, [$selector, $selector_value]); - } - SendCmd::insert_selectors($arr_cmd); - } - - public function set_credentials($credentials = []) { - - $this->credentials = $credentials; - - return $this; - } - - public function get_templateHTML() { - - $credential_out = $this->get_credentialsATTR(); - - $a = ''; - foreach ($this->current as $index => $item) { - $a .= "$index$item
"; - } - - return $a; - } - - public function get_templateObjHTML() { - - $credential_out = $this->get_credentialsATTR(); - - $a = []; - foreach ($this->current as $index => $item) { - $a[$index] = "$item"; - } - - return (object)$a; - } - - public function get_templateObj () { - - $a = []; - foreach ($this->current as $index => $item) { - $a[$index] = $item; - } - - return (object)$a; - } - - private function get_credentialsATTR() { - $credential_out = []; - foreach ($this->credentials as $index => $credential) { - $credential_out[] = "data-$index='$credential'"; - } - - return implode(' ',$credential_out); - } - - private function get_credentialsSelector() { - $credential_out = []; - foreach ($this->credentials as $index => $credential) { - $credential_out[] = "[data-$index='$credential']"; - } - - return implode('',$credential_out); - } - } - +current = CommandeQueueTimeFabric::get_times_config(); + + return $this; + } + + public function get_times_secteur_livreur($idsecteur) { + + + $this->current = CommandeQueueTimeFabric::get_times_secteur_livreur($idsecteur); + + return $this; + } + + public function get_times_shop($idshop) { + + $this->current = CommandeQueueTimeFabric::get_times_shop($idshop); + + return $this; + } + + /** + * @param $idsecteur + * + * @return \CommandeQueueTime $this + */ + public function get_times_secteur($idsecteur) { + + + $this->current = CommandeQueueTimeFabric::get_times_secteur($idsecteur); + + return $this; + } + + public function update() { + + $credential_out = $this->get_credentialsSelector(); + + $arr_cmd = []; + + foreach ($this->current as $index => $item) { + $selector = "[data-wait_debug=$index]$credential_out"; + $selector_value = $item; + + array_push($arr_cmd, [$selector, $selector_value]); + } + SendCmd::insert_selectors($arr_cmd); + } + + public function set_credentials($credentials = []) { + + $this->credentials = $credentials; + + return $this; + } + + public function get_templateHTML() { + + $credential_out = $this->get_credentialsATTR(); + + $a = ''; + foreach ($this->current as $index => $item) { + $a .= "$index$item
"; + } + + return $a; + } + + public function get_templateObjHTML() { + + $credential_out = $this->get_credentialsATTR(); + + $a = []; + foreach ($this->current as $index => $item) { + $a[$index] = "$item"; + } + + return (object)$a; + } + + public function get_templateObj () { + + $a = []; + foreach ($this->current as $index => $item) { + $a[$index] = $item; + } + + return (object)$a; + } + + private function get_credentialsATTR() { + $credential_out = []; + foreach ($this->credentials as $index => $credential) { + $credential_out[] = "data-$index='$credential'"; + } + + return implode(' ',$credential_out); + } + + private function get_credentialsSelector() { + $credential_out = []; + foreach ($this->credentials as $index => $credential) { + $credential_out[] = "[data-$index='$credential']"; + } + + return implode('',$credential_out); + } + } + diff --git a/web/bin/classes/ClassCommandeQueueTimeFabric.php b/web/bin/classes/ClassCommandeQueueTimeFabric.php index 02d6016..66f7dc0 100644 --- a/web/bin/classes/ClassCommandeQueueTimeFabric.php +++ b/web/bin/classes/ClassCommandeQueueTimeFabric.php @@ -1,174 +1,174 @@ - nb_commandes_secteur ) => (last_commande_shop_heure_livraison - NOW) + TEMP_PREP_LIV_COMMANDE sinon max_command_shop_rang + TEMP_PREP_LIV_COMMANDE - * exemple : - * Pour une commande classée R1 après le filtrage shop - * - si un coursier au moins n'as pas de commande R1, C=R1 => R secteur = nombre_commande * nb_livreurs , ex 1 * 2 = 2 - * - si tous les coursiers ont déjà une R1, C=R2 - * - si tous les coursiers ont déjà une R2, C=R3 - * -etc - */ - class CommandeQueueTimeFabric { - - static public function get_times_config() { - $current = []; - - $current['DUREE_REALISATION_COMMANDE'] = DUREE_REALISATION_COMMANDE; - $current['TIME_PREPARATION_COMMANDE'] = TIME_PREPARATION_COMMANDE; - $current['TEMPS_LIVRAISON_COMMANDE'] = TEMPS_LIVRAISON_COMMANDE; - - return $current; - } - - static public function get_times_secteur_livreur($idsecteur) { - $current = []; - - $current['LIVREUR_WORKING_NB'] = CommandeQueue::secteur_has_livreur_count($idsecteur); - $current['LIVREUR_DISPONIBLE_NB'] = CommandeQueue::secteur_has_livreur_free_count($idsecteur); - $current['LIVREUR_WAITING_COMMANDE_NB'] = CommandeQueue::secteur_has_livreur_waiting_count($idsecteur); - - $pluriel = ($current['LIVREUR_WORKING_NB'] > 1) ? 's' : ''; - $msg = $current['LIVREUR_WORKING_NB'] . " coursier$pluriel disponible$pluriel actuellement"; - $current['LIVREUR_MSG'] = ($current['LIVREUR_WORKING_NB'] == 0) ? "Aucun coursier n'est disponible actuellement" : $msg; - - return $current; - } - - static public function get_times_shop($idshop) { - $shop = new IdaeDB('shop'); - $ARR_SHOP = $shop->findOne(['idshop' => $idshop]); - $idsecteur = (int)$ARR_SHOP['idsecteur']; - $CommandeSlot = new CommandeSlot($idsecteur); - $CommandeSlot->distribute($idsecteur); - $test_shop_open = Bin::test_shop_open($idshop); - $current = []; - - $NB_LIVREUR = CommandeQueue::secteur_has_livreur_count($idsecteur); - $ARR_COMMAND_SHOP_LAST = CommandeQueue::shop_commande_queue_last($idshop); - $ARR_COMMAND_SHOP_UNDELIVERED_LAST = CommandeQueue::shop_commande_queue_undelivered_last_elemnt($idshop); - $COMMAND_SHOP_WAITING_NB = CommandeQueue::shop_commande_queue_count($idshop); - $COMMAND_SHOP_SHIFT_NB = CommandeQueue::shop_commande_queue_shift_count($idshop); - $COMMAND_SHOP_NEXT_SLOT = str_replace('R', '', $CommandeSlot->get_next_slot_shop($idshop)); - - $COMMAND_SHOP_NEXT_SLOT_MINUTES = TEMPS_LIVRAISON_COMMANDE + ($COMMAND_SHOP_NEXT_SLOT * TIME_PREPARATION_COMMANDE); - $COMMAND_SHOP_NEXT_SLOT_SECONDES = $COMMAND_SHOP_NEXT_SLOT_MINUTES * 60; - $COMMAND_SHOP_RANG = $ARR_COMMAND_SHOP_LAST['rangCommande'] ?: "S0"; - - $COMMAND_SHOP_UNDELIVERED_LAST_ORDER = $ARR_COMMAND_SHOP_UNDELIVERED_LAST['ordreSecteurCommande']; - - $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE = self::str_delay_range($COMMAND_SHOP_NEXT_SLOT_SECONDES); - $COMMAND_SHOP_FINAL_DELIVERY_DATETIME = date('H:i', ($COMMAND_SHOP_NEXT_SLOT_SECONDES + time())); - - $timeCreationCommande = strtotime($ARR_COMMAND_SHOP_LAST['dateCreationCommande'] . ' ' . $ARR_COMMAND_SHOP_LAST['heureCreationCommande']); - $COMMAND_SHOP_NEXT_SLOT_DELAY = ceil((($timeCreationCommande + $COMMAND_SHOP_NEXT_SLOT_SECONDES) - time()) / 60); - - $current['COMMAND_SHOP_NEXT_SLOT'] = "R$COMMAND_SHOP_NEXT_SLOT"; - $current['COMMAND_SHOP_NEXT_SLOT_MINUTES'] = $COMMAND_SHOP_NEXT_SLOT_MINUTES; - $current['COMMAND_SHOP_RANG'] = $COMMAND_SHOP_RANG; - $current['COMMAND_SHOP_SHIFT_NB'] = $COMMAND_SHOP_SHIFT_NB; - $current['COMMAND_SHOP_WAITING_NB'] = $COMMAND_SHOP_WAITING_NB; - - $current['COMMAND_SHOP_NEXT_SLOT_DYNAMIC_DELAY'] = $COMMAND_SHOP_NEXT_SLOT_DELAY; - $current['COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE'] = (!$test_shop_open || ($COMMAND_SHOP_SHIFT_NB >= NB_MAX_COMMANDE_SHOP)) ? '' : $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE . ' - R' . $COMMAND_SHOP_NEXT_SLOT . ' ' . $COMMAND_SHOP_SHIFT_NB . ' cmd(s)'; - $current['COMMAND_SHOP_FINAL_DELIVERY_DATETIME'] = (!$test_shop_open || ($COMMAND_SHOP_SHIFT_NB >= NB_MAX_COMMANDE_SHOP)) ? '' : $COMMAND_SHOP_FINAL_DELIVERY_DATETIME; - $current['COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE'] = self::get_time_livraison_thumb(($test_shop_open) ? $COMMAND_SHOP_NEXT_SLOT : 0); - - $current['COMMAND_SHOP_MSG'] = ($COMMAND_SHOP_SHIFT_NB >= NB_MAX_COMMANDE_SHOP) ? "Actuellement ne prend plus de nouvelle commande" : ''; - $current['COMMAND_SHOP_MSG'] = (!$test_shop_open) ? "Actuellement fermé" : $current['COMMAND_SHOP_MSG']; - - $index = TEMPS_LIVRAISON_COMMANDE + TIME_PREPARATION_COMMANDE * ceil($NB_LIVREUR / ($COMMAND_SHOP_UNDELIVERED_LAST_ORDER + 1)); - $index = $COMMAND_SHOP_UNDELIVERED_LAST_ORDER / $NB_LIVREUR; - - $current['COMMAND_SHOP_TIME'] = $COMMAND_SHOP_UNDELIVERED_LAST_ORDER . ' => ' . $index . ' ' . ceil($index); - - return $current; - } - - static private function get_time_livraison_thumb($COMMAND_SHOP_SLOT) { - - - return ''; - } - - static private function get_time_livraison_time($time) { - if (empty($time)) return time(); - if ($time < time()) return time() + TEMPS_LIVRAISON_COMMANDE; - - return $time; - } - - static public function get_times_secteur($idsecteur) { - $current = []; - - $ARR_COMMAND_SECTEUR_LAST = CommandeQueue::secteur_commande_queue_list_last($idsecteur); - $current['COMMAND_SECTEUR_NB'] = CommandeQueue::secteur_commande_queue_count($idsecteur); - $current['COMMAND_SECTEUR_UNASSIGNED_NB'] = CommandeQueue::secteur_commande_free_count($idsecteur); // sans livreur - $current['COMMAND_SECTEUR_UNDELIVERED_NB'] = CommandeQueue::secteur_commande_nonfree_count($idsecteur); // before prefin, avec ou sans livreur - - $timeLivraisonCommande = $ARR_COMMAND_SECTEUR_LAST['timeLivraisonCommande']; - - if (empty($timeLivraisonCommande)) { - $timeLivraisonCommande = time(); - $DELAY_TIME_END_COMMAND_SECTEUR = TEMPS_LIVRAISON_COMMANDE * 60; - - } else if ($timeLivraisonCommande < time()) { - $timeLivraisonCommande = time() + (TEMPS_LIVRAISON_COMMANDE * 60); - $DELAY_TIME_END_COMMAND_SECTEUR = TEMPS_LIVRAISON_COMMANDE * 60; - - } else { - $DELAY_TIME_END_COMMAND_SECTEUR = $timeLivraisonCommande - time(); - - } - - $current['COMMAND_SECTEUR_LAST_DELIVERY_HOUR'] = date('H:i', $timeLivraisonCommande); - $current['COMMAND_SECTEUR_LAST_DELIVERY_HOUR_DELAY'] = self::str_delay($DELAY_TIME_END_COMMAND_SECTEUR); - $current['COMMAND_SECTEUR_LAST_DELIVERY_MINUTES_DELAY'] = ceil($DELAY_TIME_END_COMMAND_SECTEUR / 60); - $current['COMMAND_SECTEUR_LAST_DELIVERY_THUMB_STATE'] = self::get_time_livraison_thumb($current['COMMAND_SECTEUR_LAST_DELIVERY_MINUTES_DELAY']); - - return $current; - } - - static private function str_delay($secondeLivraison) { - $heures = (int)($secondeLivraison / 3600); - $minutes = (int)(($secondeLivraison % 3600) / 60); - $str_hours = empty($heures) ? '' : $heures . ' hr'; - $str_hours .= ($heures > 1) ? 's' : ''; - $str_minutes = ($minutes == 0) ? '' : ' ' . $minutes . ' mn'; - - return $str_hours . $str_minutes; - } - - static private function str_delay_range($secondeLivraison) { - $minutes = ceil($secondeLivraison / 60); - - $p = pow(5, 1); - $minutes_round_2 = ceil($minutes / $p) * $p; - - $str = ($minutes_round_2 - 5) . ' - ' . ($minutes_round_2 + 5); - - return "$str mins"; - } - } - + nb_commandes_secteur ) => (last_commande_shop_heure_livraison - NOW) + TEMP_PREP_LIV_COMMANDE sinon max_command_shop_rang + TEMP_PREP_LIV_COMMANDE + * exemple : + * Pour une commande classée R1 après le filtrage shop + * - si un coursier au moins n'as pas de commande R1, C=R1 => R secteur = nombre_commande * nb_livreurs , ex 1 * 2 = 2 + * - si tous les coursiers ont déjà une R1, C=R2 + * - si tous les coursiers ont déjà une R2, C=R3 + * -etc + */ + class CommandeQueueTimeFabric { + + static public function get_times_config() { + $current = []; + + $current['DUREE_REALISATION_COMMANDE'] = DUREE_REALISATION_COMMANDE; + $current['TIME_PREPARATION_COMMANDE'] = TIME_PREPARATION_COMMANDE; + $current['TEMPS_LIVRAISON_COMMANDE'] = TEMPS_LIVRAISON_COMMANDE; + + return $current; + } + + static public function get_times_secteur_livreur($idsecteur) { + $current = []; + + $current['LIVREUR_WORKING_NB'] = CommandeQueue::secteur_has_livreur_count($idsecteur); + $current['LIVREUR_DISPONIBLE_NB'] = CommandeQueue::secteur_has_livreur_free_count($idsecteur); + $current['LIVREUR_WAITING_COMMANDE_NB'] = CommandeQueue::secteur_has_livreur_waiting_count($idsecteur); + + $pluriel = ($current['LIVREUR_WORKING_NB'] > 1) ? 's' : ''; + $msg = $current['LIVREUR_WORKING_NB'] . " coursier$pluriel disponible$pluriel actuellement"; + $current['LIVREUR_MSG'] = ($current['LIVREUR_WORKING_NB'] == 0) ? "Aucun coursier n'est disponible actuellement" : $msg; + + return $current; + } + + static public function get_times_shop($idshop) { + $shop = new IdaeDB('shop'); + $ARR_SHOP = $shop->findOne(['idshop' => $idshop]); + $idsecteur = (int)$ARR_SHOP['idsecteur']; + $CommandeSlot = new CommandeSlot($idsecteur); + $CommandeSlot->distribute($idsecteur); + $test_shop_open = Bin::test_shop_open($idshop); + $current = []; + + $NB_LIVREUR = CommandeQueue::secteur_has_livreur_count($idsecteur); + $ARR_COMMAND_SHOP_LAST = CommandeQueue::shop_commande_queue_last($idshop); + $ARR_COMMAND_SHOP_UNDELIVERED_LAST = CommandeQueue::shop_commande_queue_undelivered_last_elemnt($idshop); + $COMMAND_SHOP_WAITING_NB = CommandeQueue::shop_commande_queue_count($idshop); + $COMMAND_SHOP_SHIFT_NB = CommandeQueue::shop_commande_queue_shift_count($idshop); + $COMMAND_SHOP_NEXT_SLOT = str_replace('R', '', $CommandeSlot->get_next_slot_shop($idshop)); + + $COMMAND_SHOP_NEXT_SLOT_MINUTES = TEMPS_LIVRAISON_COMMANDE + ($COMMAND_SHOP_NEXT_SLOT * TIME_PREPARATION_COMMANDE); + $COMMAND_SHOP_NEXT_SLOT_SECONDES = $COMMAND_SHOP_NEXT_SLOT_MINUTES * 60; + $COMMAND_SHOP_RANG = $ARR_COMMAND_SHOP_LAST['rangCommande'] ?: "S0"; + + $COMMAND_SHOP_UNDELIVERED_LAST_ORDER = $ARR_COMMAND_SHOP_UNDELIVERED_LAST['ordreSecteurCommande']; + + $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE = self::str_delay_range($COMMAND_SHOP_NEXT_SLOT_SECONDES); + $COMMAND_SHOP_FINAL_DELIVERY_DATETIME = date('H:i', ($COMMAND_SHOP_NEXT_SLOT_SECONDES + time())); + + $timeCreationCommande = strtotime($ARR_COMMAND_SHOP_LAST['dateCreationCommande'] . ' ' . $ARR_COMMAND_SHOP_LAST['heureCreationCommande']); + $COMMAND_SHOP_NEXT_SLOT_DELAY = ceil((($timeCreationCommande + $COMMAND_SHOP_NEXT_SLOT_SECONDES) - time()) / 60); + + $current['COMMAND_SHOP_NEXT_SLOT'] = "R$COMMAND_SHOP_NEXT_SLOT"; + $current['COMMAND_SHOP_NEXT_SLOT_MINUTES'] = $COMMAND_SHOP_NEXT_SLOT_MINUTES; + $current['COMMAND_SHOP_RANG'] = $COMMAND_SHOP_RANG; + $current['COMMAND_SHOP_SHIFT_NB'] = $COMMAND_SHOP_SHIFT_NB; + $current['COMMAND_SHOP_WAITING_NB'] = $COMMAND_SHOP_WAITING_NB; + + $current['COMMAND_SHOP_NEXT_SLOT_DYNAMIC_DELAY'] = $COMMAND_SHOP_NEXT_SLOT_DELAY; + $current['COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE'] = (!$test_shop_open || ($COMMAND_SHOP_SHIFT_NB >= NB_MAX_COMMANDE_SHOP)) ? '' : $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE . ' - R' . $COMMAND_SHOP_NEXT_SLOT . ' ' . $COMMAND_SHOP_SHIFT_NB . ' cmd(s)'; + $current['COMMAND_SHOP_FINAL_DELIVERY_DATETIME'] = (!$test_shop_open || ($COMMAND_SHOP_SHIFT_NB >= NB_MAX_COMMANDE_SHOP)) ? '' : $COMMAND_SHOP_FINAL_DELIVERY_DATETIME; + $current['COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE'] = self::get_time_livraison_thumb(($test_shop_open) ? $COMMAND_SHOP_NEXT_SLOT : 0); + + $current['COMMAND_SHOP_MSG'] = ($COMMAND_SHOP_SHIFT_NB >= NB_MAX_COMMANDE_SHOP) ? "Actuellement ne prend plus de nouvelle commande" : ''; + $current['COMMAND_SHOP_MSG'] = (!$test_shop_open) ? "Actuellement fermé" : $current['COMMAND_SHOP_MSG']; + + $index = TEMPS_LIVRAISON_COMMANDE + TIME_PREPARATION_COMMANDE * ceil($NB_LIVREUR / ($COMMAND_SHOP_UNDELIVERED_LAST_ORDER + 1)); + $index = $COMMAND_SHOP_UNDELIVERED_LAST_ORDER / $NB_LIVREUR; + + $current['COMMAND_SHOP_TIME'] = $COMMAND_SHOP_UNDELIVERED_LAST_ORDER . ' => ' . $index . ' ' . ceil($index); + + return $current; + } + + static private function get_time_livraison_thumb($COMMAND_SHOP_SLOT) { + + + return ''; + } + + static private function get_time_livraison_time($time) { + if (empty($time)) return time(); + if ($time < time()) return time() + TEMPS_LIVRAISON_COMMANDE; + + return $time; + } + + static public function get_times_secteur($idsecteur) { + $current = []; + + $ARR_COMMAND_SECTEUR_LAST = CommandeQueue::secteur_commande_queue_list_last($idsecteur); + $current['COMMAND_SECTEUR_NB'] = CommandeQueue::secteur_commande_queue_count($idsecteur); + $current['COMMAND_SECTEUR_UNASSIGNED_NB'] = CommandeQueue::secteur_commande_free_count($idsecteur); // sans livreur + $current['COMMAND_SECTEUR_UNDELIVERED_NB'] = CommandeQueue::secteur_commande_nonfree_count($idsecteur); // before prefin, avec ou sans livreur + + $timeLivraisonCommande = $ARR_COMMAND_SECTEUR_LAST['timeLivraisonCommande']; + + if (empty($timeLivraisonCommande)) { + $timeLivraisonCommande = time(); + $DELAY_TIME_END_COMMAND_SECTEUR = TEMPS_LIVRAISON_COMMANDE * 60; + + } else if ($timeLivraisonCommande < time()) { + $timeLivraisonCommande = time() + (TEMPS_LIVRAISON_COMMANDE * 60); + $DELAY_TIME_END_COMMAND_SECTEUR = TEMPS_LIVRAISON_COMMANDE * 60; + + } else { + $DELAY_TIME_END_COMMAND_SECTEUR = $timeLivraisonCommande - time(); + + } + + $current['COMMAND_SECTEUR_LAST_DELIVERY_HOUR'] = date('H:i', $timeLivraisonCommande); + $current['COMMAND_SECTEUR_LAST_DELIVERY_HOUR_DELAY'] = self::str_delay($DELAY_TIME_END_COMMAND_SECTEUR); + $current['COMMAND_SECTEUR_LAST_DELIVERY_MINUTES_DELAY'] = ceil($DELAY_TIME_END_COMMAND_SECTEUR / 60); + $current['COMMAND_SECTEUR_LAST_DELIVERY_THUMB_STATE'] = self::get_time_livraison_thumb($current['COMMAND_SECTEUR_LAST_DELIVERY_MINUTES_DELAY']); + + return $current; + } + + static private function str_delay($secondeLivraison) { + $heures = (int)($secondeLivraison / 3600); + $minutes = (int)(($secondeLivraison % 3600) / 60); + $str_hours = empty($heures) ? '' : $heures . ' hr'; + $str_hours .= ($heures > 1) ? 's' : ''; + $str_minutes = ($minutes == 0) ? '' : ' ' . $minutes . ' mn'; + + return $str_hours . $str_minutes; + } + + static private function str_delay_range($secondeLivraison) { + $minutes = ceil($secondeLivraison / 60); + + $p = pow(5, 1); + $minutes_round_2 = ceil($minutes / $p) * $p; + + $str = ($minutes_round_2 - 5) . ' - ' . ($minutes_round_2 + 5); + + return "$str mins"; + } + } + diff --git a/web/bin/classes/ClassCommandeSlot.php b/web/bin/classes/ClassCommandeSlot.php index 6675134..1939e2f 100644 --- a/web/bin/classes/ClassCommandeSlot.php +++ b/web/bin/classes/ClassCommandeSlot.php @@ -1,184 +1,184 @@ -init_scheme('sitebase_base', 'commande_slot', ['fields' => ['nom', 'code']]); - $init->init_scheme('sitebase_base', 'commande_slot_ligne', ['fields' => ['nom', 'code']]); - - $this->idsecteur = $idsecteur; - $this->nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($this->idsecteur); - $this->build_shop_list(); - $this->build_slot(); - $this->feed_slot(); - } - - private function build_shop_list() { - $RS = Bin::get_shop_secteur_shift_current($this->idsecteur); - $this->list_open_shops = iterator_to_array($RS); - } - - private function build_slot() { - $i = 0; - while ($i <= NB_MAX_COMMANDE_SHOP) { - ++$i; - $this->slot_arr["R$i"] = []; - } - } - - private function feed_slot() { - $idsecteur = $this->idsecteur; - $day = date('Y-m-d'); - $APP_COMMANDE = new IdaeDB('commande'); - $RS = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['heureCommande' => 1]); - - while ($ARR = $RS->getNext()) { - $this->set_slot_commande($ARR); - } - - $this->clean($idsecteur); - } - - private function set_slot_commande($ARR) { - $ordreCommande = $ARR['ordreCommande']; - - foreach ($this->slot_arr as $index => $slot_content) { - $rangSlot = (int)str_replace('R', '', $index); - if ($ordreCommande > $rangSlot) continue; - if (sizeof($slot_content) >= $this->nb_livreur_disp) continue; - $this->slot_arr[$index][] = $ARR; - - return $index; - } - } - - private function find_idcommande_in_slot($idcommande, $haystack = []) { - - if (empty($haystack)) $haystack = $this->slot_arr; - - foreach ($haystack as $key => $value) { - $current_key = $key; - if ($idcommande == $value || (is_array($value) && $this->find_idcommande_in_slot($idcommande, $value) !== false)) { - return $current_key; - } - } - - return false; - } - - public function get_next_slot_shop($idshop) { - $ARR = CommandeQueue::shop_commande_queue_last($idshop); - - $ordreCommande = $ARR['ordreCommande'] + 1; - $slot_arr = $this->slot_arr; - foreach ($slot_arr as $index => $slot_content) { - $rangSlot = (int)str_replace('R', '', $index); - if ($ordreCommande > $rangSlot) continue; - if (sizeof($slot_content) >= $this->nb_livreur_disp) continue; - $slot_arr[$index][] = $ARR; - - return "$index"; - } - } - - public function draw_debug() { - $this->draw_slot(); - echo "
"; - $this->draw_slot_shop(); - } - - public function draw_slot() { - $out = ''; - $slot_arr = array_reverse($this->slot_arr); - foreach ($slot_arr as $rangSlot => $slot_content) { - $out .= ''; - $out .= ''; - $out .= ''; - foreach ($slot_content as $index => $ARR) { - $out .= ''; - } - $out .= ''; - $out .= ''; - } - - $out .= '
' . $rangSlot . '[' . $ARR['rangCommande'] . ' ' . $ARR['referenceCommande'] . ' ' . $ARR['codeShop'] . ']
'; - echo $out; - } - - public function draw_slot_shop() { - $out = ''; - - $DB = new IdaeDB('shop'); - $rs = $DB->find(['actifShop' => 1, 'idsecteur' => $this->idsecteur]); - - while ($arr = $rs->getNext()) { - - $idshop = (int)$arr['idshop']; - $slot = $this->get_next_slot_shop($idshop); - $shop = $arr['nomShop']; - $out .= ''; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= ''; - } - - $out .= '
$shop next $slot
'; - echo $out; - } - - public function distribute() { // 59831 - $idsecteur = $this->idsecteur; - $APP_COMMANDE = new IdaeDB('commande'); - $day = date('Y-m-d'); - - $RS = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['heureCommande' => 1]); - $nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($idsecteur); - - $DIST_SHOP = $APP_COMMANDE->distinct('idshop', ['codeCommande_statut' => ['$nin' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day]); - foreach ($DIST_SHOP as $index => $value) { - ClassRangCommande::updateRangShopCommandes($value); - } - - $tot_sect = 0; - while ($ARR = $RS->getNext()) { - ++$tot_sect; - $idcommande = (int)$ARR['idcommande']; - $slotCommande = $this->find_idcommande_in_slot($idcommande); - //$slotCommande = $this->set_slot_commande($ARR); - $APP_COMMANDE->update_id($idcommande, ['slotCommande' => $slotCommande, 'ordreSecteurCommande' => $tot_sect, 'internalSlotCommande' => ceil($tot_sect / $nb_livreur_disp)]); - } - - $this->clean($idsecteur); - } - - private function clean($idsecteur) { - - $DB_COMMANDE = new IdaeDB('commande'); - $RS = CommandeQueue::secteur_commande_queue_ended_list($idsecteur); - while ($ARR = $RS->getNext()) { - $idcommande = (int)$ARR['idcommande']; - if (!empty($ARR['heureFinCommande']) && empty($ARR['tempsTotalCommande'])) { - $timeCreationCommande = strtotime($ARR['dateCommande'] . ' ' . $ARR['heureCommande']); - $timeFinCommande = strtotime($ARR['dateCommande'] . ' ' . $ARR['heureFinCommande']); - $total = (int)ceil(($timeFinCommande - $timeCreationCommande) / 60); - $DB_COMMANDE->update_id((int)$idcommande, ['tempsTotalCommande' => $total]); - } - $slotCommande = ""; - $DB_COMMANDE->update_id((int)$idcommande, ['slotCommande' => $slotCommande, 'rangCommande' => '', 'ordreSecteurCommande' => '']); - } - } - - } +init_scheme('sitebase_base', 'commande_slot', ['fields' => ['nom', 'code']]); + $init->init_scheme('sitebase_base', 'commande_slot_ligne', ['fields' => ['nom', 'code']]); + + $this->idsecteur = $idsecteur; + $this->nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($this->idsecteur); + $this->build_shop_list(); + $this->build_slot(); + $this->feed_slot(); + } + + private function build_shop_list() { + $RS = Bin::get_shop_secteur_shift_current($this->idsecteur); + $this->list_open_shops = iterator_to_array($RS); + } + + private function build_slot() { + $i = 0; + while ($i <= NB_MAX_COMMANDE_SHOP) { + ++$i; + $this->slot_arr["R$i"] = []; + } + } + + private function feed_slot() { + $idsecteur = $this->idsecteur; + $day = date('Y-m-d'); + $APP_COMMANDE = new IdaeDB('commande'); + $RS = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['heureCommande' => 1]); + + while ($ARR = $RS->getNext()) { + $this->set_slot_commande($ARR); + } + + $this->clean($idsecteur); + } + + private function set_slot_commande($ARR) { + $ordreCommande = $ARR['ordreCommande']; + + foreach ($this->slot_arr as $index => $slot_content) { + $rangSlot = (int)str_replace('R', '', $index); + if ($ordreCommande > $rangSlot) continue; + if (sizeof($slot_content) >= $this->nb_livreur_disp) continue; + $this->slot_arr[$index][] = $ARR; + + return $index; + } + } + + private function find_idcommande_in_slot($idcommande, $haystack = []) { + + if (empty($haystack)) $haystack = $this->slot_arr; + + foreach ($haystack as $key => $value) { + $current_key = $key; + if ($idcommande == $value || (is_array($value) && $this->find_idcommande_in_slot($idcommande, $value) !== false)) { + return $current_key; + } + } + + return false; + } + + public function get_next_slot_shop($idshop) { + $ARR = CommandeQueue::shop_commande_queue_last($idshop); + + $ordreCommande = $ARR['ordreCommande'] + 1; + $slot_arr = $this->slot_arr; + foreach ($slot_arr as $index => $slot_content) { + $rangSlot = (int)str_replace('R', '', $index); + if ($ordreCommande > $rangSlot) continue; + if (sizeof($slot_content) >= $this->nb_livreur_disp) continue; + $slot_arr[$index][] = $ARR; + + return "$index"; + } + } + + public function draw_debug() { + $this->draw_slot(); + echo "
"; + $this->draw_slot_shop(); + } + + public function draw_slot() { + $out = ''; + $slot_arr = array_reverse($this->slot_arr); + foreach ($slot_arr as $rangSlot => $slot_content) { + $out .= ''; + $out .= ''; + $out .= ''; + foreach ($slot_content as $index => $ARR) { + $out .= ''; + } + $out .= ''; + $out .= ''; + } + + $out .= '
' . $rangSlot . '[' . $ARR['rangCommande'] . ' ' . $ARR['referenceCommande'] . ' ' . $ARR['codeShop'] . ']
'; + echo $out; + } + + public function draw_slot_shop() { + $out = ''; + + $DB = new IdaeDB('shop'); + $rs = $DB->find(['actifShop' => 1, 'idsecteur' => $this->idsecteur]); + + while ($arr = $rs->getNext()) { + + $idshop = (int)$arr['idshop']; + $slot = $this->get_next_slot_shop($idshop); + $shop = $arr['nomShop']; + $out .= ''; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ''; + } + + $out .= '
$shop next $slot
'; + echo $out; + } + + public function distribute() { // 59831 + $idsecteur = $this->idsecteur; + $APP_COMMANDE = new IdaeDB('commande'); + $day = date('Y-m-d'); + + $RS = $APP_COMMANDE->find(['codeCommande_statut' => ['$nin' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day])->sort(['heureCommande' => 1]); + $nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($idsecteur); + + $DIST_SHOP = $APP_COMMANDE->distinct('idshop', ['codeCommande_statut' => ['$nin' => ['END']], 'idsecteur' => (int)$idsecteur, 'dateCommande' => $day]); + foreach ($DIST_SHOP as $index => $value) { + ClassRangCommande::updateRangShopCommandes($value); + } + + $tot_sect = 0; + while ($ARR = $RS->getNext()) { + ++$tot_sect; + $idcommande = (int)$ARR['idcommande']; + $slotCommande = $this->find_idcommande_in_slot($idcommande); + //$slotCommande = $this->set_slot_commande($ARR); + $APP_COMMANDE->update_id($idcommande, ['slotCommande' => $slotCommande, 'ordreSecteurCommande' => $tot_sect, 'internalSlotCommande' => ceil($tot_sect / $nb_livreur_disp)]); + } + + $this->clean($idsecteur); + } + + private function clean($idsecteur) { + + $DB_COMMANDE = new IdaeDB('commande'); + $RS = CommandeQueue::secteur_commande_queue_ended_list($idsecteur); + while ($ARR = $RS->getNext()) { + $idcommande = (int)$ARR['idcommande']; + if (!empty($ARR['heureFinCommande']) && empty($ARR['tempsTotalCommande'])) { + $timeCreationCommande = strtotime($ARR['dateCommande'] . ' ' . $ARR['heureCommande']); + $timeFinCommande = strtotime($ARR['dateCommande'] . ' ' . $ARR['heureFinCommande']); + $total = (int)ceil(($timeFinCommande - $timeCreationCommande) / 60); + $DB_COMMANDE->update_id((int)$idcommande, ['tempsTotalCommande' => $total]); + } + $slotCommande = ""; + $DB_COMMANDE->update_id((int)$idcommande, ['slotCommande' => $slotCommande, 'rangCommande' => '', 'ordreSecteurCommande' => '']); + } + } + + } diff --git a/web/bin/classes/ClassConsoleUi.php b/web/bin/classes/ClassConsoleUi.php index 9ad091c..3d825a7 100644 --- a/web/bin/classes/ClassConsoleUi.php +++ b/web/bin/classes/ClassConsoleUi.php @@ -1,54 +1,54 @@ -findOne(["id$table"=>(int)$idcommande]); - - $html_vars = "table=$table&table_value=$idcommande"; - $html = htmlspecialchars('
'); - $html_livreur = htmlspecialchars('
'); - - AppSocket::send_cmd('act_insert_html', ['html_attributes' => ['data-table' => 'commande', - 'data-idsecteur' => $idsecteur, - 'data-type_session' => 'livreur'], - 'data' => ['red' => 'carpette'], - 'html' => $html_livreur], $room_livreur); - - AppSocket::send_cmd('act_insert_html', ['html_attributes' => ['data-table' => 'commande', - 'data-idshop' => $idshop, - 'data-idsecteur' => $idsecteur, - 'data-type_session' => 'shop'], - 'data' => ['red' => 'carpette'], - 'html' => $html], $room_shop); - $data_html_shop_2 = htmlspecialchars("
"); - - AppSocket::send_cmd('act_insert_html', ['html_attributes' => ['data-table' => $table, 'data-type_liste' => 'pool_statut_START'], - 'data' => ['some' => 'data'], - 'html' => $data_html_shop_2]); - } - - function remove_commande_from_console($idcommande) { - $table = 'commande'; - - $oith = []; - $commande_gutter_selector = "[data-console_liste] [data-table_value=$idcommande][data-table=$table]"; - $commande_shop_selector = "[data-console_liste_detail] [data-table_value=$idcommande][data-table=$table]"; - $commande_agent_selector = "[data-console_liste_detail] [data-table_value=$idcommande][data-table=$table]"; - - array_push($oith, $commande_gutter_selector); - array_push($oith, $commande_shop_selector); - array_push($oith, $commande_agent_selector); - - AppSocket::send_cmd('act_remove_selector', $oith); - - } +findOne(["id$table"=>(int)$idcommande]); + + $html_vars = "table=$table&table_value=$idcommande"; + $html = htmlspecialchars('
'); + $html_livreur = htmlspecialchars('
'); + + AppSocket::send_cmd('act_insert_html', ['html_attributes' => ['data-table' => 'commande', + 'data-idsecteur' => $idsecteur, + 'data-type_session' => 'livreur'], + 'data' => ['red' => 'carpette'], + 'html' => $html_livreur], $room_livreur); + + AppSocket::send_cmd('act_insert_html', ['html_attributes' => ['data-table' => 'commande', + 'data-idshop' => $idshop, + 'data-idsecteur' => $idsecteur, + 'data-type_session' => 'shop'], + 'data' => ['red' => 'carpette'], + 'html' => $html], $room_shop); + $data_html_shop_2 = htmlspecialchars("
"); + + AppSocket::send_cmd('act_insert_html', ['html_attributes' => ['data-table' => $table, 'data-type_liste' => 'pool_statut_START'], + 'data' => ['some' => 'data'], + 'html' => $data_html_shop_2]); + } + + function remove_commande_from_console($idcommande) { + $table = 'commande'; + + $oith = []; + $commande_gutter_selector = "[data-console_liste] [data-table_value=$idcommande][data-table=$table]"; + $commande_shop_selector = "[data-console_liste_detail] [data-table_value=$idcommande][data-table=$table]"; + $commande_agent_selector = "[data-console_liste_detail] [data-table_value=$idcommande][data-table=$table]"; + + array_push($oith, $commande_gutter_selector); + array_push($oith, $commande_shop_selector); + array_push($oith, $commande_agent_selector); + + AppSocket::send_cmd('act_remove_selector', $oith); + + } } \ No newline at end of file diff --git a/web/bin/classes/ClassDemo.php b/web/bin/classes/ClassDemo.php index a702c62..dcd6b2c 100644 --- a/web/bin/classes/ClassDemo.php +++ b/web/bin/classes/ClassDemo.php @@ -1,787 +1,787 @@ -create_affectation(); - $this->create_client(); - $this->create_client(); - $this->create_client(); - $idclient = $this->get_client(); - $this->create_cart_client(['idclient' => (int)$idclient]); - } - - function create_client() { - // mode demo => - $Action = new Action(); - - $arr_prenom = ['Lucas', - 'Enzo', - 'Nathan', - 'Mathis', - 'Louis', - 'Raphaël', - 'Gabriel', - 'Yanis', - 'Hugo', - 'Emma', - 'Léa', - 'Clara', - 'Chloé', - 'Inès', - 'Joao', - 'Jade', - 'Manon', - 'Sarah', - 'Lola', - 'Camille']; - $arr_nom = ['MARTIN', - 'BERNARD', - 'ROUX', - 'THOMAS', - 'PETIT', - 'DURAND', - 'MICHEL', - 'ROBERT', - 'RICHARD', - 'SIMON', - 'MOREAU', - 'DUBOIS', - 'BLANC', - 'LAURENT', - 'GIRARD', - 'BERTRAND', - 'GARNIER', - 'DAVID', - 'MOREL', - 'BRANC', - 'GUERIN', - 'FOURNIER', - 'ROY', - 'ROUSSEAU', - 'ANDRE', - 'GAUTIER', - 'BONNET', - 'LAMBERT']; - $arr_rue = ['quai solidor', - 'rue Jeanne Jugan', - 'bvld republique', - 'rue du chapitre', - 'rue de la montre', - 'avenue Monjtjoie', - 'rue de la mare', - 'route Riancourt', - 'bvld tregor', - 'bvld de Lambety', - 'rue miriel', - 'rue de la marne', - 'rue petite anguille', - 'avenue de la nation']; - - $prenomClient = array_random($arr_prenom)[0]; - $nomClient = array_random($arr_nom)[0]; - $nomClient_compose = array_random($arr_nom)[0]; - - $is_compose = rand(0, 4); - - $vars['prenomClient'] = $prenomClient = ucfirst($prenomClient); - $vars['nomClient'] = ucfirst(strtolower($nomClient)); - $vars['nomClient'] = $nomClient = ($is_compose == 4) ? $vars['nomClient'] : $vars['nomClient'] . '-' . strtolower($nomClient_compose); - $vars['emailClient'] = $emailClient = strtolower($nomClient) . '-' . strtolower($prenomClient) . '@yohaa.crom'; - - $vars['passwordClient'] = ucfirst($nomClient); - $vars['passwordClient_verif'] = ucfirst($nomClient); - - $vars['telephoneClient'] = "8456258475"; - $vars['mobileClient'] = "0685421352"; - - $vars['villeClient'] = 'St Malo'; - $vars['adresseClient'] = rand(1, 32) . ' ' . array_random($arr_rue)[0]; - $vars['adresse2Client'] = rand(1, 7) . ' eme étage'; - $vars['codePostalClient'] = '35400'; - - $idclient = $Action->register($vars); - - return $idclient; - - } - - function get_client() { - $APP_CLIENT = new App('client'); - $DIST_CLIENT = $APP_CLIENT->distinct_all('idclient', ['emailClient' => new MongoRegex('/.yohaa.crom/')]); - if (empty($DIST_CLIENT)) { - $this->create_client(); - - return $this->get_client(); - } - $arrand_idclient = array_random($DIST_CLIENT, 1); - - return $arrand_idclient[0]; - } - - /** - * @param array $arr_vars - * cré entre 2 et 12 panier client, puis enchaine sur la reservation livreur - */ - function create_cart_client($arr_vars = []) { - // - $BIN = new Bin(); - $APP_CLIENT = new App('client'); - $APP_SHOP = new App('shop'); - $APP_SHOP_JOURS = new App('shop_jours'); - $APP_SHOP_JOURS_SHIFT = new App('shop_jours_shift'); - $APP_PRODUIT = new App('produit'); - - // selectionner quelques clients au hasard, ou pas - if (empty($arr_vars['idclient'])) { - $DIST_CLIENT = $APP_CLIENT->distinct_all('idclient', ['emailClient' => new MongoRegex('/.yohaa.crom/')]); - $arrand_idclient = array_random($DIST_CLIENT, rand(2, 6)); - - } else { - $arrand_idclient[] = (int)$arr_vars['idclient']; - } - - // - # index du jour - $index_jour = (int)date('w'); - // - $arr_sh_j = $APP_SHOP_JOURS->distinct_all('idshop', ['actifShop_jours' => 1, 'ordreJours' => $index_jour]); - $arr_sh_j_shift = $APP_SHOP_JOURS_SHIFT->distinct_all('idshop', ['idshop' => ['$in' => $arr_sh_j]]); // $APP_SH_J_SHIFT - $arr_sh = $APP_SHOP->distinct_all('idshop', ['idshop' => ['$in' => $arr_sh_j_shift], 'actifShop' => 1]); - - if (!empty($arr_vars['idshop'])) { - $arr_sh = [(int)$arr_vars['idshop']]; - } - // $arr_sh_j_shift = [ 1 ]; - // trouver shop actif, avec produits actifs - $DIST_SHOP = $APP_PRODUIT->distinct_all('idshop', ['actifProduit' => 1, 'idshop' => ['$in' => $arr_sh]]); - - //$DIST_SHOP = array_filter($DIST_SHOP); - if (sizeof($DIST_SHOP) == 0) { - return false; - } - $arrand_idshop = array_random($DIST_SHOP, rand(2, 12)); - - // chaque client create_cart dans random shop - foreach ($arrand_idclient as $key => $idclient) { - $Cart = new Cart("client_demo_$idclient"); - - $idclient = (int)$idclient; - $idshop = array_random($arrand_idshop)[0]; - $arr_shop = $APP_SHOP->findOne(['idshop' => $idshop]); - $arr_client = $APP_CLIENT->findOne(['idclient' => $idclient]); - $DIST_PROD = array_random($APP_PRODUIT->distinct_all('idproduit', ['actifProduit' => 1, 'idshop' => $idshop]), rand(1, 4)); - $adr = $arr_client['adresseClient'] . ' ' . $arr_client['codePostalClient'] . ' ' . $arr_client['villeClient']; - // mise à jour adresse client cart - $Cart->set_shop($idshop); - $Cart->set_secteur($arr_shop['idsecteur']); - $Cart->set_adresse(['formatted_address' => $adr, - 'locality' => $arr_client['villeClient'], - 'postal_code' => $arr_client['codePostalClient'], - 'name' => $arr_client['adresseClient']]); - - foreach ($DIST_PROD as $key_prod => $idproduit) { - $Cart->add_item($idproduit); - } - if (!empty($idclient)) { - # communication - $delay = delay_minute_random(60, 240); - /*AppSocket::send_cmd('act_notify', ['options' => ['info' => 'panier ok, test commande dans ' . ceil($delay / 60000) . ' min'], - 'msg' => "demo, panier client " . $arr_client['nomClient'].' shop '.$arr_shop['nomShop']]);*/ - - $this->create_commande_client(['idclient' => $idclient]); - - # lancer commande pour ce client - /*AppSocket::run('act_run', ['route' => 'demo/create_commande_client/idclient:' . $idclient . '/demo_mode:true', - 'method' => 'POST', - 'delay' => $delay * 1000]);*/ - } - } - - } - - function create_commande_shop($arr_vars = []) { - // find client - $idclient = $this->get_client(); - $idshop = (int)$arr_vars['idshop']; - $this->create_cart_client(['idshop' => $idshop, 'idclient' => $idclient]); - } - - function create_commande_client($arr_vars = []) { - // - $APP_CLIENT = new App('client'); - $APP_SHOP = new App('shop'); - $APP_SHOP_JOURS = new App('shop_jours'); - $APP_SHOP_JOURS_SHIFT = new App('shop_jours_shift'); - $APP_PRODUIT = new App('produit'); - - // selectionner quelques clients au hasard, ou pas - if (empty($arr_vars['idclient'])) { - $DIST_CLIENT = $APP_CLIENT->distinct_all('idclient', ['emailClient' => new MongoRegex('/.yohaa.crom/')]); - $arrand_idclient = array_random($DIST_CLIENT, rand(2, 12)); - - } else { - $arrand_idclient[] = (int)$arr_vars['idclient']; - } - - $fields = ['nom', 'prenom', 'email', 'telephone', 'adresse', 'adresse2', 'codePostal', 'ville']; - foreach ($arrand_idclient as $key_rand => $idclient) { - $ARR_CLIENT = $APP_CLIENT->findOne(['idclient' => $idclient]); - $nomClient = $ARR_CLIENT['nomClient']; - $Cart = new Cart('client_demo_' . $idclient); - $arr_cart = $Cart->get_cart(); - $arr_commande = []; - $arr_client = $APP_CLIENT->findOne(['idclient' => (int)$idclient]); - foreach ($fields as $key => $field) { - $arr_commande[$field . 'Commande'] = $arr_client[$field . 'Client']; - } - - if (sizeof($arr_cart['cart_adresse']) != 0 || sizeof($arr_cart['cart_lines']) != 0) { - $arr_commande['adresseCommande'] = $arr_cart['cart_adresse']['name']; - $arr_commande['codePostalCommande'] = $arr_cart['cart_adresse']['postal_code']; - $arr_commande['villeCommande'] = $arr_cart['cart_adresse']['locality']; - } - - // création commande si shopn open - $arr_commande['demo_mode'] = 1; - $arr_commande['idclient'] = $idclient; - $arr_commande['idshop'] = $arr_cart['idshop']; - $Action = new Action(); - - $param = $Action->commande_filter_vars($arr_commande); - $pre_test = $Action->commande_test_info($param); - - if (!empty($pre_test['err'])) { - NotifySite::notify_modal('Erreur', 'alert', ['mdl_vars' => ['msg_array' => $pre_test['msg']]], session_id()); - - return false; - } - - //$this->notify(['msg' => 'tentative création commande : ' . $nomClient]); - $test = $Action->commande_set_info($arr_commande); - // $this->notify(['msg' => 'resultat tentative création commande : ' . $nomClient . ' => ' . $test]); - //// 5 min avant reserv livreur - - } - - } - - function create_secteur_shift() { - // shop jour - $APP_SECTEUR = new App('secteur'); - $APP_J = new App('jours'); - $APP_SH_J = new App('shop_jours'); - $APP_SECTEUR_JOURS_SHIFT = new App('secteur_jours_shift'); - - $RS_SECTEUR = $APP_SECTEUR->find(); - // - // - while ($ARR_SECTEUR = $RS_SECTEUR->getNext()) { - $idsecteur = (int)$ARR_SECTEUR['idsecteur']; - - $i = 0; - while ($i <= 6) { - $ARR_JOURS = $APP_J->findOne(['ordreJours' => $i]); - $idjours = (int)$ARR_JOURS['idjours']; - - $codeJours_AM = 'AM-' . $ARR_JOURS['nomJours'] . ' ' . $ARR_SECTEUR['codeSecteur']; - $codeJours_PM = 'PM-' . $ARR_JOURS['nomJours'] . ' ' . $ARR_SECTEUR['codeSecteur']; - - $heureDebut_AM = "00:01:00"; - $heureFin_AM = "15:00:00"; - - $heureDebut_PM = "15:01:00"; - $heureFin_PM = "23:59:00"; - - $TEST_JOURS_AM = $APP_SECTEUR_JOURS_SHIFT->find(['idsecteur' => $idsecteur, 'idjours' => $idjours, 'code_auto' => 'AM']); - $TEST_JOURS_PM = $APP_SECTEUR_JOURS_SHIFT->find(['idsecteur' => $idsecteur, 'idjours' => $idjours, 'code_auto' => 'PM']); - - if ($TEST_JOURS_AM->count() == 0) { - $arr_AM = ['code_auto' => 'AM', 'heureDebutSecteur_jours_shift' => $heureDebut_AM, 'heureFinSecteur_jours_shift' => $heureFin_AM]; - $APP_SECTEUR_JOURS_SHIFT->insert($arr_AM + ['idsecteur' => $idsecteur, 'idjours' => $idjours, 'codeSecteur_jours_shift' => $codeJours_AM]); - } - if ($TEST_JOURS_PM->count() == 0) { - $arr_PM = ['code_auto' => 'PM', 'heureDebutSecteur_jours_shift' => $heureDebut_PM, 'heureFinSecteur_jours_shift' => $heureFin_PM]; - $APP_SECTEUR_JOURS_SHIFT->insert($arr_PM + ['idsecteur' => $idsecteur, 'idjours' => $idjours, 'codeSecteur_jours_shift' => $codeJours_PM]); - } - $i++; - } - - } - } - - static public function create_shop_shift($table_value) { - // shop jour - $APP_SHOP = new App('shop'); - $APP_J = new App('jours'); - $APP_SH_J = new App('shop_jours'); - $APP_SH_J_SHIFT = new App('shop_jours_shift'); - - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => $table_value]); - $test_j = $APP_SH_J->find(['idshop' => $table_value]); - $test_j_s = $APP_SH_J_SHIFT->find(['idshop' => $table_value]); - $nomShop = $ARR_SHOP['nomShop']; - // - $cpount = $test_j_s->count(); - if ($test_j->count() < 7 || $test_j_s->count() == 0) { - $rs_j = $APP_J->find(); - while ($ARR_JOURS = $rs_j->getNext()) { - $idjours = (int)$ARR_JOURS['idjours']; - if ($APP_SH_J->find(['idjours' => $idjours, 'idshop' => $table_value])->count() == 0) { - $idshop_jours = $APP_SH_J->insert(['idjours' => $idjours, - 'idshop' => $table_value, - 'nomShop_jours' => $ARR_JOURS['nomJours'] . ' ' . $nomShop, - 'ordreShop_jours' => (int)$ARR_JOURS['ordreJours'], - 'actifShop_jours' => 1]); - } else { - $test = $APP_SH_J->findOne(['idjours' => $idjours, 'idshop' => $table_value]); - $idshop_jours = (int)$test['idshop_jours']; - } - $APP_SH_J->consolidate_scheme($idshop_jours); - // vardump_async([$idshop_jours,'Création shift shop auto'], true); - $test_j_s = $APP_SH_J_SHIFT->find(['idshop' => $table_value, 'idshop_jours' => $idshop_jours]); - if ($test_j_s->count() < 1) { - $nomShop_jours_shift = $ARR_JOURS['nomJours']; - $h_d = "00:01:00"; - $h_f = "14:00:00"; - $idshop_jours_shift = $APP_SH_J_SHIFT->create_update(['nomShop_jours_shift' => $nomShop_jours_shift . ' AM ' . $nomShop, - 'idshop_jours' => $idshop_jours, - 'idshop' => $table_value,], ['heureDebutShop_jours_shift' => $h_d, - 'heureFinShop_jours_shift' => $h_f, - 'actifShop_jours_shift' => 1, - 'ordreShop_jours_shift' => (int)$ARR_JOURS['ordreJours']]); - $APP_SH_J_SHIFT->consolidate_scheme($idshop_jours_shift); - $h_d = "14:01:01"; - $h_f = "23:59:59"; - $idshop_jours_shift = $APP_SH_J_SHIFT->create_update(['nomShop_jours_shift' => $nomShop_jours_shift . ' PM ' . $nomShop, - 'idshop_jours' => $idshop_jours, - 'idshop' => $table_value,], ['heureDebutShop_jours_shift' => $h_d, - 'heureFinShop_jours_shift' => $h_f, - 'actifShop_jours_shift' => 1, - 'ordreShop_jours_shift' => (int)$ARR_JOURS['ordreJours']]); - $APP_SH_J_SHIFT->consolidate_scheme($idshop_jours_shift); - } - } - } - } - - /** - * crreate affectation for 2 weeks - */ - function create_affectation_period() { - $datestart = 'now'; - // End date - $end_date = 'sunday next week + 1 week'; - - while (strtotime($datestart) <= strtotime($end_date)) { - $datestart = date("Y-m-d", strtotime("+1 day", strtotime($datestart))); - $date_time = strtotime($datestart); - $this->create_affectation($date_time); - - } - } - - function create_affectation($date_time = null) { - // mode demo => livreur affectation au même secteur que le shop - $APP_JOURS = new App('jours'); - $APP_LIVREUR = new App('livreur'); - $APP_LIV_AFFECT = new App('livreur_affectation'); - $APP_SHOP = new App('shop'); - $APP_SECTEUR_JOURS_SHIFT = new App('secteur_jours_shift'); - - $time = ($date_time) ? $date_time : time(); - $date_affectation = date('Y-m-d', $time); - $date_affectation_fr = date('d-m-Y', $time); - $date_affectation_code = date('dmy', $time); - $date_affectation_jour = date('w', $time); - $date_affectation_ordre_jour = date('l', $time); - - // les secteurs des livreurs actifs - $arr_idsecteur = $APP_LIVREUR->distinct_all('idsecteur', []); - $tabjour = [1 => "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"]; - - foreach ($arr_idsecteur as $idsecteur) { - $idsecteur = (int)$idsecteur; - - $index_jour = ((int)$date_affectation_jour - 1 < 0) ? 6 : (int)$date_affectation_jour - 1; - - $ARR_JOURS = $APP_JOURS->findOne(['ordreJours' => $index_jour]); - $idjours = $ARR_JOURS['idjours']; - - $TEST_JOURS_AM = $APP_SECTEUR_JOURS_SHIFT->findOne(['idsecteur' => $idsecteur, 'idjours' => $idjours, 'code_auto' => 'AM']); - $TEST_JOURS_PM = $APP_SECTEUR_JOURS_SHIFT->findOne(['idsecteur' => $idsecteur, 'idjours' => $idjours, 'code_auto' => 'PM']); - - $heureDebut_AM = $TEST_JOURS_AM['heureDebutSecteur_jours_shift']; - $heureFin_AM = $TEST_JOURS_AM['heureFinSecteur_jours_shift']; - - $heureDebut_PM = $TEST_JOURS_PM['heureDebutSecteur_jours_shift']; - $heureFin_PM = $TEST_JOURS_PM['heureFinSecteur_jours_shift']; - - //if ($rs_test_affect->count() == 0) { - - $arr_idliv = $APP_LIVREUR->distinct_all('idlivreur', ['actifLivreur' => 1, 'idsecteur' => $idsecteur]); - foreach ($arr_idliv as $key => $idlivreur) { - $idlivreur = (int)$idlivreur; - // verif déja crée - $VERIF_AM = ['code_auto' => 'AM', 'idlivreur' => $idlivreur, 'idsecteur' => $idsecteur, 'dateDebutLivreur_affectation' => $date_affectation]; - $VERIF_PM = ['code_auto' => 'PM', 'idlivreur' => $idlivreur, 'idsecteur' => $idsecteur, 'dateDebutLivreur_affectation' => $date_affectation]; - - $rs_test_AM = $APP_LIV_AFFECT->find($VERIF_AM); - $rs_test_PM = $APP_LIV_AFFECT->find($VERIF_PM); - $ARR_LIV = $APP_LIVREUR->findOne(['idlivreur' => $idlivreur]); - - if ($rs_test_AM->count() == 0) { - $arr_insert = ['dateDebutLivreur_affectation' => $date_affectation, - 'dateFinLivreur_affectation' => $date_affectation, - 'actifLivreur_affectation' => 1, - 'nomLivreur_affectation' => $ARR_LIV['nomLivreur'] . ' ' . $tabjour[$date_affectation_jour] . ' AM ' . $date_affectation_fr, - 'heureDebutLivreur_affectation' => $heureDebut_AM, - 'heureFinLivreur_affectation' => $heureFin_AM, - 'codeLivreur_affectation' => 'AM-' . $date_affectation_code, - 'code_auto' => 'AM', - 'idlivreur' => $idlivreur, - 'idsecteur' => $idsecteur]; - $APP_LIV_AFFECT->insert($arr_insert); - - } - if ($rs_test_PM->count() == 0) { - $arr_insert = ['dateDebutLivreur_affectation' => $date_affectation, - 'dateFinLivreur_affectation' => $date_affectation, - 'actifLivreur_affectation' => 1, - 'nomLivreur_affectation' => $ARR_LIV['nomLivreur'] . ' ' . $tabjour[$date_affectation_jour] . ' PM ' . $date_affectation_fr, - 'heureDebutLivreur_affectation' => $heureDebut_PM, - 'heureFinLivreur_affectation' => $heureFin_PM, - 'codeLivreur_affectation' => 'PM-' . $date_affectation_code, - 'code_auto' => 'PM', - 'idlivreur' => $idlivreur, - 'idsecteur' => $idsecteur]; - $APP_LIV_AFFECT->insert($arr_insert); - - // AppSocket::send_cmd('act_notify' , [ 'msg' => "demo, affectation livreur $idlivreur secteur $idsecteur " ]); - } - } - //} - } - - } - - function animate_step($array_vars = []) { - return; - $table = 'commande'; - $idcommande = (int)$array_vars['idcommande']; - $APP_COMMANDE = new App("commande"); - $APP_COMMANDE_STATUT = new App('commande_statut'); - - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - - if (empty($arr_commande['idcommande'])) return false; - if ($arr_commande['codeCommande_statut'] == 'END') return false; - - $array_vars = array_merge($array_vars, $_POST); - - $PROGRESS_RATIO = 4; - $duree_realisationCommande = DUREE_REALISATION_COMMANDE; - $time_preparation_commande = TIME_PREPARATION_COMMANDE; - $temps_livraison = TEMPS_LIVRAISON_COMMANDE; - - $timeFinPreparationCommande = $arr_commande['timeFinPreparationCommande']; - $timeLivraisonCommande = $arr_commande['timeLivraisonCommande']; - - $Bin = new Bin(); - $arr_minutes = $Bin->get_elapsed_minutes_arr_for_commande($idcommande); - - $start_time = $arr_minutes['start_time']; - $to_time = $arr_minutes['to_time']; - $max = $arr_minutes['max']; - $value_progress = $arr_minutes['value_progress']; - - $step_time_size = $max / $PROGRESS_RATIO; - - $turn = (isset($array_vars['turn'])) ? $array_vars['turn'] : 0; - $array_vars['turn'] = ++$turn; - - $progress_vars['progress_name'] = "animate_step_commande_$idcommande"; - $progress_vars['progress_value'] = $value_progress; - $progress_vars['progress_max'] = $max; - /*$progress_vars['progress_animate_to_value'] = $max; - $progress_vars['progress_animate_to_secondes'] = $max;*/ - - // $progress_vars['progress_text'] = $to_time; - // $progress_vars['progress_message'] = 'progress_message progress_message progress_message'; - - $act_vars = ['route' => 'demo/animate_step/idcommande:' . $idcommande, - 'method' => 'POST', - 'vars' => $array_vars]; - if ($turn != 0) { - $act_vars['delay_name'] = "delay_animate_step_$idcommande"; - $act_vars['delay'] = $step_time_size * 1000; - } - - // $progress_vars['progress_text'] = "$step_time_size s. value ($elapsed_value/60) max ($max/60) ".$arr_commande['codeCommande_statut']; - - if ($value_progress >= $max) { - // $progress_vars['progress_text'] = $elapsed_value . ' / ' . $max.' soit '.($step_time_size*60); - $progress_vars['progress_text'] .= ""; - } else { - $progress_vars['progress_text'] = ' '; - } - - $room_commande = "commande_$idcommande"; - - AppSocket::send_cmd('act_progress', $progress_vars); - // AppSocket::run('act_run', $act_vars); - - } - - function commande_step($array_vars = []) { - $table = 'commande'; - $idcommande = (int)$array_vars['idcommande']; - $APP_COMMANDE = new App("commande"); - $APP_COMMANDE_STATUT = new App('commande_statut'); - - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - - if (empty($_POST['mode'])) return false; - if (empty($arr_commande['idcommande'])) return false; - - $_msg = date('H:i') . ' ' . $arr_commande['codeCommande'] . ' ' . $arr_commande['nomLivreur'] . ' ' . $arr_commande['nomLivreur']; - - $idshop = (int)$arr_commande['idshop']; - $idlivreur = (int)$arr_commande['idlivreur']; - $idsecteur = (int)$arr_commande['idsecteur']; - - switch ($_POST['mode']): - case 'set_ready_shop': - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); - $IdaeAction = new IdaeAction($table); - $IdaeAction->app_update($idcommande, ['idcommande_statut' => (int)$arr_commande_statut['idcommande_statut'], - 'ordreCommande_statut' => $arr_commande_statut['ordreCommande_statut'], - 'nomCommande_statut' => $arr_commande_statut['nomCommande_statut'], - 'codeCommande_statut' => $arr_commande_statut['codeCommande_statut']]); - break; - case 'set_livreur_start': - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); - if ($arr_commande_statut['codeCommande_statut'] != 'PREFIN') { - AppSocket::run('act_run', ['route' => 'demo/commande_step/idcommande:' . $idcommande, - 'method' => 'POST', - 'vars' => ['mode' => 'set_livreur_start'], - 'delay' => 10000]); - - return false; - } - // test disponibilité shop PREFIN - // $arr_commande_statut = $APP_COMMANDE_STATUT->distinct_all('idcommande_statut',['codeCommande_statut' => ['$in'=>[ 'RUN' , 'PREFIN' ]]]); - - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'LIVENCOU']); - $IdaeAction = new IdaeAction($table); - $IdaeAction->app_update($idcommande, ['idcommande_statut' => (int)$arr_commande_statut['idcommande_statut'], - 'ordreCommande_statut' => $arr_commande_statut['ordreCommande_statut'], - 'nomCommande_statut' => $arr_commande_statut['nomCommande_statut'], - 'codeCommande_statut' => $arr_commande_statut['codeCommande_statut']]); - $arr_commande['idcommande']; - $delay_secondes = (TEMPS_LIVRAISON_COMMANDE * 60); //$arr_commande['timeLivraisonCommande'] - time(); - $delay_secondes = ($delay_secondes < 0) ? 0 : $delay_secondes; - - AppSocket::run('act_run', ['route' => 'demo/commande_step/idcommande:' . $arr_commande['idcommande'], - 'method' => 'POST', - 'vars' => ['mode' => 'set_commande_end'], - 'delay' => $delay_secondes * 1000]);// - break; - case 'set_commande_end': - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); - $IdaeAction = new IdaeAction($table); - $timeCreationCommande = strtotime($arr_commande['dateCommande'] . ' ' . $arr_commande['heureCommande']); - $IdaeAction->app_update($idcommande, ['idcommande_statut' => (int)$arr_commande_statut['idcommande_statut'], - 'ordreCommande_statut' => $arr_commande_statut['ordreCommande_statut'], - 'nomCommande_statut' => $arr_commande_statut['nomCommande_statut'], - 'heureFinCommande' => date('H:i:00'), - 'tempsTotalCommande' => ceil((time() - $timeCreationCommande) / 60), - 'codeCommande_statut' => $arr_commande_statut['codeCommande_statut']]); - break; - endswitch; - // - $Notify = new Notify(); - $Notify->notify_count_statut($table, (int)$idcommande); - if (!empty($idlivreur)) $Notify->notify_commande_livreur($idlivreur); - if (!empty($idsecteur)) $Notify->notify_livreur_affect($idsecteur); - if (!empty($idsecteur)) $Notify->notify_commande_secteur($idsecteur); - if (!empty($idshop)) $Notify->notify_commande_shop($idshop); - - $this->log($_POST['mode'] . ' idcommande : ' . $idcommande); - - /*AppSocket::send_cmd('act_notify', ['options' => ['sticky' => 1, 'info' => $_msg.' '.$delay_secondes.' secondes '], - 'msg' => $_POST['mode'] . ' idcommande : ' . $idcommande]);*/ - } - - function commande_step_statut($array_vars = []) { - - $table = 'commande'; - $idcommande = (int)$array_vars['idcommande']; - $APP_COMMANDE = new App("commande"); - $APP_COMMANDE_STATUT = new App('commande_statut'); - - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - - if (empty($arr_commande['idcommande'])) return false; - /*AppSocket::send_cmd('act_notify' , [ 'options' => ['sticky'=>1, 'info' => date('H:i:s').' STATUT demo '.$arr_commande['nomCommande'] ] , - 'msg' => date('H:i:s'). " $idcommande commande_step_statut, livraison auto" ]);*/ - // statut - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['idcommande_statut' => (int)$arr_commande['idcommande_statut']]); - $arr_commande_statut_livencours = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'LIVENCOU']); - $rs_commande_statut_next = $APP_COMMANDE_STATUT->find(['ordreCommande_statut' => ['$gt' => (int)$arr_commande_statut['ordreCommande_statut']]])->sort(['ordreCommande_statut' => 1]); - - if ($rs_commande_statut_next->count() != 0 && !empty($arr_commande['idcommande'])) { - $arr_next = $rs_commande_statut_next->getNext(); - if (!empty($arr_next['idcommande_statut'])) { - - if ($arr_commande['codeCommande_statut'] == 'PREFIN' && empty($arr_commande['idlivreur'])) { - // si pas de livreur et commande prete, on attend deux minutes // flag urgent !! - AppSocket::run('act_run', ['route' => 'demo/commande_step_statut/idcommande:' . $idcommande, - 'method' => 'POST', - 'delay' => 120000]); - - return; - } - if ($arr_next['codeCommande_statut'] == 'RESERV' && empty($arr_commande['idlivreur'])) { - $arr_next = $rs_commande_statut_next->getNext(); - } - - $IdaeAction = new IdaeAction($table); - $IdaeAction->app_update($idcommande, ['idcommande_statut' => (int)$arr_next['idcommande_statut'], 'codeCommande_statut' => $arr_next['codeCommande_statut']]); - // $APP_COMMANDE->update([ 'idcommande' => $idcommande ] , [ 'idcommande_statut' => (int)$arr_next['idcommande_statut'] ]); - // - AppSocket::reloadModule('idae/fiche_next_statut/commande/' . $idcommande, $idcommande); - - if ($_POST['data-remove']) { - AppSocket::reloadModule($_POST['data-remove'], $idcommande); - } - // - $delay_theo = ceil($arr_commande['duree_realisationCommande'] / 4) * 60 * 1000; - $delay = 60000; // 1 min de delay - // - if ($delay != 0) { - // $this->notify(['options' => ['sticky'=>1,'info' => $arr_next['codeCommande_statut']], 'msg' => "demo
$delay / $delay_theo " . $arr_commande['codeCommande']]); - - AppSocket::run('act_run', ['route' => 'demo/commande_step_statut/idcommande:' . $idcommande, - 'method' => 'POST', - 'delay' => $delay]); - - $Notify = new Notify(); - $Notify->notify_livreur_affect($arr_commande['idsecteur']); - $Notify->notify_commande_shop($arr_commande['idshop']); - } - - } - } else { - //// 3 min avant reserv livreur - } - - } - - function notify($obj, $room = '') { - - AppSocket::send_cmd('act_notify', $obj, $room); - - } - - function log($obj, $room = '') { - // AppSocket::send_cmd('act_notify', ['options' => ['info' => $obj], 'msg' => 'log'],$room); - } - - function commande_pool_livreur_start($arr_vars = []) { - $BIN = new Bin(); - $IdaeAction = new IdaeAction('commande'); - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $DB_SECTEUR = new App('secteur'); - $RS_SECTEUR = $DB_SECTEUR->find(); - while ($ARR_SECTEUR = $RS_SECTEUR->getNext()) { - $idsecteur = $ARR_SECTEUR['idsecteur']; - // $RS_COMMANDE_QUEUE = CommandeQueue::sectew($idsecteur); - - } - - } - function commande_pool($arr_vars = []) { - - $BIN = new Bin(); - $IdaeAction = new IdaeAction('commande'); - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_STATUT = new App('commande_statut'); - $DB_SECTEUR = new App('secteur'); - - $arr_commande_statut_reserv = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'RESERV']); - $update_fields = ['idcommande_statut' => (int)$arr_commande_statut_reserv['idcommande_statut'], 'codeCommande_statut' => $arr_commande_statut_reserv['codeCommande_statut']]; - - $RS_SECTEUR = $DB_SECTEUR->find(); - while ($ARR_SECTEUR = $RS_SECTEUR->getNext()) { - $idsecteur = $ARR_SECTEUR['idsecteur']; - $RS_COMMANDE_QUEUE = CommandeQueue::secteur_commande_queue_list($idsecteur); - while ($ARR_COMMANDE_QUEUE = $RS_COMMANDE_QUEUE->getNext()) { - $idcommande = (int)$ARR_COMMANDE_QUEUE['idcommande']; - $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - $RS_LIVREUR_FREE = CommandeQueue::secteur_has_livreur_free_list($idsecteur); - while ($ARR_LIVREUR = $RS_LIVREUR_FREE->getNext()) { - $idlivreur = (int)$ARR_LIVREUR['idlivreur']; - ob_start(); - $test = $BIN->test_delivery_reserv(['idcommande' => $idcommande, 'idlivreur' => $idlivreur]); - ob_end_clean(); - if ($test !== false && $test['err'] == 0) { - $IdaeAction->app_update($idcommande, $update_fields + ['idlivreur' => $idlivreur]); - - $delay_secondes = $arr_commande['timeFinPreparationCommande'] - time(); - $delay_secondes = ($delay_secondes < 0) ? 0 : $delay_secondes; - - AppSocket::run('act_run', ['route' => 'demo/commande_step/idcommande:' . $idcommande, - 'method' => 'POST', - 'vars' => ['mode' => 'set_livreur_start'], - 'delay' => $delay_secondes * 1000]); // $delay_secondes * 1000 - - } - } - } - } - - return; - - } - - function dump($vars_received) { - - AppSocket::send_cmd('act_notify', ['msg' => "demo, dump " . json_encode($vars_received, JSON_PRETTY_PRINT)]); - } - - function do_action($params = ['action', 'value']) { - // recevoir $params[value] /idclient:122/745/array_values:125:457:485:475 - $values_params = []; - $values = explode('/', $params['value']); - foreach ($values as $key_values => $value_node) { - if (strpos($value_node, ':') === false) { - $values_params[$key_values] = $value_node; - continue; - } - $tmp_node = explode(':', $value_node); - if (sizeof($tmp_node) == 2) { - $values_params[$tmp_node[0]] = $tmp_node[1]; - } elseif (sizeof($tmp_node) == 1) { - $values_params[] = $tmp_node[0]; - } else { - $node_key = $tmp_node[0]; - unset($tmp_node[0]); - $values_params[$node_key] = array_values($tmp_node); - } - } - // - $this->$params['action']($values_params); - } +create_affectation(); + $this->create_client(); + $this->create_client(); + $this->create_client(); + $idclient = $this->get_client(); + $this->create_cart_client(['idclient' => (int)$idclient]); + } + + function create_client() { + // mode demo => + $Action = new Action(); + + $arr_prenom = ['Lucas', + 'Enzo', + 'Nathan', + 'Mathis', + 'Louis', + 'Raphaël', + 'Gabriel', + 'Yanis', + 'Hugo', + 'Emma', + 'Léa', + 'Clara', + 'Chloé', + 'Inès', + 'Joao', + 'Jade', + 'Manon', + 'Sarah', + 'Lola', + 'Camille']; + $arr_nom = ['MARTIN', + 'BERNARD', + 'ROUX', + 'THOMAS', + 'PETIT', + 'DURAND', + 'MICHEL', + 'ROBERT', + 'RICHARD', + 'SIMON', + 'MOREAU', + 'DUBOIS', + 'BLANC', + 'LAURENT', + 'GIRARD', + 'BERTRAND', + 'GARNIER', + 'DAVID', + 'MOREL', + 'BRANC', + 'GUERIN', + 'FOURNIER', + 'ROY', + 'ROUSSEAU', + 'ANDRE', + 'GAUTIER', + 'BONNET', + 'LAMBERT']; + $arr_rue = ['quai solidor', + 'rue Jeanne Jugan', + 'bvld republique', + 'rue du chapitre', + 'rue de la montre', + 'avenue Monjtjoie', + 'rue de la mare', + 'route Riancourt', + 'bvld tregor', + 'bvld de Lambety', + 'rue miriel', + 'rue de la marne', + 'rue petite anguille', + 'avenue de la nation']; + + $prenomClient = array_random($arr_prenom)[0]; + $nomClient = array_random($arr_nom)[0]; + $nomClient_compose = array_random($arr_nom)[0]; + + $is_compose = rand(0, 4); + + $vars['prenomClient'] = $prenomClient = ucfirst($prenomClient); + $vars['nomClient'] = ucfirst(strtolower($nomClient)); + $vars['nomClient'] = $nomClient = ($is_compose == 4) ? $vars['nomClient'] : $vars['nomClient'] . '-' . strtolower($nomClient_compose); + $vars['emailClient'] = $emailClient = strtolower($nomClient) . '-' . strtolower($prenomClient) . '@yohaa.crom'; + + $vars['passwordClient'] = ucfirst($nomClient); + $vars['passwordClient_verif'] = ucfirst($nomClient); + + $vars['telephoneClient'] = "8456258475"; + $vars['mobileClient'] = "0685421352"; + + $vars['villeClient'] = 'St Malo'; + $vars['adresseClient'] = rand(1, 32) . ' ' . array_random($arr_rue)[0]; + $vars['adresse2Client'] = rand(1, 7) . ' eme étage'; + $vars['codePostalClient'] = '35400'; + + $idclient = $Action->register($vars); + + return $idclient; + + } + + function get_client() { + $APP_CLIENT = new App('client'); + $DIST_CLIENT = $APP_CLIENT->distinct_all('idclient', ['emailClient' => new MongoRegex('/.yohaa.crom/')]); + if (empty($DIST_CLIENT)) { + $this->create_client(); + + return $this->get_client(); + } + $arrand_idclient = array_random($DIST_CLIENT, 1); + + return $arrand_idclient[0]; + } + + /** + * @param array $arr_vars + * cré entre 2 et 12 panier client, puis enchaine sur la reservation livreur + */ + function create_cart_client($arr_vars = []) { + // + $BIN = new Bin(); + $APP_CLIENT = new App('client'); + $APP_SHOP = new App('shop'); + $APP_SHOP_JOURS = new App('shop_jours'); + $APP_SHOP_JOURS_SHIFT = new App('shop_jours_shift'); + $APP_PRODUIT = new App('produit'); + + // selectionner quelques clients au hasard, ou pas + if (empty($arr_vars['idclient'])) { + $DIST_CLIENT = $APP_CLIENT->distinct_all('idclient', ['emailClient' => new MongoRegex('/.yohaa.crom/')]); + $arrand_idclient = array_random($DIST_CLIENT, rand(2, 6)); + + } else { + $arrand_idclient[] = (int)$arr_vars['idclient']; + } + + // + # index du jour + $index_jour = (int)date('w'); + // + $arr_sh_j = $APP_SHOP_JOURS->distinct_all('idshop', ['actifShop_jours' => 1, 'ordreJours' => $index_jour]); + $arr_sh_j_shift = $APP_SHOP_JOURS_SHIFT->distinct_all('idshop', ['idshop' => ['$in' => $arr_sh_j]]); // $APP_SH_J_SHIFT + $arr_sh = $APP_SHOP->distinct_all('idshop', ['idshop' => ['$in' => $arr_sh_j_shift], 'actifShop' => 1]); + + if (!empty($arr_vars['idshop'])) { + $arr_sh = [(int)$arr_vars['idshop']]; + } + // $arr_sh_j_shift = [ 1 ]; + // trouver shop actif, avec produits actifs + $DIST_SHOP = $APP_PRODUIT->distinct_all('idshop', ['actifProduit' => 1, 'idshop' => ['$in' => $arr_sh]]); + + //$DIST_SHOP = array_filter($DIST_SHOP); + if (sizeof($DIST_SHOP) == 0) { + return false; + } + $arrand_idshop = array_random($DIST_SHOP, rand(2, 12)); + + // chaque client create_cart dans random shop + foreach ($arrand_idclient as $key => $idclient) { + $Cart = new Cart("client_demo_$idclient"); + + $idclient = (int)$idclient; + $idshop = array_random($arrand_idshop)[0]; + $arr_shop = $APP_SHOP->findOne(['idshop' => $idshop]); + $arr_client = $APP_CLIENT->findOne(['idclient' => $idclient]); + $DIST_PROD = array_random($APP_PRODUIT->distinct_all('idproduit', ['actifProduit' => 1, 'idshop' => $idshop]), rand(1, 4)); + $adr = $arr_client['adresseClient'] . ' ' . $arr_client['codePostalClient'] . ' ' . $arr_client['villeClient']; + // mise à jour adresse client cart + $Cart->set_shop($idshop); + $Cart->set_secteur($arr_shop['idsecteur']); + $Cart->set_adresse(['formatted_address' => $adr, + 'locality' => $arr_client['villeClient'], + 'postal_code' => $arr_client['codePostalClient'], + 'name' => $arr_client['adresseClient']]); + + foreach ($DIST_PROD as $key_prod => $idproduit) { + $Cart->add_item($idproduit); + } + if (!empty($idclient)) { + # communication + $delay = delay_minute_random(60, 240); + /*AppSocket::send_cmd('act_notify', ['options' => ['info' => 'panier ok, test commande dans ' . ceil($delay / 60000) . ' min'], + 'msg' => "demo, panier client " . $arr_client['nomClient'].' shop '.$arr_shop['nomShop']]);*/ + + $this->create_commande_client(['idclient' => $idclient]); + + # lancer commande pour ce client + /*AppSocket::run('act_run', ['route' => 'demo/create_commande_client/idclient:' . $idclient . '/demo_mode:true', + 'method' => 'POST', + 'delay' => $delay * 1000]);*/ + } + } + + } + + function create_commande_shop($arr_vars = []) { + // find client + $idclient = $this->get_client(); + $idshop = (int)$arr_vars['idshop']; + $this->create_cart_client(['idshop' => $idshop, 'idclient' => $idclient]); + } + + function create_commande_client($arr_vars = []) { + // + $APP_CLIENT = new App('client'); + $APP_SHOP = new App('shop'); + $APP_SHOP_JOURS = new App('shop_jours'); + $APP_SHOP_JOURS_SHIFT = new App('shop_jours_shift'); + $APP_PRODUIT = new App('produit'); + + // selectionner quelques clients au hasard, ou pas + if (empty($arr_vars['idclient'])) { + $DIST_CLIENT = $APP_CLIENT->distinct_all('idclient', ['emailClient' => new MongoRegex('/.yohaa.crom/')]); + $arrand_idclient = array_random($DIST_CLIENT, rand(2, 12)); + + } else { + $arrand_idclient[] = (int)$arr_vars['idclient']; + } + + $fields = ['nom', 'prenom', 'email', 'telephone', 'adresse', 'adresse2', 'codePostal', 'ville']; + foreach ($arrand_idclient as $key_rand => $idclient) { + $ARR_CLIENT = $APP_CLIENT->findOne(['idclient' => $idclient]); + $nomClient = $ARR_CLIENT['nomClient']; + $Cart = new Cart('client_demo_' . $idclient); + $arr_cart = $Cart->get_cart(); + $arr_commande = []; + $arr_client = $APP_CLIENT->findOne(['idclient' => (int)$idclient]); + foreach ($fields as $key => $field) { + $arr_commande[$field . 'Commande'] = $arr_client[$field . 'Client']; + } + + if (sizeof($arr_cart['cart_adresse']) != 0 || sizeof($arr_cart['cart_lines']) != 0) { + $arr_commande['adresseCommande'] = $arr_cart['cart_adresse']['name']; + $arr_commande['codePostalCommande'] = $arr_cart['cart_adresse']['postal_code']; + $arr_commande['villeCommande'] = $arr_cart['cart_adresse']['locality']; + } + + // création commande si shopn open + $arr_commande['demo_mode'] = 1; + $arr_commande['idclient'] = $idclient; + $arr_commande['idshop'] = $arr_cart['idshop']; + $Action = new Action(); + + $param = $Action->commande_filter_vars($arr_commande); + $pre_test = $Action->commande_test_info($param); + + if (!empty($pre_test['err'])) { + NotifySite::notify_modal('Erreur', 'alert', ['mdl_vars' => ['msg_array' => $pre_test['msg']]], session_id()); + + return false; + } + + //$this->notify(['msg' => 'tentative création commande : ' . $nomClient]); + $test = $Action->commande_set_info($arr_commande); + // $this->notify(['msg' => 'resultat tentative création commande : ' . $nomClient . ' => ' . $test]); + //// 5 min avant reserv livreur + + } + + } + + function create_secteur_shift() { + // shop jour + $APP_SECTEUR = new App('secteur'); + $APP_J = new App('jours'); + $APP_SH_J = new App('shop_jours'); + $APP_SECTEUR_JOURS_SHIFT = new App('secteur_jours_shift'); + + $RS_SECTEUR = $APP_SECTEUR->find(); + // + // + while ($ARR_SECTEUR = $RS_SECTEUR->getNext()) { + $idsecteur = (int)$ARR_SECTEUR['idsecteur']; + + $i = 0; + while ($i <= 6) { + $ARR_JOURS = $APP_J->findOne(['ordreJours' => $i]); + $idjours = (int)$ARR_JOURS['idjours']; + + $codeJours_AM = 'AM-' . $ARR_JOURS['nomJours'] . ' ' . $ARR_SECTEUR['codeSecteur']; + $codeJours_PM = 'PM-' . $ARR_JOURS['nomJours'] . ' ' . $ARR_SECTEUR['codeSecteur']; + + $heureDebut_AM = "00:01:00"; + $heureFin_AM = "15:00:00"; + + $heureDebut_PM = "15:01:00"; + $heureFin_PM = "23:59:00"; + + $TEST_JOURS_AM = $APP_SECTEUR_JOURS_SHIFT->find(['idsecteur' => $idsecteur, 'idjours' => $idjours, 'code_auto' => 'AM']); + $TEST_JOURS_PM = $APP_SECTEUR_JOURS_SHIFT->find(['idsecteur' => $idsecteur, 'idjours' => $idjours, 'code_auto' => 'PM']); + + if ($TEST_JOURS_AM->count() == 0) { + $arr_AM = ['code_auto' => 'AM', 'heureDebutSecteur_jours_shift' => $heureDebut_AM, 'heureFinSecteur_jours_shift' => $heureFin_AM]; + $APP_SECTEUR_JOURS_SHIFT->insert($arr_AM + ['idsecteur' => $idsecteur, 'idjours' => $idjours, 'codeSecteur_jours_shift' => $codeJours_AM]); + } + if ($TEST_JOURS_PM->count() == 0) { + $arr_PM = ['code_auto' => 'PM', 'heureDebutSecteur_jours_shift' => $heureDebut_PM, 'heureFinSecteur_jours_shift' => $heureFin_PM]; + $APP_SECTEUR_JOURS_SHIFT->insert($arr_PM + ['idsecteur' => $idsecteur, 'idjours' => $idjours, 'codeSecteur_jours_shift' => $codeJours_PM]); + } + $i++; + } + + } + } + + static public function create_shop_shift($table_value) { + // shop jour + $APP_SHOP = new App('shop'); + $APP_J = new App('jours'); + $APP_SH_J = new App('shop_jours'); + $APP_SH_J_SHIFT = new App('shop_jours_shift'); + + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => $table_value]); + $test_j = $APP_SH_J->find(['idshop' => $table_value]); + $test_j_s = $APP_SH_J_SHIFT->find(['idshop' => $table_value]); + $nomShop = $ARR_SHOP['nomShop']; + // + $cpount = $test_j_s->count(); + if ($test_j->count() < 7 || $test_j_s->count() == 0) { + $rs_j = $APP_J->find(); + while ($ARR_JOURS = $rs_j->getNext()) { + $idjours = (int)$ARR_JOURS['idjours']; + if ($APP_SH_J->find(['idjours' => $idjours, 'idshop' => $table_value])->count() == 0) { + $idshop_jours = $APP_SH_J->insert(['idjours' => $idjours, + 'idshop' => $table_value, + 'nomShop_jours' => $ARR_JOURS['nomJours'] . ' ' . $nomShop, + 'ordreShop_jours' => (int)$ARR_JOURS['ordreJours'], + 'actifShop_jours' => 1]); + } else { + $test = $APP_SH_J->findOne(['idjours' => $idjours, 'idshop' => $table_value]); + $idshop_jours = (int)$test['idshop_jours']; + } + $APP_SH_J->consolidate_scheme($idshop_jours); + // vardump_async([$idshop_jours,'Création shift shop auto'], true); + $test_j_s = $APP_SH_J_SHIFT->find(['idshop' => $table_value, 'idshop_jours' => $idshop_jours]); + if ($test_j_s->count() < 1) { + $nomShop_jours_shift = $ARR_JOURS['nomJours']; + $h_d = "00:01:00"; + $h_f = "14:00:00"; + $idshop_jours_shift = $APP_SH_J_SHIFT->create_update(['nomShop_jours_shift' => $nomShop_jours_shift . ' AM ' . $nomShop, + 'idshop_jours' => $idshop_jours, + 'idshop' => $table_value,], ['heureDebutShop_jours_shift' => $h_d, + 'heureFinShop_jours_shift' => $h_f, + 'actifShop_jours_shift' => 1, + 'ordreShop_jours_shift' => (int)$ARR_JOURS['ordreJours']]); + $APP_SH_J_SHIFT->consolidate_scheme($idshop_jours_shift); + $h_d = "14:01:01"; + $h_f = "23:59:59"; + $idshop_jours_shift = $APP_SH_J_SHIFT->create_update(['nomShop_jours_shift' => $nomShop_jours_shift . ' PM ' . $nomShop, + 'idshop_jours' => $idshop_jours, + 'idshop' => $table_value,], ['heureDebutShop_jours_shift' => $h_d, + 'heureFinShop_jours_shift' => $h_f, + 'actifShop_jours_shift' => 1, + 'ordreShop_jours_shift' => (int)$ARR_JOURS['ordreJours']]); + $APP_SH_J_SHIFT->consolidate_scheme($idshop_jours_shift); + } + } + } + } + + /** + * crreate affectation for 2 weeks + */ + function create_affectation_period() { + $datestart = 'now'; + // End date + $end_date = 'sunday next week + 1 week'; + + while (strtotime($datestart) <= strtotime($end_date)) { + $datestart = date("Y-m-d", strtotime("+1 day", strtotime($datestart))); + $date_time = strtotime($datestart); + $this->create_affectation($date_time); + + } + } + + function create_affectation($date_time = null) { + // mode demo => livreur affectation au même secteur que le shop + $APP_JOURS = new App('jours'); + $APP_LIVREUR = new App('livreur'); + $APP_LIV_AFFECT = new App('livreur_affectation'); + $APP_SHOP = new App('shop'); + $APP_SECTEUR_JOURS_SHIFT = new App('secteur_jours_shift'); + + $time = ($date_time) ? $date_time : time(); + $date_affectation = date('Y-m-d', $time); + $date_affectation_fr = date('d-m-Y', $time); + $date_affectation_code = date('dmy', $time); + $date_affectation_jour = date('w', $time); + $date_affectation_ordre_jour = date('l', $time); + + // les secteurs des livreurs actifs + $arr_idsecteur = $APP_LIVREUR->distinct_all('idsecteur', []); + $tabjour = [1 => "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"]; + + foreach ($arr_idsecteur as $idsecteur) { + $idsecteur = (int)$idsecteur; + + $index_jour = ((int)$date_affectation_jour - 1 < 0) ? 6 : (int)$date_affectation_jour - 1; + + $ARR_JOURS = $APP_JOURS->findOne(['ordreJours' => $index_jour]); + $idjours = $ARR_JOURS['idjours']; + + $TEST_JOURS_AM = $APP_SECTEUR_JOURS_SHIFT->findOne(['idsecteur' => $idsecteur, 'idjours' => $idjours, 'code_auto' => 'AM']); + $TEST_JOURS_PM = $APP_SECTEUR_JOURS_SHIFT->findOne(['idsecteur' => $idsecteur, 'idjours' => $idjours, 'code_auto' => 'PM']); + + $heureDebut_AM = $TEST_JOURS_AM['heureDebutSecteur_jours_shift']; + $heureFin_AM = $TEST_JOURS_AM['heureFinSecteur_jours_shift']; + + $heureDebut_PM = $TEST_JOURS_PM['heureDebutSecteur_jours_shift']; + $heureFin_PM = $TEST_JOURS_PM['heureFinSecteur_jours_shift']; + + //if ($rs_test_affect->count() == 0) { + + $arr_idliv = $APP_LIVREUR->distinct_all('idlivreur', ['actifLivreur' => 1, 'idsecteur' => $idsecteur]); + foreach ($arr_idliv as $key => $idlivreur) { + $idlivreur = (int)$idlivreur; + // verif déja crée + $VERIF_AM = ['code_auto' => 'AM', 'idlivreur' => $idlivreur, 'idsecteur' => $idsecteur, 'dateDebutLivreur_affectation' => $date_affectation]; + $VERIF_PM = ['code_auto' => 'PM', 'idlivreur' => $idlivreur, 'idsecteur' => $idsecteur, 'dateDebutLivreur_affectation' => $date_affectation]; + + $rs_test_AM = $APP_LIV_AFFECT->find($VERIF_AM); + $rs_test_PM = $APP_LIV_AFFECT->find($VERIF_PM); + $ARR_LIV = $APP_LIVREUR->findOne(['idlivreur' => $idlivreur]); + + if ($rs_test_AM->count() == 0) { + $arr_insert = ['dateDebutLivreur_affectation' => $date_affectation, + 'dateFinLivreur_affectation' => $date_affectation, + 'actifLivreur_affectation' => 1, + 'nomLivreur_affectation' => $ARR_LIV['nomLivreur'] . ' ' . $tabjour[$date_affectation_jour] . ' AM ' . $date_affectation_fr, + 'heureDebutLivreur_affectation' => $heureDebut_AM, + 'heureFinLivreur_affectation' => $heureFin_AM, + 'codeLivreur_affectation' => 'AM-' . $date_affectation_code, + 'code_auto' => 'AM', + 'idlivreur' => $idlivreur, + 'idsecteur' => $idsecteur]; + $APP_LIV_AFFECT->insert($arr_insert); + + } + if ($rs_test_PM->count() == 0) { + $arr_insert = ['dateDebutLivreur_affectation' => $date_affectation, + 'dateFinLivreur_affectation' => $date_affectation, + 'actifLivreur_affectation' => 1, + 'nomLivreur_affectation' => $ARR_LIV['nomLivreur'] . ' ' . $tabjour[$date_affectation_jour] . ' PM ' . $date_affectation_fr, + 'heureDebutLivreur_affectation' => $heureDebut_PM, + 'heureFinLivreur_affectation' => $heureFin_PM, + 'codeLivreur_affectation' => 'PM-' . $date_affectation_code, + 'code_auto' => 'PM', + 'idlivreur' => $idlivreur, + 'idsecteur' => $idsecteur]; + $APP_LIV_AFFECT->insert($arr_insert); + + // AppSocket::send_cmd('act_notify' , [ 'msg' => "demo, affectation livreur $idlivreur secteur $idsecteur " ]); + } + } + //} + } + + } + + function animate_step($array_vars = []) { + return; + $table = 'commande'; + $idcommande = (int)$array_vars['idcommande']; + $APP_COMMANDE = new App("commande"); + $APP_COMMANDE_STATUT = new App('commande_statut'); + + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + + if (empty($arr_commande['idcommande'])) return false; + if ($arr_commande['codeCommande_statut'] == 'END') return false; + + $array_vars = array_merge($array_vars, $_POST); + + $PROGRESS_RATIO = 4; + $duree_realisationCommande = DUREE_REALISATION_COMMANDE; + $time_preparation_commande = TIME_PREPARATION_COMMANDE; + $temps_livraison = TEMPS_LIVRAISON_COMMANDE; + + $timeFinPreparationCommande = $arr_commande['timeFinPreparationCommande']; + $timeLivraisonCommande = $arr_commande['timeLivraisonCommande']; + + $Bin = new Bin(); + $arr_minutes = $Bin->get_elapsed_minutes_arr_for_commande($idcommande); + + $start_time = $arr_minutes['start_time']; + $to_time = $arr_minutes['to_time']; + $max = $arr_minutes['max']; + $value_progress = $arr_minutes['value_progress']; + + $step_time_size = $max / $PROGRESS_RATIO; + + $turn = (isset($array_vars['turn'])) ? $array_vars['turn'] : 0; + $array_vars['turn'] = ++$turn; + + $progress_vars['progress_name'] = "animate_step_commande_$idcommande"; + $progress_vars['progress_value'] = $value_progress; + $progress_vars['progress_max'] = $max; + /*$progress_vars['progress_animate_to_value'] = $max; + $progress_vars['progress_animate_to_secondes'] = $max;*/ + + // $progress_vars['progress_text'] = $to_time; + // $progress_vars['progress_message'] = 'progress_message progress_message progress_message'; + + $act_vars = ['route' => 'demo/animate_step/idcommande:' . $idcommande, + 'method' => 'POST', + 'vars' => $array_vars]; + if ($turn != 0) { + $act_vars['delay_name'] = "delay_animate_step_$idcommande"; + $act_vars['delay'] = $step_time_size * 1000; + } + + // $progress_vars['progress_text'] = "$step_time_size s. value ($elapsed_value/60) max ($max/60) ".$arr_commande['codeCommande_statut']; + + if ($value_progress >= $max) { + // $progress_vars['progress_text'] = $elapsed_value . ' / ' . $max.' soit '.($step_time_size*60); + $progress_vars['progress_text'] .= ""; + } else { + $progress_vars['progress_text'] = ' '; + } + + $room_commande = "commande_$idcommande"; + + AppSocket::send_cmd('act_progress', $progress_vars); + // AppSocket::run('act_run', $act_vars); + + } + + function commande_step($array_vars = []) { + $table = 'commande'; + $idcommande = (int)$array_vars['idcommande']; + $APP_COMMANDE = new App("commande"); + $APP_COMMANDE_STATUT = new App('commande_statut'); + + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + + if (empty($_POST['mode'])) return false; + if (empty($arr_commande['idcommande'])) return false; + + $_msg = date('H:i') . ' ' . $arr_commande['codeCommande'] . ' ' . $arr_commande['nomLivreur'] . ' ' . $arr_commande['nomLivreur']; + + $idshop = (int)$arr_commande['idshop']; + $idlivreur = (int)$arr_commande['idlivreur']; + $idsecteur = (int)$arr_commande['idsecteur']; + + switch ($_POST['mode']): + case 'set_ready_shop': + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); + $IdaeAction = new IdaeAction($table); + $IdaeAction->app_update($idcommande, ['idcommande_statut' => (int)$arr_commande_statut['idcommande_statut'], + 'ordreCommande_statut' => $arr_commande_statut['ordreCommande_statut'], + 'nomCommande_statut' => $arr_commande_statut['nomCommande_statut'], + 'codeCommande_statut' => $arr_commande_statut['codeCommande_statut']]); + break; + case 'set_livreur_start': + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'PREFIN']); + if ($arr_commande_statut['codeCommande_statut'] != 'PREFIN') { + AppSocket::run('act_run', ['route' => 'demo/commande_step/idcommande:' . $idcommande, + 'method' => 'POST', + 'vars' => ['mode' => 'set_livreur_start'], + 'delay' => 10000]); + + return false; + } + // test disponibilité shop PREFIN + // $arr_commande_statut = $APP_COMMANDE_STATUT->distinct_all('idcommande_statut',['codeCommande_statut' => ['$in'=>[ 'RUN' , 'PREFIN' ]]]); + + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'LIVENCOU']); + $IdaeAction = new IdaeAction($table); + $IdaeAction->app_update($idcommande, ['idcommande_statut' => (int)$arr_commande_statut['idcommande_statut'], + 'ordreCommande_statut' => $arr_commande_statut['ordreCommande_statut'], + 'nomCommande_statut' => $arr_commande_statut['nomCommande_statut'], + 'codeCommande_statut' => $arr_commande_statut['codeCommande_statut']]); + $arr_commande['idcommande']; + $delay_secondes = (TEMPS_LIVRAISON_COMMANDE * 60); //$arr_commande['timeLivraisonCommande'] - time(); + $delay_secondes = ($delay_secondes < 0) ? 0 : $delay_secondes; + + AppSocket::run('act_run', ['route' => 'demo/commande_step/idcommande:' . $arr_commande['idcommande'], + 'method' => 'POST', + 'vars' => ['mode' => 'set_commande_end'], + 'delay' => $delay_secondes * 1000]);// + break; + case 'set_commande_end': + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); + $IdaeAction = new IdaeAction($table); + $timeCreationCommande = strtotime($arr_commande['dateCommande'] . ' ' . $arr_commande['heureCommande']); + $IdaeAction->app_update($idcommande, ['idcommande_statut' => (int)$arr_commande_statut['idcommande_statut'], + 'ordreCommande_statut' => $arr_commande_statut['ordreCommande_statut'], + 'nomCommande_statut' => $arr_commande_statut['nomCommande_statut'], + 'heureFinCommande' => date('H:i:00'), + 'tempsTotalCommande' => ceil((time() - $timeCreationCommande) / 60), + 'codeCommande_statut' => $arr_commande_statut['codeCommande_statut']]); + break; + endswitch; + // + $Notify = new Notify(); + $Notify->notify_count_statut($table, (int)$idcommande); + if (!empty($idlivreur)) $Notify->notify_commande_livreur($idlivreur); + if (!empty($idsecteur)) $Notify->notify_livreur_affect($idsecteur); + if (!empty($idsecteur)) $Notify->notify_commande_secteur($idsecteur); + if (!empty($idshop)) $Notify->notify_commande_shop($idshop); + + $this->log($_POST['mode'] . ' idcommande : ' . $idcommande); + + /*AppSocket::send_cmd('act_notify', ['options' => ['sticky' => 1, 'info' => $_msg.' '.$delay_secondes.' secondes '], + 'msg' => $_POST['mode'] . ' idcommande : ' . $idcommande]);*/ + } + + function commande_step_statut($array_vars = []) { + + $table = 'commande'; + $idcommande = (int)$array_vars['idcommande']; + $APP_COMMANDE = new App("commande"); + $APP_COMMANDE_STATUT = new App('commande_statut'); + + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + + if (empty($arr_commande['idcommande'])) return false; + /*AppSocket::send_cmd('act_notify' , [ 'options' => ['sticky'=>1, 'info' => date('H:i:s').' STATUT demo '.$arr_commande['nomCommande'] ] , + 'msg' => date('H:i:s'). " $idcommande commande_step_statut, livraison auto" ]);*/ + // statut + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['idcommande_statut' => (int)$arr_commande['idcommande_statut']]); + $arr_commande_statut_livencours = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'LIVENCOU']); + $rs_commande_statut_next = $APP_COMMANDE_STATUT->find(['ordreCommande_statut' => ['$gt' => (int)$arr_commande_statut['ordreCommande_statut']]])->sort(['ordreCommande_statut' => 1]); + + if ($rs_commande_statut_next->count() != 0 && !empty($arr_commande['idcommande'])) { + $arr_next = $rs_commande_statut_next->getNext(); + if (!empty($arr_next['idcommande_statut'])) { + + if ($arr_commande['codeCommande_statut'] == 'PREFIN' && empty($arr_commande['idlivreur'])) { + // si pas de livreur et commande prete, on attend deux minutes // flag urgent !! + AppSocket::run('act_run', ['route' => 'demo/commande_step_statut/idcommande:' . $idcommande, + 'method' => 'POST', + 'delay' => 120000]); + + return; + } + if ($arr_next['codeCommande_statut'] == 'RESERV' && empty($arr_commande['idlivreur'])) { + $arr_next = $rs_commande_statut_next->getNext(); + } + + $IdaeAction = new IdaeAction($table); + $IdaeAction->app_update($idcommande, ['idcommande_statut' => (int)$arr_next['idcommande_statut'], 'codeCommande_statut' => $arr_next['codeCommande_statut']]); + // $APP_COMMANDE->update([ 'idcommande' => $idcommande ] , [ 'idcommande_statut' => (int)$arr_next['idcommande_statut'] ]); + // + AppSocket::reloadModule('idae/fiche_next_statut/commande/' . $idcommande, $idcommande); + + if ($_POST['data-remove']) { + AppSocket::reloadModule($_POST['data-remove'], $idcommande); + } + // + $delay_theo = ceil($arr_commande['duree_realisationCommande'] / 4) * 60 * 1000; + $delay = 60000; // 1 min de delay + // + if ($delay != 0) { + // $this->notify(['options' => ['sticky'=>1,'info' => $arr_next['codeCommande_statut']], 'msg' => "demo
$delay / $delay_theo " . $arr_commande['codeCommande']]); + + AppSocket::run('act_run', ['route' => 'demo/commande_step_statut/idcommande:' . $idcommande, + 'method' => 'POST', + 'delay' => $delay]); + + $Notify = new Notify(); + $Notify->notify_livreur_affect($arr_commande['idsecteur']); + $Notify->notify_commande_shop($arr_commande['idshop']); + } + + } + } else { + //// 3 min avant reserv livreur + } + + } + + function notify($obj, $room = '') { + + AppSocket::send_cmd('act_notify', $obj, $room); + + } + + function log($obj, $room = '') { + // AppSocket::send_cmd('act_notify', ['options' => ['info' => $obj], 'msg' => 'log'],$room); + } + + function commande_pool_livreur_start($arr_vars = []) { + $BIN = new Bin(); + $IdaeAction = new IdaeAction('commande'); + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $DB_SECTEUR = new App('secteur'); + $RS_SECTEUR = $DB_SECTEUR->find(); + while ($ARR_SECTEUR = $RS_SECTEUR->getNext()) { + $idsecteur = $ARR_SECTEUR['idsecteur']; + // $RS_COMMANDE_QUEUE = CommandeQueue::sectew($idsecteur); + + } + + } + function commande_pool($arr_vars = []) { + + $BIN = new Bin(); + $IdaeAction = new IdaeAction('commande'); + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_STATUT = new App('commande_statut'); + $DB_SECTEUR = new App('secteur'); + + $arr_commande_statut_reserv = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'RESERV']); + $update_fields = ['idcommande_statut' => (int)$arr_commande_statut_reserv['idcommande_statut'], 'codeCommande_statut' => $arr_commande_statut_reserv['codeCommande_statut']]; + + $RS_SECTEUR = $DB_SECTEUR->find(); + while ($ARR_SECTEUR = $RS_SECTEUR->getNext()) { + $idsecteur = $ARR_SECTEUR['idsecteur']; + $RS_COMMANDE_QUEUE = CommandeQueue::secteur_commande_queue_list($idsecteur); + while ($ARR_COMMANDE_QUEUE = $RS_COMMANDE_QUEUE->getNext()) { + $idcommande = (int)$ARR_COMMANDE_QUEUE['idcommande']; + $arr_commande = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + $RS_LIVREUR_FREE = CommandeQueue::secteur_has_livreur_free_list($idsecteur); + while ($ARR_LIVREUR = $RS_LIVREUR_FREE->getNext()) { + $idlivreur = (int)$ARR_LIVREUR['idlivreur']; + ob_start(); + $test = $BIN->test_delivery_reserv(['idcommande' => $idcommande, 'idlivreur' => $idlivreur]); + ob_end_clean(); + if ($test !== false && $test['err'] == 0) { + $IdaeAction->app_update($idcommande, $update_fields + ['idlivreur' => $idlivreur]); + + $delay_secondes = $arr_commande['timeFinPreparationCommande'] - time(); + $delay_secondes = ($delay_secondes < 0) ? 0 : $delay_secondes; + + AppSocket::run('act_run', ['route' => 'demo/commande_step/idcommande:' . $idcommande, + 'method' => 'POST', + 'vars' => ['mode' => 'set_livreur_start'], + 'delay' => $delay_secondes * 1000]); // $delay_secondes * 1000 + + } + } + } + } + + return; + + } + + function dump($vars_received) { + + AppSocket::send_cmd('act_notify', ['msg' => "demo, dump " . json_encode($vars_received, JSON_PRETTY_PRINT)]); + } + + function do_action($params = ['action', 'value']) { + // recevoir $params[value] /idclient:122/745/array_values:125:457:485:475 + $values_params = []; + $values = explode('/', $params['value']); + foreach ($values as $key_values => $value_node) { + if (strpos($value_node, ':') === false) { + $values_params[$key_values] = $value_node; + continue; + } + $tmp_node = explode(':', $value_node); + if (sizeof($tmp_node) == 2) { + $values_params[$tmp_node[0]] = $tmp_node[1]; + } elseif (sizeof($tmp_node) == 1) { + $values_params[] = $tmp_node[0]; + } else { + $node_key = $tmp_node[0]; + unset($tmp_node[0]); + $values_params[$node_key] = array_values($tmp_node); + } + } + // + $this->$params['action']($values_params); + } } \ No newline at end of file diff --git a/web/bin/classes/ClassDispatch.php b/web/bin/classes/ClassDispatch.php index 5fe38c9..d8f397a 100644 --- a/web/bin/classes/ClassDispatch.php +++ b/web/bin/classes/ClassDispatch.php @@ -1,417 +1,417 @@ -find(); - - $Not = new Notify(); - while ($ARR_SECTEUR = $RS_SECTEUR->getNext()) { - /** - * debug - */ - $Not->notify_commande_secteur($ARR_SECTEUR['idsecteur']); - $ARR_COMMANDE_SECTEUR = $BIN->secteur_commande_free_queue($ARR_SECTEUR['idsecteur']); - - $Notify = new Notify(); - $Notify->notify_commande_secteur($ARR_SECTEUR['idsecteur']); - foreach ($ARR_COMMANDE_SECTEUR as $idkey_liv => $ARR_COMMANDE) { - $this->propose_commande($ARR_COMMANDE['idcommande']); - } - - } - } - - /** - * dispatch commands to available coursiers in secteur - * - * @param $idsecteur - */ - public function propose_commande_secteur_pool($idsecteur) { - $BIN = new Bin(); - - $ARR_COMMANDE_SECTEUR = $BIN->secteur_commande_free_queue($idsecteur); - - foreach ($ARR_COMMANDE_SECTEUR as $idkey_liv => $ARR_COMMANDE) { - $this->propose_commande($ARR_COMMANDE['idcommande']); - } - } - - /** - * remove command shown to available coursiers - * - * @param $idcommande - */ - public function remove_propose_commande($table_value) { - $table = 'commande'; - $APP_COMMANDE = new App($table); - $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$table_value]); - - $idlivreur = $ARR_COMMANDE['idlivreur']; - - // deactivate commande_proposition for all coursiers - $RS_REM = $APP_COMMANDE_PROPOSITION->find(['idcommande' => (int)$table_value]); - while ($ARR_REM = $RS_REM->getNext()) { - $APP_COMMANDE_PROPOSITION->update(['idcommande_proposition' => (int)$ARR_REM['idcommande_proposition']], ['actifCommande_proposition' => 0]); - if ($ARR_REM['idlivreur'] == $ARR_COMMANDE['idlivreur']) { - // activate commande_proposition for coursier if one - $APP_COMMANDE_PROPOSITION->update(['idcommande_proposition' => (int)$ARR_REM['idcommande_proposition']], ['livreur_take' => $idlivreur, 'acceptCommande_proposition' => 1]); - } - } - - // enlever annonce commande dans autre console livreur - $secteur_selector = "[data-type_session=livreur][data-see_less_commande][data-idlivreur=$idlivreur][data-table_value=$table_value]"; - AppSocket::send_cmd('act_remove_selector', [$secteur_selector]); - - // enlever commande dans console livreur - $secteur_selector = "[data-type_session=livreur][data-console_liste]:not([data-idlivreur=$idlivreur]) [data-table_value=$table_value][data-table=$table]"; - AppSocket::send_cmd('act_remove_selector', [$secteur_selector]); - } - - /** - * remove command shown to one coursiers - * - * @param $table_value - * @param $idlivreur - */ - public function remove_propose_commande_coursier($table_value, $idlivreur) { - $table = 'commande'; - - // enlever commande dans console livreur - $secteur_selector = "[data-type_session=livreur][data-console_liste][data-idlivreur=$idlivreur] [data-table_value=$table_value][data-table=$table]"; - AppSocket::send_cmd('act_remove_selector', [$secteur_selector]); - } - - public function create_commande_proposition($idcommande, $idlivreur) { - - $APP_COMMANDE = new IdaeDB('commande'); - $APP_COMMANDE_PROPOSITION = new IdaeDB('commande_proposition'); - - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - - if (empty($ARR_COMMANDE['idcommande'])) return false; - $idsecteur = (int)$ARR_COMMANDE['idsecteur']; - $idshop = (int)$ARR_COMMANDE['idshop']; - - $time = time(); - $arr_insert = ['idcommande' => (int)$idcommande, - 'idsecteur' => $idsecteur, - 'idshop' => $idshop, - 'idlivreur' => (int)$idlivreur, - 'actifCommande_proposition' => 1, - 'dateCommande_proposition' => date('Y-m-d', $time), - 'timeCommande_proposition' => $time, - 'heureCommande_proposition' => date('H:i:s', $time), - 'referenceCommande_proposition' => $ARR_COMMANDE['referenceCommande'], - 'heureFinPreparationCommande_proposition' => $ARR_COMMANDE['heureFinPreparationCommande'], - 'timeFinPreparationCommande_proposition' => $ARR_COMMANDE['timeFinPreparationCommande']]; - - return $APP_COMMANDE_PROPOSITION->insert($arr_insert); - } - - /** - * @param $idcommande - * - * @return bool - * @throws \MongoCursorException - */ - public function propose_commande($idcommande) { - - $APP_COMMANDE = new App('commande'); - $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); - $BIN = new Bin(); - - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - - if (empty($ARR_COMMANDE['idcommande'])) return false; - $idsecteur = (int)$ARR_COMMANDE['idsecteur']; - $idshop = (int)$ARR_COMMANDE['idshop']; - $room_shop = 'shop_' . $idshop; - $room_livreur = []; - $time = time(); - //AppSocket::send_cmd('act_notify', ['msg' => "propose commande $idcommande " . $ARR_COMMANDE['codeCommande'].' '. $ARR_COMMANDE['referenceCommande']]); - - // NE PAS PROPOSER SI SHOP COMMANDE NON PREFIN > NBLIV DISP - $shop_has_other_commande_non_prefin = CommandeQueue::shop_has_other_commande_non_prefin($idshop, $idcommande); // shop_has_other_commandefree_non_prefin_list - - if ($shop_has_other_commande_non_prefin) { - return false; - } - - $arr_livreur_free = $BIN->test_livreur_affect_free($idsecteur); - - // proposition - foreach ($arr_livreur_free as $idkey_liv => $arr_livreur) { - $idlivreur = (int)$arr_livreur['idlivreur']; - // proposal deja actif ? - $TEST_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->find(['idlivreur' => $idlivreur, - 'idsecteur' => $idsecteur, - 'livreur_take' => ['$ne' => $idlivreur], - 'dateCommande_proposition' => date('Y-m-d'), - 'endedCommande_proposition' => ['$ne' => 1], - 'timeFinPreparationCommande_proposition' => ['$lt' => $ARR_COMMANDE['timeFinPreparationCommande']], - 'actifCommande_proposition' => 1])->sort(['timeFinPreparationCommande_proposition' => 1]); - if ($TEST_COMMANDE_PROPOSITION->count() != 0) { - // AppSocket::send_cmd('act_notify', ['msg' => "NOT propose commande $idcommande ".$arr_livreur['nomLivreur'].$TEST_COMMANDE_PROPOSITION->count() ]); - - continue; - } - - $ARR_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->findOne(['idcommande' => (int)$idcommande, 'idlivreur' => (int)$arr_livreur['idlivreur']]); - - if (empty($ARR_COMMANDE_PROPOSITION['idcommande'])) { - $idcommande_proposition = $this->create_commande_proposition($idcommande, $idlivreur); - } else { - $idcommande_proposition = (int)$ARR_COMMANDE_PROPOSITION['idcommande_proposition']; - } - - $room_livreur[] = 'livreur_' . $idlivreur; - } - - // shopww - SendCmd::insert_mdl('app_console_thumb', 'commande', $idcommande, ['data-table' => 'commande', 'data-type_session' => 'shop', 'data-idsecteur' => $idsecteur, 'data-idshop' => $idshop], $room_shop); - // livreur si - if (!empty($room_livreur)) { - SendCmd::insert_mdl('app_fiche/app_fiche_reserv', 'commande', $idcommande, ['data-table' => 'commande', 'data-idsecteur' => $idsecteur, 'data-type_session' => 'livreur'], $room_livreur); - } else {// sinon - - } - // agent - SendCmd::insert_mdl('app_console/agent/app_console_fiche', 'commande', $idcommande, ['data-type_session' => 'agent', 'data-type_liste' => 'pool_statut_START'], 'room_agent'); - } - - /** - * show command shop - * - * @param $idcommande - */ - public function propose_commande_shop($idcommande) { - $APP_COMMANDE = new App('commande'); - - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - $idsecteur = (int)$ARR_COMMANDE['idsecteur']; - $idshop = (int)$ARR_COMMANDE['idshop']; - - $room_shop = 'shop_' . $idshop; - // shop - SendCmd::insert_mdl('app_console_thumb', 'commande', $idcommande, ['data-table' => 'commande', 'data-type_session' => 'shop', 'data-idsecteur' => $idsecteur, 'data-idshop' => $idshop], $room_shop); - - } - - public function propose_commande_coursier($idlivreur) { - ini_set('display_errors', 'On'); - $BIN = new Bin(); - $APP_COMMANDE = new App('commande'); - $APP_LIVREUR = new App('livreur'); - $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); - $ARR_LIVREUR = $APP_LIVREUR->findOne(['idlivreur' => (int)$idlivreur]); - - if (empty($ARR_LIVREUR['actifLivreur'])) return false; - - $room_livreur = 'livreur_' . $idlivreur; - $idsecteur = $ARR_LIVREUR['idsecteur']; - $ARR_COMMANDE_SECTEUR = CommandeQueue::secteur_commande_free_list($idsecteur); - - if (empty($ARR_COMMANDE_SECTEUR)) return false; - // - $QY = ['idsecteur' => $idsecteur, 'codeCommande_statut' => ['$ne' => 'END'], 'idlivreur' => ['$in' => ['', 0, null, (int)$idlivreur]]]; - $SORT = ['idlivreur' => -1, 'slotCommande' => 1, 'rangCommande' => 1]; - $RS = $APP_COMMANDE->find($QY)->sort($SORT); - // - $ARR_COMMANDE = $RS->getNext(); - $idcommande = (int)$ARR_COMMANDE['idcommande']; - $idshop = (int)$ARR_COMMANDE['idshop']; - - $shop_has_other_commande_non_prefin = CommandeQueue::shop_has_other_commande_non_prefin($idshop, $idcommande); - - if ($shop_has_other_commande_non_prefin) { - return false; - } - echo "GO ON"; - // test si livreur est engagé - $HAS = CommandeProposition::livreur_has_proposition_before_commande($idlivreur, $idcommande); - //var_dump($HAS); - //if (!empty($HAS)) return false; - // test si livreur a déja une proposition sur cette commande - $ARR_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->findOne(['idcommande' => (int)$idcommande, 'idlivreur' => (int)$idlivreur]); - if (empty($ARR_COMMANDE_PROPOSITION['idcommande'])) { - - $this->create_commande_proposition($idcommande, $idlivreur);// $APP_COMMANDE_PROPOSITION->insert($arr_insert); - } else { - $ARR_COMMANDE_PROPOSITION['idcommande_proposition']; - } - - $html_tags = ['data-table' => 'commande', 'data-idlivreur' => $idlivreur, 'data-idsecteur' => $idsecteur, 'data-type_session' => 'livreur']; - - SendCmd::insert_mdl('app_fiche/app_fiche_reserv', 'commande', $idcommande, $html_tags, $room_livreur); - - /*$Notify = new Notify(); - $Notify->notify_commande_change($idcommande);*/ - } - - public function propose_commande_coursier_old($idlivreur) { - $BIN = new Bin(); - $APP_COMMANDE = new App('commande'); - $APP_LIVREUR = new App('livreur'); - $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); - $ARR_LIVREUR = $APP_LIVREUR->findOne(['idlivreur' => (int)$idlivreur]); - - if (empty($ARR_LIVREUR['actifLivreur'])) return false; - $table = 'commande'; - $room = "livreur_" . $idlivreur; - $room_livreur = 'livreur_' . $idlivreur; - - $idsecteur = $ARR_LIVREUR['idsecteur']; - - $ARR_COMMANDE_SECTEUR = CommandeQueue::secteur_commande_free_list($idsecteur); - if (empty($ARR_COMMANDE_SECTEUR)) { - return false; - } - // - $QY = ['idsecteur' => $idsecteur, 'codeCommande_statut' => ['$ne' => 'end'], 'idlivreur' => ['$in' => ['', 0, null, (int)$idlivreur]]]; - $SORT = ['slotCommande' => 1, 'rangCommande' => 1]; - $RS = $APP_COMMANDE->find($QY)->sort($SORT); - $ARR_RS = iterator_to_array($RS); - // - $ARR_COMMANDE = array_values($ARR_COMMANDE_SECTEUR)[0]; - $idcommande = (int)$ARR_COMMANDE['idcommande']; - $idshop = (int)$ARR_COMMANDE['idshop']; - - $IS_FREE = $BIN->test_livreur_is_free($idlivreur); - if (!empty($IS_FREE)) return false; - // test si livreur deja vu une commande, non traitée par lui ni personne - $LAST_SEEN = CommandeProposition::livreur_last_commande_seen_still_active($idlivreur); - if (!empty($LAST_SEEN)) { - $LAST_SEEN_BEFORE = CommandeQueue::shop_has_other_commande_non_prefin_count($idshop, $LAST_SEEN['idcommande']); - if (empty($LAST_SEEN_BEFORE)) { - $html_tags = ['data-table' => 'commande', 'data-idlivreur' => $idlivreur, 'data-idsecteur' => $idsecteur, 'data-type_session' => 'livreur']; - - SendCmd::insert_mdl('app_fiche/app_fiche_reserv', 'commande', $LAST_SEEN['idcommande'], $html_tags, $room_livreur); - - $Notify = new Notify(); - $Notify->notify_commande_change($LAST_SEEN['idcommande']); - - return true; - - } - } - // test si livreur est engagé - $HAS = CommandeProposition::livreur_has_proposition_before_commande($idlivreur, $idcommande); - - if (!empty($HAS)) return false; - // test si livreur a déja une proposition sur cette commande - $ARR_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->findOne(['idcommande' => (int)$idcommande, 'idlivreur' => (int)$idlivreur]); - if (empty($ARR_COMMANDE_PROPOSITION['idcommande'])) { - $arr_insert = ['idcommande' => (int)$idcommande, - 'idsecteur' => $idsecteur, - 'idshop' => $idshop, - 'idlivreur' => (int)$idlivreur, - 'actifCommande_proposition' => 1, - 'dateCommande_proposition' => date('Y-m-d'), - 'timeCommande_proposition' => time(), - 'heureCommande_proposition' => date('H:i:s'), - 'referenceCommande_proposition' => $ARR_COMMANDE['referenceCommande'], - 'heureFinPreparationCommande_proposition' => $ARR_COMMANDE['heureFinPreparationCommande'], - 'timeFinPreparationCommande_proposition' => $ARR_COMMANDE['timeFinPreparationCommande']]; - - $idcommande_proposition = $APP_COMMANDE_PROPOSITION->insert($arr_insert); - } else { - $idcommande_proposition = (int)$ARR_COMMANDE_PROPOSITION['idcommande_proposition']; - } - - $html_tags = ['data-table' => 'commande', 'data-idlivreur' => $idlivreur, 'data-idsecteur' => $idsecteur, 'data-type_session' => 'livreur']; - - SendCmd::insert_mdl('app_fiche/app_fiche_reserv', 'commande', $idcommande, $html_tags, $room_livreur); - - $Notify = new Notify(); - $Notify->notify_commande_change($idcommande); - } - - /** - * statut console for agent only - * - * @param $idcommande - */ - public function propose_commande_statut($table_value) { - $table = 'commande'; - $APP_COMMANDE = new App($table); - $APP_COMMANDE->consolidate_scheme((int)$table_value); - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$table_value]); - if (empty($ARR_COMMANDE['idcommande'])) return false; - - $remove_selector = "[data-type_session=agent][data-type_liste]:not([data-type_liste=pool_statut_" . $ARR_COMMANDE['codeCommande_statut'] . "]) [data-table_value=$table_value][data-table=$table]"; - - // pour console agent - SendCmd::remove_selector([$remove_selector], 'room_agent'); - SendCmd::insert_mdl('app_console/agent/app_console_fiche', $table, $table_value, '[data-type_session=agent][data-type_liste=pool_statut_' . $ARR_COMMANDE['codeCommande_statut'] . ']', 'room_agent'); - - } - - public function propose_commande_sound($table_value) { - $APP_COMMANDE = new IdaeDB('commande'); - $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); - - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => $table_value]); - $ARR_COMMANDE_STATUT = $APP_COMMANDE_STATUT->findOne(['idcommande_statut' => (int)$ARR_COMMANDE['idcommande_statut']]); - - $idshop = $ARR_COMMANDE['idshop']; - $idlivreur = $ARR_COMMANDE['idlivreur']; - - switch ($ARR_COMMANDE_STATUT['codeCommande_statut']): - case 'RESERV'; - case 'LIVENCOU'; - SendCmd::play_sound("shop_$idshop"); - break; - case 'PREFIN'; - SendCmd::play_sound("livreur_$idlivreur"); - break; - endswitch; - - } - - /** - * remove commande from console sop / livreur when status END - * - * @param $table_value - * - * @return bool - */ - public function remove_commande($table_value) { - $table = 'commande'; - $APP_COMMANDE = new App($table); - $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); - - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$table_value]); - $ARR_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->findOne(['idcommande' => (int)$table_value, 'idlivreur' => (int)$ARR_COMMANDE['idlivreur']]); - if (empty($ARR_COMMANDE['idcommande'])) return false; - if (empty($ARR_COMMANDE_PROPOSITION['idcommande'])) return false; - - $room_shop = 'shop_' . $ARR_COMMANDE['idshop']; - $room_livreur = 'livreur_' . $ARR_COMMANDE['idlivreur']; - - $upd = $APP_COMMANDE_PROPOSITION->update(['idcommande_proposition' => (int)$ARR_COMMANDE_PROPOSITION['idcommande_proposition']], ['actifCommande_proposition' => 0, 'endedCommande_proposition' => 1]); - - $oith = []; - $commande_gutter_selector = "[data-console_liste] module[data-table_value=$table_value][data-table=$table]"; - $commande_shop_selector = "[data-console_liste_detail] module[data-table_value=$table_value][data-table=$table]"; - - array_push($oith, $commande_shop_selector); - array_push($oith, $commande_gutter_selector); - - SendCmd::remove_selector([$commande_gutter_selector, $commande_shop_selector], $room_shop); - SendCmd::remove_selector([$commande_gutter_selector], $room_livreur); - } - } +find(); + + $Not = new Notify(); + while ($ARR_SECTEUR = $RS_SECTEUR->getNext()) { + /** + * debug + */ + $Not->notify_commande_secteur($ARR_SECTEUR['idsecteur']); + $ARR_COMMANDE_SECTEUR = $BIN->secteur_commande_free_queue($ARR_SECTEUR['idsecteur']); + + $Notify = new Notify(); + $Notify->notify_commande_secteur($ARR_SECTEUR['idsecteur']); + foreach ($ARR_COMMANDE_SECTEUR as $idkey_liv => $ARR_COMMANDE) { + $this->propose_commande($ARR_COMMANDE['idcommande']); + } + + } + } + + /** + * dispatch commands to available coursiers in secteur + * + * @param $idsecteur + */ + public function propose_commande_secteur_pool($idsecteur) { + $BIN = new Bin(); + + $ARR_COMMANDE_SECTEUR = $BIN->secteur_commande_free_queue($idsecteur); + + foreach ($ARR_COMMANDE_SECTEUR as $idkey_liv => $ARR_COMMANDE) { + $this->propose_commande($ARR_COMMANDE['idcommande']); + } + } + + /** + * remove command shown to available coursiers + * + * @param $idcommande + */ + public function remove_propose_commande($table_value) { + $table = 'commande'; + $APP_COMMANDE = new App($table); + $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$table_value]); + + $idlivreur = $ARR_COMMANDE['idlivreur']; + + // deactivate commande_proposition for all coursiers + $RS_REM = $APP_COMMANDE_PROPOSITION->find(['idcommande' => (int)$table_value]); + while ($ARR_REM = $RS_REM->getNext()) { + $APP_COMMANDE_PROPOSITION->update(['idcommande_proposition' => (int)$ARR_REM['idcommande_proposition']], ['actifCommande_proposition' => 0]); + if ($ARR_REM['idlivreur'] == $ARR_COMMANDE['idlivreur']) { + // activate commande_proposition for coursier if one + $APP_COMMANDE_PROPOSITION->update(['idcommande_proposition' => (int)$ARR_REM['idcommande_proposition']], ['livreur_take' => $idlivreur, 'acceptCommande_proposition' => 1]); + } + } + + // enlever annonce commande dans autre console livreur + $secteur_selector = "[data-type_session=livreur][data-see_less_commande][data-idlivreur=$idlivreur][data-table_value=$table_value]"; + AppSocket::send_cmd('act_remove_selector', [$secteur_selector]); + + // enlever commande dans console livreur + $secteur_selector = "[data-type_session=livreur][data-console_liste]:not([data-idlivreur=$idlivreur]) [data-table_value=$table_value][data-table=$table]"; + AppSocket::send_cmd('act_remove_selector', [$secteur_selector]); + } + + /** + * remove command shown to one coursiers + * + * @param $table_value + * @param $idlivreur + */ + public function remove_propose_commande_coursier($table_value, $idlivreur) { + $table = 'commande'; + + // enlever commande dans console livreur + $secteur_selector = "[data-type_session=livreur][data-console_liste][data-idlivreur=$idlivreur] [data-table_value=$table_value][data-table=$table]"; + AppSocket::send_cmd('act_remove_selector', [$secteur_selector]); + } + + public function create_commande_proposition($idcommande, $idlivreur) { + + $APP_COMMANDE = new IdaeDB('commande'); + $APP_COMMANDE_PROPOSITION = new IdaeDB('commande_proposition'); + + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + + if (empty($ARR_COMMANDE['idcommande'])) return false; + $idsecteur = (int)$ARR_COMMANDE['idsecteur']; + $idshop = (int)$ARR_COMMANDE['idshop']; + + $time = time(); + $arr_insert = ['idcommande' => (int)$idcommande, + 'idsecteur' => $idsecteur, + 'idshop' => $idshop, + 'idlivreur' => (int)$idlivreur, + 'actifCommande_proposition' => 1, + 'dateCommande_proposition' => date('Y-m-d', $time), + 'timeCommande_proposition' => $time, + 'heureCommande_proposition' => date('H:i:s', $time), + 'referenceCommande_proposition' => $ARR_COMMANDE['referenceCommande'], + 'heureFinPreparationCommande_proposition' => $ARR_COMMANDE['heureFinPreparationCommande'], + 'timeFinPreparationCommande_proposition' => $ARR_COMMANDE['timeFinPreparationCommande']]; + + return $APP_COMMANDE_PROPOSITION->insert($arr_insert); + } + + /** + * @param $idcommande + * + * @return bool + * @throws \MongoCursorException + */ + public function propose_commande($idcommande) { + + $APP_COMMANDE = new App('commande'); + $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); + $BIN = new Bin(); + + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + + if (empty($ARR_COMMANDE['idcommande'])) return false; + $idsecteur = (int)$ARR_COMMANDE['idsecteur']; + $idshop = (int)$ARR_COMMANDE['idshop']; + $room_shop = 'shop_' . $idshop; + $room_livreur = []; + $time = time(); + //AppSocket::send_cmd('act_notify', ['msg' => "propose commande $idcommande " . $ARR_COMMANDE['codeCommande'].' '. $ARR_COMMANDE['referenceCommande']]); + + // NE PAS PROPOSER SI SHOP COMMANDE NON PREFIN > NBLIV DISP + $shop_has_other_commande_non_prefin = CommandeQueue::shop_has_other_commande_non_prefin($idshop, $idcommande); // shop_has_other_commandefree_non_prefin_list + + if ($shop_has_other_commande_non_prefin) { + return false; + } + + $arr_livreur_free = $BIN->test_livreur_affect_free($idsecteur); + + // proposition + foreach ($arr_livreur_free as $idkey_liv => $arr_livreur) { + $idlivreur = (int)$arr_livreur['idlivreur']; + // proposal deja actif ? + $TEST_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->find(['idlivreur' => $idlivreur, + 'idsecteur' => $idsecteur, + 'livreur_take' => ['$ne' => $idlivreur], + 'dateCommande_proposition' => date('Y-m-d'), + 'endedCommande_proposition' => ['$ne' => 1], + 'timeFinPreparationCommande_proposition' => ['$lt' => $ARR_COMMANDE['timeFinPreparationCommande']], + 'actifCommande_proposition' => 1])->sort(['timeFinPreparationCommande_proposition' => 1]); + if ($TEST_COMMANDE_PROPOSITION->count() != 0) { + // AppSocket::send_cmd('act_notify', ['msg' => "NOT propose commande $idcommande ".$arr_livreur['nomLivreur'].$TEST_COMMANDE_PROPOSITION->count() ]); + + continue; + } + + $ARR_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->findOne(['idcommande' => (int)$idcommande, 'idlivreur' => (int)$arr_livreur['idlivreur']]); + + if (empty($ARR_COMMANDE_PROPOSITION['idcommande'])) { + $idcommande_proposition = $this->create_commande_proposition($idcommande, $idlivreur); + } else { + $idcommande_proposition = (int)$ARR_COMMANDE_PROPOSITION['idcommande_proposition']; + } + + $room_livreur[] = 'livreur_' . $idlivreur; + } + + // shopww + SendCmd::insert_mdl('app_console_thumb', 'commande', $idcommande, ['data-table' => 'commande', 'data-type_session' => 'shop', 'data-idsecteur' => $idsecteur, 'data-idshop' => $idshop], $room_shop); + // livreur si + if (!empty($room_livreur)) { + SendCmd::insert_mdl('app_fiche/app_fiche_reserv', 'commande', $idcommande, ['data-table' => 'commande', 'data-idsecteur' => $idsecteur, 'data-type_session' => 'livreur'], $room_livreur); + } else {// sinon + + } + // agent + SendCmd::insert_mdl('app_console/agent/app_console_fiche', 'commande', $idcommande, ['data-type_session' => 'agent', 'data-type_liste' => 'pool_statut_START'], 'room_agent'); + } + + /** + * show command shop + * + * @param $idcommande + */ + public function propose_commande_shop($idcommande) { + $APP_COMMANDE = new App('commande'); + + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + $idsecteur = (int)$ARR_COMMANDE['idsecteur']; + $idshop = (int)$ARR_COMMANDE['idshop']; + + $room_shop = 'shop_' . $idshop; + // shop + SendCmd::insert_mdl('app_console_thumb', 'commande', $idcommande, ['data-table' => 'commande', 'data-type_session' => 'shop', 'data-idsecteur' => $idsecteur, 'data-idshop' => $idshop], $room_shop); + + } + + public function propose_commande_coursier($idlivreur) { + ini_set('display_errors', 'On'); + $BIN = new Bin(); + $APP_COMMANDE = new App('commande'); + $APP_LIVREUR = new App('livreur'); + $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); + $ARR_LIVREUR = $APP_LIVREUR->findOne(['idlivreur' => (int)$idlivreur]); + + if (empty($ARR_LIVREUR['actifLivreur'])) return false; + + $room_livreur = 'livreur_' . $idlivreur; + $idsecteur = $ARR_LIVREUR['idsecteur']; + $ARR_COMMANDE_SECTEUR = CommandeQueue::secteur_commande_free_list($idsecteur); + + if (empty($ARR_COMMANDE_SECTEUR)) return false; + // + $QY = ['idsecteur' => $idsecteur, 'codeCommande_statut' => ['$ne' => 'END'], 'idlivreur' => ['$in' => ['', 0, null, (int)$idlivreur]]]; + $SORT = ['idlivreur' => -1, 'slotCommande' => 1, 'rangCommande' => 1]; + $RS = $APP_COMMANDE->find($QY)->sort($SORT); + // + $ARR_COMMANDE = $RS->getNext(); + $idcommande = (int)$ARR_COMMANDE['idcommande']; + $idshop = (int)$ARR_COMMANDE['idshop']; + + $shop_has_other_commande_non_prefin = CommandeQueue::shop_has_other_commande_non_prefin($idshop, $idcommande); + + if ($shop_has_other_commande_non_prefin) { + return false; + } + echo "GO ON"; + // test si livreur est engagé + $HAS = CommandeProposition::livreur_has_proposition_before_commande($idlivreur, $idcommande); + //var_dump($HAS); + //if (!empty($HAS)) return false; + // test si livreur a déja une proposition sur cette commande + $ARR_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->findOne(['idcommande' => (int)$idcommande, 'idlivreur' => (int)$idlivreur]); + if (empty($ARR_COMMANDE_PROPOSITION['idcommande'])) { + + $this->create_commande_proposition($idcommande, $idlivreur);// $APP_COMMANDE_PROPOSITION->insert($arr_insert); + } else { + $ARR_COMMANDE_PROPOSITION['idcommande_proposition']; + } + + $html_tags = ['data-table' => 'commande', 'data-idlivreur' => $idlivreur, 'data-idsecteur' => $idsecteur, 'data-type_session' => 'livreur']; + + SendCmd::insert_mdl('app_fiche/app_fiche_reserv', 'commande', $idcommande, $html_tags, $room_livreur); + + /*$Notify = new Notify(); + $Notify->notify_commande_change($idcommande);*/ + } + + public function propose_commande_coursier_old($idlivreur) { + $BIN = new Bin(); + $APP_COMMANDE = new App('commande'); + $APP_LIVREUR = new App('livreur'); + $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); + $ARR_LIVREUR = $APP_LIVREUR->findOne(['idlivreur' => (int)$idlivreur]); + + if (empty($ARR_LIVREUR['actifLivreur'])) return false; + $table = 'commande'; + $room = "livreur_" . $idlivreur; + $room_livreur = 'livreur_' . $idlivreur; + + $idsecteur = $ARR_LIVREUR['idsecteur']; + + $ARR_COMMANDE_SECTEUR = CommandeQueue::secteur_commande_free_list($idsecteur); + if (empty($ARR_COMMANDE_SECTEUR)) { + return false; + } + // + $QY = ['idsecteur' => $idsecteur, 'codeCommande_statut' => ['$ne' => 'end'], 'idlivreur' => ['$in' => ['', 0, null, (int)$idlivreur]]]; + $SORT = ['slotCommande' => 1, 'rangCommande' => 1]; + $RS = $APP_COMMANDE->find($QY)->sort($SORT); + $ARR_RS = iterator_to_array($RS); + // + $ARR_COMMANDE = array_values($ARR_COMMANDE_SECTEUR)[0]; + $idcommande = (int)$ARR_COMMANDE['idcommande']; + $idshop = (int)$ARR_COMMANDE['idshop']; + + $IS_FREE = $BIN->test_livreur_is_free($idlivreur); + if (!empty($IS_FREE)) return false; + // test si livreur deja vu une commande, non traitée par lui ni personne + $LAST_SEEN = CommandeProposition::livreur_last_commande_seen_still_active($idlivreur); + if (!empty($LAST_SEEN)) { + $LAST_SEEN_BEFORE = CommandeQueue::shop_has_other_commande_non_prefin_count($idshop, $LAST_SEEN['idcommande']); + if (empty($LAST_SEEN_BEFORE)) { + $html_tags = ['data-table' => 'commande', 'data-idlivreur' => $idlivreur, 'data-idsecteur' => $idsecteur, 'data-type_session' => 'livreur']; + + SendCmd::insert_mdl('app_fiche/app_fiche_reserv', 'commande', $LAST_SEEN['idcommande'], $html_tags, $room_livreur); + + $Notify = new Notify(); + $Notify->notify_commande_change($LAST_SEEN['idcommande']); + + return true; + + } + } + // test si livreur est engagé + $HAS = CommandeProposition::livreur_has_proposition_before_commande($idlivreur, $idcommande); + + if (!empty($HAS)) return false; + // test si livreur a déja une proposition sur cette commande + $ARR_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->findOne(['idcommande' => (int)$idcommande, 'idlivreur' => (int)$idlivreur]); + if (empty($ARR_COMMANDE_PROPOSITION['idcommande'])) { + $arr_insert = ['idcommande' => (int)$idcommande, + 'idsecteur' => $idsecteur, + 'idshop' => $idshop, + 'idlivreur' => (int)$idlivreur, + 'actifCommande_proposition' => 1, + 'dateCommande_proposition' => date('Y-m-d'), + 'timeCommande_proposition' => time(), + 'heureCommande_proposition' => date('H:i:s'), + 'referenceCommande_proposition' => $ARR_COMMANDE['referenceCommande'], + 'heureFinPreparationCommande_proposition' => $ARR_COMMANDE['heureFinPreparationCommande'], + 'timeFinPreparationCommande_proposition' => $ARR_COMMANDE['timeFinPreparationCommande']]; + + $idcommande_proposition = $APP_COMMANDE_PROPOSITION->insert($arr_insert); + } else { + $idcommande_proposition = (int)$ARR_COMMANDE_PROPOSITION['idcommande_proposition']; + } + + $html_tags = ['data-table' => 'commande', 'data-idlivreur' => $idlivreur, 'data-idsecteur' => $idsecteur, 'data-type_session' => 'livreur']; + + SendCmd::insert_mdl('app_fiche/app_fiche_reserv', 'commande', $idcommande, $html_tags, $room_livreur); + + $Notify = new Notify(); + $Notify->notify_commande_change($idcommande); + } + + /** + * statut console for agent only + * + * @param $idcommande + */ + public function propose_commande_statut($table_value) { + $table = 'commande'; + $APP_COMMANDE = new App($table); + $APP_COMMANDE->consolidate_scheme((int)$table_value); + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$table_value]); + if (empty($ARR_COMMANDE['idcommande'])) return false; + + $remove_selector = "[data-type_session=agent][data-type_liste]:not([data-type_liste=pool_statut_" . $ARR_COMMANDE['codeCommande_statut'] . "]) [data-table_value=$table_value][data-table=$table]"; + + // pour console agent + SendCmd::remove_selector([$remove_selector], 'room_agent'); + SendCmd::insert_mdl('app_console/agent/app_console_fiche', $table, $table_value, '[data-type_session=agent][data-type_liste=pool_statut_' . $ARR_COMMANDE['codeCommande_statut'] . ']', 'room_agent'); + + } + + public function propose_commande_sound($table_value) { + $APP_COMMANDE = new IdaeDB('commande'); + $APP_COMMANDE_STATUT = new IdaeDB('commande_statut'); + + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => $table_value]); + $ARR_COMMANDE_STATUT = $APP_COMMANDE_STATUT->findOne(['idcommande_statut' => (int)$ARR_COMMANDE['idcommande_statut']]); + + $idshop = $ARR_COMMANDE['idshop']; + $idlivreur = $ARR_COMMANDE['idlivreur']; + + switch ($ARR_COMMANDE_STATUT['codeCommande_statut']): + case 'RESERV'; + case 'LIVENCOU'; + SendCmd::play_sound("shop_$idshop"); + break; + case 'PREFIN'; + SendCmd::play_sound("livreur_$idlivreur"); + break; + endswitch; + + } + + /** + * remove commande from console sop / livreur when status END + * + * @param $table_value + * + * @return bool + */ + public function remove_commande($table_value) { + $table = 'commande'; + $APP_COMMANDE = new App($table); + $APP_COMMANDE_PROPOSITION = new App('commande_proposition'); + + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$table_value]); + $ARR_COMMANDE_PROPOSITION = $APP_COMMANDE_PROPOSITION->findOne(['idcommande' => (int)$table_value, 'idlivreur' => (int)$ARR_COMMANDE['idlivreur']]); + if (empty($ARR_COMMANDE['idcommande'])) return false; + if (empty($ARR_COMMANDE_PROPOSITION['idcommande'])) return false; + + $room_shop = 'shop_' . $ARR_COMMANDE['idshop']; + $room_livreur = 'livreur_' . $ARR_COMMANDE['idlivreur']; + + $upd = $APP_COMMANDE_PROPOSITION->update(['idcommande_proposition' => (int)$ARR_COMMANDE_PROPOSITION['idcommande_proposition']], ['actifCommande_proposition' => 0, 'endedCommande_proposition' => 1]); + + $oith = []; + $commande_gutter_selector = "[data-console_liste] module[data-table_value=$table_value][data-table=$table]"; + $commande_shop_selector = "[data-console_liste_detail] module[data-table_value=$table_value][data-table=$table]"; + + array_push($oith, $commande_shop_selector); + array_push($oith, $commande_gutter_selector); + + SendCmd::remove_selector([$commande_gutter_selector, $commande_shop_selector], $room_shop); + SendCmd::remove_selector([$commande_gutter_selector], $room_livreur); + } + } diff --git a/web/bin/classes/ClassFragment.php b/web/bin/classes/ClassFragment.php index c3e6d20..80c04b9 100644 --- a/web/bin/classes/ClassFragment.php +++ b/web/bin/classes/ClassFragment.php @@ -1,455 +1,455 @@ -get_cart(); - $parameters['site_page'] = $this->get_page(); - - $html = $LATTE->renderToString(APPTPL . 'fragments/menu_bar.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function shop_search($inner = false) { - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - $Cart = new Cart(); - $parameters['var_cart'] = $Cart->get_cart(); - $parameters['site_page'] = $this->get_page(); - $parameters['map_adresse'] = $parameters['var_cart']['cart_adresse']['formatted_address'] ?: null; - $LATTE->setAutoRefresh(true); - $html = $LATTE->renderToString(APPTPL . 'fragments/shop_search.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function do_action($params = ['action', - 'value']) { - // - - if (strpos($params['value'], '/') === false) { - $this->$params['action']($params['value']); - } else { - $this->$params['action'](explode('/', $params['value'])); - } - // Helper::dump($params); - } - - function cart_small($inner = false) { - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - $Cart = new Cart(); - $parameters['var_cart'] = $Cart->get_cart(); - - $html = $LATTE->renderToString(APPTPL . 'fragments/cart_small.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function cart_edit_line($inner = false) { - global $LATTE; - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - $Cart = new Cart(); - $arr_cart = $Cart->get_cart(); - $parameters['cart_line'] = $arr_cart['cart_lines'][$_REQUEST['cart_line_key']]; - $parameters['cart_line_key'] = $_REQUEST['cart_line_key']; - $html = $LATTE->renderToString(APPTPL . 'fragments/cart_big_item.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - public function cart_big($inner = false) { - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - $Cart = new Cart(); - $parameters['var_cart'] = $Cart->get_cart(); - - $html = $LATTE->renderToString(APPTPL . 'fragments/cart_big.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function cart_sum($inner = false) { - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - $Cart = new Cart(); - $parameters['var_cart'] = $Cart->get_cart(); - //Helper::dump($parameters['var_cart']); - $html = $LATTE->renderToString(APPTPL . 'fragments/cart_small.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function livraison_estimation($idshop, $inner = false) { - global $LATTE; - - $Bin = new Bin(); - $APP_SHOP = new App('shop'); - - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $idshop = (int)$ARR_SHOP['idshop']; - $idsecteur = (int)$ARR_SHOP['idsecteur']; - - $configs = CommandeQueueConsole::consoleShopSite($idshop); - - $times_shop = $configs->console_shop->get_templateObjHTML(); - $times_shop_obj = $configs->console_shop->get_templateObj(); - - $times_secteur = $configs->console_secteur_livreur->get_templateObjHTML(); - $times_secteur_obj = $configs->console_secteur_livreur->get_templateObj(); - - $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE = $times_shop->COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE; - $COMMAND_SHOP_FINAL_DELIVERY_DATETIME = $times_shop->COMMAND_SHOP_FINAL_DELIVERY_DATETIME; - $COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE = $times_shop->COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE; - $COMMAND_SHOP_MSG = $times_shop->COMMAND_SHOP_MSG; - $COMMAND_SHOP_SHIFT = $times_shop->COMMAND_SHOP_SHIFT_NB; - - $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE_OBJ = $times_shop_obj->COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE; - $COMMAND_SHOP_FINAL_DELIVERY_DATETIME_OBJ = $times_shop_obj->COMMAND_SHOP_FINAL_DELIVERY_DATETIME; - $COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE_OBJ = $times_shop_obj->COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE; - $COMMAND_SHOP_SHIFT_OBJ = $times_shop_obj->COMMAND_SHOP_SHIFT_NB; - - $LIVREUR_WORKING_NB = $times_secteur->LIVREUR_WORKING_NB; - $LIVREUR_MSG = $times_secteur->LIVREUR_MSG; - $LIVREUR_DISPONIBLE_NB = $times_secteur->LIVREUR_DISPONIBLE_NB; - $LIVREUR_WAITING_COMMANDE_NB = $times_secteur->LIVREUR_WAITING_COMMANDE_NB; - - $LIVREUR_WORKING_NB_OBJ = $times_secteur_obj->LIVREUR_WORKING_NB; - $LIVREUR_DISPONIBLE_NB_OBJ = $times_secteur_obj->LIVREUR_DISPONIBLE_NB; - $LIVREUR_WAITING_COMMANDE_NB_OBJ = $times_secteur_obj->LIVREUR_WAITING_COMMANDE_NB; - - $parameters['LIVREUR_WORKING_NB'] = $times_secteur->LIVREUR_WORKING_NB; - $parameters['LIVREUR_MSG'] = $times_secteur->LIVREUR_MSG; - $parameters['LIVREUR_DISPONIBLE_NB'] = $times_secteur->LIVREUR_DISPONIBLE_NB; - $parameters['LIVREUR_WAITING_COMMANDE_NB'] = $times_secteur->LIVREUR_WAITING_COMMANDE_NB; - $parameters['COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE'] = $times_shop->COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE; - $parameters['COMMAND_SHOP_MSG'] = $times_shop->COMMAND_SHOP_MSG; - - $var_liv_affect = $parameters['var_liv_affect'] = $Bin->test_livreur_affect_free($idsecteur); - - $parameters['idsecteur'] = $idsecteur; - $parameters['var_liv_affect'] = $var_liv_affect; - - $parameters['idshop'] = $idshop; - $parameters['idsecteur'] = $idsecteur; - - $parameters['tempsLivraison'] = $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE; - $parameters['heureLivraison'] = $COMMAND_SHOP_FINAL_DELIVERY_DATETIME; - - - $html = $LATTE->renderToString(APPTPL . 'fragments/livraison_estimation.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - } - - function commande_confirm_info() { - Helper::dump($_POST); - } - - function livraison_ligne($inner = false) { - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $parameters['num_livraison_ligne'] = 121; - $html = $LATTE->renderToString(APPTPL . 'fragments/livraison_ligne.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - } - - function login($inner = false) { - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - if (empty($_SESSION['client'])) { - $html = $LATTE->renderToString(APPTPL . 'fragments/login.html', $parameters); - - } else { - $html = $LATTE->renderToString(APPTPL . 'fragments/login_done.html', $parameters); - - } - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function login_multi($inner = false) { - global $LATTE; - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $type = $parameters['type'] = $_GET['type']; - $parameters['Type'] = ucfirst($type); - - switch ($type): - case 'livreur': - case 'client': - case 'delivery': - case 'shop': - $tpl = 'fragments/login_multi.html'; - break; - case 'agent': - $tpl = 'idae/fragments/login_multi.html'; - break; - endswitch; - - $LATTE->setAutoRefresh(true); - if (empty($_SESSION[$type])) { - $html = $LATTE->renderToString(APPTPL . $tpl, $parameters); - } else { - $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_done.html', $parameters); - } - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function login_multi_register($inner = false) { - global $LATTE; - $parameters = array_merge($_GET, $_POST); - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $type = $parameters['type'] = $_GET['type']; - $parameters['Type'] = ucfirst($type); - - $LATTE->setAutoRefresh(true); - $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_register.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function idae_login_multi($inner = false) { - global $LATTE; - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $type = $parameters['type'] = $_GET['type']; - $parameters['Type'] = ucfirst($type); - - if (empty($_SESSION[$type])) { - $html = $LATTE->renderToString(APPTPL . 'idae/fragments/login_multi.html', $parameters); - - } else { - $html = $LATTE->renderToString(APPTPL . 'idae/fragments/login_multi_done.html', $parameters); - } - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function login_multi_done($inner = false) { - global $LATTE; - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $type = $parameters['type'] = $_GET['type']; - $parameters['Type'] = ucfirst($type); - $html = ''; - if (!empty($_SESSION[$type])) { - $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_done.html', $parameters); - } - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function login_retrieve($inner = false) { - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - $Cart = new Cart(); - $parameters['var_cart'] = $Cart->get_cart(); - - $html = $LATTE->renderToString(APPTPL . 'fragments/login_retrieve.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function login_multi_retrieve($inner = true) { - - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - $parameters['type'] = $_GET['type']; - - $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_retrieve.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - - } - - function login_multi_init($inner = true) { - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - $parameters['type'] = $_GET['type']; - $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_init.html', $_GET); - - if ($inner) { - return $html; - } else { - echo $html; - } - } - - function footer($inner = true) { - global $LATTE; - - $APP_SECTEUR = new App('secteur'); - $APP_SH_J = new App('shop_jours'); - $APP_SH_J_SHIFT = new App('shop_jours_shift'); - # index jour - $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; - - // - $arr_sh_j = $APP_SH_J->distinct_all('idshop', ['actifShop_jours' => 1, - 'ordreJours' => $index_jour]); - $arr_sh_j_shift = $APP_SH_J_SHIFT->distinct_all('idshop', ['idshop' => ['$in' => $arr_sh_j]]); // $APP_SH_J_SHIFT - // - $parameters['nomJours'] = sizeof($arr_sh_j); - - # Shop liste - $APP_SH = new App('shop'); - $arr_sh = $APP_SH->distinct_all('idshop', ["actifShop" => 1, - 'idshop' => ['$in' => $arr_sh_j_shift]], ['_id' => 0]); - - $arr_sect = $APP_SH->distinct_all('idsecteur', ['idshop' => ['$in' => $arr_sh_j_shift]], ['_id' => 0]); - $rs_secteur = $APP_SECTEUR->find(['idsecteur' => ['$in' => $arr_sect]])->limit(6)->sort(['nomSecteur' => 1]); - $rs_shop = $APP_SH->find(['idshop' => ['$in' => $arr_sh]])->limit(6)->sort(['nomShop' => 1]); - while ($arr_secteur = $rs_secteur->getNext()) { - $idsecteur = (int)$arr_secteur['idsecteur']; - $parameters['var_secteur_liste'][$idsecteur] = $arr_secteur; - $parameters['var_secteur_liste'][$idsecteur]['link'] = Router::build_route('secteur', ['idsecteur' => $idsecteur]); - } - while ($arr_shop = $rs_shop->getNext()) { - $idshop = (int)$arr_shop['idshop']; - $parameters['var_shop_liste'][$idshop] = $arr_shop; - $parameters['var_shop_liste'][$idshop]['link'] = Router::build_route('restaurant', ['idshop' => $idshop]); - } - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $html = $LATTE->renderToString(APPTPL . 'fragments/footer.html', $parameters); - - if ($inner) { - return $html; - } else { - echo $html; - } - } - - function notify($inner = true) { - global $LATTE; - - $LATTE->setAutoRefresh(); - $html = $LATTE->renderToString(APPTPL . 'fragments/notify.html', $_GET + ['warm' => 'up.' . time()]); - - if ($inner) { - return $html; - } else { - echo $html; - } - } - - function commande_end($inner = true) { - global $LATTE; - - $LATTE->setAutoRefresh(); - $html = $LATTE->renderToString(APPTPL . 'fragments/commande_end.html', $_GET + ['warm' => 'up.' . time()]); - - if ($inner) { - return $html; - } else { - echo $html; - } - } +get_cart(); + $parameters['site_page'] = $this->get_page(); + + $html = $LATTE->renderToString(APPTPL . 'fragments/menu_bar.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function shop_search($inner = false) { + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + $Cart = new Cart(); + $parameters['var_cart'] = $Cart->get_cart(); + $parameters['site_page'] = $this->get_page(); + $parameters['map_adresse'] = $parameters['var_cart']['cart_adresse']['formatted_address'] ?: null; + $LATTE->setAutoRefresh(true); + $html = $LATTE->renderToString(APPTPL . 'fragments/shop_search.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function do_action($params = ['action', + 'value']) { + // + + if (strpos($params['value'], '/') === false) { + $this->$params['action']($params['value']); + } else { + $this->$params['action'](explode('/', $params['value'])); + } + // Helper::dump($params); + } + + function cart_small($inner = false) { + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + $Cart = new Cart(); + $parameters['var_cart'] = $Cart->get_cart(); + + $html = $LATTE->renderToString(APPTPL . 'fragments/cart_small.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function cart_edit_line($inner = false) { + global $LATTE; + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + $Cart = new Cart(); + $arr_cart = $Cart->get_cart(); + $parameters['cart_line'] = $arr_cart['cart_lines'][$_REQUEST['cart_line_key']]; + $parameters['cart_line_key'] = $_REQUEST['cart_line_key']; + $html = $LATTE->renderToString(APPTPL . 'fragments/cart_big_item.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + public function cart_big($inner = false) { + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + $Cart = new Cart(); + $parameters['var_cart'] = $Cart->get_cart(); + + $html = $LATTE->renderToString(APPTPL . 'fragments/cart_big.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function cart_sum($inner = false) { + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + $Cart = new Cart(); + $parameters['var_cart'] = $Cart->get_cart(); + //Helper::dump($parameters['var_cart']); + $html = $LATTE->renderToString(APPTPL . 'fragments/cart_small.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function livraison_estimation($idshop, $inner = false) { + global $LATTE; + + $Bin = new Bin(); + $APP_SHOP = new App('shop'); + + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $idshop = (int)$ARR_SHOP['idshop']; + $idsecteur = (int)$ARR_SHOP['idsecteur']; + + $configs = CommandeQueueConsole::consoleShopSite($idshop); + + $times_shop = $configs->console_shop->get_templateObjHTML(); + $times_shop_obj = $configs->console_shop->get_templateObj(); + + $times_secteur = $configs->console_secteur_livreur->get_templateObjHTML(); + $times_secteur_obj = $configs->console_secteur_livreur->get_templateObj(); + + $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE = $times_shop->COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE; + $COMMAND_SHOP_FINAL_DELIVERY_DATETIME = $times_shop->COMMAND_SHOP_FINAL_DELIVERY_DATETIME; + $COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE = $times_shop->COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE; + $COMMAND_SHOP_MSG = $times_shop->COMMAND_SHOP_MSG; + $COMMAND_SHOP_SHIFT = $times_shop->COMMAND_SHOP_SHIFT_NB; + + $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE_OBJ = $times_shop_obj->COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE; + $COMMAND_SHOP_FINAL_DELIVERY_DATETIME_OBJ = $times_shop_obj->COMMAND_SHOP_FINAL_DELIVERY_DATETIME; + $COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE_OBJ = $times_shop_obj->COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE; + $COMMAND_SHOP_SHIFT_OBJ = $times_shop_obj->COMMAND_SHOP_SHIFT_NB; + + $LIVREUR_WORKING_NB = $times_secteur->LIVREUR_WORKING_NB; + $LIVREUR_MSG = $times_secteur->LIVREUR_MSG; + $LIVREUR_DISPONIBLE_NB = $times_secteur->LIVREUR_DISPONIBLE_NB; + $LIVREUR_WAITING_COMMANDE_NB = $times_secteur->LIVREUR_WAITING_COMMANDE_NB; + + $LIVREUR_WORKING_NB_OBJ = $times_secteur_obj->LIVREUR_WORKING_NB; + $LIVREUR_DISPONIBLE_NB_OBJ = $times_secteur_obj->LIVREUR_DISPONIBLE_NB; + $LIVREUR_WAITING_COMMANDE_NB_OBJ = $times_secteur_obj->LIVREUR_WAITING_COMMANDE_NB; + + $parameters['LIVREUR_WORKING_NB'] = $times_secteur->LIVREUR_WORKING_NB; + $parameters['LIVREUR_MSG'] = $times_secteur->LIVREUR_MSG; + $parameters['LIVREUR_DISPONIBLE_NB'] = $times_secteur->LIVREUR_DISPONIBLE_NB; + $parameters['LIVREUR_WAITING_COMMANDE_NB'] = $times_secteur->LIVREUR_WAITING_COMMANDE_NB; + $parameters['COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE'] = $times_shop->COMMAND_SHOP_FINAL_DELIVERY_THUMB_STATE; + $parameters['COMMAND_SHOP_MSG'] = $times_shop->COMMAND_SHOP_MSG; + + $var_liv_affect = $parameters['var_liv_affect'] = $Bin->test_livreur_affect_free($idsecteur); + + $parameters['idsecteur'] = $idsecteur; + $parameters['var_liv_affect'] = $var_liv_affect; + + $parameters['idshop'] = $idshop; + $parameters['idsecteur'] = $idsecteur; + + $parameters['tempsLivraison'] = $COMMAND_SHOP_FINAL_DELIVERY_DELAY_RANGE; + $parameters['heureLivraison'] = $COMMAND_SHOP_FINAL_DELIVERY_DATETIME; + + + $html = $LATTE->renderToString(APPTPL . 'fragments/livraison_estimation.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + } + + function commande_confirm_info() { + Helper::dump($_POST); + } + + function livraison_ligne($inner = false) { + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $parameters['num_livraison_ligne'] = 121; + $html = $LATTE->renderToString(APPTPL . 'fragments/livraison_ligne.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + } + + function login($inner = false) { + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + if (empty($_SESSION['client'])) { + $html = $LATTE->renderToString(APPTPL . 'fragments/login.html', $parameters); + + } else { + $html = $LATTE->renderToString(APPTPL . 'fragments/login_done.html', $parameters); + + } + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function login_multi($inner = false) { + global $LATTE; + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $type = $parameters['type'] = $_GET['type']; + $parameters['Type'] = ucfirst($type); + + switch ($type): + case 'livreur': + case 'client': + case 'delivery': + case 'shop': + $tpl = 'fragments/login_multi.html'; + break; + case 'agent': + $tpl = 'idae/fragments/login_multi.html'; + break; + endswitch; + + $LATTE->setAutoRefresh(true); + if (empty($_SESSION[$type])) { + $html = $LATTE->renderToString(APPTPL . $tpl, $parameters); + } else { + $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_done.html', $parameters); + } + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function login_multi_register($inner = false) { + global $LATTE; + $parameters = array_merge($_GET, $_POST); + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $type = $parameters['type'] = $_GET['type']; + $parameters['Type'] = ucfirst($type); + + $LATTE->setAutoRefresh(true); + $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_register.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function idae_login_multi($inner = false) { + global $LATTE; + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $type = $parameters['type'] = $_GET['type']; + $parameters['Type'] = ucfirst($type); + + if (empty($_SESSION[$type])) { + $html = $LATTE->renderToString(APPTPL . 'idae/fragments/login_multi.html', $parameters); + + } else { + $html = $LATTE->renderToString(APPTPL . 'idae/fragments/login_multi_done.html', $parameters); + } + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function login_multi_done($inner = false) { + global $LATTE; + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $type = $parameters['type'] = $_GET['type']; + $parameters['Type'] = ucfirst($type); + $html = ''; + if (!empty($_SESSION[$type])) { + $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_done.html', $parameters); + } + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function login_retrieve($inner = false) { + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + $Cart = new Cart(); + $parameters['var_cart'] = $Cart->get_cart(); + + $html = $LATTE->renderToString(APPTPL . 'fragments/login_retrieve.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function login_multi_retrieve($inner = true) { + + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + $parameters['type'] = $_GET['type']; + + $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_retrieve.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + + } + + function login_multi_init($inner = true) { + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + $parameters['type'] = $_GET['type']; + $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_init.html', $_GET); + + if ($inner) { + return $html; + } else { + echo $html; + } + } + + function footer($inner = true) { + global $LATTE; + + $APP_SECTEUR = new App('secteur'); + $APP_SH_J = new App('shop_jours'); + $APP_SH_J_SHIFT = new App('shop_jours_shift'); + # index jour + $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; + + // + $arr_sh_j = $APP_SH_J->distinct_all('idshop', ['actifShop_jours' => 1, + 'ordreJours' => $index_jour]); + $arr_sh_j_shift = $APP_SH_J_SHIFT->distinct_all('idshop', ['idshop' => ['$in' => $arr_sh_j]]); // $APP_SH_J_SHIFT + // + $parameters['nomJours'] = sizeof($arr_sh_j); + + # Shop liste + $APP_SH = new App('shop'); + $arr_sh = $APP_SH->distinct_all('idshop', ["actifShop" => 1, + 'idshop' => ['$in' => $arr_sh_j_shift]], ['_id' => 0]); + + $arr_sect = $APP_SH->distinct_all('idsecteur', ['idshop' => ['$in' => $arr_sh_j_shift]], ['_id' => 0]); + $rs_secteur = $APP_SECTEUR->find(['idsecteur' => ['$in' => $arr_sect]])->limit(6)->sort(['nomSecteur' => 1]); + $rs_shop = $APP_SH->find(['idshop' => ['$in' => $arr_sh]])->limit(6)->sort(['nomShop' => 1]); + while ($arr_secteur = $rs_secteur->getNext()) { + $idsecteur = (int)$arr_secteur['idsecteur']; + $parameters['var_secteur_liste'][$idsecteur] = $arr_secteur; + $parameters['var_secteur_liste'][$idsecteur]['link'] = Router::build_route('secteur', ['idsecteur' => $idsecteur]); + } + while ($arr_shop = $rs_shop->getNext()) { + $idshop = (int)$arr_shop['idshop']; + $parameters['var_shop_liste'][$idshop] = $arr_shop; + $parameters['var_shop_liste'][$idshop]['link'] = Router::build_route('restaurant', ['idshop' => $idshop]); + } + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $html = $LATTE->renderToString(APPTPL . 'fragments/footer.html', $parameters); + + if ($inner) { + return $html; + } else { + echo $html; + } + } + + function notify($inner = true) { + global $LATTE; + + $LATTE->setAutoRefresh(); + $html = $LATTE->renderToString(APPTPL . 'fragments/notify.html', $_GET + ['warm' => 'up.' . time()]); + + if ($inner) { + return $html; + } else { + echo $html; + } + } + + function commande_end($inner = true) { + global $LATTE; + + $LATTE->setAutoRefresh(); + $html = $LATTE->renderToString(APPTPL . 'fragments/commande_end.html', $_GET + ['warm' => 'up.' . time()]); + + if ($inner) { + return $html; + } else { + echo $html; + } + } } \ No newline at end of file diff --git a/web/bin/classes/ClassHelper.php b/web/bin/classes/ClassHelper.php index 5323b3c..ae28449 100644 --- a/web/bin/classes/ClassHelper.php +++ b/web/bin/classes/ClassHelper.php @@ -1,18 +1,18 @@ -"; - echo json_encode($vars, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ; - // echo ""; - } +"; + echo json_encode($vars, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ; + // echo ""; + } } \ No newline at end of file diff --git a/web/bin/classes/ClassIdae.php b/web/bin/classes/ClassIdae.php index 8680525..d280a3b 100644 --- a/web/bin/classes/ClassIdae.php +++ b/web/bin/classes/ClassIdae.php @@ -1,773 +1,773 @@ -table = $table; - parent::__construct($table); - } - - static function module_exists($module) { - $arr_mdl = explode('/', $module); - $file = end($arr_mdl); - array_pop($arr_mdl); - $path = implode('/', $arr_mdl); - - $arr_file[] = APPMDL . 'app/app_' . $module . '.php'; - $arr_file[] = APPMDL . 'app/' . $module . '.php'; - $arr_file[] = APPMDL . 'app/' . $path . '/app_' . $file . '.php'; - $arr_file[] = APPMDL . 'app/' . $path . '/' . $file . '.php'; - - foreach ($arr_file as $val) { - if (file_exists($val)) { - //echo $val; - return $val; - } - } - - return false; - } - - function fiche_mail($table_value) { - global $LATTE; - - $APP_HAS_FIELD = new App('appscheme_has_field'); - $APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); - $APP_LIGNE = new App('commande_ligne'); - - $table = $this->table; - $Table = ucfirst($table); - - $APPOBJ = $this->appobj($table_value); - $APP_TABLE = $this->app_table_one; - - $ARR = $APPOBJ->ARR; - - $parameters = $ARR; - $parameters['table'] = $table; - $parameters['table_value'] = (int)$table_value; - $parameters['nomTable'] = $APPOBJ->NAME_APP; - - $field_list = $this->get_field_list_all(); - foreach ($this->grilleFK as $keyFK => $fieldFK) { - $table_fk = $fieldFK['table']; - if (!isset($ARR["id$table_fk"])) continue; - $APP_TMP = new App($table_fk); - $field_list_fk = $APP_TMP->get_field_list_raw(); - $ARR_TMP = $APP_TMP->findOne(["id$table_fk" => (int)$ARR["id$table_fk"]], ['_id' => 0]); - foreach ($field_list_fk as $key => $field) { - $field_name = $field['field_name']; - if (isset($ARR_TMP[$field_name])) { - $parameters[$field_name] = $this->cast_field(['codeAppscheme_field_type' => $field['codeAppscheme_field_type'], - 'field_value' => $ARR_TMP[$field_name], - 'field_name' => $field['field_name'], - 'field_name_raw' => $field['field_name_raw'],]); - } - - } - } - foreach ($field_list as $key => $field) { - $field_name = $field['field_name']; - if (isset($ARR[$field_name])) { - $parameters[$field_name] = $this->cast_field(['codeAppscheme_field_type' => $field['codeAppscheme_field_type'], - 'field_value' => $ARR[$field_name], - 'field_name' => $field['field_name'], - 'field_name_raw' => $field['field_name_raw'],]); - } - } - - if (!empty($APP_TABLE['hasLigneScheme'])) { - $rs_ligne = $APP_LIGNE->find(["id$table" => $table_value]); - $arr_ligne = iterator_to_array($rs_ligne); - - $RS_HAS_TABLE_FIELD = $APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$APP_LIGNE->idappscheme])->sort(['ordreAppscheme_has_table_field' => 1]); - $ARR_HAS_TABLE_FIELD = iterator_to_array($RS_HAS_TABLE_FIELD); - - $parameters['fields'] = $ARR_HAS_TABLE_FIELD; - $parameters['liste'] = $arr_ligne; - } - $LATTE->setAutoRefresh(true); - - return $html = $LATTE->renderToString(APPTPL . "idae/fiche_mail.html", $parameters); - } - - /** - * @deprecated - */ - function fiche($table_value) { - global $LATTE; - - $table = $this->table; - $Table = ucfirst($table); - - $APPOBJ = $this->appobj($table_value); - $APP_TABLE = $this->app_table_one; - - $ARR = $APPOBJ->ARR; - // Helper::dump($ARR); - $parameters['table'] = $table; - $parameters['table_value'] = (int)$table_value; - $parameters['nomTable'] = $APPOBJ->NAME_APP; - $export_values = []; - - // Helper::dump($APP_TABLE); - if (!empty($APP_TABLE['hasLigneScheme'])) { - $idae_liste = new Idae($table . '_ligne'); - $table_ligne = $idae_liste->liste(["id$table" => $table_value]); - $parameters ['html_fiche_ligne'] = $table_ligne; - } - - foreach ($APPOBJ->ARR_GROUP_FIELD as $key => $val) { - $arrg = $val['group']; - $arr_fields = $val['field']; - - $arr_fields = array_filter($arr_fields); - - $export_values[$key] = []; - foreach ($arr_fields as $keyf => $valf) { - if (empty($ARR[$valf['codeAppscheme_field'] . $Table])) { - continue; - } - - $export_key = ucfirst(idioma($valf['nomAppscheme_field'])); - $export_code = ucfirst($valf['codeAppscheme_field']); - $export_icon = $valf['iconAppscheme_field']; - $export_value = $this->draw_field(['field_name_raw' => $valf['codeAppscheme_field'], - 'table' => $table, - 'field_value' => $ARR[$valf['codeAppscheme_field'] . $Table]]); - - $export_values[$key][$export_code] = [$export_icon, - $export_key, - $export_value]; - } - } - $parameters ['var_fiche_main'] = array_filter($export_values); - - // GRILLE FK - $export_values_fk = []; - foreach ($APPOBJ->GRILLE_FK as $field): - $table_k = $field['table_fk']; - $Table_k = ucfirst($field['table_fk']); - // query for name if needed - if (empty($ARR['nom' . ucfirst($field['table_fk'])])) { - $arr = $this->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); - $dsp_code = $arr['code' . $Table_k]; - $dsp_name = $arr['nom' . $Table_k]; - - } else { - $dsp_code = $ARR['code' . $Table_k]; - $dsp_name = $ARR['nom' . $Table_k]; - } - if (empty($dsp_name) && empty($dsp_code)) { - continue; - } - $export_value_fk = []; - $export_value_fk['code ' . $Table_k] = $this->draw_field(['field_name_raw' => 'code', - 'table' => $table_k, - 'field_value' => $dsp_code]); - $export_value_fk['nom ' . $Table_k] = $this->draw_field(['field_name_raw' => 'nom', - 'table' => $table_k, - 'field_value' => $dsp_name]); - - $export_values_fk[$field['table_fk']] = $export_value_fk; - endforeach; - $parameters ['var_fiche_fk'] = array_filter($export_values_fk); - - // Statuts ++ - $export_values_state = []; - $arr_has = ['statut', - 'type', - 'categorie', - 'group']; - foreach ($arr_has as $key => $value): - $Value = ucfirst($value); - if (empty($APP_TABLE['has' . $Value . 'Scheme'])) { - continue; - } - $_table = $table . '_' . $value; - $_Table = ucfirst($_table); - $APPTMP = new App($_table); - $_id = 'id' . $_table; - $_nom = 'nom' . $_Table; - $_icon = 'icon' . $_Table; - $_code = 'code' . $_Table; - if (!empty($ARR[$_nom])): - // - $export_value_fk = []; - $export_value_fk['icon'] = $this->draw_field(['field_name_raw' => 'icon', - 'table' => $_table, - 'field_value' => $ARR[$_icon]]); - $export_value_fk['code'] = $this->draw_field(['field_name_raw' => 'code', - 'table' => $_table, - 'field_value' => $ARR[$_code]]); - $export_value_fk['nom'] = $this->draw_field(['field_name_raw' => 'nom', - 'table' => $_table, - 'field_value' => $ARR[$_nom]]); - $export_value_fk['color'] = $this->draw_field(['field_name_raw' => 'color', - 'table' => $_table, - 'field_value' => $ARR['color' . $_Table]]); - - $export_values_state[$_table] = $export_value_fk; - - // $rs_tmp = $APPTMP->find(); - // echo function_prod::draw_select_input($_table, $table_value); - endif; - if ($value == 'statut') { - $add_vars = []; - if ($_SESSION['livreur']) { - $add_vars = ['START', - 'RESERV', - 'LIVENCOU', - 'END']; - } - if ($_SESSION['shop']) { - $add_vars = ['START', - 'RESERV', - 'PREFIN']; - } - $step = (int)$ARR['ordre' . $_Table]; - $next_step = ++$step; - $arr_tmp = $APPTMP->find([$_code => ['$in' => $add_vars], - 'ordre' . $_Table => (int)$next_step])->getNext(); - - $next_idcommande_statut = $arr_tmp[$_id]; - $next_nomCommande_statut = $arr_tmp[$_nom]; - $next_icon_statut = $this->draw_field(['field_name_raw' => 'icon', - 'table' => $_table, - 'field_value' => $arr_tmp[$_icon]]); - $parameters['next_idcommande_statut'] = $next_idcommande_statut; - $parameters['next_icon_statut'] = $next_icon_statut; - $parameters['next_nomCommande_statut'] = $next_nomCommande_statut; - } - endforeach; - - $parameters ['var_fiche_state'] = array_filter($export_values_state); - // Helper::dump($parameters ['var_fiche_state']); - if (!empty($APP_TABLE['hasStatutScheme'])) { - $parameters ['html_fiche_statut'] = $LATTE->renderToString(APPTPL . "idae/fiche_statut.html", $parameters); - $parameters ['html_fiche_next_statut'] = $this->fiche_next_statut($table_value, true); - } - - if ($_SESSION['shop']) { - if ($this->table == 'produit') { - $parameters['html_edit_link'] = 'modifier'; - } - } - - if (!empty($APP_TABLE['hasImageScheme'])) { - $parameters ['html_fiche_image'] = $this->fiche_image($table_value, true); - } - echo $html = $LATTE->renderToString(APPTPL . "idae/fiche.html", $parameters); - - //Helper::dump($parameters); - } - /** - * @deprecated - */ - function liste($vars = []) { - global $LATTE; - - $table = $this->table; - $Table = ucfirst($table); - - $parameters['table'] = $table; - - array_walk_recursive($vars, 'CleanStr', $vars); - $vars = empty($vars) ? [] : function_prod::cleanPostMongo($vars, 1); - - $rs = $this->find($vars); - $arr = iterator_to_array($rs); - - $APP_HAS_FIELD = new App('appscheme_has_field'); - $APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); - $RS_HAS_TABLE_FIELD = $APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$this->idappscheme])->sort(['ordreAppscheme_has_table_field' => 1]); - $ARR_HAS_TABLE_FIELD = iterator_to_array($RS_HAS_TABLE_FIELD); - // has_totalAppscheme_field - $parameters['fields'] = $ARR_HAS_TABLE_FIELD; - $parameters['liste'] = $arr; - - return $html = $LATTE->renderToString(APPTPL . "idae/table.html", $parameters); - } - - function fiche_next_statut($table_value, $inner = false) { - - global $LATTE; - - $table = $this->table; - $Table = ucfirst($table); - - $APPOBJ = $this->appobj((int)$table_value); - $ARR = $APPOBJ->ARR; - $APP_TABLE = $APPOBJ->APP_TABLE; - if (empty($APP_TABLE['hasStatutScheme'])) { - return false; - } - if (!empty($_SESSION['type_session'])) { - $type_session = $_SESSION['type_session']; - $name_idtype_session = "id$type_session"; - $idtype_session = (int)$_SESSION[$name_idtype_session]; - if (!empty($APPOBJ->$name_idtype_session) && $APPOBJ->$name_idtype_session != $idtype_session) { - return false; - } - if ($type_session == 'livreur') { - if (!empty($ARR[$name_idtype_session]) && $ARR[$name_idtype_session] != $idtype_session) return false; - } - } - $parameters = $ARR; - $parameters['table'] = $table; - $parameters['table_value'] = (int)$table_value; - $parameters['session_idlivreur'] = $idtype_session; - $export_values = []; - - // Statuts ++ - $export_values_state = []; - $arr_has = ['statut']; - $value = 'statut'; - - $Value = ucfirst($value); - $_table = $table . '_' . $value; - $_Table = ucfirst($_table); - $APPTMP = new App($_table); - $_id = 'id' . $_table; - $_nom = 'nom' . $_Table; - $_icon = 'icon' . $_Table; - $_code = 'code' . $_Table; - $_color = 'color' . $_Table; - - $add_vars = []; - if ($_SESSION['livreur']) { - $add_vars = ['START', - 'RESERV', - 'LIVENCOU', - 'END']; // 'LIVENCOU', - } - if ($_SESSION['shop']) { - $add_vars = ['START', - 'RUN', - 'PREFIN']; - } - $step = (int)$ARR['ordre' . $_Table]; - $next_step = ++$step; - $arr_tmp = $APPTMP->find([$_code => ['$in' => $add_vars], - 'ordre' . $_Table => (int)$next_step])->getNext(); - - $next_idcommande_statut = $arr_tmp[$_id]; - $next_nomCommande_statut = $arr_tmp[$_nom]; - $next_colorCommande_statut = $arr_tmp[$_color]; - $next_icon_statut = $this->draw_field(['field_name_raw' => 'icon', - 'table' => $_table, - 'field_value' => $arr_tmp[$_icon]]); - - $parameters['next_idcommande_statut'] = $next_idcommande_statut; - $parameters['next_icon_statut'] = $next_icon_statut; - $parameters['next_nomCommande_statut'] = $next_nomCommande_statut; - $parameters['next_colorCommande_statut'] = $next_colorCommande_statut; - $parameters['codeCommande_statut'] = $ARR['code' . $_Table]; - - $parameters['idsecteur'] = $ARR['idsecteur']; - $LATTE->setAutoRefresh(true); - - if ($inner) { - return $html = $LATTE->renderToString(APPTPL . "idae/fiche_next_statut.html", $parameters); - - } else { - echo $html = $LATTE->renderToString(APPTPL . "idae/fiche_next_statut.html", $parameters); - } - } - /** - * @deprecated - */ - function fiche_image($table_value, $inner = false) { - global $LATTE; - - $table = $this->table; - $Table = ucfirst($table); - - $parameters['table'] = $table; - $parameters['table_value'] = (int)$table_value; - - $AppSite = new AppSite(); - $arr_tpl = $AppSite->makeTplData($table, $table_value); - $parameters['fiche_image'] = $arr_tpl; - - if ($inner) { - return $html = $LATTE->renderToString(APPTPL . "idae/fiche_image.html", $parameters); - - } else { - echo $html = $LATTE->renderToString(APPTPL . "idae/fiche_image.html", $parameters); - } - } - - /** - * @param null $table_value - * @param array $arr_vars - * - * @return array - * - * @deprecated - */ - public function get_table_fields($table_value = null, $arr_vars = []) { - $table = $this->table;; - $Table = ucfirst($table); - - $vars = empty($arr_vars['vars']) ? [] : function_prod::cleanPostMongo($arr_vars['vars'], 1); - // - $APP_FIELD = new App('appscheme_field'); - $APP_FIELD_GROUP = new App('appscheme_field_group'); - $APP_HAS_FIELD = new App('appscheme_has_field'); - - $APPOBJ = $this->appobj($table_value, $vars); - $ARR = $APPOBJ->ARR; - $idappscheme = $this->idappscheme; - - $DIST_FIELD_FILTER = []; - $DIST_NOFIELD_FILTER = []; - if (!empty($arr_vars['codeAppscheme_field'])) { - $DIST_FIELD_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field' => ['$in' => (array)$arr_vars['codeAppscheme_field']]]); - $DIST_FIELD_FILTER = array_merge($DIST_FIELD_FILTER_APP, $DIST_FIELD_FILTER); - } - if (!empty($arr_vars['nocodeAppscheme_field'])) { - $DIST_FIELD_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field' => ['$in' => (array)$arr_vars['nocodeAppscheme_field']]]); - $DIST_NOFIELD_FILTER = array_merge($DIST_FIELD_FILTER_APP, $DIST_NOFIELD_FILTER); - } - $DIST_FIELD_TYPE_FILTER = []; - if (!empty($arr_vars['codeAppscheme_field_type'])) { - $DIST_FIELD_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field_type' => $arr_vars['codeAppscheme_field_type']]); - $DIST_FIELD_TYPE_FILTER = array_merge($DIST_FIELD_FILTER_APP, $DIST_FIELD_TYPE_FILTER); - } - $DIST_GROUP_FILTER = []; - if (!empty($arr_vars['codeAppscheme_field_group'])) { - if (is_array($arr_vars['codeAppscheme_field_group'])) { - $DIST_GROUP_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field_group' => ['$in' => $arr_vars['codeAppscheme_field_group']]]); - } else { - $DIST_GROUP_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field_group' => $arr_vars['codeAppscheme_field_group']]); - } - $DIST_GROUP_FILTER = array_merge($DIST_GROUP_FILTER_APP, $DIST_GROUP_FILTER); - } - // - $ARGS = ['idappscheme' => $idappscheme]; - if (!empty($DIST_FIELD_FILTER)) { - $ARGS['idappscheme_field'] = ['$in' => $DIST_FIELD_FILTER]; - } - if (!empty($DIST_NOFIELD_FILTER)) { - $ARGS['idappscheme_field'] = ['$nin' => $DIST_NOFIELD_FILTER]; - } - if (!empty($DIST_FIELD_TYPE_FILTER)) { - $ARGS['idappscheme_field'] = ['$in' => $DIST_FIELD_TYPE_FILTER]; - } - if (!empty($DIST_FIELD_TYPE_FILTER)) { - $ARGS['idappscheme_field'] = ['$in' => $DIST_FIELD_TYPE_FILTER]; - } - if (isset($arr_vars['in_mini_fiche'])) { - $ARGS['in_mini_fiche'] = $arr_vars['in_mini_fiche']; - } - $ARGS_GROUP = []; - if (!empty($DIST_GROUP_FILTER)) { - $ARGS_GROUP['idappscheme_field'] = ['$in' => $DIST_GROUP_FILTER]; - } - $RS_HAS_FIELD = $APP_HAS_FIELD->distinct_all('idappscheme_field', $ARGS); - - $DIST_FIELD_GROUP = $APP_FIELD->distinct_all('idappscheme_field_group', $ARGS_GROUP + ['idappscheme_field' => ['$in' => $RS_HAS_FIELD]]); - $RS_FIELD_GROUP = $APP_FIELD_GROUP->find(['idappscheme_field_group' => ['$in' => $DIST_FIELD_GROUP]])->sort(['ordreAppscheme_field_group' => 1]); - $COLLECT = []; - foreach ($RS_FIELD_GROUP as $key => $ARR_FIELD_GROUP) { - $idappscheme_field_group = (int)$ARR_FIELD_GROUP['idappscheme_field_group']; - $RS_FIELD = $APP_FIELD->find(['idappscheme_field_group' => $idappscheme_field_group, - 'idappscheme_field' => ['$in' => $RS_HAS_FIELD]]); - $COLLECT[$key]['appscheme_field_group'] = $ARR_FIELD_GROUP; - foreach ($RS_FIELD as $keyf => $ARR_FIELD) { - /*if (!empty($arr_vars['show_empty'])) { - if (!isset($ARR[$ARR_FIELD['codeAppscheme_field'] . $Table])) continue; - }*/ - $code = $ARR_FIELD['codeAppscheme_field']; - $COLLECT[$key]['appscheme_fields'][$code]['css_bold'] = in_array($code, ['nom', - 'code']) ? 'text-bold' : ''; - foreach (['nom', - 'petitNom', - 'icon', - 'color'] as $keyff => $valuef) { - $COLLECT[$key]['appscheme_fields'][$code][$valuef] = $ARR_FIELD[$valuef . 'Appscheme_field']; - - } - $COLLECT[$key]['appscheme_fields'][$code]['value_raw'] = $ARR[$ARR_FIELD['codeAppscheme_field'] . $Table]; - $COLLECT[$key]['appscheme_fields'][$code]['value_html'] = $this->draw_field(['field_name_raw' => $ARR_FIELD['codeAppscheme_field'], - 'table' => $table, - 'field_value' => $ARR[$ARR_FIELD['codeAppscheme_field'] . $Table]]); - $COLLECT[$key]['appscheme_fields'][$code]['value_input'] = $this->draw_field_input(['field_name_raw' => $ARR_FIELD['codeAppscheme_field'], - 'table' => $table, - 'field_value' => ($ARR_FIELD['codeAppscheme_field'] != 'password') ? $ARR[$ARR_FIELD['codeAppscheme_field'] . $Table] : '']); - - } - } - - return $COLLECT; - } - - function get_fk_fields($table_value = null, $arr_vars = []) { // grille_fk - $APPOBJ = $this->appobj($table_value, $arr_vars); - $ARR = $APPOBJ->ARR; - $COLLECT = []; - foreach ($this->get_grille_fk() as $field): - // query for name - $arr = $this->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); - $dsp_code = $arr['code' . ucfirst($field['table_fk'])]; - $dsp_name = $arr['nom' . ucfirst($field['table_fk'])]; - if (empty($dsp_name)) continue; - $table = $field['table_fk']; - $table_value = $ARR[$field['idtable_fk']]; - $COLLECT[$dsp_code]['table'] = $table; - $COLLECT[$dsp_code]['table_value'] = $table_value; - $COLLECT[$dsp_code]['value_html'] = $table_value; - $COLLECT[$dsp_code]['value_mdl'] = $table_value; - $COLLECT[$dsp_code]['value_input'] = $table; - endforeach; - - return $COLLECT; - } - - public function liste_titre($arr_vars = []) { - - $out_vars = []; - $APP_SCH = new App('appscheme'); - $APP = new App('appscheme_has_field'); - if (!empty($arr_vars['vars'])) { - $arr_vars += $arr_vars['vars']; - unset($arr_vars['vars']); - } - foreach ($arr_vars as $name_vars => $value_vars): - $ARR = $APP->findOne(['codeAppscheme_has_field' => $name_vars]); - if ($ARR['_id'] != ''): - $out_vars[] = $ARR['nomAppscheme_field'] . ' ' . $ARR['nomAppscheme'] . ' : ' . $value_vars; - else: - $table = str_replace('id', '', $name_vars); - $ARR = $APP_SCH->findOne(['codeAppscheme' => $table]); - if ($ARR['_id'] != ''): - $APP_TMP = new App($table); - $ARR_TMP = $APP_TMP->findOne([$name_vars => (int)$value_vars]); - if (empty($ARR_TMP['nom' . ucfirst($table)])) continue; - $out_vars[] = ' ' . $ARR['nomAppscheme'] . ' : ' . $ARR_TMP['nom' . ucfirst($table)]; - endif; - endif; - - endforeach; - $out = implode('', $out_vars); - if (!empty($arr_vars['groupBy'])) $out .= ' groupé par : ' . $arr_vars['groupBy']; - if (!empty($arr_vars['sortBy'])) $out .= ' trié par : ' . $arr_vars['sortBy']; - if (!empty($arr_vars['search'])) $out .= ' Recherche : "' . $arr_vars['search'] . '"'; - - return $out; - } - - /** - * @param array $vars - * - * @return mixed - */ - public function liste_statut($vars = []) { - global $LATTE; - - $table = $this->table; - $Table = ucfirst($table); - - $APPOBJ = $this->appobj(); - $ARR = $APPOBJ->ARR; - - $parameters['table'] = []; - - $_table = $table . '_statut'; - $_Table = ucfirst($_table); - $APPTMP = new App($_table); - $_id = 'id' . $_table; - $_nom = 'nom' . $_Table; - $_icon = 'icon' . $_Table; - $_code = 'code' . $_Table; - $_ordre = 'ordre' . $_Table; - - $RS_STATUT = $APPTMP->find($vars)->sort([$_ordre => 1]); - - while ($ARR_STATUT = $RS_STATUT->getNext()) { - $add_vars = []; - $collect = []; - if ($_SESSION['livreur']) { - $add_vars = ['START', - 'RESERV', - 'LIVENCOU', - 'END']; - } - if ($_SESSION['shop']) { - $add_vars = ['START', - 'RUN', - 'PREFIN']; - } - $arr_has = ['icon', - 'nom', - 'code', - 'color']; - - $collect["id"] = $ARR_STATUT[$_id]; - $collect["id" . $_table] = $ARR_STATUT[$_id]; - foreach ($arr_has as $keyh => $valueh): - $collect[$valueh] = $this->draw_field(['field_name' => $valueh . $_table, - 'field_name_raw' => $valueh, - 'table' => $_table, - 'field_value' => $ARR_STATUT[$valueh . $_Table]]); - endforeach; - - $step = (int)$ARR['ordre' . $_Table]; - $next_step = ++$step; - $arr_tmp = $APPTMP->find([$_code => ['$in' => $add_vars], - 'ordre' . $_Table => (int)$next_step])->getNext(); - - $next_idcommande_statut = $arr_tmp[$_id]; - $next_nomCommande_statut = $arr_tmp[$_nom]; - $next_icon_statut = $this->draw_field(['field_name_raw' => 'icon', - 'table' => $_table, - 'field_value' => $arr_tmp[$_icon]]); - - $collect['next_idcommande_statut'] = $next_idcommande_statut; - $collect['next_icon_statut'] = $next_icon_statut; - $collect['next_nom' . $table . '_statut'] = $next_nomCommande_statut; - $collect['codeCommande_statut'] = $ARR['code' . $_Table]; - - $parameters[] = $collect; - - } - - return $parameters; - } - - /** - * @param string $module - * @param array $http_vars - * - * @deprecated - */ - public function module($module, $http_vars = []) { - - $type_session = $_SESSION['type_session']; - $name_idtype_session = "id$type_session"; - $idtype_session = (int)$_SESSION[$name_idtype_session]; - $APP_SESSION = new App($type_session); - global $ARR_SESSION; - $ARR_SESSION = $APP_SESSION->findOne([$name_idtype_session => $idtype_session]); - if (empty($_POST)) { - // $_POST = []; - } - if (!empty($_GET)) { - $_POST = array_merge($_GET, $_POST);; - } - if (is_array($http_vars)) { - $_POST = array_merge($_POST, $http_vars); - $this->HTTP_VARS = array_merge($_POST, $http_vars); - } else { - parse_str($http_vars, $_POST); - $this->HTTP_VARS = $_POST; - } - $attr = ''; - if (!empty($this->table)) { - $table = $this->table; - $attr .= "data-table='$table' "; - $attr .= "data-crypted_table='" . encrypt_url($table) . "' "; - } elseif (!empty($this->HTTP_VARS['table'])) { - $table = $this->HTTP_VARS['table']; - $this->set_table($table); - $attr .= "data-table='$table' "; - $attr .= "data-crypted_table='" . encrypt_url($table) . "' "; - - } - if (!empty($this->HTTP_VARS['table_value'])) { - $table_value = $this->HTTP_VARS['table_value']; - $attr .= "data-table_value='$table_value' "; - $attr .= "data-crypted_table_value='" . encrypt_url($table_value) . "' "; - - } - - if (!empty($this->table)) { - if ($this->has_field_fk($type_session)) { - $this->HTTP_VARS['vars'][$name_idtype_session] = $idtype_session; - } - if ($this->grilleFK && $APP_SESSION->grilleFK) { - $intersect_fk = array_intersect(array_column($this->grilleFK, 'table'), array_column($APP_SESSION->grilleFK, 'table')); - if (sizeof($intersect_fk != 0)) { - $vars = []; - foreach ($intersect_fk as $key_ifk => $value_fk) { - if (!empty($ARR_SESSION["id$value_fk"])) $this->HTTP_VARS['vars']["id$value_fk"] = (int)$ARR_SESSION["id$value_fk"]; - } - } - - } - } - - $this->module_route = "idae/module/$module"; - - $attr .= 'data-vars="' . http_build_query($this->HTTP_VARS) . '" '; - $attr .= 'data-crypted_vars="' . encrypt_url(http_build_query($this->HTTP_VARS)) . '" '; - - $attr = html_entity_decode($attr); - - $moduleTag = 'module'; - $start = ($moduleTag != 'none') ? "<$moduleTag data-mdl='idae/module/$module' $attr title='module=$module' value='red' >" : ""; // - $end = ($moduleTag != 'none') ? "" : ""; - - $arr_mdl = explode('/', $module); - $file = end($arr_mdl); - array_pop($arr_mdl); - $path = implode('/', $arr_mdl); - - $file_1 = APPMDL . 'app/app_' . $module . '.php'; - $file_2 = APPMDL . 'app/' . $module . '.php'; - $file_3 = APPMDL . 'app/' . $path . '/app_' . $file . '.php'; - $file_4 = APPMDL . 'app/' . $path . '/' . $file . '.php'; - - if (!empty($table)) { - $a = 'app_custom/' . $table . '/' . $table . '_' . $file; - $test_custom = Idae::module_exists('app_custom/' . $table . '/' . $table . '_' . $file); - if (!empty($test_custom)) { - $Idae_tmp = new Idae($table); - - return $Idae_tmp->module('app_custom/' . $table . '/' . $table . '_' . $file, $this->HTTP_VARS); - } - } - - ob_start(); - - if (file_exists($file_1)) { - include($file_1); - } elseif (file_exists($file_2)) { - include($file_2); - } elseif (file_exists($file_3)) { - include($file_3); - } elseif (file_exists($file_4)) { - include($file_4); - } else { - echo "missing module $module
"; - } - $final = ob_get_contents(); - $final = $start . $final . $end; - ob_end_clean(); - - return trim($final); - } - - public static function getInstance($table = '') { - - if (is_null(self::$_instance)) { - self::$_instance = new Idae($table); - } else if (!is_null(self::$_instance) && self::$_instance->table = $table) { - self::$_instance = new Idae($table); - } - - return self::$_instance; - } +table = $table; + parent::__construct($table); + } + + static function module_exists($module) { + $arr_mdl = explode('/', $module); + $file = end($arr_mdl); + array_pop($arr_mdl); + $path = implode('/', $arr_mdl); + + $arr_file[] = APPMDL . 'app/app_' . $module . '.php'; + $arr_file[] = APPMDL . 'app/' . $module . '.php'; + $arr_file[] = APPMDL . 'app/' . $path . '/app_' . $file . '.php'; + $arr_file[] = APPMDL . 'app/' . $path . '/' . $file . '.php'; + + foreach ($arr_file as $val) { + if (file_exists($val)) { + //echo $val; + return $val; + } + } + + return false; + } + + function fiche_mail($table_value) { + global $LATTE; + + $APP_HAS_FIELD = new App('appscheme_has_field'); + $APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); + $APP_LIGNE = new App('commande_ligne'); + + $table = $this->table; + $Table = ucfirst($table); + + $APPOBJ = $this->appobj($table_value); + $APP_TABLE = $this->app_table_one; + + $ARR = $APPOBJ->ARR; + + $parameters = $ARR; + $parameters['table'] = $table; + $parameters['table_value'] = (int)$table_value; + $parameters['nomTable'] = $APPOBJ->NAME_APP; + + $field_list = $this->get_field_list_all(); + foreach ($this->grilleFK as $keyFK => $fieldFK) { + $table_fk = $fieldFK['table']; + if (!isset($ARR["id$table_fk"])) continue; + $APP_TMP = new App($table_fk); + $field_list_fk = $APP_TMP->get_field_list_raw(); + $ARR_TMP = $APP_TMP->findOne(["id$table_fk" => (int)$ARR["id$table_fk"]], ['_id' => 0]); + foreach ($field_list_fk as $key => $field) { + $field_name = $field['field_name']; + if (isset($ARR_TMP[$field_name])) { + $parameters[$field_name] = $this->cast_field(['codeAppscheme_field_type' => $field['codeAppscheme_field_type'], + 'field_value' => $ARR_TMP[$field_name], + 'field_name' => $field['field_name'], + 'field_name_raw' => $field['field_name_raw'],]); + } + + } + } + foreach ($field_list as $key => $field) { + $field_name = $field['field_name']; + if (isset($ARR[$field_name])) { + $parameters[$field_name] = $this->cast_field(['codeAppscheme_field_type' => $field['codeAppscheme_field_type'], + 'field_value' => $ARR[$field_name], + 'field_name' => $field['field_name'], + 'field_name_raw' => $field['field_name_raw'],]); + } + } + + if (!empty($APP_TABLE['hasLigneScheme'])) { + $rs_ligne = $APP_LIGNE->find(["id$table" => $table_value]); + $arr_ligne = iterator_to_array($rs_ligne); + + $RS_HAS_TABLE_FIELD = $APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$APP_LIGNE->idappscheme])->sort(['ordreAppscheme_has_table_field' => 1]); + $ARR_HAS_TABLE_FIELD = iterator_to_array($RS_HAS_TABLE_FIELD); + + $parameters['fields'] = $ARR_HAS_TABLE_FIELD; + $parameters['liste'] = $arr_ligne; + } + $LATTE->setAutoRefresh(true); + + return $html = $LATTE->renderToString(APPTPL . "idae/fiche_mail.html", $parameters); + } + + /** + * @deprecated + */ + function fiche($table_value) { + global $LATTE; + + $table = $this->table; + $Table = ucfirst($table); + + $APPOBJ = $this->appobj($table_value); + $APP_TABLE = $this->app_table_one; + + $ARR = $APPOBJ->ARR; + // Helper::dump($ARR); + $parameters['table'] = $table; + $parameters['table_value'] = (int)$table_value; + $parameters['nomTable'] = $APPOBJ->NAME_APP; + $export_values = []; + + // Helper::dump($APP_TABLE); + if (!empty($APP_TABLE['hasLigneScheme'])) { + $idae_liste = new Idae($table . '_ligne'); + $table_ligne = $idae_liste->liste(["id$table" => $table_value]); + $parameters ['html_fiche_ligne'] = $table_ligne; + } + + foreach ($APPOBJ->ARR_GROUP_FIELD as $key => $val) { + $arrg = $val['group']; + $arr_fields = $val['field']; + + $arr_fields = array_filter($arr_fields); + + $export_values[$key] = []; + foreach ($arr_fields as $keyf => $valf) { + if (empty($ARR[$valf['codeAppscheme_field'] . $Table])) { + continue; + } + + $export_key = ucfirst(idioma($valf['nomAppscheme_field'])); + $export_code = ucfirst($valf['codeAppscheme_field']); + $export_icon = $valf['iconAppscheme_field']; + $export_value = $this->draw_field(['field_name_raw' => $valf['codeAppscheme_field'], + 'table' => $table, + 'field_value' => $ARR[$valf['codeAppscheme_field'] . $Table]]); + + $export_values[$key][$export_code] = [$export_icon, + $export_key, + $export_value]; + } + } + $parameters ['var_fiche_main'] = array_filter($export_values); + + // GRILLE FK + $export_values_fk = []; + foreach ($APPOBJ->GRILLE_FK as $field): + $table_k = $field['table_fk']; + $Table_k = ucfirst($field['table_fk']); + // query for name if needed + if (empty($ARR['nom' . ucfirst($field['table_fk'])])) { + $arr = $this->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); + $dsp_code = $arr['code' . $Table_k]; + $dsp_name = $arr['nom' . $Table_k]; + + } else { + $dsp_code = $ARR['code' . $Table_k]; + $dsp_name = $ARR['nom' . $Table_k]; + } + if (empty($dsp_name) && empty($dsp_code)) { + continue; + } + $export_value_fk = []; + $export_value_fk['code ' . $Table_k] = $this->draw_field(['field_name_raw' => 'code', + 'table' => $table_k, + 'field_value' => $dsp_code]); + $export_value_fk['nom ' . $Table_k] = $this->draw_field(['field_name_raw' => 'nom', + 'table' => $table_k, + 'field_value' => $dsp_name]); + + $export_values_fk[$field['table_fk']] = $export_value_fk; + endforeach; + $parameters ['var_fiche_fk'] = array_filter($export_values_fk); + + // Statuts ++ + $export_values_state = []; + $arr_has = ['statut', + 'type', + 'categorie', + 'group']; + foreach ($arr_has as $key => $value): + $Value = ucfirst($value); + if (empty($APP_TABLE['has' . $Value . 'Scheme'])) { + continue; + } + $_table = $table . '_' . $value; + $_Table = ucfirst($_table); + $APPTMP = new App($_table); + $_id = 'id' . $_table; + $_nom = 'nom' . $_Table; + $_icon = 'icon' . $_Table; + $_code = 'code' . $_Table; + if (!empty($ARR[$_nom])): + // + $export_value_fk = []; + $export_value_fk['icon'] = $this->draw_field(['field_name_raw' => 'icon', + 'table' => $_table, + 'field_value' => $ARR[$_icon]]); + $export_value_fk['code'] = $this->draw_field(['field_name_raw' => 'code', + 'table' => $_table, + 'field_value' => $ARR[$_code]]); + $export_value_fk['nom'] = $this->draw_field(['field_name_raw' => 'nom', + 'table' => $_table, + 'field_value' => $ARR[$_nom]]); + $export_value_fk['color'] = $this->draw_field(['field_name_raw' => 'color', + 'table' => $_table, + 'field_value' => $ARR['color' . $_Table]]); + + $export_values_state[$_table] = $export_value_fk; + + // $rs_tmp = $APPTMP->find(); + // echo function_prod::draw_select_input($_table, $table_value); + endif; + if ($value == 'statut') { + $add_vars = []; + if ($_SESSION['livreur']) { + $add_vars = ['START', + 'RESERV', + 'LIVENCOU', + 'END']; + } + if ($_SESSION['shop']) { + $add_vars = ['START', + 'RESERV', + 'PREFIN']; + } + $step = (int)$ARR['ordre' . $_Table]; + $next_step = ++$step; + $arr_tmp = $APPTMP->find([$_code => ['$in' => $add_vars], + 'ordre' . $_Table => (int)$next_step])->getNext(); + + $next_idcommande_statut = $arr_tmp[$_id]; + $next_nomCommande_statut = $arr_tmp[$_nom]; + $next_icon_statut = $this->draw_field(['field_name_raw' => 'icon', + 'table' => $_table, + 'field_value' => $arr_tmp[$_icon]]); + $parameters['next_idcommande_statut'] = $next_idcommande_statut; + $parameters['next_icon_statut'] = $next_icon_statut; + $parameters['next_nomCommande_statut'] = $next_nomCommande_statut; + } + endforeach; + + $parameters ['var_fiche_state'] = array_filter($export_values_state); + // Helper::dump($parameters ['var_fiche_state']); + if (!empty($APP_TABLE['hasStatutScheme'])) { + $parameters ['html_fiche_statut'] = $LATTE->renderToString(APPTPL . "idae/fiche_statut.html", $parameters); + $parameters ['html_fiche_next_statut'] = $this->fiche_next_statut($table_value, true); + } + + if ($_SESSION['shop']) { + if ($this->table == 'produit') { + $parameters['html_edit_link'] = 'modifier'; + } + } + + if (!empty($APP_TABLE['hasImageScheme'])) { + $parameters ['html_fiche_image'] = $this->fiche_image($table_value, true); + } + echo $html = $LATTE->renderToString(APPTPL . "idae/fiche.html", $parameters); + + //Helper::dump($parameters); + } + /** + * @deprecated + */ + function liste($vars = []) { + global $LATTE; + + $table = $this->table; + $Table = ucfirst($table); + + $parameters['table'] = $table; + + array_walk_recursive($vars, 'CleanStr', $vars); + $vars = empty($vars) ? [] : function_prod::cleanPostMongo($vars, 1); + + $rs = $this->find($vars); + $arr = iterator_to_array($rs); + + $APP_HAS_FIELD = new App('appscheme_has_field'); + $APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); + $RS_HAS_TABLE_FIELD = $APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$this->idappscheme])->sort(['ordreAppscheme_has_table_field' => 1]); + $ARR_HAS_TABLE_FIELD = iterator_to_array($RS_HAS_TABLE_FIELD); + // has_totalAppscheme_field + $parameters['fields'] = $ARR_HAS_TABLE_FIELD; + $parameters['liste'] = $arr; + + return $html = $LATTE->renderToString(APPTPL . "idae/table.html", $parameters); + } + + function fiche_next_statut($table_value, $inner = false) { + + global $LATTE; + + $table = $this->table; + $Table = ucfirst($table); + + $APPOBJ = $this->appobj((int)$table_value); + $ARR = $APPOBJ->ARR; + $APP_TABLE = $APPOBJ->APP_TABLE; + if (empty($APP_TABLE['hasStatutScheme'])) { + return false; + } + if (!empty($_SESSION['type_session'])) { + $type_session = $_SESSION['type_session']; + $name_idtype_session = "id$type_session"; + $idtype_session = (int)$_SESSION[$name_idtype_session]; + if (!empty($APPOBJ->$name_idtype_session) && $APPOBJ->$name_idtype_session != $idtype_session) { + return false; + } + if ($type_session == 'livreur') { + if (!empty($ARR[$name_idtype_session]) && $ARR[$name_idtype_session] != $idtype_session) return false; + } + } + $parameters = $ARR; + $parameters['table'] = $table; + $parameters['table_value'] = (int)$table_value; + $parameters['session_idlivreur'] = $idtype_session; + $export_values = []; + + // Statuts ++ + $export_values_state = []; + $arr_has = ['statut']; + $value = 'statut'; + + $Value = ucfirst($value); + $_table = $table . '_' . $value; + $_Table = ucfirst($_table); + $APPTMP = new App($_table); + $_id = 'id' . $_table; + $_nom = 'nom' . $_Table; + $_icon = 'icon' . $_Table; + $_code = 'code' . $_Table; + $_color = 'color' . $_Table; + + $add_vars = []; + if ($_SESSION['livreur']) { + $add_vars = ['START', + 'RESERV', + 'LIVENCOU', + 'END']; // 'LIVENCOU', + } + if ($_SESSION['shop']) { + $add_vars = ['START', + 'RUN', + 'PREFIN']; + } + $step = (int)$ARR['ordre' . $_Table]; + $next_step = ++$step; + $arr_tmp = $APPTMP->find([$_code => ['$in' => $add_vars], + 'ordre' . $_Table => (int)$next_step])->getNext(); + + $next_idcommande_statut = $arr_tmp[$_id]; + $next_nomCommande_statut = $arr_tmp[$_nom]; + $next_colorCommande_statut = $arr_tmp[$_color]; + $next_icon_statut = $this->draw_field(['field_name_raw' => 'icon', + 'table' => $_table, + 'field_value' => $arr_tmp[$_icon]]); + + $parameters['next_idcommande_statut'] = $next_idcommande_statut; + $parameters['next_icon_statut'] = $next_icon_statut; + $parameters['next_nomCommande_statut'] = $next_nomCommande_statut; + $parameters['next_colorCommande_statut'] = $next_colorCommande_statut; + $parameters['codeCommande_statut'] = $ARR['code' . $_Table]; + + $parameters['idsecteur'] = $ARR['idsecteur']; + $LATTE->setAutoRefresh(true); + + if ($inner) { + return $html = $LATTE->renderToString(APPTPL . "idae/fiche_next_statut.html", $parameters); + + } else { + echo $html = $LATTE->renderToString(APPTPL . "idae/fiche_next_statut.html", $parameters); + } + } + /** + * @deprecated + */ + function fiche_image($table_value, $inner = false) { + global $LATTE; + + $table = $this->table; + $Table = ucfirst($table); + + $parameters['table'] = $table; + $parameters['table_value'] = (int)$table_value; + + $AppSite = new AppSite(); + $arr_tpl = $AppSite->makeTplData($table, $table_value); + $parameters['fiche_image'] = $arr_tpl; + + if ($inner) { + return $html = $LATTE->renderToString(APPTPL . "idae/fiche_image.html", $parameters); + + } else { + echo $html = $LATTE->renderToString(APPTPL . "idae/fiche_image.html", $parameters); + } + } + + /** + * @param null $table_value + * @param array $arr_vars + * + * @return array + * + * @deprecated + */ + public function get_table_fields($table_value = null, $arr_vars = []) { + $table = $this->table;; + $Table = ucfirst($table); + + $vars = empty($arr_vars['vars']) ? [] : function_prod::cleanPostMongo($arr_vars['vars'], 1); + // + $APP_FIELD = new App('appscheme_field'); + $APP_FIELD_GROUP = new App('appscheme_field_group'); + $APP_HAS_FIELD = new App('appscheme_has_field'); + + $APPOBJ = $this->appobj($table_value, $vars); + $ARR = $APPOBJ->ARR; + $idappscheme = $this->idappscheme; + + $DIST_FIELD_FILTER = []; + $DIST_NOFIELD_FILTER = []; + if (!empty($arr_vars['codeAppscheme_field'])) { + $DIST_FIELD_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field' => ['$in' => (array)$arr_vars['codeAppscheme_field']]]); + $DIST_FIELD_FILTER = array_merge($DIST_FIELD_FILTER_APP, $DIST_FIELD_FILTER); + } + if (!empty($arr_vars['nocodeAppscheme_field'])) { + $DIST_FIELD_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field' => ['$in' => (array)$arr_vars['nocodeAppscheme_field']]]); + $DIST_NOFIELD_FILTER = array_merge($DIST_FIELD_FILTER_APP, $DIST_NOFIELD_FILTER); + } + $DIST_FIELD_TYPE_FILTER = []; + if (!empty($arr_vars['codeAppscheme_field_type'])) { + $DIST_FIELD_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field_type' => $arr_vars['codeAppscheme_field_type']]); + $DIST_FIELD_TYPE_FILTER = array_merge($DIST_FIELD_FILTER_APP, $DIST_FIELD_TYPE_FILTER); + } + $DIST_GROUP_FILTER = []; + if (!empty($arr_vars['codeAppscheme_field_group'])) { + if (is_array($arr_vars['codeAppscheme_field_group'])) { + $DIST_GROUP_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field_group' => ['$in' => $arr_vars['codeAppscheme_field_group']]]); + } else { + $DIST_GROUP_FILTER_APP = $APP_FIELD->distinct_all('idappscheme_field', ['codeAppscheme_field_group' => $arr_vars['codeAppscheme_field_group']]); + } + $DIST_GROUP_FILTER = array_merge($DIST_GROUP_FILTER_APP, $DIST_GROUP_FILTER); + } + // + $ARGS = ['idappscheme' => $idappscheme]; + if (!empty($DIST_FIELD_FILTER)) { + $ARGS['idappscheme_field'] = ['$in' => $DIST_FIELD_FILTER]; + } + if (!empty($DIST_NOFIELD_FILTER)) { + $ARGS['idappscheme_field'] = ['$nin' => $DIST_NOFIELD_FILTER]; + } + if (!empty($DIST_FIELD_TYPE_FILTER)) { + $ARGS['idappscheme_field'] = ['$in' => $DIST_FIELD_TYPE_FILTER]; + } + if (!empty($DIST_FIELD_TYPE_FILTER)) { + $ARGS['idappscheme_field'] = ['$in' => $DIST_FIELD_TYPE_FILTER]; + } + if (isset($arr_vars['in_mini_fiche'])) { + $ARGS['in_mini_fiche'] = $arr_vars['in_mini_fiche']; + } + $ARGS_GROUP = []; + if (!empty($DIST_GROUP_FILTER)) { + $ARGS_GROUP['idappscheme_field'] = ['$in' => $DIST_GROUP_FILTER]; + } + $RS_HAS_FIELD = $APP_HAS_FIELD->distinct_all('idappscheme_field', $ARGS); + + $DIST_FIELD_GROUP = $APP_FIELD->distinct_all('idappscheme_field_group', $ARGS_GROUP + ['idappscheme_field' => ['$in' => $RS_HAS_FIELD]]); + $RS_FIELD_GROUP = $APP_FIELD_GROUP->find(['idappscheme_field_group' => ['$in' => $DIST_FIELD_GROUP]])->sort(['ordreAppscheme_field_group' => 1]); + $COLLECT = []; + foreach ($RS_FIELD_GROUP as $key => $ARR_FIELD_GROUP) { + $idappscheme_field_group = (int)$ARR_FIELD_GROUP['idappscheme_field_group']; + $RS_FIELD = $APP_FIELD->find(['idappscheme_field_group' => $idappscheme_field_group, + 'idappscheme_field' => ['$in' => $RS_HAS_FIELD]]); + $COLLECT[$key]['appscheme_field_group'] = $ARR_FIELD_GROUP; + foreach ($RS_FIELD as $keyf => $ARR_FIELD) { + /*if (!empty($arr_vars['show_empty'])) { + if (!isset($ARR[$ARR_FIELD['codeAppscheme_field'] . $Table])) continue; + }*/ + $code = $ARR_FIELD['codeAppscheme_field']; + $COLLECT[$key]['appscheme_fields'][$code]['css_bold'] = in_array($code, ['nom', + 'code']) ? 'text-bold' : ''; + foreach (['nom', + 'petitNom', + 'icon', + 'color'] as $keyff => $valuef) { + $COLLECT[$key]['appscheme_fields'][$code][$valuef] = $ARR_FIELD[$valuef . 'Appscheme_field']; + + } + $COLLECT[$key]['appscheme_fields'][$code]['value_raw'] = $ARR[$ARR_FIELD['codeAppscheme_field'] . $Table]; + $COLLECT[$key]['appscheme_fields'][$code]['value_html'] = $this->draw_field(['field_name_raw' => $ARR_FIELD['codeAppscheme_field'], + 'table' => $table, + 'field_value' => $ARR[$ARR_FIELD['codeAppscheme_field'] . $Table]]); + $COLLECT[$key]['appscheme_fields'][$code]['value_input'] = $this->draw_field_input(['field_name_raw' => $ARR_FIELD['codeAppscheme_field'], + 'table' => $table, + 'field_value' => ($ARR_FIELD['codeAppscheme_field'] != 'password') ? $ARR[$ARR_FIELD['codeAppscheme_field'] . $Table] : '']); + + } + } + + return $COLLECT; + } + + function get_fk_fields($table_value = null, $arr_vars = []) { // grille_fk + $APPOBJ = $this->appobj($table_value, $arr_vars); + $ARR = $APPOBJ->ARR; + $COLLECT = []; + foreach ($this->get_grille_fk() as $field): + // query for name + $arr = $this->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); + $dsp_code = $arr['code' . ucfirst($field['table_fk'])]; + $dsp_name = $arr['nom' . ucfirst($field['table_fk'])]; + if (empty($dsp_name)) continue; + $table = $field['table_fk']; + $table_value = $ARR[$field['idtable_fk']]; + $COLLECT[$dsp_code]['table'] = $table; + $COLLECT[$dsp_code]['table_value'] = $table_value; + $COLLECT[$dsp_code]['value_html'] = $table_value; + $COLLECT[$dsp_code]['value_mdl'] = $table_value; + $COLLECT[$dsp_code]['value_input'] = $table; + endforeach; + + return $COLLECT; + } + + public function liste_titre($arr_vars = []) { + + $out_vars = []; + $APP_SCH = new App('appscheme'); + $APP = new App('appscheme_has_field'); + if (!empty($arr_vars['vars'])) { + $arr_vars += $arr_vars['vars']; + unset($arr_vars['vars']); + } + foreach ($arr_vars as $name_vars => $value_vars): + $ARR = $APP->findOne(['codeAppscheme_has_field' => $name_vars]); + if ($ARR['_id'] != ''): + $out_vars[] = $ARR['nomAppscheme_field'] . ' ' . $ARR['nomAppscheme'] . ' : ' . $value_vars; + else: + $table = str_replace('id', '', $name_vars); + $ARR = $APP_SCH->findOne(['codeAppscheme' => $table]); + if ($ARR['_id'] != ''): + $APP_TMP = new App($table); + $ARR_TMP = $APP_TMP->findOne([$name_vars => (int)$value_vars]); + if (empty($ARR_TMP['nom' . ucfirst($table)])) continue; + $out_vars[] = ' ' . $ARR['nomAppscheme'] . ' : ' . $ARR_TMP['nom' . ucfirst($table)]; + endif; + endif; + + endforeach; + $out = implode('', $out_vars); + if (!empty($arr_vars['groupBy'])) $out .= ' groupé par : ' . $arr_vars['groupBy']; + if (!empty($arr_vars['sortBy'])) $out .= ' trié par : ' . $arr_vars['sortBy']; + if (!empty($arr_vars['search'])) $out .= ' Recherche : "' . $arr_vars['search'] . '"'; + + return $out; + } + + /** + * @param array $vars + * + * @return mixed + */ + public function liste_statut($vars = []) { + global $LATTE; + + $table = $this->table; + $Table = ucfirst($table); + + $APPOBJ = $this->appobj(); + $ARR = $APPOBJ->ARR; + + $parameters['table'] = []; + + $_table = $table . '_statut'; + $_Table = ucfirst($_table); + $APPTMP = new App($_table); + $_id = 'id' . $_table; + $_nom = 'nom' . $_Table; + $_icon = 'icon' . $_Table; + $_code = 'code' . $_Table; + $_ordre = 'ordre' . $_Table; + + $RS_STATUT = $APPTMP->find($vars)->sort([$_ordre => 1]); + + while ($ARR_STATUT = $RS_STATUT->getNext()) { + $add_vars = []; + $collect = []; + if ($_SESSION['livreur']) { + $add_vars = ['START', + 'RESERV', + 'LIVENCOU', + 'END']; + } + if ($_SESSION['shop']) { + $add_vars = ['START', + 'RUN', + 'PREFIN']; + } + $arr_has = ['icon', + 'nom', + 'code', + 'color']; + + $collect["id"] = $ARR_STATUT[$_id]; + $collect["id" . $_table] = $ARR_STATUT[$_id]; + foreach ($arr_has as $keyh => $valueh): + $collect[$valueh] = $this->draw_field(['field_name' => $valueh . $_table, + 'field_name_raw' => $valueh, + 'table' => $_table, + 'field_value' => $ARR_STATUT[$valueh . $_Table]]); + endforeach; + + $step = (int)$ARR['ordre' . $_Table]; + $next_step = ++$step; + $arr_tmp = $APPTMP->find([$_code => ['$in' => $add_vars], + 'ordre' . $_Table => (int)$next_step])->getNext(); + + $next_idcommande_statut = $arr_tmp[$_id]; + $next_nomCommande_statut = $arr_tmp[$_nom]; + $next_icon_statut = $this->draw_field(['field_name_raw' => 'icon', + 'table' => $_table, + 'field_value' => $arr_tmp[$_icon]]); + + $collect['next_idcommande_statut'] = $next_idcommande_statut; + $collect['next_icon_statut'] = $next_icon_statut; + $collect['next_nom' . $table . '_statut'] = $next_nomCommande_statut; + $collect['codeCommande_statut'] = $ARR['code' . $_Table]; + + $parameters[] = $collect; + + } + + return $parameters; + } + + /** + * @param string $module + * @param array $http_vars + * + * @deprecated + */ + public function module($module, $http_vars = []) { + + $type_session = $_SESSION['type_session']; + $name_idtype_session = "id$type_session"; + $idtype_session = (int)$_SESSION[$name_idtype_session]; + $APP_SESSION = new App($type_session); + global $ARR_SESSION; + $ARR_SESSION = $APP_SESSION->findOne([$name_idtype_session => $idtype_session]); + if (empty($_POST)) { + // $_POST = []; + } + if (!empty($_GET)) { + $_POST = array_merge($_GET, $_POST);; + } + if (is_array($http_vars)) { + $_POST = array_merge($_POST, $http_vars); + $this->HTTP_VARS = array_merge($_POST, $http_vars); + } else { + parse_str($http_vars, $_POST); + $this->HTTP_VARS = $_POST; + } + $attr = ''; + if (!empty($this->table)) { + $table = $this->table; + $attr .= "data-table='$table' "; + $attr .= "data-crypted_table='" . encrypt_url($table) . "' "; + } elseif (!empty($this->HTTP_VARS['table'])) { + $table = $this->HTTP_VARS['table']; + $this->set_table($table); + $attr .= "data-table='$table' "; + $attr .= "data-crypted_table='" . encrypt_url($table) . "' "; + + } + if (!empty($this->HTTP_VARS['table_value'])) { + $table_value = $this->HTTP_VARS['table_value']; + $attr .= "data-table_value='$table_value' "; + $attr .= "data-crypted_table_value='" . encrypt_url($table_value) . "' "; + + } + + if (!empty($this->table)) { + if ($this->has_field_fk($type_session)) { + $this->HTTP_VARS['vars'][$name_idtype_session] = $idtype_session; + } + if ($this->grilleFK && $APP_SESSION->grilleFK) { + $intersect_fk = array_intersect(array_column($this->grilleFK, 'table'), array_column($APP_SESSION->grilleFK, 'table')); + if (sizeof($intersect_fk != 0)) { + $vars = []; + foreach ($intersect_fk as $key_ifk => $value_fk) { + if (!empty($ARR_SESSION["id$value_fk"])) $this->HTTP_VARS['vars']["id$value_fk"] = (int)$ARR_SESSION["id$value_fk"]; + } + } + + } + } + + $this->module_route = "idae/module/$module"; + + $attr .= 'data-vars="' . http_build_query($this->HTTP_VARS) . '" '; + $attr .= 'data-crypted_vars="' . encrypt_url(http_build_query($this->HTTP_VARS)) . '" '; + + $attr = html_entity_decode($attr); + + $moduleTag = 'module'; + $start = ($moduleTag != 'none') ? "<$moduleTag data-mdl='idae/module/$module' $attr title='module=$module' value='red' >" : ""; // + $end = ($moduleTag != 'none') ? "" : ""; + + $arr_mdl = explode('/', $module); + $file = end($arr_mdl); + array_pop($arr_mdl); + $path = implode('/', $arr_mdl); + + $file_1 = APPMDL . 'app/app_' . $module . '.php'; + $file_2 = APPMDL . 'app/' . $module . '.php'; + $file_3 = APPMDL . 'app/' . $path . '/app_' . $file . '.php'; + $file_4 = APPMDL . 'app/' . $path . '/' . $file . '.php'; + + if (!empty($table)) { + $a = 'app_custom/' . $table . '/' . $table . '_' . $file; + $test_custom = Idae::module_exists('app_custom/' . $table . '/' . $table . '_' . $file); + if (!empty($test_custom)) { + $Idae_tmp = new Idae($table); + + return $Idae_tmp->module('app_custom/' . $table . '/' . $table . '_' . $file, $this->HTTP_VARS); + } + } + + ob_start(); + + if (file_exists($file_1)) { + include($file_1); + } elseif (file_exists($file_2)) { + include($file_2); + } elseif (file_exists($file_3)) { + include($file_3); + } elseif (file_exists($file_4)) { + include($file_4); + } else { + echo "missing module $module
"; + } + $final = ob_get_contents(); + $final = $start . $final . $end; + ob_end_clean(); + + return trim($final); + } + + public static function getInstance($table = '') { + + if (is_null(self::$_instance)) { + self::$_instance = new Idae($table); + } else if (!is_null(self::$_instance) && self::$_instance->table = $table) { + self::$_instance = new Idae($table); + } + + return self::$_instance; + } } \ No newline at end of file diff --git a/web/bin/classes/ClassIdaeAction.php b/web/bin/classes/ClassIdaeAction.php index e70cb93..ab3d695 100644 --- a/web/bin/classes/ClassIdaeAction.php +++ b/web/bin/classes/ClassIdaeAction.php @@ -1,277 +1,277 @@ -table; - $Table = ucfirst($this->table); - - $update_vars['dateCreation' . ucfirst($table)] = date('Y-m-d'); - $update_vars['heureCreation' . ucfirst($table)] = date('H:i:s'); - $update_vars['timeCreation' . ucfirst($table)] = time(); - // - $vars = empty($update_vars) ? [] : function_prod::cleanPostMongo($update_vars, 1); - // INSERT - $APP_TABLE = new App($table); - $table_value = $APP_TABLE->insert($vars); - $arr = $APP_TABLE->findOne(["id$table" => $table_value]); - AppSocket::send_cmd('act_add_data', $arr, 'OWN'); - - if (sizeof($arr) != 0) { - SendCmd::notify_mdl('app_fiche_mini', $table, $arr["id$table"], [], session_id()); - } - - echo json_encode($arr, JSON_FORCE_OBJECT); - } - - function app_update_silent($table_value = null, $update_vars = []) { - $this->app_update($table_value, $update_vars, true); - } - - function app_update($table_value = null, $update_vars = [], $silent = false) { - if (empty($table_value)) { - return; - } - $table = $this->table; - $table_value = (int)$table_value; - $name_id = 'id' . $this->table; - $Table = ucfirst($this->table); - - array_walk_recursive($update_vars, 'CleanStr', $update_vars); - $vars = empty($update_vars) ? [] : function_prod::cleanPostMongo($update_vars, 1); - - $arr_one = $this->findOne([$name_id => $table_value]); - - if (isset($vars['password' . $Table]) && empty(trim($vars['password' . $Table]))) { - unset($vars['password' . $Table]); - } - - // assignation livreur - if ($table == 'commande' && empty($arr_one['idlivreur']) && !empty($vars['idlivreur'])) { - $BIN = new Bin(); - $test = $BIN->test_delivery_reserv(['idcommande' => $table_value, - 'idlivreur' => (int)$vars['idlivreur']]); - - if ($test == false) return false; - - if ($test['err'] == 1) { - $Dispatch = new Dispatch(); - $Dispatch->remove_propose_commande_coursier($table_value, $vars['idlivreur']); - - SendCmd::notify_mdl('/app_gui/app_notify', $table, $table_value, $test, session_id()); - - return false; - } - // statut - $APP_COMMANDE_STATUT = new App('commande_statut'); - // statut + livreur - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'RESERV']); - if ((int)$arr_one['ordreCommande_statut'] < (int)$arr_commande_statut['ordreCommande_statut']) { - // statut "reserv" seulement si pas deja avancée - $vars['idcommande_statut'] = (int)$arr_commande_statut['idcommande_statut']; - $vars['ordreCommande_statut'] = (int)$arr_commande_statut['ordreCommande_statut']; - $vars['codeCommande_statut'] = 'RESERV'; - } - // commande facture - $APP_CMD_FACT = new App('commande_facture'); - $APP_CMD_FACT->update_native(['idcommande' => $table_value], ['idlivreur' => (int)$vars['idlivreur']]); - - $vars['idlivreur'] = $idlivreur = (int)$vars['idlivreur']; - $idcommande = $table_value; - $room_livreur = 'livreur_' . $idlivreur; - $html_vars = "table=commande&table_value=$idcommande"; - - } - /** - * UPDATE - */ - $updated_fields = $this->update([$name_id => $table_value], $vars); - - $postAction = new ActionPost($table); - $postAction->app_update($table,$table_value,$arr_one); - -/* if (!empty($_POST['data-reload']) && $table == 'commande') { - $data_reload = !empty($_POST['data-reload']) ? $_POST['data-reload'] : "idae/fiche_next_statut/$table/$table_value"; - AppSocket::reloadModule($data_reload, $table_value); - } - if ($_POST['data-remove']) { - AppSocket::reloadModule($_POST['data-remove'], $table_value); - } - if ($table == 'livreur_affectation' && isset($update_vars['actifLivreur_affectation']) && isset($update_vars['idsecteur'])) { - $Notify = new Notify(); - $Notify->notify_livreur_affect($update_vars['idsecteur']); - } - if ($table == 'shop' && isset($update_vars['tempsAttenteShop'])) { - $Notify = new Notify(); - $Notify->notify_wait_time_secteur($arr_one['idsecteur']); - } - if ($table == 'commande') { - $Notify = new Notify(); - $Notify->notify_commande_change((int)$table_value); - - $Demo = new Demo(); - $Demo->animate_step(['idcommande' => $table_value]); - - if (ENVIRONEMENT == 'PREPROD_LAN') { - if (!empty($arr_one['idlivreur'])) { - } - } - } - if ($table == 'commande' && !empty($vars[$name_id . '_statut'])) { - - $idshop = $arr_new['idshop']; - $Dispatch = new Dispatch(); - - if (!empty($vars['idcommande_statut'])) { - - $APP_COMMANDE_STATUT = new App('commande_statut'); - - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['idcommande_statut' => (int)$vars['idcommande_statut']]); - if ((int)$arr_one['ordreCommande_statut'] <> (int)$arr_commande_statut['ordreCommande_statut']) { - $Dispatch->propose_commande_statut($table_value); - - switch ($arr_commande_statut['codeCommande_statut']): - case 'RESERV'; - case 'LIVENCOU'; - SendCmd::play_sound("shop_$idshop"); - break; - case 'PREFIN'; - SendCmd::play_sound("livreur_$idlivreur"); - break; - endswitch; - } - } - - if ($table == 'commande' && empty($arr_one['idlivreur']) && !empty($vars['idlivreur'])) { - $Dispatch->remove_propose_commande($table_value); - } - - AppSocket::reloadMdlTest('fiche_next_statut_' . $arr_one['idsecteur'], '*'); - - $codeStatut = $arr_new['code' . $Table . '_statut']; - - if (ENVIRONEMENT == 'PREPROD_LAN') { - - } - if ($codeStatut == 'LIVENCOU' && ($arr_one['demo_mode'] != 1)) { - - $apiKey = "9635f9c81664a3d549b4e76f1211963a7595bc88"; - $smspartner = new SMSPartnerAPI(false); - $result = $smspartner->checkCredits("?apiKey=$apiKey"); - $phoneNumber = ($arr_one['demo_mode'] == 1) ? '0688096140' : $arr_one['telephoneCommande']; - - $fields = ["apiKey" => $apiKey, - "phoneNumbers" => $phoneNumber, - "message" => "La livraison de votre commande est en cours", - "sender" => "TACTACITY"]; - - $result = $smspartner->sendSms($fields); - } - if ($codeStatut == 'END') { - $Dispatch = new Dispatch(); - $Dispatch->remove_commande($table_value); - } - }*/ - - if (!$silent) { - if (sizeof($updated_fields) != 0) { - SendCmd::notify_mdl('app_fiche/app_fiche_updated', $table, $table_value, [], session_id()); - } - } - - echo json_encode($updated_fields, JSON_PRETTY_PRINT); - } - - function app_delete($table_value = null) { - if (empty($table_value)) return false; - $table = $_REQUEST['table']; - $table_value = (int)$_REQUEST['table_value']; - - $vars = ['table' => $table, - 'table_value' => $table_value]; - AppSocket::send_cmd('act_close_mdl', $vars); - } - - function app_img_delete($table_value = null, $update_vars = []) { - - $APP = IdaeConnect::getInstance(); - $base = $_REQUEST['base'] ?: 'sitebase_image'; - $db = $APP->plug_base($base); - $grid = empty($collection) ? $db->getGridFs() : $db->getGridFs($collection); - $grid->remove(['filename' => $_REQUEST['fileName']]); - $grid->remove(['filename' => $_REQUEST['fileName'] . ".jpg"]); - - SendCmd::sendScript('reloadModule', ['idae/module/app_img_dyn']); - } - - function upload_img($table_value = null, $update_vars = []) { - - global $IMG_SIZE_ARR; - - $table = $this->table; - $table_value = (int)$table_value; - - $bytes = file_get_contents($_FILES['files']['tmp_name'][0]); - $arr_type = explode('.', $_FILES['files']['name'][0]); - $ext = strtolower(end($arr_type)); - $codeTailleImage = $_POST['size']; - $codeImage = empty($_POST['codeImage']) ? $table . '-' . strtolower($codeTailleImage) . '-' . $table_value : $_POST['codeImage']; - $width = $IMG_SIZE_ARR[$codeTailleImage][0]; - $height = $IMG_SIZE_ARR[$codeTailleImage][1]; - - $file_name = empty($_POST['keep_file_name']) ? $codeImage . '.' . strtolower($ext) : $_FILES['files']['name'][0]; - $real_filename = $_FILES['files']['name'][0]; - - $base = empty($_POST['base']) ? 'sitebase_image' : $_POST['base']; - $collection = empty($_POST['collection']) ? 'fs' : $_POST['collection']; - - // Taille demandée - $Rz['width'] = $width; - $Rz['height'] = $height; - $ins = ['table' => $table, - 'table_value' => $table_value, - 'tag' => $table, - 'codeTailleImage' => $codeTailleImage, - 'filename' => $file_name, - 'real_filename' => $real_filename, - 'width' => $width, - 'height' => $height]; - - $resized_bytes = IdaeImage::thumbImageBytes($bytes, $Rz); - IdaeImage::saveImageBytes($file_name, $resized_bytes, $ins, $base, $collection); - SendCmd::sendScript('reloadModule', ['idae/module/app_img_dyn']); - - // THUMB - $new_file_name = str_replace($codeTailleImage, 'thumb', $file_name); - - $ins_thumb = ['table' => $table, - 'table_value' => $table_value, - 'codeTailleImage' => 'thumb', - 'thumb' => 1, - 'filename' => $new_file_name, - 'real_filename' => $real_filename, - 'tag' => $table, - 'width' => 50, - 'height' => 50]; - - $Rz['width'] = 50; - $Rz['height'] = 50; - $smallbytes = IdaeImage::thumbImageBytes($bytes, $Rz); - IdaeImage::saveImageBytes($new_file_name, $smallbytes, $ins_thumb, $base, $collection); - - IdaeDataSchemeImage::buildImageSizes($table, $table_value, $codeTailleImage, $base, $collection); - - } +table; + $Table = ucfirst($this->table); + + $update_vars['dateCreation' . ucfirst($table)] = date('Y-m-d'); + $update_vars['heureCreation' . ucfirst($table)] = date('H:i:s'); + $update_vars['timeCreation' . ucfirst($table)] = time(); + // + $vars = empty($update_vars) ? [] : function_prod::cleanPostMongo($update_vars, 1); + // INSERT + $APP_TABLE = new App($table); + $table_value = $APP_TABLE->insert($vars); + $arr = $APP_TABLE->findOne(["id$table" => $table_value]); + AppSocket::send_cmd('act_add_data', $arr, 'OWN'); + + if (sizeof($arr) != 0) { + SendCmd::notify_mdl('app_fiche_mini', $table, $arr["id$table"], [], session_id()); + } + + echo json_encode($arr, JSON_FORCE_OBJECT); + } + + function app_update_silent($table_value = null, $update_vars = []) { + $this->app_update($table_value, $update_vars, true); + } + + function app_update($table_value = null, $update_vars = [], $silent = false) { + if (empty($table_value)) { + return; + } + $table = $this->table; + $table_value = (int)$table_value; + $name_id = 'id' . $this->table; + $Table = ucfirst($this->table); + + array_walk_recursive($update_vars, 'CleanStr', $update_vars); + $vars = empty($update_vars) ? [] : function_prod::cleanPostMongo($update_vars, 1); + + $arr_one = $this->findOne([$name_id => $table_value]); + + if (isset($vars['password' . $Table]) && empty(trim($vars['password' . $Table]))) { + unset($vars['password' . $Table]); + } + + // assignation livreur + if ($table == 'commande' && empty($arr_one['idlivreur']) && !empty($vars['idlivreur'])) { + $BIN = new Bin(); + $test = $BIN->test_delivery_reserv(['idcommande' => $table_value, + 'idlivreur' => (int)$vars['idlivreur']]); + + if ($test == false) return false; + + if ($test['err'] == 1) { + $Dispatch = new Dispatch(); + $Dispatch->remove_propose_commande_coursier($table_value, $vars['idlivreur']); + + SendCmd::notify_mdl('/app_gui/app_notify', $table, $table_value, $test, session_id()); + + return false; + } + // statut + $APP_COMMANDE_STATUT = new App('commande_statut'); + // statut + livreur + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'RESERV']); + if ((int)$arr_one['ordreCommande_statut'] < (int)$arr_commande_statut['ordreCommande_statut']) { + // statut "reserv" seulement si pas deja avancée + $vars['idcommande_statut'] = (int)$arr_commande_statut['idcommande_statut']; + $vars['ordreCommande_statut'] = (int)$arr_commande_statut['ordreCommande_statut']; + $vars['codeCommande_statut'] = 'RESERV'; + } + // commande facture + $APP_CMD_FACT = new App('commande_facture'); + $APP_CMD_FACT->update_native(['idcommande' => $table_value], ['idlivreur' => (int)$vars['idlivreur']]); + + $vars['idlivreur'] = $idlivreur = (int)$vars['idlivreur']; + $idcommande = $table_value; + $room_livreur = 'livreur_' . $idlivreur; + $html_vars = "table=commande&table_value=$idcommande"; + + } + /** + * UPDATE + */ + $updated_fields = $this->update([$name_id => $table_value], $vars); + + $postAction = new ActionPost($table); + $postAction->app_update($table,$table_value,$arr_one); + +/* if (!empty($_POST['data-reload']) && $table == 'commande') { + $data_reload = !empty($_POST['data-reload']) ? $_POST['data-reload'] : "idae/fiche_next_statut/$table/$table_value"; + AppSocket::reloadModule($data_reload, $table_value); + } + if ($_POST['data-remove']) { + AppSocket::reloadModule($_POST['data-remove'], $table_value); + } + if ($table == 'livreur_affectation' && isset($update_vars['actifLivreur_affectation']) && isset($update_vars['idsecteur'])) { + $Notify = new Notify(); + $Notify->notify_livreur_affect($update_vars['idsecteur']); + } + if ($table == 'shop' && isset($update_vars['tempsAttenteShop'])) { + $Notify = new Notify(); + $Notify->notify_wait_time_secteur($arr_one['idsecteur']); + } + if ($table == 'commande') { + $Notify = new Notify(); + $Notify->notify_commande_change((int)$table_value); + + $Demo = new Demo(); + $Demo->animate_step(['idcommande' => $table_value]); + + if (ENVIRONEMENT == 'PREPROD_LAN') { + if (!empty($arr_one['idlivreur'])) { + } + } + } + if ($table == 'commande' && !empty($vars[$name_id . '_statut'])) { + + $idshop = $arr_new['idshop']; + $Dispatch = new Dispatch(); + + if (!empty($vars['idcommande_statut'])) { + + $APP_COMMANDE_STATUT = new App('commande_statut'); + + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['idcommande_statut' => (int)$vars['idcommande_statut']]); + if ((int)$arr_one['ordreCommande_statut'] <> (int)$arr_commande_statut['ordreCommande_statut']) { + $Dispatch->propose_commande_statut($table_value); + + switch ($arr_commande_statut['codeCommande_statut']): + case 'RESERV'; + case 'LIVENCOU'; + SendCmd::play_sound("shop_$idshop"); + break; + case 'PREFIN'; + SendCmd::play_sound("livreur_$idlivreur"); + break; + endswitch; + } + } + + if ($table == 'commande' && empty($arr_one['idlivreur']) && !empty($vars['idlivreur'])) { + $Dispatch->remove_propose_commande($table_value); + } + + AppSocket::reloadMdlTest('fiche_next_statut_' . $arr_one['idsecteur'], '*'); + + $codeStatut = $arr_new['code' . $Table . '_statut']; + + if (ENVIRONEMENT == 'PREPROD_LAN') { + + } + if ($codeStatut == 'LIVENCOU' && ($arr_one['demo_mode'] != 1)) { + + $apiKey = "9635f9c81664a3d549b4e76f1211963a7595bc88"; + $smspartner = new SMSPartnerAPI(false); + $result = $smspartner->checkCredits("?apiKey=$apiKey"); + $phoneNumber = ($arr_one['demo_mode'] == 1) ? '0688096140' : $arr_one['telephoneCommande']; + + $fields = ["apiKey" => $apiKey, + "phoneNumbers" => $phoneNumber, + "message" => "La livraison de votre commande est en cours", + "sender" => "TACTACITY"]; + + $result = $smspartner->sendSms($fields); + } + if ($codeStatut == 'END') { + $Dispatch = new Dispatch(); + $Dispatch->remove_commande($table_value); + } + }*/ + + if (!$silent) { + if (sizeof($updated_fields) != 0) { + SendCmd::notify_mdl('app_fiche/app_fiche_updated', $table, $table_value, [], session_id()); + } + } + + echo json_encode($updated_fields, JSON_PRETTY_PRINT); + } + + function app_delete($table_value = null) { + if (empty($table_value)) return false; + $table = $_REQUEST['table']; + $table_value = (int)$_REQUEST['table_value']; + + $vars = ['table' => $table, + 'table_value' => $table_value]; + AppSocket::send_cmd('act_close_mdl', $vars); + } + + function app_img_delete($table_value = null, $update_vars = []) { + + $APP = IdaeConnect::getInstance(); + $base = $_REQUEST['base'] ?: 'sitebase_image'; + $db = $APP->plug_base($base); + $grid = empty($collection) ? $db->getGridFs() : $db->getGridFs($collection); + $grid->remove(['filename' => $_REQUEST['fileName']]); + $grid->remove(['filename' => $_REQUEST['fileName'] . ".jpg"]); + + SendCmd::sendScript('reloadModule', ['idae/module/app_img_dyn']); + } + + function upload_img($table_value = null, $update_vars = []) { + + global $IMG_SIZE_ARR; + + $table = $this->table; + $table_value = (int)$table_value; + + $bytes = file_get_contents($_FILES['files']['tmp_name'][0]); + $arr_type = explode('.', $_FILES['files']['name'][0]); + $ext = strtolower(end($arr_type)); + $codeTailleImage = $_POST['size']; + $codeImage = empty($_POST['codeImage']) ? $table . '-' . strtolower($codeTailleImage) . '-' . $table_value : $_POST['codeImage']; + $width = $IMG_SIZE_ARR[$codeTailleImage][0]; + $height = $IMG_SIZE_ARR[$codeTailleImage][1]; + + $file_name = empty($_POST['keep_file_name']) ? $codeImage . '.' . strtolower($ext) : $_FILES['files']['name'][0]; + $real_filename = $_FILES['files']['name'][0]; + + $base = empty($_POST['base']) ? 'sitebase_image' : $_POST['base']; + $collection = empty($_POST['collection']) ? 'fs' : $_POST['collection']; + + // Taille demandée + $Rz['width'] = $width; + $Rz['height'] = $height; + $ins = ['table' => $table, + 'table_value' => $table_value, + 'tag' => $table, + 'codeTailleImage' => $codeTailleImage, + 'filename' => $file_name, + 'real_filename' => $real_filename, + 'width' => $width, + 'height' => $height]; + + $resized_bytes = IdaeImage::thumbImageBytes($bytes, $Rz); + IdaeImage::saveImageBytes($file_name, $resized_bytes, $ins, $base, $collection); + SendCmd::sendScript('reloadModule', ['idae/module/app_img_dyn']); + + // THUMB + $new_file_name = str_replace($codeTailleImage, 'thumb', $file_name); + + $ins_thumb = ['table' => $table, + 'table_value' => $table_value, + 'codeTailleImage' => 'thumb', + 'thumb' => 1, + 'filename' => $new_file_name, + 'real_filename' => $real_filename, + 'tag' => $table, + 'width' => 50, + 'height' => 50]; + + $Rz['width'] = 50; + $Rz['height'] = 50; + $smallbytes = IdaeImage::thumbImageBytes($bytes, $Rz); + IdaeImage::saveImageBytes($new_file_name, $smallbytes, $ins_thumb, $base, $collection); + + IdaeDataSchemeImage::buildImageSizes($table, $table_value, $codeTailleImage, $base, $collection); + + } } \ No newline at end of file diff --git a/web/bin/classes/ClassIdaeImage.php b/web/bin/classes/ClassIdaeImage.php index 9a14fd5..b3a5a57 100644 --- a/web/bin/classes/ClassIdaeImage.php +++ b/web/bin/classes/ClassIdaeImage.php @@ -1,314 +1,314 @@ -setImageCompression(imagick::COMPRESSION_JPEG); - $im->setImageCompressionQuality(50); - $im->thumbnailImage($im->getImageWidth(), null); - $bytesOut = $im->getimageblob(); - - return $bytesOut; - } - - function imageBytesAnnotate($im, $vars = array('fillColor' => 'ffffff88', - 'opacity' => 60)) { - $draw = new ImagickDraw(); - $draw->setFillColor('#ffffff88'); - $draw->setFontSize(10); - //$im->annotateImage($draw , 40 , $height - 10 , 0 , "croisieres-maw.com"); - - $draw->setFillColor('#00000088'); - $draw->setFontSize(10); - - //$im->annotateImage($draw , 40 , $height - 9 , 0 , "croisieres-maw.com"); - - return $im; - } - - static function thumbImageBytes($bytes, $vars = array('width' => 120, - 'height' => 60)) { - $source_image = imagecreatefromstring($bytes); - $source_width = imagesx($source_image); - $source_height = imagesy($source_image); - $target_width = $vars['width']; - $target_height = $vars['height']; - - $source_aspect_ratio = $source_width / $source_height; - $desired_aspect_ratio = $target_width / $target_height; - - if ($source_aspect_ratio > $desired_aspect_ratio) { - /* - * Triggered when source image is wider - */ - $temp_height = $target_height; - $temp_width = ( int )($target_height * $source_aspect_ratio); - } else { - /* - * Triggered otherwise (i.e. source image is similar or taller) - */ - $temp_width = $target_width; - $temp_height = ( int )($target_width / $source_aspect_ratio); - } - /** - * Resize the image into a temporary GD image - */ - $temp_gdim = imagecreatetruecolor($temp_width, $temp_height); - imagecopyresampled($temp_gdim, $source_image, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height); - /** - * Copy cropped region from temporary image into the desired GD image - */ - $x0 = ($temp_width - $target_width) / 2; - $y0 = ($temp_height - $target_height) / 2; - $desired_gdim = imagecreatetruecolor($target_width, $target_height); - imagecopy($desired_gdim, $temp_gdim, 0, 0, $x0, $y0, $target_width, $target_height); - - ob_start(); - imagejpeg($desired_gdim); - $imageData = ob_get_contents(); - imagedestroy($temp_gdim); - imagedestroy($desired_gdim); - imagedestroy($source_image); - ob_end_clean(); - - return $imageData; - - } - - static function saveImageBytes($file_name, $bytes, $metadata = [], $base = 'sitebase_image', $collection = null) { - $APP = new App(); - $db = $APP->plug_base($base); - $grid = empty($collection) ? $db->getGridFs() : $db->getGridFs($collection); - $grid->remove(['filename' => $file_name]); - - $ins['filename'] = $file_name; - $ins['metadata'] = $metadata; - - return $grid->storeBytes($bytes, $ins); - } - - static function imageBytesResize($bytes, $vars = array('width' => 120, - 'height' => 60)) { - if (empty($bytes)) { - return; - } - $im = new \Imagick(); - $im->readImageBlob($bytes); - $im->setImageCompression(imagick::COMPRESSION_JPEG); - $im->setImageCompressionQuality(80); - $geo = $im->getImageGeometry(); - $width = $vars['width']; - $height = $vars['height']; - - if (($geo['width'] / $width) < ($geo['height'] / $height)) { - $im->cropImage($geo['width'], floor($height * $geo['width'] / $width), 0, (($geo['height'] - ($height * $geo['width'] / $width)) / 2)); - } else { - $im->cropImage(ceil($width * $geo['height'] / $height), $geo['height'], (($geo['width'] - ($width * $geo['height'] / $height)) / 2), 0); - } - //$im->charcoalImage (2,1); - $im->thumbnailImage($width, $height, true); - - $draw = new ImagickDraw(); - $draw->setFillColor('#ffffff88'); - $draw->setFontSize(10); - //$im->annotateImage($draw , 10 , $height - 10 , 0 , "croisieres-maw.com"); - - $bytesOut = $im->getimageblob(); - - return $bytesOut; - } - - static function gridImage($id, $col = 'appimg', $base = 'sitebase_base', $width = 120, $height = 60) { - $APP = new App(); - $grid = empty($col) ? $APP->plug_base($base)->getGridFs() : $APP->plug_base($base)->getGridFs($col); - $data = $grid->findOne(array('_id' => new MongoId($id))); - $im = new Imagick(); - $bytes = $data->getBytes(); - $im->readImageBlob($bytes); - $im->setImageCompression(imagick::COMPRESSION_JPEG); - $im->setImageCompressionQuality(80); - $im->thumbnailImage($width, $height, true); - $bytesOut = $im->getimageblob(); - - return $bytesOut; - } - - static function cropImage($id, $col = 'fs', $base = 'sitebase_image', $vars = array()) { - $APP = new App(); - $grid = empty($col) ? $APP->plug_base($base)->getGridFs() : $APP->plug_base($base)->getGridFs($col); - $data = $grid->findOne(array('_id' => new MongoId($id))); - - $im = new Imagick(); - $bytes = $data->getBytes(); - $im->readImageBlob($bytes); - $im->setImagePage(0, 0, 0, 0); - - $geo = $im->getImageGeometry(); - // <=> // taille ecran => - $im->thumbnailImage($vars['display_width'], $vars['display_height'], true); - // on crop now - $im->cropImage($vars['width'], $vars['height'], $vars['x1'], $vars['y1']); - $im->thumbnailImage($vars['final_width'], $vars['final_height'], true); - // taiile finale demandé (ratio ) - /* $im->cropImage($width,$height,$x,$y); - $im->thumbnailImage($fw,$fh,true);*/ - // - $im->adaptiveSharpenImage(2, 1); - // - $bytesOut = $im->getimageblob(); - - return $bytesOut; - } - - function thumbImage($name, $width = 120, $height = null) { - $im = new Imagick(); - $im->readImageBlob($name); - $im->setImageCompression(imagick::COMPRESSION_JPEG); - $im->setImageCompressionQuality(90); - $im->thumbnailImage($width, $height, true); - $bytesOut = $im->getimageblob(); - - return $bytesOut; - } - - function reflectImage($name) { - $outname = str_replace('.jpg', '_reflect.png', $name); - /* Lecture de l'image */ - clearstatcache(); - //if(!file_exists($name)) return false; - $AgetHeaders = @get_headers($name); - if (preg_match("|200|", $AgetHeaders[0])) { - // file exists - } else { - // file doesn't exists - return false; - } - $im = new Imagick($name); - // profile icc - //$icc_rgb = file_get_contents(PATHICC.'ISOcoated_v2_eci.icc'); - //$im->profileImage('icc', $icc_rgb); - //$im->setImageColorSpace(Imagick::COLORSPACE_RGB); - // - /* Thumbnail the image */ - $im->thumbnailImage($im->getImageWidth(), null); - $reflection = $im->clone(); - $reflection->flipImage(); - $gradient = new Imagick(); - $gradient->newPseudoImage($reflection->getImageWidth(), $reflection->getImageHeight() * 0.5, "gradient:transparent-black"); - $reflection->compositeImage($gradient, imagick::COMPOSITE_DSTOUT, 0, 0); - $gradient->newPseudoImage($reflection->getImageWidth(), $reflection->getImageHeight() * 0.5, "gradient:black"); - $reflection->compositeImage($gradient, imagick::COMPOSITE_DSTOUT, 0, $reflection->getImageHeight() * 0.5); - $opacity = new Imagick(); - $opacity->newImage($reflection->getImageWidth(), $reflection->getImageHeight(), new ImagickPixel('black')); - $opacity->setImageOpacity(0.4); - $reflection->compositeImage($opacity, imagick::COMPOSITE_DSTOUT, 0, 0); - - $canvas = new Imagick(); - - $width = $im->getImageWidth(); - $height = ($im->getImageHeight() * 1.5); - - $canvas->newImage($width, $height, 'none', "png"); - $canvas->compositeImage($im, imagick::COMPOSITE_SRCOVER, 0, 0); - $canvas->compositeImage($reflection, imagick::COMPOSITE_SRCOVER, 0, $im->getImageHeight()); - $bytesOut = $canvas->getimageblob(); - //$canvas->writeImage(PATHTMP.'destination.jpg'); - //echo $outname; - return $bytesOut; //$bytesOut; - } - - function makeThumb($file, $idd, $width = 250, $height = 120, $sizeName, $tag, $nameSizeFrom = 'large') { - IdaeImage::makeGdThumb($file, $width, $height, $sizeName, $tag, $nameSizeFrom); - - return; - $db = skelMongo::connectBase('sitebase_image'); //$con->sitebase_image; - $grid = $db->getGridFS(); - $thumb = str_replace($nameSizeFrom, $sizeName, $file); - $test = $grid->findOne($file); - if (!empty($test) && !empty($test->file['chunkSize'])) { - $image = $test->getBytes(); - $image = imagecreatefromstring($image); - $grid->remove(array('filename' => $thumb)); - // - $im = new Imagick(); - //echo $im->identifyImage($image); - //var_dump($im->getImageType($file)); exit; - // - //$im->readimageblob($image); - $geo = $im->getImageGeometry(); - if (($geo['width'] / $width) < ($geo['height'] / $height)) { - $im->cropImage($geo['width'], floor($height * $geo['width'] / $width), 0, (($geo['height'] - ($height * $geo['width'] / $width)) / 2)); - } else { - $im->cropImage(ceil($width * $geo['height'] / $height), $geo['height'], (($geo['width'] - ($width * $geo['height'] / $height)) / 2), 0); - } - //$im->charcoalImage (2,1); - $im->thumbnailImage($width, $height, true); - $bytesOut = $im->getimageblob(); - $myMeta = array('filename' => $thumb, - 'metadata' => array('width' => $width, - 'heigh' => $height, - 'tag' => $tag, - 'name' => $thumb, - 'size' => $sizeName, - 'mysqlid' => $idd, - 'contentType' => 'image/jpeg')); - $grid->storeBytes($bytesOut, $myMeta); - // echo "done ".$thumb; - } - } - // - // - // $file,$idd,$width=250,$height=120,$sizeName,$tag,$nameSizeFrom='large' - static function makeGdThumb($file, $thumb_width = 250, $thumb_height = 120, $sizeName, $tag, $nameSizeFrom = 'large', $metadata = []) { - // - $APP = new App(); - ob_start(); - $time = time(); - // - $db = $APP->plug_base('sitebase_image'); //$con->sitebase_image; - $grid = $db->getGridFS(); - $thumb = str_replace($nameSizeFrom, $sizeName, $file); - $jpgName = str_replace('.jpg', '', $thumb) . '.jpg'; - $test = $grid->findOne($file); - if (!file_exists(PATHTMP . 'GDTMP/')) { - @mkdir(PATHTMP . 'GDTMP/', 0777); - } - if (!empty($test) && !empty($test->file['chunkSize'])): - $image = $test->getBytes(); - $nametmp = PATHTMP . 'GDTMP/' . $time . '-' . $file . '-' . $sizeName; - $nameNewtmp = PATHTMP . 'GDTMP/' . $thumb; - file_put_contents($nametmp, $image); - $thumbNail = PhpThumbFactory::create($nametmp); - $thumbNail->adaptiveResize($thumb_width, $thumb_height)->save($nameNewtmp, 'jpg'); - $bytesOut = $thumbNail->getImageAsString(); - $grid->remove(array('filename' => $thumb)); - - $finalOut = file_get_contents($nameNewtmp); - $myMeta = array('filename' => $thumb, - 'uploadDate' => new MongoDate(), - 'metadata' => array_merge(array('time' => time(), - 'date' => date('Y-m-d'), - 'heure' => date('H:i:s'), - 'width' => $thumb_width, - 'heigh' => $thumb_height, - 'tag' => $tag, - 'table' => $tag, - 'mongoTag' => $tag, - 'filename' => $thumb, - 'real_filename' => $thumb, - 'size' => $sizeName), $metadata)); - $grid->storeBytes($finalOut, $myMeta, array('safe' => true)); - unlink($nametmp); - endif; - ob_end_clean(); - - return $thumb; - } - } - +setImageCompression(imagick::COMPRESSION_JPEG); + $im->setImageCompressionQuality(50); + $im->thumbnailImage($im->getImageWidth(), null); + $bytesOut = $im->getimageblob(); + + return $bytesOut; + } + + function imageBytesAnnotate($im, $vars = array('fillColor' => 'ffffff88', + 'opacity' => 60)) { + $draw = new ImagickDraw(); + $draw->setFillColor('#ffffff88'); + $draw->setFontSize(10); + //$im->annotateImage($draw , 40 , $height - 10 , 0 , "croisieres-maw.com"); + + $draw->setFillColor('#00000088'); + $draw->setFontSize(10); + + //$im->annotateImage($draw , 40 , $height - 9 , 0 , "croisieres-maw.com"); + + return $im; + } + + static function thumbImageBytes($bytes, $vars = array('width' => 120, + 'height' => 60)) { + $source_image = imagecreatefromstring($bytes); + $source_width = imagesx($source_image); + $source_height = imagesy($source_image); + $target_width = $vars['width']; + $target_height = $vars['height']; + + $source_aspect_ratio = $source_width / $source_height; + $desired_aspect_ratio = $target_width / $target_height; + + if ($source_aspect_ratio > $desired_aspect_ratio) { + /* + * Triggered when source image is wider + */ + $temp_height = $target_height; + $temp_width = ( int )($target_height * $source_aspect_ratio); + } else { + /* + * Triggered otherwise (i.e. source image is similar or taller) + */ + $temp_width = $target_width; + $temp_height = ( int )($target_width / $source_aspect_ratio); + } + /** + * Resize the image into a temporary GD image + */ + $temp_gdim = imagecreatetruecolor($temp_width, $temp_height); + imagecopyresampled($temp_gdim, $source_image, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height); + /** + * Copy cropped region from temporary image into the desired GD image + */ + $x0 = ($temp_width - $target_width) / 2; + $y0 = ($temp_height - $target_height) / 2; + $desired_gdim = imagecreatetruecolor($target_width, $target_height); + imagecopy($desired_gdim, $temp_gdim, 0, 0, $x0, $y0, $target_width, $target_height); + + ob_start(); + imagejpeg($desired_gdim); + $imageData = ob_get_contents(); + imagedestroy($temp_gdim); + imagedestroy($desired_gdim); + imagedestroy($source_image); + ob_end_clean(); + + return $imageData; + + } + + static function saveImageBytes($file_name, $bytes, $metadata = [], $base = 'sitebase_image', $collection = null) { + $APP = new App(); + $db = $APP->plug_base($base); + $grid = empty($collection) ? $db->getGridFs() : $db->getGridFs($collection); + $grid->remove(['filename' => $file_name]); + + $ins['filename'] = $file_name; + $ins['metadata'] = $metadata; + + return $grid->storeBytes($bytes, $ins); + } + + static function imageBytesResize($bytes, $vars = array('width' => 120, + 'height' => 60)) { + if (empty($bytes)) { + return; + } + $im = new \Imagick(); + $im->readImageBlob($bytes); + $im->setImageCompression(imagick::COMPRESSION_JPEG); + $im->setImageCompressionQuality(80); + $geo = $im->getImageGeometry(); + $width = $vars['width']; + $height = $vars['height']; + + if (($geo['width'] / $width) < ($geo['height'] / $height)) { + $im->cropImage($geo['width'], floor($height * $geo['width'] / $width), 0, (($geo['height'] - ($height * $geo['width'] / $width)) / 2)); + } else { + $im->cropImage(ceil($width * $geo['height'] / $height), $geo['height'], (($geo['width'] - ($width * $geo['height'] / $height)) / 2), 0); + } + //$im->charcoalImage (2,1); + $im->thumbnailImage($width, $height, true); + + $draw = new ImagickDraw(); + $draw->setFillColor('#ffffff88'); + $draw->setFontSize(10); + //$im->annotateImage($draw , 10 , $height - 10 , 0 , "croisieres-maw.com"); + + $bytesOut = $im->getimageblob(); + + return $bytesOut; + } + + static function gridImage($id, $col = 'appimg', $base = 'sitebase_base', $width = 120, $height = 60) { + $APP = new App(); + $grid = empty($col) ? $APP->plug_base($base)->getGridFs() : $APP->plug_base($base)->getGridFs($col); + $data = $grid->findOne(array('_id' => new MongoId($id))); + $im = new Imagick(); + $bytes = $data->getBytes(); + $im->readImageBlob($bytes); + $im->setImageCompression(imagick::COMPRESSION_JPEG); + $im->setImageCompressionQuality(80); + $im->thumbnailImage($width, $height, true); + $bytesOut = $im->getimageblob(); + + return $bytesOut; + } + + static function cropImage($id, $col = 'fs', $base = 'sitebase_image', $vars = array()) { + $APP = new App(); + $grid = empty($col) ? $APP->plug_base($base)->getGridFs() : $APP->plug_base($base)->getGridFs($col); + $data = $grid->findOne(array('_id' => new MongoId($id))); + + $im = new Imagick(); + $bytes = $data->getBytes(); + $im->readImageBlob($bytes); + $im->setImagePage(0, 0, 0, 0); + + $geo = $im->getImageGeometry(); + // <=> // taille ecran => + $im->thumbnailImage($vars['display_width'], $vars['display_height'], true); + // on crop now + $im->cropImage($vars['width'], $vars['height'], $vars['x1'], $vars['y1']); + $im->thumbnailImage($vars['final_width'], $vars['final_height'], true); + // taiile finale demandé (ratio ) + /* $im->cropImage($width,$height,$x,$y); + $im->thumbnailImage($fw,$fh,true);*/ + // + $im->adaptiveSharpenImage(2, 1); + // + $bytesOut = $im->getimageblob(); + + return $bytesOut; + } + + function thumbImage($name, $width = 120, $height = null) { + $im = new Imagick(); + $im->readImageBlob($name); + $im->setImageCompression(imagick::COMPRESSION_JPEG); + $im->setImageCompressionQuality(90); + $im->thumbnailImage($width, $height, true); + $bytesOut = $im->getimageblob(); + + return $bytesOut; + } + + function reflectImage($name) { + $outname = str_replace('.jpg', '_reflect.png', $name); + /* Lecture de l'image */ + clearstatcache(); + //if(!file_exists($name)) return false; + $AgetHeaders = @get_headers($name); + if (preg_match("|200|", $AgetHeaders[0])) { + // file exists + } else { + // file doesn't exists + return false; + } + $im = new Imagick($name); + // profile icc + //$icc_rgb = file_get_contents(PATHICC.'ISOcoated_v2_eci.icc'); + //$im->profileImage('icc', $icc_rgb); + //$im->setImageColorSpace(Imagick::COLORSPACE_RGB); + // + /* Thumbnail the image */ + $im->thumbnailImage($im->getImageWidth(), null); + $reflection = $im->clone(); + $reflection->flipImage(); + $gradient = new Imagick(); + $gradient->newPseudoImage($reflection->getImageWidth(), $reflection->getImageHeight() * 0.5, "gradient:transparent-black"); + $reflection->compositeImage($gradient, imagick::COMPOSITE_DSTOUT, 0, 0); + $gradient->newPseudoImage($reflection->getImageWidth(), $reflection->getImageHeight() * 0.5, "gradient:black"); + $reflection->compositeImage($gradient, imagick::COMPOSITE_DSTOUT, 0, $reflection->getImageHeight() * 0.5); + $opacity = new Imagick(); + $opacity->newImage($reflection->getImageWidth(), $reflection->getImageHeight(), new ImagickPixel('black')); + $opacity->setImageOpacity(0.4); + $reflection->compositeImage($opacity, imagick::COMPOSITE_DSTOUT, 0, 0); + + $canvas = new Imagick(); + + $width = $im->getImageWidth(); + $height = ($im->getImageHeight() * 1.5); + + $canvas->newImage($width, $height, 'none', "png"); + $canvas->compositeImage($im, imagick::COMPOSITE_SRCOVER, 0, 0); + $canvas->compositeImage($reflection, imagick::COMPOSITE_SRCOVER, 0, $im->getImageHeight()); + $bytesOut = $canvas->getimageblob(); + //$canvas->writeImage(PATHTMP.'destination.jpg'); + //echo $outname; + return $bytesOut; //$bytesOut; + } + + function makeThumb($file, $idd, $width = 250, $height = 120, $sizeName, $tag, $nameSizeFrom = 'large') { + IdaeImage::makeGdThumb($file, $width, $height, $sizeName, $tag, $nameSizeFrom); + + return; + $db = skelMongo::connectBase('sitebase_image'); //$con->sitebase_image; + $grid = $db->getGridFS(); + $thumb = str_replace($nameSizeFrom, $sizeName, $file); + $test = $grid->findOne($file); + if (!empty($test) && !empty($test->file['chunkSize'])) { + $image = $test->getBytes(); + $image = imagecreatefromstring($image); + $grid->remove(array('filename' => $thumb)); + // + $im = new Imagick(); + //echo $im->identifyImage($image); + //var_dump($im->getImageType($file)); exit; + // + //$im->readimageblob($image); + $geo = $im->getImageGeometry(); + if (($geo['width'] / $width) < ($geo['height'] / $height)) { + $im->cropImage($geo['width'], floor($height * $geo['width'] / $width), 0, (($geo['height'] - ($height * $geo['width'] / $width)) / 2)); + } else { + $im->cropImage(ceil($width * $geo['height'] / $height), $geo['height'], (($geo['width'] - ($width * $geo['height'] / $height)) / 2), 0); + } + //$im->charcoalImage (2,1); + $im->thumbnailImage($width, $height, true); + $bytesOut = $im->getimageblob(); + $myMeta = array('filename' => $thumb, + 'metadata' => array('width' => $width, + 'heigh' => $height, + 'tag' => $tag, + 'name' => $thumb, + 'size' => $sizeName, + 'mysqlid' => $idd, + 'contentType' => 'image/jpeg')); + $grid->storeBytes($bytesOut, $myMeta); + // echo "done ".$thumb; + } + } + // + // + // $file,$idd,$width=250,$height=120,$sizeName,$tag,$nameSizeFrom='large' + static function makeGdThumb($file, $thumb_width = 250, $thumb_height = 120, $sizeName, $tag, $nameSizeFrom = 'large', $metadata = []) { + // + $APP = new App(); + ob_start(); + $time = time(); + // + $db = $APP->plug_base('sitebase_image'); //$con->sitebase_image; + $grid = $db->getGridFS(); + $thumb = str_replace($nameSizeFrom, $sizeName, $file); + $jpgName = str_replace('.jpg', '', $thumb) . '.jpg'; + $test = $grid->findOne($file); + if (!file_exists(PATHTMP . 'GDTMP/')) { + @mkdir(PATHTMP . 'GDTMP/', 0777); + } + if (!empty($test) && !empty($test->file['chunkSize'])): + $image = $test->getBytes(); + $nametmp = PATHTMP . 'GDTMP/' . $time . '-' . $file . '-' . $sizeName; + $nameNewtmp = PATHTMP . 'GDTMP/' . $thumb; + file_put_contents($nametmp, $image); + $thumbNail = PhpThumbFactory::create($nametmp); + $thumbNail->adaptiveResize($thumb_width, $thumb_height)->save($nameNewtmp, 'jpg'); + $bytesOut = $thumbNail->getImageAsString(); + $grid->remove(array('filename' => $thumb)); + + $finalOut = file_get_contents($nameNewtmp); + $myMeta = array('filename' => $thumb, + 'uploadDate' => new MongoDate(), + 'metadata' => array_merge(array('time' => time(), + 'date' => date('Y-m-d'), + 'heure' => date('H:i:s'), + 'width' => $thumb_width, + 'heigh' => $thumb_height, + 'tag' => $tag, + 'table' => $tag, + 'mongoTag' => $tag, + 'filename' => $thumb, + 'real_filename' => $thumb, + 'size' => $sizeName), $metadata)); + $grid->storeBytes($finalOut, $myMeta, array('safe' => true)); + unlink($nametmp); + endif; + ob_end_clean(); + + return $thumb; + } + } + ?> \ No newline at end of file diff --git a/web/bin/classes/ClassInStyle.php b/web/bin/classes/ClassInStyle.php index 4f73d99..36c5bb7 100644 --- a/web/bin/classes/ClassInStyle.php +++ b/web/bin/classes/ClassInStyle.php @@ -1,132 +1,132 @@ -]+>(?[^<]+)<\/style>/s', $document, $matches); - - // If no CSS style - if (empty($matches)){ - return $document; - } - - // Strip out extra newlines and tabs from CSS - $css = preg_replace("/[\n\r\t]+/s", "", $matches['css']); - - // Extract each CSS declaration - preg_match_all('/([-a-zA-Z0-9_ ,#\.]+){([^}]+)}/s', $css, $rules, PREG_SET_ORDER); - - // For each CSS declaration, make the selector and style declaration into an array - // Array index 1 is the CSS selector - // Array index 2 is the CSS rule(s) - foreach ($rules as $rule) { - // If the CSS selector is multiple, we should split them up - if (strstr($rule['1'], ',')) { - // Strip out spaces after a comma for consistency - $rule['1'] = str_replace(', ', ',', $rule['1']); - - // Unset any previous combos - unset($selectors); - - // Make each selector declaration its own - // Create a separate array element in styles array for each declaration - $selectors = explode(',', $rule['1']); - foreach($selectors as $selector) { - $selector = trim($selector); - if (!isset($styles[$selector])) { - $styles[$selector] =''; - } - $styles[$selector] .= trim($rule['2']); - if ($debug) { echo $selector . ' { ' . trim($rule['2']) . ' }
'; } - } - } else { - $selector = trim($rule['1']); - if (!isset($styles[$selector])) { - $styles[$selector] = ''; - } - $styles[$selector] .= trim($rule['2']); - if ($debug) { echo $selector . ' { ' . trim($rule['2']) . ' }
'; } - } - } - - // DEBUG: Show selector and declaration - if ($debug) { - echo '
';
-				foreach ($styles as $selector=>$styling) {
-					echo $selector . ':
'; - echo $styling . '

'; - } - echo '

'; - } - - // For each style declaration, find the selector in the HTML and add the inline CSS - if (!empty($styles)) { - - // Load Simple HTML DOM helper - require_once('simple_html_dom.php'); - $html_dom = new simple_html_dom(); - - // Load in the HTML without the head and style definitions - $html_dom->load(preg_replace('/\(.+?)\<\/head>/s', '', $document)); - - foreach ($styles as $selector=>$styling) { - foreach ($html_dom->find($selector) as $element) { - // Check to make sure the style doesn't already exist - if (!stristr($element->style, $styling)) { - if (strlen($element->style) > 0 && substr(rtrim($element->style), -1) !== ';') { - $element->style .= ';'; - } - // If there is any existing style, this will append to it - $element->style .= $styling; - } - } - } - $inline_css_message = $html_dom->save(); - - // Strip class attribute - if ($strip_class === true) { - $inline_css_message = preg_replace('~(<[a-z0-0][^>]*)(\s(?:class|id)\s*=\s*(([\'"]).*?\4|[^\s]*))~usi', '\1', $inline_css_message); - } - - $html_dom->__destruct(); - - return $inline_css_message; - } - - return false; - } - } - - /* End of file instyle.php */ +]+>(?[^<]+)<\/style>/s', $document, $matches); + + // If no CSS style + if (empty($matches)){ + return $document; + } + + // Strip out extra newlines and tabs from CSS + $css = preg_replace("/[\n\r\t]+/s", "", $matches['css']); + + // Extract each CSS declaration + preg_match_all('/([-a-zA-Z0-9_ ,#\.]+){([^}]+)}/s', $css, $rules, PREG_SET_ORDER); + + // For each CSS declaration, make the selector and style declaration into an array + // Array index 1 is the CSS selector + // Array index 2 is the CSS rule(s) + foreach ($rules as $rule) { + // If the CSS selector is multiple, we should split them up + if (strstr($rule['1'], ',')) { + // Strip out spaces after a comma for consistency + $rule['1'] = str_replace(', ', ',', $rule['1']); + + // Unset any previous combos + unset($selectors); + + // Make each selector declaration its own + // Create a separate array element in styles array for each declaration + $selectors = explode(',', $rule['1']); + foreach($selectors as $selector) { + $selector = trim($selector); + if (!isset($styles[$selector])) { + $styles[$selector] =''; + } + $styles[$selector] .= trim($rule['2']); + if ($debug) { echo $selector . ' { ' . trim($rule['2']) . ' }
'; } + } + } else { + $selector = trim($rule['1']); + if (!isset($styles[$selector])) { + $styles[$selector] = ''; + } + $styles[$selector] .= trim($rule['2']); + if ($debug) { echo $selector . ' { ' . trim($rule['2']) . ' }
'; } + } + } + + // DEBUG: Show selector and declaration + if ($debug) { + echo '
';
+				foreach ($styles as $selector=>$styling) {
+					echo $selector . ':
'; + echo $styling . '

'; + } + echo '

'; + } + + // For each style declaration, find the selector in the HTML and add the inline CSS + if (!empty($styles)) { + + // Load Simple HTML DOM helper + require_once('simple_html_dom.php'); + $html_dom = new simple_html_dom(); + + // Load in the HTML without the head and style definitions + $html_dom->load(preg_replace('/\(.+?)\<\/head>/s', '', $document)); + + foreach ($styles as $selector=>$styling) { + foreach ($html_dom->find($selector) as $element) { + // Check to make sure the style doesn't already exist + if (!stristr($element->style, $styling)) { + if (strlen($element->style) > 0 && substr(rtrim($element->style), -1) !== ';') { + $element->style .= ';'; + } + // If there is any existing style, this will append to it + $element->style .= $styling; + } + } + } + $inline_css_message = $html_dom->save(); + + // Strip class attribute + if ($strip_class === true) { + $inline_css_message = preg_replace('~(<[a-z0-0][^>]*)(\s(?:class|id)\s*=\s*(([\'"]).*?\4|[^\s]*))~usi', '\1', $inline_css_message); + } + + $html_dom->__destruct(); + + return $inline_css_message; + } + + return false; + } + } + + /* End of file instyle.php */ diff --git a/web/bin/classes/ClassNotify.php b/web/bin/classes/ClassNotify.php index 2e069b2..f88e81b 100644 --- a/web/bin/classes/ClassNotify.php +++ b/web/bin/classes/ClassNotify.php @@ -1,363 +1,363 @@ -get_times_config(); - - $configs->get_times_secteur->update(); - $configs->get_times_secteur_livreur->update(); - - $DB = new IdaeDB('shop'); - - $session_data = IdaeSession::getInstance()->get_session(); - $rs = $DB->find(['actifShop' => 1]); - - while ($arr = $rs->getNext()) { - $configs = CommandeQueueConsole::consoleShop($arr['idshop']); - $configs->console_shop->update(); - $configs->console_secteur->update(); - $configs->console_secteur_livreur->update(); - $configs = CommandeQueueConsole::consoleShopSite($arr['idshop']); - $configs->console_shop->update(); - $configs->console_secteur_livreur->update(); - $configs = CommandeQueueConsole::consoleLivreur($arr['idlivreur']); - $configs->console_secteur->update(); - $configs->console_secteur_livreur->update(); - - } - - - $APP_COMMANDE = new App('commande'); - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); - - $this->notify_count_statut('commande', (int)$idcommande); - $this->notify_commande_shop($ARR_COMMANDE['idshop']); - - $this->notify_commande_secteur($ARR_COMMANDE['idsecteur']); - $this->notify_commande_free_secteur($ARR_COMMANDE['idsecteur']); - $this->notify_livreur_affect($ARR_COMMANDE['idsecteur']); - - $this->notify_wait_time_secteur($ARR_COMMANDE['idsecteur']); - - if (!empty($ARR_COMMANDE['idlivreur'])) $this->notify_commande_livreur((int)$ARR_COMMANDE['idlivreur']); - - } - - function notify_livreur($idsecteur) { - if (empty($idsecteur)) { - return; - } - $BIN = new Bin(); - $affect_val = sizeof($BIN->test_livreur_affect($idsecteur)); - $free_val = sizeof($BIN->test_livreur_affect_free($idsecteur)); - - $affect = "[data-count-livreur_affect=$idsecteur]"; - $free = "[data-count-livreur_affect_free=$idsecteur]"; - - AppSocket::send_cmd('act_insert_selector', [[$affect, - $affect_val], - [$free, - $free_val]]); - } - - function notify_livreur_affect($idsecteur) { - if (empty($idsecteur)) { - return; - } - - $BIN = new Bin(); - $affect_val = sizeof($BIN->test_livreur_affect($idsecteur)); - $free_val = sizeof($BIN->test_livreur_affect_free($idsecteur)); - - $affect = "[data-count-livreur_affect=$idsecteur]"; - $free = "[data-count-livreur_affect_free=$idsecteur]"; - - AppSocket::send_cmd('act_insert_selector', [[$affect, - $affect_val], - [$free, - $free_val]]); - } - - function notify_commande_forshop($idshop) { - if (empty($idshop)) { - return; - } - $BIN = new Bin(); - $commande_shop_val = sizeof($BIN->test_commande_shop($idshop)); - $commande_shop_wait_val = sizeof($BIN->test_commande_shop_wait($idshop)); - $commande_shop_livencou_val = sizeof($BIN->test_commande_shop_livencou($idshop)); - - $commande_shop = "[data-count-commande_shop=$idshop]"; - $commande_shop_wait = "[data-count-commande_shop_wait=$idshop]"; - $commande_shop_livencou = "[data-count-commande_shop_livencou=$idshop]"; - - $_table = 'commande_statut'; - $_id = "id$_table"; - - $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; - $NOW = date('H:i:s'); - $APP_SHOP = new App('shop'); - $APP_SH_J = new App('shop_jours'); - $APP_SH_J_SHIFT = new App('shop_jours_shift'); - $APP_SHIFT_RUN = new App('shop_jours_shift_run'); - $arr_sh = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, - 'ordreJours' => $index_jour]); - $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, - 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], - 'actifShop_jours_shift' => 1, - 'heureDebutShop_jours_shift' => ['$lte' => $NOW], - 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); - $idshop_jours_shift = (int)$arr_sh_shift[0]['idshop_jours_shift']; - # creation ou recuperation shift_run - $arr_run = ['idshop' => $idshop, - 'idshop_jours_shift' => $idshop_jours_shift, - 'dateDebutShop_jours_shift_run' => date('Y-m-d'), - 'nomShop_jours_shift_run' => date('d-m-Y') . ' ' . $arr_sh_shift[0]['heureDebutShop_jours_shift'], - 'heureDebutShop_jours_shift_run' => $arr_sh_shift[0]['heureDebutShop_jours_shift']]; - - $APP_COMMANDE = new App('commande'); - $APPTMP = new App($_table); - - $RS_STATUT = $APPTMP->find(); - $arr_commande_statut = []; - - while ($ARR_STATUT = $RS_STATUT->getNext()) { - $id = (int)$ARR_STATUT[$_id]; - // only same shift run - //$CT_NO_LIV = $APP_COMMANDE->find([ 'idlivreur' => null , 'dateCreationCommande' => date('Y-m-d') , 'idcommande_statut' => $id , 'idsecteur' => $idsecteur ]); - $CT = $APP_COMMANDE->find(['idshop' => $idshop, - 'idcommande_statut' => $id, - 'idshop_jours_shift' => $idshop_jours_shift]); - array_push($arr_commande_statut, ["[data-idshop][data-count=commande_statut][data-table_value=$id][data-table=commande]", - $CT->count()]); - //echo $CT_NO_LIV->count(); - /*if ( $CT_NO_LIV->count() != 0 ) { - array_push($arr_commande_statut , [ "[data-idsecteur=$idsecteur][data-count=commande_statut][data-table_value=$id][data-table=commande]" , $CT_NO_LIV->count() ]); - }*/ - } - - AppSocket::send_cmd('act_insert_selector', $arr_commande_statut); - AppSocket::send_cmd('act_insert_selector', [[$commande_shop, - $commande_shop_val], - [$commande_shop_wait, - $commande_shop_wait_val], - [$commande_shop_livencou, - $commande_shop_livencou_val]]); - } - - function notify_count_statut($table, $idcommande) { - if (empty($idcommande)) { - return; - } - - $_table = "commande_statut"; - $_id = "id$_table"; - - $APP_COMMANDE = new App($table); - $APPTMP = new App($_table); - $APP_SH_J = new App('shop_jours'); - $APP_LIV_AFFECT = new App('livreur_affectation'); - $APP_LIVREUR = new App('livreur'); - - $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); - - $idshop = (int)$ARR_COMMANDE['idshop']; - $idlivreur = (int)$ARR_COMMANDE['idlivreur']; - $idsecteur = (int)$ARR_COMMANDE['idsecteur']; - $idcommande_statut = (int)$ARR_COMMANDE['idcommande_statut']; - - if (empty($ARR_COMMANDE['idlivreur'])) { - $CT = $APP_COMMANDE->find(['idsecteur' => $idsecteur, - 'idlivreur' => ['$exists' => false], - 'dateCreationCommande' => date('Y-m-d')]); - - $arr_commande_statut = []; - array_push($arr_commande_statut, ["[data-idsecteur=$idsecteur][data-count=$_table][data-table_value=$idcommande_statut][data-table=commande]", - $CT->count()]); - AppSocket::send_cmd('act_insert_selector', $arr_commande_statut); - - } - - } - - /** - * Nombre de commandes en cours pour un livreur - * - * @param $idlivreur - */ - function notify_commande_livreur($idlivreur) { - if (empty($idlivreur)) { - return; - } - - $APP_COMMANDE = new App('commande'); - $arr_commande_statut = []; - - $CT = $APP_COMMANDE->find(['idlivreur' => (int)$idlivreur, - 'codeCommande_statut' => ['$nin' => ['END']]]); - array_push($arr_commande_statut, ["[data-idlivreur=$idlivreur][data-count_livreur=commande]", - $CT->count()]); - - AppSocket::send_cmd('act_insert_selector', $arr_commande_statut); - } - - /** - * Nombre de commandes en cours pour un secteur - * - * @param $idsecteur - */ - function notify_commande_secteur($idsecteur) { - if (empty($idsecteur)) { - return; - } - $room_secteur = "secteur_$idsecteur"; - $CT = CommandeQueue::secteur_commande_queue_count($idsecteur); - - SendCmd::insert_selector("[data-idsecteur=$idsecteur][data-count_secteur=commande]", $CT, $room_secteur); - } - - /** - * Nombre de commandes sans livreur free pour un secteur - * - * @param $idsecteur - */ - function notify_commande_free_secteur($idsecteur) { - if (empty($idsecteur)) { - return; - } - - $room_secteur = "secteur_$idsecteur"; - $secteur_commande_free_count = CommandeQueue::secteur_commande_free_count($idsecteur); - - SendCmd::insert_selector("[data-idsecteur=$idsecteur][data-count_secteur_commande_free=commande]", $secteur_commande_free_count, $room_secteur); - } - - /** - * Nombre de commandes en cours pour un shop - * - * @param $idshop - */ - function notify_commande_shop($idshop) { - if (empty($idshop)) { - return; - } - - $APP_COMMANDE = new App('commande'); - $arr_commande_statut = []; - - $room_shop = "shop_$idshop"; - - $CT = $APP_COMMANDE->find(['idshop' => (int)$idshop, - 'codeCommande_statut' => ['$nin' => ['END']]]); - array_push($arr_commande_statut, ["[data-idshop=$idshop][data-count_shop=commande]", - $CT->count()]); - - AppSocket::send_cmd('act_insert_selector', $arr_commande_statut, $room_shop); - } - - /** - * @param $idsecteur - * - * @throws \MongoConnectionException - * @throws \MongoCursorTimeoutException - */ - function notify_wait_time_secteur($idsecteur) { - $APP_SHOP = new App('shop'); - $RS_SHOP = $APP_SHOP->find(['idsecteur' => (int)$idsecteur]); - while ($ARR_SHOP = $RS_SHOP->getNext()) { - $this->notify_wait_time_shop($ARR_SHOP['idshop']); - } - } - - /** - * @deprecated - * Temps attente client pour un shop - * - * @param $idshop - */ - function notify_wait_time_shop($idshop) { - return; - $arr_cmd = []; - $Bin = new Bin(); - $APP_SHOP = new App('shop'); - - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); - // temps d'une livraison - $time_livraison = $Bin->get_wait_time_shop_secteur($idshop) ?: time(); - $test_shop_open = $Bin::test_shop_open($idshop); - $idsecteur = (int)$ARR_SHOP['idsecteur']; - - $heure_livraison = date('H:i', $time_livraison); - $secondeLivraison = $time_livraison - time(); // en minutes - $tempsLivraison = ceil($secondeLivraison / 60); // en minutes - - $plus = CommandeQueue::secteur_shop_other_commande_non_prefin_count($idshop); - - $etat = 5; - if ($ARR_SHOP['actifShop'] && $test_shop_open) { - if ($tempsLivraison <= 35) { - $etat = '1'; - } elseif ($tempsLivraison >= 150) { - $etat = 5; - } elseif ($tempsLivraison >= 120) { - $etat = 4; - } elseif ($tempsLivraison >= 90) { - $etat = 3; - } elseif ($tempsLivraison >= 60) { - $etat = 2; - } - - //$tempsLivraison = $Bin->get_value_wait_time_shop_secteur($idshop) . ' donc ' . $plus; - - } else { - $tempsLivraison = '--'; - $heure_livraison = 'fermé'; - } - $NB_LIVREUR_DISP = CommandeQueue::secteur_has_livreur_free_count($idsecteur); - $NB_COMMAND_SHOP_WAITING = CommandeQueue::shop_commande_queue_count($idshop); - $NB_COMMAND_OTHER_SHOP_WAITING = CommandeQueue::secteur_shop_other_commande_non_prefin_count($idshop); - $NB_LIVREUR_WORK = CommandeQueue::secteur_has_livreur_count($idsecteur); - $ARR_COMMAND_SECTEUR_LAST = CommandeQueue::secteur_commande_queue_list_last($idsecteur); - - $NB_COMMAND_SECTEUR_WAITING = CommandeQueue::secteur_commande_queue_count($idsecteur); - - $ARR_COMMANDES_SECTEUR_LAST = CommandeQueue::secteur_commande_nonfree_list($idsecteur); - - $timeLivraisonCommande = $ARR_COMMAND_SECTEUR_LAST['timeLivraisonCommande'] ?: time(); - $minuteLivraisonCommande = ceil(($timeLivraisonCommande - time()) / 60); - $heureLivraisonCommande = date('H:i', $timeLivraisonCommande); - - $facteur = ($NB_LIVREUR_DISP <= $NB_COMMAND_SHOP_WAITING)? TIME_PREPARATION_COMMANDE + TEMPS_LIVRAISON_COMMANDE : TEMPS_LIVRAISON_COMMANDE ; - - $DEBUG = $heureLivraisonCommande.' + '.$facteur; - - $temps_total = TIME_PREPARATION_COMMANDE + (($NB_LIVREUR_DISP <= $NB_COMMAND_SHOP_WAITING) ? TEMPS_LIVRAISON_COMMANDE : 0) + ($NB_COMMAND_OTHER_SHOP_WAITING * TEMPS_LIVRAISON_COMMANDE) + (($NB_LIVREUR_WORK <= $NB_COMMAND_OTHER_SHOP_WAITING) ? TIME_PREPARATION_COMMANDE : 0); - $temps_total = $temps_total + (($NB_LIVREUR_WORK <= $NB_COMMAND_SHOP_WAITING) ? TEMPS_LIVRAISON_COMMANDE : 0); - - $tes = $tempsLivraison + ($plus * $temps_total); - - array_push($arr_cmd, ["[data-wait_time][data-idshop=$idshop]", - $DEBUG.'
'.$tes . ' / ' . $heure_livraison . ' : ' . $tempsLivraison . '-' . $plus . '-' . $temps_total . '
' . "$minuteLivraisonCommande +" . (TEMPS_LIVRAISON_COMMANDE + TIME_PREPARATION_COMMANDE)]); - array_push($arr_cmd, ["[data-wait_hour][data-idshop=$idshop]", - $heure_livraison]); - array_push($arr_cmd, ["[data-wait_thumb][data-idshop=$idshop]", - "
"]); - - SendCmd::insert_selectors($arr_cmd); - //AppSocket::send_cmd('act_insert_selector', $arr_cmd); - } - } +get_times_config(); + + $configs->get_times_secteur->update(); + $configs->get_times_secteur_livreur->update(); + + $DB = new IdaeDB('shop'); + + $session_data = IdaeSession::getInstance()->get_session(); + $rs = $DB->find(['actifShop' => 1]); + + while ($arr = $rs->getNext()) { + $configs = CommandeQueueConsole::consoleShop($arr['idshop']); + $configs->console_shop->update(); + $configs->console_secteur->update(); + $configs->console_secteur_livreur->update(); + $configs = CommandeQueueConsole::consoleShopSite($arr['idshop']); + $configs->console_shop->update(); + $configs->console_secteur_livreur->update(); + $configs = CommandeQueueConsole::consoleLivreur($arr['idlivreur']); + $configs->console_secteur->update(); + $configs->console_secteur_livreur->update(); + + } + + + $APP_COMMANDE = new App('commande'); + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => (int)$idcommande]); + + $this->notify_count_statut('commande', (int)$idcommande); + $this->notify_commande_shop($ARR_COMMANDE['idshop']); + + $this->notify_commande_secteur($ARR_COMMANDE['idsecteur']); + $this->notify_commande_free_secteur($ARR_COMMANDE['idsecteur']); + $this->notify_livreur_affect($ARR_COMMANDE['idsecteur']); + + $this->notify_wait_time_secteur($ARR_COMMANDE['idsecteur']); + + if (!empty($ARR_COMMANDE['idlivreur'])) $this->notify_commande_livreur((int)$ARR_COMMANDE['idlivreur']); + + } + + function notify_livreur($idsecteur) { + if (empty($idsecteur)) { + return; + } + $BIN = new Bin(); + $affect_val = sizeof($BIN->test_livreur_affect($idsecteur)); + $free_val = sizeof($BIN->test_livreur_affect_free($idsecteur)); + + $affect = "[data-count-livreur_affect=$idsecteur]"; + $free = "[data-count-livreur_affect_free=$idsecteur]"; + + AppSocket::send_cmd('act_insert_selector', [[$affect, + $affect_val], + [$free, + $free_val]]); + } + + function notify_livreur_affect($idsecteur) { + if (empty($idsecteur)) { + return; + } + + $BIN = new Bin(); + $affect_val = sizeof($BIN->test_livreur_affect($idsecteur)); + $free_val = sizeof($BIN->test_livreur_affect_free($idsecteur)); + + $affect = "[data-count-livreur_affect=$idsecteur]"; + $free = "[data-count-livreur_affect_free=$idsecteur]"; + + AppSocket::send_cmd('act_insert_selector', [[$affect, + $affect_val], + [$free, + $free_val]]); + } + + function notify_commande_forshop($idshop) { + if (empty($idshop)) { + return; + } + $BIN = new Bin(); + $commande_shop_val = sizeof($BIN->test_commande_shop($idshop)); + $commande_shop_wait_val = sizeof($BIN->test_commande_shop_wait($idshop)); + $commande_shop_livencou_val = sizeof($BIN->test_commande_shop_livencou($idshop)); + + $commande_shop = "[data-count-commande_shop=$idshop]"; + $commande_shop_wait = "[data-count-commande_shop_wait=$idshop]"; + $commande_shop_livencou = "[data-count-commande_shop_livencou=$idshop]"; + + $_table = 'commande_statut'; + $_id = "id$_table"; + + $index_jour = ((int)date('w') - 1 < 0) ? 6 : (int)date('w') - 1; + $NOW = date('H:i:s'); + $APP_SHOP = new App('shop'); + $APP_SH_J = new App('shop_jours'); + $APP_SH_J_SHIFT = new App('shop_jours_shift'); + $APP_SHIFT_RUN = new App('shop_jours_shift_run'); + $arr_sh = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + $arr_sh_j = $APP_SH_J->findOne(['idshop' => $idshop, + 'ordreJours' => $index_jour]); + $arr_sh_shift = iterator_to_array($APP_SH_J_SHIFT->find(['idshop' => $idshop, + 'idshop_jours' => (int)$arr_sh_j['idshop_jours'], + 'actifShop_jours_shift' => 1, + 'heureDebutShop_jours_shift' => ['$lte' => $NOW], + 'heureFinShop_jours_shift' => ['$gte' => $NOW]], ['_id' => 0])->sort(['heureDebutShop_jours_shift' => 1])); + $idshop_jours_shift = (int)$arr_sh_shift[0]['idshop_jours_shift']; + # creation ou recuperation shift_run + $arr_run = ['idshop' => $idshop, + 'idshop_jours_shift' => $idshop_jours_shift, + 'dateDebutShop_jours_shift_run' => date('Y-m-d'), + 'nomShop_jours_shift_run' => date('d-m-Y') . ' ' . $arr_sh_shift[0]['heureDebutShop_jours_shift'], + 'heureDebutShop_jours_shift_run' => $arr_sh_shift[0]['heureDebutShop_jours_shift']]; + + $APP_COMMANDE = new App('commande'); + $APPTMP = new App($_table); + + $RS_STATUT = $APPTMP->find(); + $arr_commande_statut = []; + + while ($ARR_STATUT = $RS_STATUT->getNext()) { + $id = (int)$ARR_STATUT[$_id]; + // only same shift run + //$CT_NO_LIV = $APP_COMMANDE->find([ 'idlivreur' => null , 'dateCreationCommande' => date('Y-m-d') , 'idcommande_statut' => $id , 'idsecteur' => $idsecteur ]); + $CT = $APP_COMMANDE->find(['idshop' => $idshop, + 'idcommande_statut' => $id, + 'idshop_jours_shift' => $idshop_jours_shift]); + array_push($arr_commande_statut, ["[data-idshop][data-count=commande_statut][data-table_value=$id][data-table=commande]", + $CT->count()]); + //echo $CT_NO_LIV->count(); + /*if ( $CT_NO_LIV->count() != 0 ) { + array_push($arr_commande_statut , [ "[data-idsecteur=$idsecteur][data-count=commande_statut][data-table_value=$id][data-table=commande]" , $CT_NO_LIV->count() ]); + }*/ + } + + AppSocket::send_cmd('act_insert_selector', $arr_commande_statut); + AppSocket::send_cmd('act_insert_selector', [[$commande_shop, + $commande_shop_val], + [$commande_shop_wait, + $commande_shop_wait_val], + [$commande_shop_livencou, + $commande_shop_livencou_val]]); + } + + function notify_count_statut($table, $idcommande) { + if (empty($idcommande)) { + return; + } + + $_table = "commande_statut"; + $_id = "id$_table"; + + $APP_COMMANDE = new App($table); + $APPTMP = new App($_table); + $APP_SH_J = new App('shop_jours'); + $APP_LIV_AFFECT = new App('livreur_affectation'); + $APP_LIVREUR = new App('livreur'); + + $ARR_COMMANDE = $APP_COMMANDE->findOne(['idcommande' => $idcommande]); + + $idshop = (int)$ARR_COMMANDE['idshop']; + $idlivreur = (int)$ARR_COMMANDE['idlivreur']; + $idsecteur = (int)$ARR_COMMANDE['idsecteur']; + $idcommande_statut = (int)$ARR_COMMANDE['idcommande_statut']; + + if (empty($ARR_COMMANDE['idlivreur'])) { + $CT = $APP_COMMANDE->find(['idsecteur' => $idsecteur, + 'idlivreur' => ['$exists' => false], + 'dateCreationCommande' => date('Y-m-d')]); + + $arr_commande_statut = []; + array_push($arr_commande_statut, ["[data-idsecteur=$idsecteur][data-count=$_table][data-table_value=$idcommande_statut][data-table=commande]", + $CT->count()]); + AppSocket::send_cmd('act_insert_selector', $arr_commande_statut); + + } + + } + + /** + * Nombre de commandes en cours pour un livreur + * + * @param $idlivreur + */ + function notify_commande_livreur($idlivreur) { + if (empty($idlivreur)) { + return; + } + + $APP_COMMANDE = new App('commande'); + $arr_commande_statut = []; + + $CT = $APP_COMMANDE->find(['idlivreur' => (int)$idlivreur, + 'codeCommande_statut' => ['$nin' => ['END']]]); + array_push($arr_commande_statut, ["[data-idlivreur=$idlivreur][data-count_livreur=commande]", + $CT->count()]); + + AppSocket::send_cmd('act_insert_selector', $arr_commande_statut); + } + + /** + * Nombre de commandes en cours pour un secteur + * + * @param $idsecteur + */ + function notify_commande_secteur($idsecteur) { + if (empty($idsecteur)) { + return; + } + $room_secteur = "secteur_$idsecteur"; + $CT = CommandeQueue::secteur_commande_queue_count($idsecteur); + + SendCmd::insert_selector("[data-idsecteur=$idsecteur][data-count_secteur=commande]", $CT, $room_secteur); + } + + /** + * Nombre de commandes sans livreur free pour un secteur + * + * @param $idsecteur + */ + function notify_commande_free_secteur($idsecteur) { + if (empty($idsecteur)) { + return; + } + + $room_secteur = "secteur_$idsecteur"; + $secteur_commande_free_count = CommandeQueue::secteur_commande_free_count($idsecteur); + + SendCmd::insert_selector("[data-idsecteur=$idsecteur][data-count_secteur_commande_free=commande]", $secteur_commande_free_count, $room_secteur); + } + + /** + * Nombre de commandes en cours pour un shop + * + * @param $idshop + */ + function notify_commande_shop($idshop) { + if (empty($idshop)) { + return; + } + + $APP_COMMANDE = new App('commande'); + $arr_commande_statut = []; + + $room_shop = "shop_$idshop"; + + $CT = $APP_COMMANDE->find(['idshop' => (int)$idshop, + 'codeCommande_statut' => ['$nin' => ['END']]]); + array_push($arr_commande_statut, ["[data-idshop=$idshop][data-count_shop=commande]", + $CT->count()]); + + AppSocket::send_cmd('act_insert_selector', $arr_commande_statut, $room_shop); + } + + /** + * @param $idsecteur + * + * @throws \MongoConnectionException + * @throws \MongoCursorTimeoutException + */ + function notify_wait_time_secteur($idsecteur) { + $APP_SHOP = new App('shop'); + $RS_SHOP = $APP_SHOP->find(['idsecteur' => (int)$idsecteur]); + while ($ARR_SHOP = $RS_SHOP->getNext()) { + $this->notify_wait_time_shop($ARR_SHOP['idshop']); + } + } + + /** + * @deprecated + * Temps attente client pour un shop + * + * @param $idshop + */ + function notify_wait_time_shop($idshop) { + return; + $arr_cmd = []; + $Bin = new Bin(); + $APP_SHOP = new App('shop'); + + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$idshop]); + // temps d'une livraison + $time_livraison = $Bin->get_wait_time_shop_secteur($idshop) ?: time(); + $test_shop_open = $Bin::test_shop_open($idshop); + $idsecteur = (int)$ARR_SHOP['idsecteur']; + + $heure_livraison = date('H:i', $time_livraison); + $secondeLivraison = $time_livraison - time(); // en minutes + $tempsLivraison = ceil($secondeLivraison / 60); // en minutes + + $plus = CommandeQueue::secteur_shop_other_commande_non_prefin_count($idshop); + + $etat = 5; + if ($ARR_SHOP['actifShop'] && $test_shop_open) { + if ($tempsLivraison <= 35) { + $etat = '1'; + } elseif ($tempsLivraison >= 150) { + $etat = 5; + } elseif ($tempsLivraison >= 120) { + $etat = 4; + } elseif ($tempsLivraison >= 90) { + $etat = 3; + } elseif ($tempsLivraison >= 60) { + $etat = 2; + } + + //$tempsLivraison = $Bin->get_value_wait_time_shop_secteur($idshop) . ' donc ' . $plus; + + } else { + $tempsLivraison = '--'; + $heure_livraison = 'fermé'; + } + $NB_LIVREUR_DISP = CommandeQueue::secteur_has_livreur_free_count($idsecteur); + $NB_COMMAND_SHOP_WAITING = CommandeQueue::shop_commande_queue_count($idshop); + $NB_COMMAND_OTHER_SHOP_WAITING = CommandeQueue::secteur_shop_other_commande_non_prefin_count($idshop); + $NB_LIVREUR_WORK = CommandeQueue::secteur_has_livreur_count($idsecteur); + $ARR_COMMAND_SECTEUR_LAST = CommandeQueue::secteur_commande_queue_list_last($idsecteur); + + $NB_COMMAND_SECTEUR_WAITING = CommandeQueue::secteur_commande_queue_count($idsecteur); + + $ARR_COMMANDES_SECTEUR_LAST = CommandeQueue::secteur_commande_nonfree_list($idsecteur); + + $timeLivraisonCommande = $ARR_COMMAND_SECTEUR_LAST['timeLivraisonCommande'] ?: time(); + $minuteLivraisonCommande = ceil(($timeLivraisonCommande - time()) / 60); + $heureLivraisonCommande = date('H:i', $timeLivraisonCommande); + + $facteur = ($NB_LIVREUR_DISP <= $NB_COMMAND_SHOP_WAITING)? TIME_PREPARATION_COMMANDE + TEMPS_LIVRAISON_COMMANDE : TEMPS_LIVRAISON_COMMANDE ; + + $DEBUG = $heureLivraisonCommande.' + '.$facteur; + + $temps_total = TIME_PREPARATION_COMMANDE + (($NB_LIVREUR_DISP <= $NB_COMMAND_SHOP_WAITING) ? TEMPS_LIVRAISON_COMMANDE : 0) + ($NB_COMMAND_OTHER_SHOP_WAITING * TEMPS_LIVRAISON_COMMANDE) + (($NB_LIVREUR_WORK <= $NB_COMMAND_OTHER_SHOP_WAITING) ? TIME_PREPARATION_COMMANDE : 0); + $temps_total = $temps_total + (($NB_LIVREUR_WORK <= $NB_COMMAND_SHOP_WAITING) ? TEMPS_LIVRAISON_COMMANDE : 0); + + $tes = $tempsLivraison + ($plus * $temps_total); + + array_push($arr_cmd, ["[data-wait_time][data-idshop=$idshop]", + $DEBUG.'
'.$tes . ' / ' . $heure_livraison . ' : ' . $tempsLivraison . '-' . $plus . '-' . $temps_total . '
' . "$minuteLivraisonCommande +" . (TEMPS_LIVRAISON_COMMANDE + TIME_PREPARATION_COMMANDE)]); + array_push($arr_cmd, ["[data-wait_hour][data-idshop=$idshop]", + $heure_livraison]); + array_push($arr_cmd, ["[data-wait_thumb][data-idshop=$idshop]", + "
"]); + + SendCmd::insert_selectors($arr_cmd); + //AppSocket::send_cmd('act_insert_selector', $arr_cmd); + } + } diff --git a/web/bin/classes/ClassNotifySite.php b/web/bin/classes/ClassNotifySite.php index d915feb..ed1fe0f 100644 --- a/web/bin/classes/ClassNotifySite.php +++ b/web/bin/classes/ClassNotifySite.php @@ -1,77 +1,77 @@ - $msg, 'mdl' => '/fragment/notify', 'type' => $type, 'mdl_vars' => $mdl_vars],$args), $id); - } - static function notify_idae( $msg,$type = 'alert', $args=[], $id = null) { - $id = $id ?: session_id(); - $args['type'] = $type; - - switch ($type): - case 'alert' : - $args['icon'] = 'exclamation-triangle'; - $args['color'] = 'orange'; - break; - case 'success' : - $args['icon'] = 'check-circle'; - $args['color'] = 'green'; - break; - case 'error' : - $args['icon'] = 'ban'; - $args['color'] = 'red'; - break; - default : - $args['icon'] = 'exclamation-triangle'; - $args['color'] = 'orange'; - break; - endswitch; - AppSocket::send_cmd('act_notify',['msg' => $msg, 'options'=>['vars' => $args,'type' => $type,'mdl' => '/fragment/notify']], $id); - // AppSocket::send_cmd('act_notify', array_merge(['msg' => $msg, 'type' => $type, 'options'=>['vars' => $mdl_vars,'mdl' => '/fragment/notify']],$args), $id); - } - static function notify_mdl($mdl, $args=[], $id = null) { - $id = $id ?: session_id(); - AppSocket::send_cmd('act_notify',['msg' => '', 'options'=>['vars' => $args,'mdl' => $mdl]], $id); - // AppSocket::send_cmd('act_notify', array_merge(['msg' => $msg, 'type' => $type, 'options'=>['vars' => $mdl_vars,'mdl' => '/fragment/notify']],$args), $id); - } - static function notify_notification( $title,$body='',$type = 'alert', $args=[], $id = null) { // html5 - $id = $id ?: session_id(); - $mdl_vars = $args['mdl_vars'] ?: []; - AppSocket::send_cmd('act_notify_notification', array_merge(['title' => $title,'body'=> $body, 'mdl' => '/fragment/notify', 'type' => $type, 'mdl_vars' => $mdl_vars],$args), $id); - } + $msg, 'mdl' => '/fragment/notify', 'type' => $type, 'mdl_vars' => $mdl_vars],$args), $id); + } + static function notify_idae( $msg,$type = 'alert', $args=[], $id = null) { + $id = $id ?: session_id(); + $args['type'] = $type; + + switch ($type): + case 'alert' : + $args['icon'] = 'exclamation-triangle'; + $args['color'] = 'orange'; + break; + case 'success' : + $args['icon'] = 'check-circle'; + $args['color'] = 'green'; + break; + case 'error' : + $args['icon'] = 'ban'; + $args['color'] = 'red'; + break; + default : + $args['icon'] = 'exclamation-triangle'; + $args['color'] = 'orange'; + break; + endswitch; + AppSocket::send_cmd('act_notify',['msg' => $msg, 'options'=>['vars' => $args,'type' => $type,'mdl' => '/fragment/notify']], $id); + // AppSocket::send_cmd('act_notify', array_merge(['msg' => $msg, 'type' => $type, 'options'=>['vars' => $mdl_vars,'mdl' => '/fragment/notify']],$args), $id); + } + static function notify_mdl($mdl, $args=[], $id = null) { + $id = $id ?: session_id(); + AppSocket::send_cmd('act_notify',['msg' => '', 'options'=>['vars' => $args,'mdl' => $mdl]], $id); + // AppSocket::send_cmd('act_notify', array_merge(['msg' => $msg, 'type' => $type, 'options'=>['vars' => $mdl_vars,'mdl' => '/fragment/notify']],$args), $id); + } + static function notify_notification( $title,$body='',$type = 'alert', $args=[], $id = null) { // html5 + $id = $id ?: session_id(); + $mdl_vars = $args['mdl_vars'] ?: []; + AppSocket::send_cmd('act_notify_notification', array_merge(['title' => $title,'body'=> $body, 'mdl' => '/fragment/notify', 'type' => $type, 'mdl_vars' => $mdl_vars],$args), $id); + } } \ No newline at end of file diff --git a/web/bin/classes/ClassPage.php b/web/bin/classes/ClassPage.php index e8ccd0c..de71fd4 100644 --- a/web/bin/classes/ClassPage.php +++ b/web/bin/classes/ClassPage.php @@ -1,124 +1,124 @@ -setAutoRefresh(true); - - class Page extends AppSite { - - function __construct() { - parent::__construct(); - $this->Fragment = new Fragment(); - } - - public function index() { - # active page - $this->set_page('index'); - - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - - # - # Shop liste - $APP_SH = new App('shop'); - $rs_sh = $APP_SH->find([], ['_id' => 0]); - $parameters_index['var_shop_list'] = iterator_to_array($rs_sh, false); - foreach ($parameters_index['var_shop_list'] as $key => $val) { - $url = Router::build_route('restaurant', ['idshop' => $val['idshop']]); - $parameters_index['var_shop_list'][$key]['route'] = $url; - // - } - $LATTE->setAutoRefresh(false); - $html = $LATTE->renderToString(APPTPL . 'pages/index.html', $parameters_index); - - $this->render($html); - - } - - function do_action($params = ['action', 'value']) { - if (strpos($params['value'], '/') === false && strpos($params['action'], '/') === false) { - $this->$params['action']($params['value']); - } else if (strpos($params['action'], '/') === false) { - $this->$params['action'](explode('/', $params['value'])); - } else { - $actions = explode('/', $params['action']); - $this->$params['action'](explode('/', $params['value'])); - } - // Helper::dump($params); - } - - - - function login_register($inner = false) { - # active page - $this->set_page('login_register'); - - global $LATTE; - - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $parameters['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']; - $parameters['type'] = 'client'; - - if (empty($_SESSION['client'])) { - $html = $LATTE->renderToString(APPTPL . 'pages/login_register.html', $parameters); - } else { - $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_done.html', $parameters); - - } - - $this->render($html); - - } - - function login_init($params = []) { - # active page - $this->set_page('login_mail'); - - global $LATTE; - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $parameters['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']; - $parameters['type'] = $type = $params[0]; - $parameters['Type'] = $Type = ucfirst($params[0]); - $parameters['private_key'] = $Type = $params[1]; - - $parameters['link'] = http_build_query($parameters); - - $APP_CLI = new App($type); - - $test_cli = $APP_CLI->findOne(["private_key" => $params[1]]); - if (empty($test_cli['private_key'])) { - $this->render("opération impossible"); - - return; - } - $parameters['vars'] = $test_cli; - $html = $LATTE->renderToString(APPTPL . 'pages/login_init.html', $parameters); - - $this->render($html); - - } - - function login_multi($params = []) { - # active page - $this->set_page('login_multi_' . $params['type']); - - global $LATTE; - $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; - $parameters['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']; - $parameters['type'] = $type = $params['type']; - $parameters['Type'] = $Type = ucfirst($type); - - $parameters['link'] = http_build_query($parameters); - - $html = $LATTE->renderToString(APPTPL . 'pages/login_multi.html', $parameters); - - $this->render($html); - - } +setAutoRefresh(true); + + class Page extends AppSite { + + function __construct() { + parent::__construct(); + $this->Fragment = new Fragment(); + } + + public function index() { + # active page + $this->set_page('index'); + + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + + # + # Shop liste + $APP_SH = new App('shop'); + $rs_sh = $APP_SH->find([], ['_id' => 0]); + $parameters_index['var_shop_list'] = iterator_to_array($rs_sh, false); + foreach ($parameters_index['var_shop_list'] as $key => $val) { + $url = Router::build_route('restaurant', ['idshop' => $val['idshop']]); + $parameters_index['var_shop_list'][$key]['route'] = $url; + // + } + $LATTE->setAutoRefresh(false); + $html = $LATTE->renderToString(APPTPL . 'pages/index.html', $parameters_index); + + $this->render($html); + + } + + function do_action($params = ['action', 'value']) { + if (strpos($params['value'], '/') === false && strpos($params['action'], '/') === false) { + $this->$params['action']($params['value']); + } else if (strpos($params['action'], '/') === false) { + $this->$params['action'](explode('/', $params['value'])); + } else { + $actions = explode('/', $params['action']); + $this->$params['action'](explode('/', $params['value'])); + } + // Helper::dump($params); + } + + + + function login_register($inner = false) { + # active page + $this->set_page('login_register'); + + global $LATTE; + + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $parameters['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']; + $parameters['type'] = 'client'; + + if (empty($_SESSION['client'])) { + $html = $LATTE->renderToString(APPTPL . 'pages/login_register.html', $parameters); + } else { + $html = $LATTE->renderToString(APPTPL . 'fragments/login_multi_done.html', $parameters); + + } + + $this->render($html); + + } + + function login_init($params = []) { + # active page + $this->set_page('login_mail'); + + global $LATTE; + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $parameters['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']; + $parameters['type'] = $type = $params[0]; + $parameters['Type'] = $Type = ucfirst($params[0]); + $parameters['private_key'] = $Type = $params[1]; + + $parameters['link'] = http_build_query($parameters); + + $APP_CLI = new App($type); + + $test_cli = $APP_CLI->findOne(["private_key" => $params[1]]); + if (empty($test_cli['private_key'])) { + $this->render("opération impossible"); + + return; + } + $parameters['vars'] = $test_cli; + $html = $LATTE->renderToString(APPTPL . 'pages/login_init.html', $parameters); + + $this->render($html); + + } + + function login_multi($params = []) { + # active page + $this->set_page('login_multi_' . $params['type']); + + global $LATTE; + $parameters['HTTPCUSTOMERSITE'] = HTTPCUSTOMERSITE; + $parameters['HTTP_REFERER'] = $_SERVER['HTTP_REFERER']; + $parameters['type'] = $type = $params['type']; + $parameters['Type'] = $Type = ucfirst($type); + + $parameters['link'] = http_build_query($parameters); + + $html = $LATTE->renderToString(APPTPL . 'pages/login_multi.html', $parameters); + + $this->render($html); + + } } \ No newline at end of file diff --git a/web/bin/classes/ClassProgress.php b/web/bin/classes/ClassProgress.php index 75efa19..63eb108 100644 --- a/web/bin/classes/ClassProgress.php +++ b/web/bin/classes/ClassProgress.php @@ -1,11 +1,11 @@ -findOne(['idshop' => (int)$idshop]); - $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); - - $list = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['heureCommande' => 1]); - - $nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($arr_shop['idsecteur']); - $i = 0; - $rang = 1; - - $index_turn = 0; - foreach ($list as $index => $item) { - if ($i >= $nb_livreur_disp) { - $i = 0; - ++$rang; - } - $heureCommande = $item['heureCommande']; - ++$i; - ++$index_turn; - - $idcommande = (int)$item['idcommande']; - - $arr_upd['idcommande'] = $idcommande; - $arr_upd['ordreCommande'] = $index_turn; - $arr_upd['debugRangCommandeModulo'] = $index_turn; - $arr_upd['debugRangCommande'] = "S$index_turn"; - $arr_upd['rangCommande'] = "S$index_turn"; - $arr_upd['attentePreparationCommande'] = $rang; - - $APP_COMMANDE->update_id($idcommande, $arr_upd); - } - } - } +findOne(['idshop' => (int)$idshop]); + $arr_commande_statut = $APP_COMMANDE_STATUT->findOne(['codeCommande_statut' => 'END']); + + $list = $APP_COMMANDE->find(['ordreCommande_statut' => ['$lt' => $arr_commande_statut['ordreCommande_statut']], 'idshop' => (int)$idshop, 'dateCommande' => $day])->sort(['heureCommande' => 1]); + + $nb_livreur_disp = CommandeQueue::secteur_has_livreur_count($arr_shop['idsecteur']); + $i = 0; + $rang = 1; + + $index_turn = 0; + foreach ($list as $index => $item) { + if ($i >= $nb_livreur_disp) { + $i = 0; + ++$rang; + } + $heureCommande = $item['heureCommande']; + ++$i; + ++$index_turn; + + $idcommande = (int)$item['idcommande']; + + $arr_upd['idcommande'] = $idcommande; + $arr_upd['ordreCommande'] = $index_turn; + $arr_upd['debugRangCommandeModulo'] = $index_turn; + $arr_upd['debugRangCommande'] = "S$index_turn"; + $arr_upd['rangCommande'] = "S$index_turn"; + $arr_upd['attentePreparationCommande'] = $rang; + + $APP_COMMANDE->update_id($idcommande, $arr_upd); + } + } + } diff --git a/web/bin/classes/ClassRouter.php b/web/bin/classes/ClassRouter.php index 9d11b25..888d161 100644 --- a/web/bin/classes/ClassRouter.php +++ b/web/bin/classes/ClassRouter.php @@ -1,78 +1,78 @@ -do_match(); - } - - function do_match() { - - $this->addRoutes($this->routes()); - // - $match = $this->match(); - - - if ($match) { - // var_dump($match); - // var_dump(json_decode(file_get_contents('php://input'), JSON_OBJECT_AS_ARRAY | JSON_PRETTY_PRINT)); - - // echo json_decode(file_get_contents('php://input'),JSON_OBJECT_AS_ARRAY | JSON_PRETTY_PRINT); - if (is_string($match['target']) && strpos($match['target'], '#') !== false) { - $is_cl = explode('#', $match['target']); - - if (sizeof($is_cl) == 2) { - $cl = new $is_cl[0](); - $meth = $is_cl[1]; - $cl->$meth($match['params']); - } - } else if (is_callable($match['target'])) { - // var_dump($match); - call_user_func_array($match['target'], $match['params']); - } else { - // no route was matched - echo "404"; - // header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found'); - } - } - } - - public function routes() { - return [ - ['POST', '/api/idql/[*:scheme]', function (string $scheme) { - $_POST = json_decode(file_get_contents('php://input'), JSON_OBJECT_AS_ARRAY | JSON_PRETTY_PRINT); - - $defaulIdql = [ - 'method' => 'find', - 'scheme' => $scheme, - 'limit' => 10, - 'page' => 0, - ]; - - $idql = array_merge($defaulIdql,$_POST ); - - //IdaeApiQuery::idql($idql); - $api = new IdaeApiRest(); - $api->doIdql($idql); - - }], - ['GET|POST|PATCH|PUT', '/api/[*:uri_vars]', function ($uri_vars) { - $api = new IdaeApiRest(); - $api->doRest(); - }], - ]; - } - - } - +do_match(); + } + + function do_match() { + + $this->addRoutes($this->routes()); + // + $match = $this->match(); + + + if ($match) { + // var_dump($match); + // var_dump(json_decode(file_get_contents('php://input'), JSON_OBJECT_AS_ARRAY | JSON_PRETTY_PRINT)); + + // echo json_decode(file_get_contents('php://input'),JSON_OBJECT_AS_ARRAY | JSON_PRETTY_PRINT); + if (is_string($match['target']) && strpos($match['target'], '#') !== false) { + $is_cl = explode('#', $match['target']); + + if (sizeof($is_cl) == 2) { + $cl = new $is_cl[0](); + $meth = $is_cl[1]; + $cl->$meth($match['params']); + } + } else if (is_callable($match['target'])) { + // var_dump($match); + call_user_func_array($match['target'], $match['params']); + } else { + // no route was matched + echo "404"; + // header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found'); + } + } + } + + public function routes() { + return [ + ['POST', '/api/idql/[*:scheme]', function (string $scheme) { + $_POST = json_decode(file_get_contents('php://input'), JSON_OBJECT_AS_ARRAY | JSON_PRETTY_PRINT); + + $defaulIdql = [ + 'method' => 'find', + 'scheme' => $scheme, + 'limit' => 10, + 'page' => 0, + ]; + + $idql = array_merge($defaulIdql,$_POST ); + + //IdaeApiQuery::idql($idql); + $api = new IdaeApiRest(); + $api->doIdql($idql); + + }], + ['GET|POST|PATCH|PUT', '/api/[*:uri_vars]', function ($uri_vars) { + $api = new IdaeApiRest(); + $api->doRest(); + }], + ]; + } + + } + diff --git a/web/bin/classes/ClassSMSPartnerAPI.php b/web/bin/classes/ClassSMSPartnerAPI.php index 47603c8..bd1df4b 100644 --- a/web/bin/classes/ClassSMSPartnerAPI.php +++ b/web/bin/classes/ClassSMSPartnerAPI.php @@ -1,88 +1,88 @@ -setDebug($debug); - } - - public function setDebug($debug) { - $this->debug = $debug; - } - - public function getDebug() { - return $this->debug; - } - - public function checkCredits($params) { - if (empty($params)) - return false; - - $result = $this->_postRequest(self::BASE_URL . 'me' . $params); - - return $this->returnJson($result); - } - - public function checkStatusByNumber($params) { - if (empty($params)) - return false; - - $result = $this->_postRequest(self::BASE_URL . 'message-status' . $params); - - return $this->returnJson($result); - } - - public function sendSms($fields) { - if (empty($fields)) - return false; - - $result = $this->_postRequest(self::BASE_URL . 'send', $fields); - - return $this->returnJson($result); - } - - /** - * Requête cURL - Vous n'êtes pas sensé appeler cette méthode - * @access private - * - */ - private function _postRequest($url, $fields = []) { - $curl = curl_init(); - - curl_setopt($curl, CURLOPT_URL, $url); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_TIMEOUT, 10); - if (!empty($fields)) { - curl_setopt($curl, CURLOPT_POST, 1); - curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fields)); - } - - $result = curl_exec($curl); - if ($result === false) { - if ($this->debug) - echo curl_error($curl); - else - $result = curl_error($curl); - } else - curl_close($curl); - - return $result; - } - - private function returnJson($string) { - $json_array = json_encode($string); - if (is_null($json_array)) - return $string; - else - return $json_array; - } - } - +setDebug($debug); + } + + public function setDebug($debug) { + $this->debug = $debug; + } + + public function getDebug() { + return $this->debug; + } + + public function checkCredits($params) { + if (empty($params)) + return false; + + $result = $this->_postRequest(self::BASE_URL . 'me' . $params); + + return $this->returnJson($result); + } + + public function checkStatusByNumber($params) { + if (empty($params)) + return false; + + $result = $this->_postRequest(self::BASE_URL . 'message-status' . $params); + + return $this->returnJson($result); + } + + public function sendSms($fields) { + if (empty($fields)) + return false; + + $result = $this->_postRequest(self::BASE_URL . 'send', $fields); + + return $this->returnJson($result); + } + + /** + * Requête cURL - Vous n'êtes pas sensé appeler cette méthode + * @access private + * + */ + private function _postRequest($url, $fields = []) { + $curl = curl_init(); + + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_TIMEOUT, 10); + if (!empty($fields)) { + curl_setopt($curl, CURLOPT_POST, 1); + curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fields)); + } + + $result = curl_exec($curl); + if ($result === false) { + if ($this->debug) + echo curl_error($curl); + else + $result = curl_error($curl); + } else + curl_close($curl); + + return $result; + } + + private function returnJson($string) { + $json_array = json_encode($string); + if (is_null($json_array)) + return $string; + else + return $json_array; + } + } + diff --git a/web/bin/classes/ClassSMTP.php b/web/bin/classes/ClassSMTP.php index 39a598e..9b92be4 100644 --- a/web/bin/classes/ClassSMTP.php +++ b/web/bin/classes/ClassSMTP.php @@ -1,844 +1,844 @@ -smtp_conn = 0; - $this->error = null; - $this->helo_rply = null; - - $this->do_debug = 0; - } - - ///////////////////////////////////////////////// - // CONNECTION FUNCTIONS - ///////////////////////////////////////////////// - - /** - * Connect to the server specified on the port specified. - * If the port is not specified use the default SMTP_PORT. - * If tval is specified then a connection will try and be - * established with the server for that number of seconds. - * If tval is not specified the default is 30 seconds to - * try on the connection. - * - * SMTP CODE SUCCESS: 220 - * SMTP CODE FAILURE: 421 - * @access public - * @return bool - */ - public function Connect($host, $port = 0, $tval = 30) { - // set the error val to null so there is no confusion - $this->error = null; - - // make sure we are __not__ connected - if ($this->connected()) { - // already connected, generate error - $this->error = ["error" => "Already connected to a server"]; - - return false; - } - - if (empty($port)) { - $port = $this->SMTP_PORT; - } - - // connect to the smtp server - $this->smtp_conn = @fsockopen($host, // the host of the server - $port, // the port to use - $errno, // error number if any - $errstr, // error message if any - $tval); // give up after ? secs - // verify we connected properly - if (empty($this->smtp_conn)) { - $this->error = ["error" => "Failed to connect to server", - "errno" => $errno, - "errstr" => $errstr]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '
'; - } - - return false; - } - - // SMTP server can take longer to respond, give longer timeout for first read - // Windows does not have support for this timeout function - if (substr(PHP_OS, 0, 3) != "WIN") - socket_set_timeout($this->smtp_conn, $tval, 0); - - // get any announcement - $announce = $this->get_lines(); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '
'; - } - - return true; - } - - /** - * Returns true if connected to a server otherwise false - * @access public - * @return bool - */ - public function Connected() { - if (!empty($this->smtp_conn)) { - $sock_status = socket_get_status($this->smtp_conn); - if ($sock_status["eof"]) { - // the socket is valid but we are not connected - if ($this->do_debug >= 1) { - echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; - } - $this->Close(); - - return false; - } - - return true; // everything looks good - } - - return false; - } - - /** - * Closes the socket and cleans up the state of the class. - * It is not considered good to use this function without - * first trying to use QUIT. - * @access public - * @return void - */ - public function Close() { - $this->error = null; // so there is no confusion - $this->helo_rply = null; - if (!empty($this->smtp_conn)) { - // close the connection and cleanup - fclose($this->smtp_conn); - $this->smtp_conn = 0; - } - } - - /** - * Read in as many lines as possible - * either before eof or socket timeout occurs on the operation. - * With SMTP we can tell if we have more lines to read if the - * 4th character is '-' symbol. If it is a space then we don't - * need to read anything else. - * @access private - * @return string - */ - private function get_lines() { - $data = ""; - while ($str = @fgets($this->smtp_conn, 515)) { - if ($this->do_debug >= 4) { - echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '
'; - echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '
'; - } - $data .= $str; - if ($this->do_debug >= 4) { - echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '
'; - } - // if 4th character is a space, we are done reading, break the loop - if (substr($str, 3, 1) == " ") { - break; - } - } - - return $data; - } - - /** - * Initiate a TLS communication with the server. - * - * SMTP CODE 220 Ready to start TLS - * SMTP CODE 501 Syntax error (no parameters allowed) - * SMTP CODE 454 TLS not available due to temporary reason - * @access public - * @return bool success - */ - public function StartTLS() { - $this->error = null; # to avoid confusion - - if (!$this->connected()) { - $this->error = ["error" => "Called StartTLS() without being connected"]; - - return false; - } - - fputs($this->smtp_conn, "STARTTLS" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if ($code != 220) { - $this->error = - ["error" => "STARTTLS not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - // Begin encrypted connection - if (!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { - return false; - } - - return true; - } - - ///////////////////////////////////////////////// - // SMTP COMMANDS - ///////////////////////////////////////////////// - - /** - * Performs SMTP authentication. Must be run after running the - * Hello() method. Returns true if successfully authenticated. - * @access public - * @return bool - */ - public function Authenticate($username, $password) { - // Start authentication - fputs($this->smtp_conn, "AUTH LOGIN" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($code != 334) { - $this->error = - ["error" => "AUTH not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - // Send encoded username - fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($code != 334) { - $this->error = - ["error" => "Username not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - // Send encoded password - fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($code != 235) { - $this->error = - ["error" => "Password not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - return true; - } - - /** - * Issues a data command and sends the msg_data to the server - * finializing the mail transaction. $msg_data is the message - * that is to be send with the headers. Each header needs to be - * on a single line followed by a with the message headers - * and the message body being seperated by and additional . - * - * Implements rfc 821: DATA - * - * SMTP CODE INTERMEDIATE: 354 - * [data] - * . - * SMTP CODE SUCCESS: 250 - * SMTP CODE FAILURE: 552,554,451,452 - * SMTP CODE FAILURE: 451,554 - * SMTP CODE ERROR : 500,501,503,421 - * @access public - * @return bool - */ - public function Data($msg_data) { - $this->error = null; // so no confusion is caused - - if (!$this->connected()) { - $this->error = [ - "error" => "Called Data() without being connected"]; - - return false; - } - - fputs($this->smtp_conn, "DATA" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if ($code != 354) { - $this->error = - ["error" => "DATA command not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - /* the server is ready to accept data! - * according to rfc 821 we should not send more than 1000 - * including the CRLF - * characters on a single line so we will break the data up - * into lines by \r and/or \n then if needed we will break - * each of those into smaller lines to fit within the limit. - * in addition we will be looking for lines that start with - * a period '.' and append and additional period '.' to that - * line. NOTE: this does not count towards limit. - */ - - // normalize the line breaks so we know the explode works - $msg_data = str_replace("\r\n", "\n", $msg_data); - $msg_data = str_replace("\r", "\n", $msg_data); - $lines = explode("\n", $msg_data); - - /* we need to find a good way to determine is headers are - * in the msg_data or if it is a straight msg body - * currently I am assuming rfc 822 definitions of msg headers - * and if the first field of the first line (':' sperated) - * does not contain a space then it _should_ be a header - * and we can process all lines before a blank "" line as - * headers. - */ - - $field = substr($lines[0], 0, strpos($lines[0], ":")); - $in_headers = false; - if (!empty($field) && !strstr($field, " ")) { - $in_headers = true; - } - - $max_line_length = 998; // used below; set here for ease in change - - while (list(, $line) = @each($lines)) { - $lines_out = null; - if ($line == "" && $in_headers) { - $in_headers = false; - } - // ok we need to break this line up into several smaller lines - while (strlen($line) > $max_line_length) { - $pos = strrpos(substr($line, 0, $max_line_length), " "); - - // Patch to fix DOS attack - if (!$pos) { - $pos = $max_line_length - 1; - $lines_out[] = substr($line, 0, $pos); - $line = substr($line, $pos); - } else { - $lines_out[] = substr($line, 0, $pos); - $line = substr($line, $pos + 1); - } - - /* if processing headers add a LWSP-char to the front of new line - * rfc 822 on long msg headers - */ - if ($in_headers) { - $line = "\t" . $line; - } - } - $lines_out[] = $line; - - // send the lines to the server - while (list(, $line_out) = @each($lines_out)) { - if (strlen($line_out) > 0) { - if (substr($line_out, 0, 1) == ".") { - $line_out = "." . $line_out; - } - } - fputs($this->smtp_conn, $line_out . $this->CRLF); - } - } - - // message data has been sent - fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if ($code != 250) { - $this->error = - ["error" => "DATA not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - return true; - } - - /** - * Sends the HELO command to the smtp server. - * This makes sure that we and the server are in - * the same known state. - * - * Implements from rfc 821: HELO - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE ERROR : 500, 501, 504, 421 - * @access public - * @return bool - */ - public function Hello($host = '') { - $this->error = null; // so no confusion is caused - - if (!$this->connected()) { - $this->error = [ - "error" => "Called Hello() without being connected"]; - - return false; - } - - // if hostname for HELO was not specified send default - if (empty($host)) { - // determine appropriate default to send to server - $host = "localhost"; - } - - // Send extended hello first (RFC 2821) - if (!$this->SendHello("EHLO", $host)) { - if (!$this->SendHello("HELO", $host)) { - return false; - } - } - - return true; - } - - /** - * Sends a HELO/EHLO command. - * @access private - * @return bool - */ - private function SendHello($hello, $host) { - fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '
'; - } - - if ($code != 250) { - $this->error = - ["error" => $hello . " not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - $this->helo_rply = $rply; - - return true; - } - - /** - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more Recipient - * commands may be called followed by a Data command. - * - * Implements rfc 821: MAIL FROM: - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE SUCCESS: 552,451,452 - * SMTP CODE SUCCESS: 500,501,421 - * @access public - * @return bool - */ - public function Mail($from) { - $this->error = null; // so no confusion is caused - - if (!$this->connected()) { - $this->error = [ - "error" => "Called Mail() without being connected"]; - - return false; - } - - $useVerp = ($this->do_verp ? "XVERP" : ""); - fputs($this->smtp_conn, "MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if ($code != 250) { - $this->error = - ["error" => "MAIL not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - return true; - } - - /** - * Sends the quit command to the server and then closes the socket - * if there is no error or the $close_on_error argument is true. - * - * Implements from rfc 821: QUIT - * - * SMTP CODE SUCCESS: 221 - * SMTP CODE ERROR : 500 - * @access public - * @return bool - */ - public function Quit($close_on_error = true) { - $this->error = null; // so there is no confusion - - if (!$this->connected()) { - $this->error = [ - "error" => "Called Quit() without being connected"]; - - return false; - } - - // send the quit command to the server - fputs($this->smtp_conn, "quit" . $this->CRLF); - - // get any good-bye messages - $byemsg = $this->get_lines(); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '
'; - } - - $rval = true; - $e = null; - - $code = substr($byemsg, 0, 3); - if ($code != 221) { - // use e as a tmp var cause Close will overwrite $this->error - $e = ["error" => "SMTP server rejected quit command", - "smtp_code" => $code, - "smtp_rply" => substr($byemsg, 4)]; - $rval = false; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '
'; - } - } - - if (empty($e) || $close_on_error) { - $this->Close(); - } - - return $rval; - } - - /** - * Sends the command RCPT to the SMTP server with the TO: argument of $to. - * Returns true if the recipient was accepted false if it was rejected. - * - * Implements from rfc 821: RCPT TO: - * - * SMTP CODE SUCCESS: 250,251 - * SMTP CODE FAILURE: 550,551,552,553,450,451,452 - * SMTP CODE ERROR : 500,501,503,421 - * @access public - * @return bool - */ - public function Recipient($to) { - $this->error = null; // so no confusion is caused - - if (!$this->connected()) { - $this->error = [ - "error" => "Called Recipient() without being connected"]; - - return false; - } - - fputs($this->smtp_conn, "RCPT TO:<" . $to . ">" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if ($code != 250 && $code != 251) { - $this->error = - ["error" => "RCPT not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - return true; - } - - /** - * Sends the RSET command to abort and transaction that is - * currently in progress. Returns true if successful false - * otherwise. - * - * Implements rfc 821: RSET - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE ERROR : 500,501,504,421 - * @access public - * @return bool - */ - public function Reset() { - $this->error = null; // so no confusion is caused - - if (!$this->connected()) { - $this->error = [ - "error" => "Called Reset() without being connected"]; - - return false; - } - - fputs($this->smtp_conn, "RSET" . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if ($code != 250) { - $this->error = - ["error" => "RSET failed", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - return true; - } - - /** - * Starts a mail transaction from the email address specified in - * $from. Returns true if successful or false otherwise. If True - * the mail transaction is started and then one or more Recipient - * commands may be called followed by a Data command. This command - * will send the message to the users terminal if they are logged - * in and send them an email. - * - * Implements rfc 821: SAML FROM: - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE SUCCESS: 552,451,452 - * SMTP CODE SUCCESS: 500,501,502,421 - * @access public - * @return bool - */ - public function SendAndMail($from) { - $this->error = null; // so no confusion is caused - - if (!$this->connected()) { - $this->error = [ - "error" => "Called SendAndMail() without being connected"]; - - return false; - } - - fputs($this->smtp_conn, "SAML FROM:" . $from . $this->CRLF); - - $rply = $this->get_lines(); - $code = substr($rply, 0, 3); - - if ($this->do_debug >= 2) { - echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; - } - - if ($code != 250) { - $this->error = - ["error" => "SAML not accepted from server", - "smtp_code" => $code, - "smtp_msg" => substr($rply, 4)]; - if ($this->do_debug >= 1) { - echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; - } - - return false; - } - - return true; - } - - /** - * This is an optional command for SMTP that this class does not - * support. This method is here to make the RFC821 Definition - * complete for this class and __may__ be implimented in the future - * - * Implements from rfc 821: TURN - * - * SMTP CODE SUCCESS: 250 - * SMTP CODE FAILURE: 502 - * SMTP CODE ERROR : 500, 503 - * @access public - * @return bool - */ - public function Turn() { - $this->error = ["error" => "This method, TURN, of the SMTP " . - "is not implemented"]; - if ($this->do_debug >= 1) { - echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '
'; - } - - return false; - } - - ///////////////////////////////////////////////// - // INTERNAL FUNCTIONS - ///////////////////////////////////////////////// - - /** - * Get the current error - * @access public - * @return array - */ - public function getError() { - return $this->error; - } - - } - +smtp_conn = 0; + $this->error = null; + $this->helo_rply = null; + + $this->do_debug = 0; + } + + ///////////////////////////////////////////////// + // CONNECTION FUNCTIONS + ///////////////////////////////////////////////// + + /** + * Connect to the server specified on the port specified. + * If the port is not specified use the default SMTP_PORT. + * If tval is specified then a connection will try and be + * established with the server for that number of seconds. + * If tval is not specified the default is 30 seconds to + * try on the connection. + * + * SMTP CODE SUCCESS: 220 + * SMTP CODE FAILURE: 421 + * @access public + * @return bool + */ + public function Connect($host, $port = 0, $tval = 30) { + // set the error val to null so there is no confusion + $this->error = null; + + // make sure we are __not__ connected + if ($this->connected()) { + // already connected, generate error + $this->error = ["error" => "Already connected to a server"]; + + return false; + } + + if (empty($port)) { + $port = $this->SMTP_PORT; + } + + // connect to the smtp server + $this->smtp_conn = @fsockopen($host, // the host of the server + $port, // the port to use + $errno, // error number if any + $errstr, // error message if any + $tval); // give up after ? secs + // verify we connected properly + if (empty($this->smtp_conn)) { + $this->error = ["error" => "Failed to connect to server", + "errno" => $errno, + "errstr" => $errstr]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '
'; + } + + return false; + } + + // SMTP server can take longer to respond, give longer timeout for first read + // Windows does not have support for this timeout function + if (substr(PHP_OS, 0, 3) != "WIN") + socket_set_timeout($this->smtp_conn, $tval, 0); + + // get any announcement + $announce = $this->get_lines(); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '
'; + } + + return true; + } + + /** + * Returns true if connected to a server otherwise false + * @access public + * @return bool + */ + public function Connected() { + if (!empty($this->smtp_conn)) { + $sock_status = socket_get_status($this->smtp_conn); + if ($sock_status["eof"]) { + // the socket is valid but we are not connected + if ($this->do_debug >= 1) { + echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; + } + $this->Close(); + + return false; + } + + return true; // everything looks good + } + + return false; + } + + /** + * Closes the socket and cleans up the state of the class. + * It is not considered good to use this function without + * first trying to use QUIT. + * @access public + * @return void + */ + public function Close() { + $this->error = null; // so there is no confusion + $this->helo_rply = null; + if (!empty($this->smtp_conn)) { + // close the connection and cleanup + fclose($this->smtp_conn); + $this->smtp_conn = 0; + } + } + + /** + * Read in as many lines as possible + * either before eof or socket timeout occurs on the operation. + * With SMTP we can tell if we have more lines to read if the + * 4th character is '-' symbol. If it is a space then we don't + * need to read anything else. + * @access private + * @return string + */ + private function get_lines() { + $data = ""; + while ($str = @fgets($this->smtp_conn, 515)) { + if ($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '
'; + echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '
'; + } + $data .= $str; + if ($this->do_debug >= 4) { + echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '
'; + } + // if 4th character is a space, we are done reading, break the loop + if (substr($str, 3, 1) == " ") { + break; + } + } + + return $data; + } + + /** + * Initiate a TLS communication with the server. + * + * SMTP CODE 220 Ready to start TLS + * SMTP CODE 501 Syntax error (no parameters allowed) + * SMTP CODE 454 TLS not available due to temporary reason + * @access public + * @return bool success + */ + public function StartTLS() { + $this->error = null; # to avoid confusion + + if (!$this->connected()) { + $this->error = ["error" => "Called StartTLS() without being connected"]; + + return false; + } + + fputs($this->smtp_conn, "STARTTLS" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; + } + + if ($code != 220) { + $this->error = + ["error" => "STARTTLS not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + // Begin encrypted connection + if (!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { + return false; + } + + return true; + } + + ///////////////////////////////////////////////// + // SMTP COMMANDS + ///////////////////////////////////////////////// + + /** + * Performs SMTP authentication. Must be run after running the + * Hello() method. Returns true if successfully authenticated. + * @access public + * @return bool + */ + public function Authenticate($username, $password) { + // Start authentication + fputs($this->smtp_conn, "AUTH LOGIN" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($code != 334) { + $this->error = + ["error" => "AUTH not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + // Send encoded username + fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($code != 334) { + $this->error = + ["error" => "Username not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + // Send encoded password + fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($code != 235) { + $this->error = + ["error" => "Password not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + return true; + } + + /** + * Issues a data command and sends the msg_data to the server + * finializing the mail transaction. $msg_data is the message + * that is to be send with the headers. Each header needs to be + * on a single line followed by a with the message headers + * and the message body being seperated by and additional . + * + * Implements rfc 821: DATA + * + * SMTP CODE INTERMEDIATE: 354 + * [data] + * . + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 552,554,451,452 + * SMTP CODE FAILURE: 451,554 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + public function Data($msg_data) { + $this->error = null; // so no confusion is caused + + if (!$this->connected()) { + $this->error = [ + "error" => "Called Data() without being connected"]; + + return false; + } + + fputs($this->smtp_conn, "DATA" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; + } + + if ($code != 354) { + $this->error = + ["error" => "DATA command not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + /* the server is ready to accept data! + * according to rfc 821 we should not send more than 1000 + * including the CRLF + * characters on a single line so we will break the data up + * into lines by \r and/or \n then if needed we will break + * each of those into smaller lines to fit within the limit. + * in addition we will be looking for lines that start with + * a period '.' and append and additional period '.' to that + * line. NOTE: this does not count towards limit. + */ + + // normalize the line breaks so we know the explode works + $msg_data = str_replace("\r\n", "\n", $msg_data); + $msg_data = str_replace("\r", "\n", $msg_data); + $lines = explode("\n", $msg_data); + + /* we need to find a good way to determine is headers are + * in the msg_data or if it is a straight msg body + * currently I am assuming rfc 822 definitions of msg headers + * and if the first field of the first line (':' sperated) + * does not contain a space then it _should_ be a header + * and we can process all lines before a blank "" line as + * headers. + */ + + $field = substr($lines[0], 0, strpos($lines[0], ":")); + $in_headers = false; + if (!empty($field) && !strstr($field, " ")) { + $in_headers = true; + } + + $max_line_length = 998; // used below; set here for ease in change + + while (list(, $line) = @each($lines)) { + $lines_out = null; + if ($line == "" && $in_headers) { + $in_headers = false; + } + // ok we need to break this line up into several smaller lines + while (strlen($line) > $max_line_length) { + $pos = strrpos(substr($line, 0, $max_line_length), " "); + + // Patch to fix DOS attack + if (!$pos) { + $pos = $max_line_length - 1; + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos); + } else { + $lines_out[] = substr($line, 0, $pos); + $line = substr($line, $pos + 1); + } + + /* if processing headers add a LWSP-char to the front of new line + * rfc 822 on long msg headers + */ + if ($in_headers) { + $line = "\t" . $line; + } + } + $lines_out[] = $line; + + // send the lines to the server + while (list(, $line_out) = @each($lines_out)) { + if (strlen($line_out) > 0) { + if (substr($line_out, 0, 1) == ".") { + $line_out = "." . $line_out; + } + } + fputs($this->smtp_conn, $line_out . $this->CRLF); + } + } + + // message data has been sent + fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; + } + + if ($code != 250) { + $this->error = + ["error" => "DATA not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + return true; + } + + /** + * Sends the HELO command to the smtp server. + * This makes sure that we and the server are in + * the same known state. + * + * Implements from rfc 821: HELO + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500, 501, 504, 421 + * @access public + * @return bool + */ + public function Hello($host = '') { + $this->error = null; // so no confusion is caused + + if (!$this->connected()) { + $this->error = [ + "error" => "Called Hello() without being connected"]; + + return false; + } + + // if hostname for HELO was not specified send default + if (empty($host)) { + // determine appropriate default to send to server + $host = "localhost"; + } + + // Send extended hello first (RFC 2821) + if (!$this->SendHello("EHLO", $host)) { + if (!$this->SendHello("HELO", $host)) { + return false; + } + } + + return true; + } + + /** + * Sends a HELO/EHLO command. + * @access private + * @return bool + */ + private function SendHello($hello, $host) { + fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '
'; + } + + if ($code != 250) { + $this->error = + ["error" => $hello . " not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + $this->helo_rply = $rply; + + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. + * + * Implements rfc 821: MAIL FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,421 + * @access public + * @return bool + */ + public function Mail($from) { + $this->error = null; // so no confusion is caused + + if (!$this->connected()) { + $this->error = [ + "error" => "Called Mail() without being connected"]; + + return false; + } + + $useVerp = ($this->do_verp ? "XVERP" : ""); + fputs($this->smtp_conn, "MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; + } + + if ($code != 250) { + $this->error = + ["error" => "MAIL not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + return true; + } + + /** + * Sends the quit command to the server and then closes the socket + * if there is no error or the $close_on_error argument is true. + * + * Implements from rfc 821: QUIT + * + * SMTP CODE SUCCESS: 221 + * SMTP CODE ERROR : 500 + * @access public + * @return bool + */ + public function Quit($close_on_error = true) { + $this->error = null; // so there is no confusion + + if (!$this->connected()) { + $this->error = [ + "error" => "Called Quit() without being connected"]; + + return false; + } + + // send the quit command to the server + fputs($this->smtp_conn, "quit" . $this->CRLF); + + // get any good-bye messages + $byemsg = $this->get_lines(); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '
'; + } + + $rval = true; + $e = null; + + $code = substr($byemsg, 0, 3); + if ($code != 221) { + // use e as a tmp var cause Close will overwrite $this->error + $e = ["error" => "SMTP server rejected quit command", + "smtp_code" => $code, + "smtp_rply" => substr($byemsg, 4)]; + $rval = false; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '
'; + } + } + + if (empty($e) || $close_on_error) { + $this->Close(); + } + + return $rval; + } + + /** + * Sends the command RCPT to the SMTP server with the TO: argument of $to. + * Returns true if the recipient was accepted false if it was rejected. + * + * Implements from rfc 821: RCPT TO: + * + * SMTP CODE SUCCESS: 250,251 + * SMTP CODE FAILURE: 550,551,552,553,450,451,452 + * SMTP CODE ERROR : 500,501,503,421 + * @access public + * @return bool + */ + public function Recipient($to) { + $this->error = null; // so no confusion is caused + + if (!$this->connected()) { + $this->error = [ + "error" => "Called Recipient() without being connected"]; + + return false; + } + + fputs($this->smtp_conn, "RCPT TO:<" . $to . ">" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; + } + + if ($code != 250 && $code != 251) { + $this->error = + ["error" => "RCPT not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + return true; + } + + /** + * Sends the RSET command to abort and transaction that is + * currently in progress. Returns true if successful false + * otherwise. + * + * Implements rfc 821: RSET + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE ERROR : 500,501,504,421 + * @access public + * @return bool + */ + public function Reset() { + $this->error = null; // so no confusion is caused + + if (!$this->connected()) { + $this->error = [ + "error" => "Called Reset() without being connected"]; + + return false; + } + + fputs($this->smtp_conn, "RSET" . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; + } + + if ($code != 250) { + $this->error = + ["error" => "RSET failed", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + return true; + } + + /** + * Starts a mail transaction from the email address specified in + * $from. Returns true if successful or false otherwise. If True + * the mail transaction is started and then one or more Recipient + * commands may be called followed by a Data command. This command + * will send the message to the users terminal if they are logged + * in and send them an email. + * + * Implements rfc 821: SAML FROM: + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE SUCCESS: 552,451,452 + * SMTP CODE SUCCESS: 500,501,502,421 + * @access public + * @return bool + */ + public function SendAndMail($from) { + $this->error = null; // so no confusion is caused + + if (!$this->connected()) { + $this->error = [ + "error" => "Called SendAndMail() without being connected"]; + + return false; + } + + fputs($this->smtp_conn, "SAML FROM:" . $from . $this->CRLF); + + $rply = $this->get_lines(); + $code = substr($rply, 0, 3); + + if ($this->do_debug >= 2) { + echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '
'; + } + + if ($code != 250) { + $this->error = + ["error" => "SAML not accepted from server", + "smtp_code" => $code, + "smtp_msg" => substr($rply, 4)]; + if ($this->do_debug >= 1) { + echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '
'; + } + + return false; + } + + return true; + } + + /** + * This is an optional command for SMTP that this class does not + * support. This method is here to make the RFC821 Definition + * complete for this class and __may__ be implimented in the future + * + * Implements from rfc 821: TURN + * + * SMTP CODE SUCCESS: 250 + * SMTP CODE FAILURE: 502 + * SMTP CODE ERROR : 500, 503 + * @access public + * @return bool + */ + public function Turn() { + $this->error = ["error" => "This method, TURN, of the SMTP " . + "is not implemented"]; + if ($this->do_debug >= 1) { + echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '
'; + } + + return false; + } + + ///////////////////////////////////////////////// + // INTERNAL FUNCTIONS + ///////////////////////////////////////////////// + + /** + * Get the current error + * @access public + * @return array + */ + public function getError() { + return $this->error; + } + + } + ?> \ No newline at end of file diff --git a/web/bin/classes/ClassSendCmd.php b/web/bin/classes/ClassSendCmd.php index ec10f4c..2677046 100644 --- a/web/bin/classes/ClassSendCmd.php +++ b/web/bin/classes/ClassSendCmd.php @@ -1,115 +1,115 @@ - 'play_notification', - 'arguments' => [], - 'options' => []], $room); - } - - static function remove_selector($remove_selector, $room) { - AppSocket::send_cmd('act_remove_selector', $remove_selector, $room); - } - - /** - * @param $module - * @param $table - * @param null $table_value - * @param $target_selector - * @param $room - * - * @return bool - */ - static function insert_mdl($module, $table, $table_value = null, $target_selector, $room) { - if (empty($table)) return false; - if (empty($target_selector)) return false; - - $target_selector = SendCmd::build_selector($target_selector); - AppSocket::send_cmd('act_insert_mdl', ['table' => $table, - 'table_value' => $table_value, - 'mdl' => $module, - 'target_selector' => $target_selector], $room); - } - - static function insert_selectors($target_selector_and_value = [], $room = null) { - if (empty($target_selector_and_value)) return false; - - AppSocket::send_cmd('act_insert_selector', $target_selector_and_value, $room); - } - - /** - * @param $target_selector - * @param $value - * @param $room - * - * @return bool - */ - static function insert_selector($target_selector, $value, $room) { - if (empty($target_selector)) return false; - - AppSocket::send_cmd('act_insert_selector', [$target_selector, - $value], $room); - } - - /** - * @param $mdl - * @param $table - * @param $table_value - * @param array $extra_vars - * @param $room_session_id - * - * @return bool - */ - static function notify_mdl($mdl, $table, $table_value, $extra_vars = [], $room_session_id) { - if (empty($room_session_id)) return false; - $extra_vars['table'] = $table; - $extra_vars['table_value'] = $table_value; - $httpvars = http_build_query($extra_vars); - NotifySite::notify_mdl('idae/module/' . $mdl . '/' . $httpvars, $extra_vars, $room_session_id); - } - - static function build_selector($target_selector) { - - if (!is_array($target_selector)) { - return $target_selector; - } - $return = ''; - foreach ($target_selector as $key => $selector) { - if (is_array($selector)) { - switch ($key) { - case ':not': - //$return .= "$key(".SendCmd::build_selector($selector).")"; - break; - default: - break; - } - $return .= ' ' . SendCmd::build_selector($selector); - - } else { - switch ($key) { - case ':not': - //$return .= "$key($selector)"; - break; - default: - $return .= "[$key=$selector]"; - break; - } - - } - } - - return $return; - } - - static function sendScript($script_name,$arguments = [],$room=null) { - AppSocket::send_cmd('act_script', ['script' => $script_name, - 'arguments' => $arguments], $room); - } + 'play_notification', + 'arguments' => [], + 'options' => []], $room); + } + + static function remove_selector($remove_selector, $room) { + AppSocket::send_cmd('act_remove_selector', $remove_selector, $room); + } + + /** + * @param $module + * @param $table + * @param null $table_value + * @param $target_selector + * @param $room + * + * @return bool + */ + static function insert_mdl($module, $table, $table_value = null, $target_selector, $room) { + if (empty($table)) return false; + if (empty($target_selector)) return false; + + $target_selector = SendCmd::build_selector($target_selector); + AppSocket::send_cmd('act_insert_mdl', ['table' => $table, + 'table_value' => $table_value, + 'mdl' => $module, + 'target_selector' => $target_selector], $room); + } + + static function insert_selectors($target_selector_and_value = [], $room = null) { + if (empty($target_selector_and_value)) return false; + + AppSocket::send_cmd('act_insert_selector', $target_selector_and_value, $room); + } + + /** + * @param $target_selector + * @param $value + * @param $room + * + * @return bool + */ + static function insert_selector($target_selector, $value, $room) { + if (empty($target_selector)) return false; + + AppSocket::send_cmd('act_insert_selector', [$target_selector, + $value], $room); + } + + /** + * @param $mdl + * @param $table + * @param $table_value + * @param array $extra_vars + * @param $room_session_id + * + * @return bool + */ + static function notify_mdl($mdl, $table, $table_value, $extra_vars = [], $room_session_id) { + if (empty($room_session_id)) return false; + $extra_vars['table'] = $table; + $extra_vars['table_value'] = $table_value; + $httpvars = http_build_query($extra_vars); + NotifySite::notify_mdl('idae/module/' . $mdl . '/' . $httpvars, $extra_vars, $room_session_id); + } + + static function build_selector($target_selector) { + + if (!is_array($target_selector)) { + return $target_selector; + } + $return = ''; + foreach ($target_selector as $key => $selector) { + if (is_array($selector)) { + switch ($key) { + case ':not': + //$return .= "$key(".SendCmd::build_selector($selector).")"; + break; + default: + break; + } + $return .= ' ' . SendCmd::build_selector($selector); + + } else { + switch ($key) { + case ':not': + //$return .= "$key($selector)"; + break; + default: + $return .= "[$key=$selector]"; + break; + } + + } + } + + return $return; + } + + static function sendScript($script_name,$arguments = [],$room=null) { + AppSocket::send_cmd('act_script', ['script' => $script_name, + 'arguments' => $arguments], $room); + } } \ No newline at end of file diff --git a/web/bin/classes/ClassSession.php b/web/bin/classes/ClassSession.php index d830a16..a3ffdbe 100644 --- a/web/bin/classes/ClassSession.php +++ b/web/bin/classes/ClassSession.php @@ -1,64 +1,64 @@ - 'admin', 'username' => MDB_USER, 'password' => MDB_PASSWORD]; - - $this->conn = new MongoClient('mongodb://admin:gwetme2011@127.0.0.1',$opt); - - $sitebase_app = DEFINED(MDB_PREFIX) ? 'sitebase_session' : MDB_PREFIX . 'sitebase_session'; - if(ENVIRONEMENT=='PREPROD') $sitebase_app .='_preprod'; - if(ENVIRONEMENT=='PREPROD_LAN') $sitebase_app .='_preprod'; - - $this->dbSession = $this->conn->$sitebase_app->session; - $this->maxTime = 3600; - - - $this->dbSession->ensureIndex(['timeStamp' => 1]); - $this->dbSession->ensureIndex(['timeStamp' => -1]); - } - - public function open() { return true; } - - public function close() { return true; } - - public function read($id) { - $this->gc(); - $doc = $this->dbSession->findOne(["_id" => $id], ["sessionData" => 1]); - - return $doc['sessionData']; - } - - public function gc() { - $lastAccessed = time() - $this->maxTime; - $this->dbSession->remove(["timeStamp" => ['$lt' => $lastAccessed]]); - } - - public function write($id, $data) { - // - if(empty($id)) return false; - $set = ["sessionData" => $data, "timeStamp" => time(),'date_heure'=>date('d-m-Y H:i:s', time() - $this->maxTime),'referrer'=>$_SERVER['HTTP_REFERER'],'nodebug'=>true,'MDB_PREFIX'=>MDB_PREFIX,'ENVIRONEMENT'=>ENVIRONEMENT ]; - $this->dbSession->update(["_id" => $id],['$set'=>$set],['upsert'=>true]); - - return true; - } - - public function destroy($id) { - $this->dbSession->remove(["_id" => $id]); - - return true; - } - } - - - // session_set_save_handler(); - // ini_set('session.save_handler', 'user'); + 'admin', 'username' => MDB_USER, 'password' => MDB_PASSWORD]; + + $this->conn = new MongoClient('mongodb://admin:gwetme2011@127.0.0.1',$opt); + + $sitebase_app = DEFINED(MDB_PREFIX) ? 'sitebase_session' : MDB_PREFIX . 'sitebase_session'; + if(ENVIRONEMENT=='PREPROD') $sitebase_app .='_preprod'; + if(ENVIRONEMENT=='PREPROD_LAN') $sitebase_app .='_preprod'; + + $this->dbSession = $this->conn->$sitebase_app->session; + $this->maxTime = 3600; + + + $this->dbSession->ensureIndex(['timeStamp' => 1]); + $this->dbSession->ensureIndex(['timeStamp' => -1]); + } + + public function open() { return true; } + + public function close() { return true; } + + public function read($id) { + $this->gc(); + $doc = $this->dbSession->findOne(["_id" => $id], ["sessionData" => 1]); + + return $doc['sessionData']; + } + + public function gc() { + $lastAccessed = time() - $this->maxTime; + $this->dbSession->remove(["timeStamp" => ['$lt' => $lastAccessed]]); + } + + public function write($id, $data) { + // + if(empty($id)) return false; + $set = ["sessionData" => $data, "timeStamp" => time(),'date_heure'=>date('d-m-Y H:i:s', time() - $this->maxTime),'referrer'=>$_SERVER['HTTP_REFERER'],'nodebug'=>true,'MDB_PREFIX'=>MDB_PREFIX,'ENVIRONEMENT'=>ENVIRONEMENT ]; + $this->dbSession->update(["_id" => $id],['$set'=>$set],['upsert'=>true]); + + return true; + } + + public function destroy($id) { + $this->dbSession->remove(["_id" => $id]); + + return true; + } + } + + + // session_set_save_handler(); + // ini_set('session.save_handler', 'user'); diff --git a/web/bin/classes/Index.php b/web/bin/classes/Index.php index af62260..f954598 100644 --- a/web/bin/classes/Index.php +++ b/web/bin/classes/Index.php @@ -1,21 +1,21 @@ -renderToString(APPTPL.'orbit_big.html', $parameters); - - } +renderToString(APPTPL.'orbit_big.html', $parameters); + + } } \ No newline at end of file diff --git a/web/bin/classes/UploadHandler.php b/web/bin/classes/UploadHandler.php index 285d046..02d0d0b 100644 --- a/web/bin/classes/UploadHandler.php +++ b/web/bin/classes/UploadHandler.php @@ -1,1411 +1,1411 @@ - 'The uploaded file exceeds the upload_max_filesize directive in php.ini', - 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', - 3 => 'The uploaded file was only partially uploaded', - 4 => 'No file was uploaded', - 6 => 'Missing a temporary folder', - 7 => 'Failed to write file to disk', - 8 => 'A PHP extension stopped the file upload', - 'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini', - 'max_file_size' => 'File is too big', - 'min_file_size' => 'File is too small', - 'accept_file_types' => 'Filetype not allowed', - 'max_number_of_files' => 'Maximum number of files exceeded', - 'max_width' => 'Image exceeds maximum width', - 'min_width' => 'Image requires a minimum width', - 'max_height' => 'Image exceeds maximum height', - 'min_height' => 'Image requires a minimum height', - 'abort' => 'File upload aborted', - 'image_resize' => 'Failed to resize image' - ); - - protected $image_objects = array(); - - public function __construct($options = null, $initialize = true, $error_messages = null) { - $this->response = array(); - $this->options = array( - 'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')), - 'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/', - 'upload_url' => $this->get_full_url().'/files/', - 'input_stream' => 'php://input', - 'user_dirs' => false, - 'mkdir_mode' => 0755, - 'param_name' => 'files', - // Set the following option to 'POST', if your server does not support - // DELETE requests. This is a parameter sent to the client: - 'delete_type' => 'DELETE', - 'access_control_allow_origin' => '*', - 'access_control_allow_credentials' => false, - 'access_control_allow_methods' => array( - 'OPTIONS', - 'HEAD', - 'GET', - 'POST', - 'PUT', - 'PATCH', - 'DELETE' - ), - 'access_control_allow_headers' => array( - 'Content-Type', - 'Content-Range', - 'Content-Disposition' - ), - // By default, allow redirects to the referer protocol+host: - 'redirect_allow_target' => '/^'.preg_quote( - parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_SCHEME) - .'://' - .parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_HOST) - .'/', // Trailing slash to not match subdomains by mistake - '/' // preg_quote delimiter param - ).'/', - // Enable to provide file downloads via GET requests to the PHP script: - // 1. Set to 1 to download files via readfile method through PHP - // 2. Set to 2 to send a X-Sendfile header for lighttpd/Apache - // 3. Set to 3 to send a X-Accel-Redirect header for nginx - // If set to 2 or 3, adjust the upload_url option to the base path of - // the redirect parameter, e.g. '/files/'. - 'download_via_php' => false, - // Read files in chunks to avoid memory limits when download_via_php - // is enabled, set to 0 to disable chunked reading of files: - 'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB - // Defines which files can be displayed inline when downloaded: - 'inline_file_types' => '/\.(gif|jpe?g|png)$/i', - // Defines which files (based on their names) are accepted for upload: - 'accept_file_types' => '/.+$/i', - // The php.ini settings upload_max_filesize and post_max_size - // take precedence over the following max_file_size setting: - 'max_file_size' => null, - 'min_file_size' => 1, - // The maximum number of files for the upload directory: - 'max_number_of_files' => null, - // Defines which files are handled as image files: - 'image_file_types' => '/\.(gif|jpe?g|png)$/i', - // Use exif_imagetype on all files to correct file extensions: - 'correct_image_extensions' => false, - // Image resolution restrictions: - 'max_width' => null, - 'max_height' => null, - 'min_width' => 1, - 'min_height' => 1, - // Set the following option to false to enable resumable uploads: - 'discard_aborted_uploads' => true, - // Set to 0 to use the GD library to scale and orient images, - // set to 1 to use imagick (if installed, falls back to GD), - // set to 2 to use the ImageMagick convert binary directly: - 'image_library' => 1, - // Uncomment the following to define an array of resource limits - // for imagick: - /* - 'imagick_resource_limits' => array( - imagick::RESOURCETYPE_MAP => 32, - imagick::RESOURCETYPE_MEMORY => 32 - ), - */ - // Command or path for to the ImageMagick convert binary: - 'convert_bin' => 'convert', - // Uncomment the following to add parameters in front of each - // ImageMagick convert call (the limit constraints seem only - // to have an effect if put in front): - /* - 'convert_params' => '-limit memory 32MiB -limit map 32MiB', - */ - // Command or path for to the ImageMagick identify binary: - 'identify_bin' => 'identify', - 'image_versions' => array( - // The empty image version key defines options for the original image. - // Keep in mind: these image manipulations are inherited by all other image versions from this point onwards. - // Also note that the property 'no_cache' is not inherited, since it's not a manipulation. - '' => array( - // Automatically rotate images based on EXIF meta data: - 'auto_orient' => true - ), - // You can add arrays to generate different versions. - // The name of the key is the name of the version (example: 'medium'). - // the array contains the options to apply. - /* - 'medium' => array( - 'max_width' => 800, - 'max_height' => 600 - ), - */ - 'thumbnail' => array( - // Uncomment the following to use a defined directory for the thumbnails - // instead of a subdirectory based on the version identifier. - // Make sure that this directory doesn't allow execution of files if you - // don't pose any restrictions on the type of uploaded files, e.g. by - // copying the .htaccess file from the files directory for Apache: - //'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/thumb/', - //'upload_url' => $this->get_full_url().'/thumb/', - // Uncomment the following to force the max - // dimensions and e.g. create square thumbnails: - // 'auto_orient' => true, - // 'crop' => true, - // 'jpeg_quality' => 70, - // 'no_cache' => true, (there's a caching option, but this remembers thumbnail sizes from a previous action!) - // 'strip' => true, (this strips EXIF tags, such as geolocation) - 'max_width' => 80, // either specify width, or set to 0. Then width is automatically adjusted - keeping aspect ratio to a specified max_height. - 'max_height' => 80 // either specify height, or set to 0. Then height is automatically adjusted - keeping aspect ratio to a specified max_width. - ) - ), - 'print_response' => true - ); - if ($options) { - $this->options = $options + $this->options; - } - if ($error_messages) { - $this->error_messages = $error_messages + $this->error_messages; - } - if ($initialize) { - $this->initialize(); - } - } - - protected function initialize() { - switch ($this->get_server_var('REQUEST_METHOD')) { - case 'OPTIONS': - case 'HEAD': - $this->head(); - break; - case 'GET': - $this->get($this->options['print_response']); - break; - case 'PATCH': - case 'PUT': - case 'POST': - $this->post($this->options['print_response']); - break; - case 'DELETE': - $this->delete($this->options['print_response']); - break; - default: - $this->header('HTTP/1.1 405 Method Not Allowed'); - } - } - - protected function get_full_url() { - $https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 || - !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && - strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0; - return - ($https ? 'https://' : 'http://'). - (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : ''). - (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME']. - ($https && $_SERVER['SERVER_PORT'] === 443 || - $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))). - substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/')); - } - - protected function get_user_id() { - @session_start(); - return session_id(); - } - - protected function get_user_path() { - if ($this->options['user_dirs']) { - return $this->get_user_id().'/'; - } - return ''; - } - - protected function get_upload_path($file_name = null, $version = null) { - $file_name = $file_name ? $file_name : ''; - if (empty($version)) { - $version_path = ''; - } else { - $version_dir = @$this->options['image_versions'][$version]['upload_dir']; - if ($version_dir) { - return $version_dir.$this->get_user_path().$file_name; - } - $version_path = $version.'/'; - } - return $this->options['upload_dir'].$this->get_user_path() - .$version_path.$file_name; - } - - protected function get_query_separator($url) { - return strpos($url, '?') === false ? '?' : '&'; - } - - protected function get_download_url($file_name, $version = null, $direct = false) { - if (!$direct && $this->options['download_via_php']) { - $url = $this->options['script_url'] - .$this->get_query_separator($this->options['script_url']) - .$this->get_singular_param_name() - .'='.rawurlencode($file_name); - if ($version) { - $url .= '&version='.rawurlencode($version); - } - return $url.'&download=1'; - } - if (empty($version)) { - $version_path = ''; - } else { - $version_url = @$this->options['image_versions'][$version]['upload_url']; - if ($version_url) { - return $version_url.$this->get_user_path().rawurlencode($file_name); - } - $version_path = rawurlencode($version).'/'; - } - return $this->options['upload_url'].$this->get_user_path() - .$version_path.rawurlencode($file_name); - } - - protected function set_additional_file_properties($file) { - $file->deleteUrl = $this->options['script_url'] - .$this->get_query_separator($this->options['script_url']) - .$this->get_singular_param_name() - .'='.rawurlencode($file->name); - $file->deleteType = $this->options['delete_type']; - if ($file->deleteType !== 'DELETE') { - $file->deleteUrl .= '&_method=DELETE'; - } - if ($this->options['access_control_allow_credentials']) { - $file->deleteWithCredentials = true; - } - } - - // Fix for overflowing signed 32 bit integers, - // works for sizes up to 2^32-1 bytes (4 GiB - 1): - protected function fix_integer_overflow($size) { - if ($size < 0) { - $size += 2.0 * (PHP_INT_MAX + 1); - } - return $size; - } - - protected function get_file_size($file_path, $clear_stat_cache = false) { - if ($clear_stat_cache) { - if (version_compare(PHP_VERSION, '5.3.0') >= 0) { - clearstatcache(true, $file_path); - } else { - clearstatcache(); - } - } - return $this->fix_integer_overflow(filesize($file_path)); - } - - protected function is_valid_file_object($file_name) { - $file_path = $this->get_upload_path($file_name); - if (is_file($file_path) && $file_name[0] !== '.') { - return true; - } - return false; - } - - protected function get_file_object($file_name) { - if ($this->is_valid_file_object($file_name)) { - $file = new \stdClass(); - $file->name = $file_name; - $file->size = $this->get_file_size( - $this->get_upload_path($file_name) - ); - $file->url = $this->get_download_url($file->name); - foreach ($this->options['image_versions'] as $version => $options) { - if (!empty($version)) { - if (is_file($this->get_upload_path($file_name, $version))) { - $file->{$version.'Url'} = $this->get_download_url( - $file->name, - $version - ); - } - } - } - $this->set_additional_file_properties($file); - return $file; - } - return null; - } - - protected function get_file_objects($iteration_method = 'get_file_object') { - $upload_dir = $this->get_upload_path(); - if (!is_dir($upload_dir)) { - return array(); - } - return array_values(array_filter(array_map( - array($this, $iteration_method), - scandir($upload_dir) - ))); - } - - protected function count_file_objects() { - return count($this->get_file_objects('is_valid_file_object')); - } - - protected function get_error_message($error) { - return isset($this->error_messages[$error]) ? - $this->error_messages[$error] : $error; - } - - public function get_config_bytes($val) { - $val = trim($val); - $last = strtolower($val[strlen($val)-1]); - $val = (int)$val; - switch ($last) { - case 'g': - $val *= 1024; - case 'm': - $val *= 1024; - case 'k': - $val *= 1024; - } - return $this->fix_integer_overflow($val); - } - - protected function validate($uploaded_file, $file, $error, $index) { - if ($error) { - $file->error = $this->get_error_message($error); - return false; - } - $content_length = $this->fix_integer_overflow( - (int)$this->get_server_var('CONTENT_LENGTH') - ); - $post_max_size = $this->get_config_bytes(ini_get('post_max_size')); - if ($post_max_size && ($content_length > $post_max_size)) { - $file->error = $this->get_error_message('post_max_size'); - return false; - } - if (!preg_match($this->options['accept_file_types'], $file->name)) { - $file->error = $this->get_error_message('accept_file_types'); - return false; - } - if ($uploaded_file && is_uploaded_file($uploaded_file)) { - $file_size = $this->get_file_size($uploaded_file); - } else { - $file_size = $content_length; - } - if ($this->options['max_file_size'] && ( - $file_size > $this->options['max_file_size'] || - $file->size > $this->options['max_file_size']) - ) { - $file->error = $this->get_error_message('max_file_size'); - return false; - } - if ($this->options['min_file_size'] && - $file_size < $this->options['min_file_size']) { - $file->error = $this->get_error_message('min_file_size'); - return false; - } - if (is_int($this->options['max_number_of_files']) && - ($this->count_file_objects() >= $this->options['max_number_of_files']) && - // Ignore additional chunks of existing files: - !is_file($this->get_upload_path($file->name))) { - $file->error = $this->get_error_message('max_number_of_files'); - return false; - } - $max_width = @$this->options['max_width']; - $max_height = @$this->options['max_height']; - $min_width = @$this->options['min_width']; - $min_height = @$this->options['min_height']; - if (($max_width || $max_height || $min_width || $min_height) - && preg_match($this->options['image_file_types'], $file->name)) { - list($img_width, $img_height) = $this->get_image_size($uploaded_file); - - // If we are auto rotating the image by default, do the checks on - // the correct orientation - if ( - @$this->options['image_versions']['']['auto_orient'] && - function_exists('exif_read_data') && - ($exif = @exif_read_data($uploaded_file)) && - (((int) @$exif['Orientation']) >= 5) - ) { - $tmp = $img_width; - $img_width = $img_height; - $img_height = $tmp; - unset($tmp); - } - - } - if (!empty($img_width)) { - if ($max_width && $img_width > $max_width) { - $file->error = $this->get_error_message('max_width'); - return false; - } - if ($max_height && $img_height > $max_height) { - $file->error = $this->get_error_message('max_height'); - return false; - } - if ($min_width && $img_width < $min_width) { - $file->error = $this->get_error_message('min_width'); - return false; - } - if ($min_height && $img_height < $min_height) { - $file->error = $this->get_error_message('min_height'); - return false; - } - } - return true; - } - - protected function upcount_name_callback($matches) { - $index = isset($matches[1]) ? ((int)$matches[1]) + 1 : 1; - $ext = isset($matches[2]) ? $matches[2] : ''; - return ' ('.$index.')'.$ext; - } - - protected function upcount_name($name) { - return preg_replace_callback( - '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', - array($this, 'upcount_name_callback'), - $name, - 1 - ); - } - - protected function get_unique_filename($file_path, $name, $size, $type, $error, - $index, $content_range) { - while(is_dir($this->get_upload_path($name))) { - $name = $this->upcount_name($name); - } - // Keep an existing filename if this is part of a chunked upload: - $uploaded_bytes = $this->fix_integer_overflow((int)$content_range[1]); - while (is_file($this->get_upload_path($name))) { - if ($uploaded_bytes === $this->get_file_size( - $this->get_upload_path($name))) { - break; - } - $name = $this->upcount_name($name); - } - return $name; - } - - protected function fix_file_extension($file_path, $name, $size, $type, $error, - $index, $content_range) { - // Add missing file extension for known image types: - if (strpos($name, '.') === false && - preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) { - $name .= '.'.$matches[1]; - } - if ($this->options['correct_image_extensions'] && - function_exists('exif_imagetype')) { - switch (@exif_imagetype($file_path)){ - case IMAGETYPE_JPEG: - $extensions = array('jpg', 'jpeg'); - break; - case IMAGETYPE_PNG: - $extensions = array('png'); - break; - case IMAGETYPE_GIF: - $extensions = array('gif'); - break; - } - // Adjust incorrect image file extensions: - if (!empty($extensions)) { - $parts = explode('.', $name); - $extIndex = count($parts) - 1; - $ext = strtolower(@$parts[$extIndex]); - if (!in_array($ext, $extensions)) { - $parts[$extIndex] = $extensions[0]; - $name = implode('.', $parts); - } - } - } - return $name; - } - - protected function trim_file_name($file_path, $name, $size, $type, $error, - $index, $content_range) { - // Remove path information and dots around the filename, to prevent uploading - // into different directories or replacing hidden system files. - // Also remove control characters and spaces (\x00..\x20) around the filename: - $name = trim($this->basename(stripslashes($name)), ".\x00..\x20"); - // Use a timestamp for empty filenames: - if (!$name) { - $name = str_replace('.', '-', microtime(true)); - } - return $name; - } - - protected function get_file_name($file_path, $name, $size, $type, $error, - $index, $content_range) { - $name = $this->trim_file_name($file_path, $name, $size, $type, $error, - $index, $content_range); - return $this->get_unique_filename( - $file_path, - $this->fix_file_extension($file_path, $name, $size, $type, $error, - $index, $content_range), - $size, - $type, - $error, - $index, - $content_range - ); - } - - protected function get_scaled_image_file_paths($file_name, $version) { - $file_path = $this->get_upload_path($file_name); - if (!empty($version)) { - $version_dir = $this->get_upload_path(null, $version); - if (!is_dir($version_dir)) { - mkdir($version_dir, $this->options['mkdir_mode'], true); - } - $new_file_path = $version_dir.'/'.$file_name; - } else { - $new_file_path = $file_path; - } - return array($file_path, $new_file_path); - } - - protected function gd_get_image_object($file_path, $func, $no_cache = false) { - if (empty($this->image_objects[$file_path]) || $no_cache) { - $this->gd_destroy_image_object($file_path); - $this->image_objects[$file_path] = $func($file_path); - } - return $this->image_objects[$file_path]; - } - - protected function gd_set_image_object($file_path, $image) { - $this->gd_destroy_image_object($file_path); - $this->image_objects[$file_path] = $image; - } - - protected function gd_destroy_image_object($file_path) { - $image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ; - return $image && imagedestroy($image); - } - - protected function gd_imageflip($image, $mode) { - if (function_exists('imageflip')) { - return imageflip($image, $mode); - } - $new_width = $src_width = imagesx($image); - $new_height = $src_height = imagesy($image); - $new_img = imagecreatetruecolor($new_width, $new_height); - $src_x = 0; - $src_y = 0; - switch ($mode) { - case '1': // flip on the horizontal axis - $src_y = $new_height - 1; - $src_height = -$new_height; - break; - case '2': // flip on the vertical axis - $src_x = $new_width - 1; - $src_width = -$new_width; - break; - case '3': // flip on both axes - $src_y = $new_height - 1; - $src_height = -$new_height; - $src_x = $new_width - 1; - $src_width = -$new_width; - break; - default: - return $image; - } - imagecopyresampled( - $new_img, - $image, - 0, - 0, - $src_x, - $src_y, - $new_width, - $new_height, - $src_width, - $src_height - ); - return $new_img; - } - - protected function gd_orient_image($file_path, $src_img) { - if (!function_exists('exif_read_data')) { - return false; - } - $exif = @exif_read_data($file_path); - if ($exif === false) { - return false; - } - $orientation = (int)@$exif['Orientation']; - if ($orientation < 2 || $orientation > 8) { - return false; - } - switch ($orientation) { - case 2: - $new_img = $this->gd_imageflip( - $src_img, - defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2 - ); - break; - case 3: - $new_img = imagerotate($src_img, 180, 0); - break; - case 4: - $new_img = $this->gd_imageflip( - $src_img, - defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1 - ); - break; - case 5: - $tmp_img = $this->gd_imageflip( - $src_img, - defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1 - ); - $new_img = imagerotate($tmp_img, 270, 0); - imagedestroy($tmp_img); - break; - case 6: - $new_img = imagerotate($src_img, 270, 0); - break; - case 7: - $tmp_img = $this->gd_imageflip( - $src_img, - defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2 - ); - $new_img = imagerotate($tmp_img, 270, 0); - imagedestroy($tmp_img); - break; - case 8: - $new_img = imagerotate($src_img, 90, 0); - break; - default: - return false; - } - $this->gd_set_image_object($file_path, $new_img); - return true; - } - - protected function gd_create_scaled_image($file_name, $version, $options) { - if (!function_exists('imagecreatetruecolor')) { - error_log('Function not found: imagecreatetruecolor'); - return false; - } - list($file_path, $new_file_path) = - $this->get_scaled_image_file_paths($file_name, $version); - $type = strtolower(substr(strrchr($file_name, '.'), 1)); - switch ($type) { - case 'jpg': - case 'jpeg': - $src_func = 'imagecreatefromjpeg'; - $write_func = 'imagejpeg'; - $image_quality = isset($options['jpeg_quality']) ? - $options['jpeg_quality'] : 75; - break; - case 'gif': - $src_func = 'imagecreatefromgif'; - $write_func = 'imagegif'; - $image_quality = null; - break; - case 'png': - $src_func = 'imagecreatefrompng'; - $write_func = 'imagepng'; - $image_quality = isset($options['png_quality']) ? - $options['png_quality'] : 9; - break; - default: - return false; - } - $src_img = $this->gd_get_image_object( - $file_path, - $src_func, - !empty($options['no_cache']) - ); - $image_oriented = false; - if (!empty($options['auto_orient']) && $this->gd_orient_image( - $file_path, - $src_img - )) { - $image_oriented = true; - $src_img = $this->gd_get_image_object( - $file_path, - $src_func - ); - } - $max_width = $img_width = imagesx($src_img); - $max_height = $img_height = imagesy($src_img); - if (!empty($options['max_width'])) { - $max_width = $options['max_width']; - } - if (!empty($options['max_height'])) { - $max_height = $options['max_height']; - } - $scale = min( - $max_width / $img_width, - $max_height / $img_height - ); - if ($scale >= 1) { - if ($image_oriented) { - return $write_func($src_img, $new_file_path, $image_quality); - } - if ($file_path !== $new_file_path) { - return copy($file_path, $new_file_path); - } - return true; - } - if (empty($options['crop'])) { - $new_width = $img_width * $scale; - $new_height = $img_height * $scale; - $dst_x = 0; - $dst_y = 0; - $new_img = imagecreatetruecolor($new_width, $new_height); - } else { - if (($img_width / $img_height) >= ($max_width / $max_height)) { - $new_width = $img_width / ($img_height / $max_height); - $new_height = $max_height; - } else { - $new_width = $max_width; - $new_height = $img_height / ($img_width / $max_width); - } - $dst_x = 0 - ($new_width - $max_width) / 2; - $dst_y = 0 - ($new_height - $max_height) / 2; - $new_img = imagecreatetruecolor($max_width, $max_height); - } - // Handle transparency in GIF and PNG images: - switch ($type) { - case 'gif': - case 'png': - imagecolortransparent($new_img, imagecolorallocate($new_img, 0, 0, 0)); - case 'png': - imagealphablending($new_img, false); - imagesavealpha($new_img, true); - break; - } - $success = imagecopyresampled( - $new_img, - $src_img, - $dst_x, - $dst_y, - 0, - 0, - $new_width, - $new_height, - $img_width, - $img_height - ) && $write_func($new_img, $new_file_path, $image_quality); - $this->gd_set_image_object($file_path, $new_img); - return $success; - } - - protected function imagick_get_image_object($file_path, $no_cache = false) { - if (empty($this->image_objects[$file_path]) || $no_cache) { - $this->imagick_destroy_image_object($file_path); - $image = new \Imagick(); - if (!empty($this->options['imagick_resource_limits'])) { - foreach ($this->options['imagick_resource_limits'] as $type => $limit) { - $image->setResourceLimit($type, $limit); - } - } - $image->readImage($file_path); - $this->image_objects[$file_path] = $image; - } - return $this->image_objects[$file_path]; - } - - protected function imagick_set_image_object($file_path, $image) { - $this->imagick_destroy_image_object($file_path); - $this->image_objects[$file_path] = $image; - } - - protected function imagick_destroy_image_object($file_path) { - $image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ; - return $image && $image->destroy(); - } - - protected function imagick_orient_image($image) { - $orientation = $image->getImageOrientation(); - $background = new \ImagickPixel('none'); - switch ($orientation) { - case \imagick::ORIENTATION_TOPRIGHT: // 2 - $image->flopImage(); // horizontal flop around y-axis - break; - case \imagick::ORIENTATION_BOTTOMRIGHT: // 3 - $image->rotateImage($background, 180); - break; - case \imagick::ORIENTATION_BOTTOMLEFT: // 4 - $image->flipImage(); // vertical flip around x-axis - break; - case \imagick::ORIENTATION_LEFTTOP: // 5 - $image->flopImage(); // horizontal flop around y-axis - $image->rotateImage($background, 270); - break; - case \imagick::ORIENTATION_RIGHTTOP: // 6 - $image->rotateImage($background, 90); - break; - case \imagick::ORIENTATION_RIGHTBOTTOM: // 7 - $image->flipImage(); // vertical flip around x-axis - $image->rotateImage($background, 270); - break; - case \imagick::ORIENTATION_LEFTBOTTOM: // 8 - $image->rotateImage($background, 270); - break; - default: - return false; - } - $image->setImageOrientation(\imagick::ORIENTATION_TOPLEFT); // 1 - return true; - } - - protected function imagick_create_scaled_image($file_name, $version, $options) { - list($file_path, $new_file_path) = - $this->get_scaled_image_file_paths($file_name, $version); - $image = $this->imagick_get_image_object( - $file_path, - !empty($options['crop']) || !empty($options['no_cache']) - ); - if ($image->getImageFormat() === 'GIF') { - // Handle animated GIFs: - $images = $image->coalesceImages(); - foreach ($images as $frame) { - $image = $frame; - $this->imagick_set_image_object($file_name, $image); - break; - } - } - $image_oriented = false; - if (!empty($options['auto_orient'])) { - $image_oriented = $this->imagick_orient_image($image); - } - - $image_resize = false; - $new_width = $max_width = $img_width = $image->getImageWidth(); - $new_height = $max_height = $img_height = $image->getImageHeight(); - - // use isset(). User might be setting max_width = 0 (auto in regular resizing). Value 0 would be considered empty when you use empty() - if (isset($options['max_width'])) { - $image_resize = true; - $new_width = $max_width = $options['max_width']; - } - if (isset($options['max_height'])) { - $image_resize = true; - $new_height = $max_height = $options['max_height']; - } - - $image_strip = (isset($options['strip']) ? $options['strip'] : false); - - if ( !$image_oriented && ($max_width >= $img_width) && ($max_height >= $img_height) && !$image_strip && empty($options["jpeg_quality"]) ) { - if ($file_path !== $new_file_path) { - return copy($file_path, $new_file_path); - } - return true; - } - $crop = (isset($options['crop']) ? $options['crop'] : false); - - if ($crop) { - $x = 0; - $y = 0; - if (($img_width / $img_height) >= ($max_width / $max_height)) { - $new_width = 0; // Enables proportional scaling based on max_height - $x = ($img_width / ($img_height / $max_height) - $max_width) / 2; - } else { - $new_height = 0; // Enables proportional scaling based on max_width - $y = ($img_height / ($img_width / $max_width) - $max_height) / 2; - } - } - $success = $image->resizeImage( - $new_width, - $new_height, - isset($options['filter']) ? $options['filter'] : \imagick::FILTER_LANCZOS, - isset($options['blur']) ? $options['blur'] : 1, - $new_width && $new_height // fit image into constraints if not to be cropped - ); - if ($success && $crop) { - $success = $image->cropImage( - $max_width, - $max_height, - $x, - $y - ); - if ($success) { - $success = $image->setImagePage($max_width, $max_height, 0, 0); - } - } - $type = strtolower(substr(strrchr($file_name, '.'), 1)); - switch ($type) { - case 'jpg': - case 'jpeg': - if (!empty($options['jpeg_quality'])) { - $image->setImageCompression(\imagick::COMPRESSION_JPEG); - $image->setImageCompressionQuality($options['jpeg_quality']); - } - break; - } - if ( $image_strip ) { - $image->stripImage(); - } - return $success && $image->writeImage($new_file_path); - } - - protected function imagemagick_create_scaled_image($file_name, $version, $options) { - list($file_path, $new_file_path) = - $this->get_scaled_image_file_paths($file_name, $version); - $resize = @$options['max_width'] - .(empty($options['max_height']) ? '' : 'X'.$options['max_height']); - if (!$resize && empty($options['auto_orient'])) { - if ($file_path !== $new_file_path) { - return copy($file_path, $new_file_path); - } - return true; - } - $cmd = $this->options['convert_bin']; - if (!empty($this->options['convert_params'])) { - $cmd .= ' '.$this->options['convert_params']; - } - $cmd .= ' '.escapeshellarg($file_path); - if (!empty($options['auto_orient'])) { - $cmd .= ' -auto-orient'; - } - if ($resize) { - // Handle animated GIFs: - $cmd .= ' -coalesce'; - if (empty($options['crop'])) { - $cmd .= ' -resize '.escapeshellarg($resize.'>'); - } else { - $cmd .= ' -resize '.escapeshellarg($resize.'^'); - $cmd .= ' -gravity center'; - $cmd .= ' -crop '.escapeshellarg($resize.'+0+0'); - } - // Make sure the page dimensions are correct (fixes offsets of animated GIFs): - $cmd .= ' +repage'; - } - if (!empty($options['convert_params'])) { - $cmd .= ' '.$options['convert_params']; - } - $cmd .= ' '.escapeshellarg($new_file_path); - exec($cmd, $output, $error); - if ($error) { - error_log(implode('\n', $output)); - return false; - } - return true; - } - - protected function get_image_size($file_path) { - if ($this->options['image_library']) { - if (extension_loaded('imagick')) { - $image = new \Imagick(); - try { - if (@$image->pingImage($file_path)) { - $dimensions = array($image->getImageWidth(), $image->getImageHeight()); - $image->destroy(); - return $dimensions; - } - return false; - } catch (\Exception $e) { - error_log($e->getMessage()); - } - } - if ($this->options['image_library'] === 2) { - $cmd = $this->options['identify_bin']; - $cmd .= ' -ping '.escapeshellarg($file_path); - exec($cmd, $output, $error); - if (!$error && !empty($output)) { - // image.jpg JPEG 1920x1080 1920x1080+0+0 8-bit sRGB 465KB 0.000u 0:00.000 - $infos = preg_split('/\s+/', substr($output[0], strlen($file_path))); - $dimensions = preg_split('/x/', $infos[2]); - return $dimensions; - } - return false; - } - } - if (!function_exists('getimagesize')) { - error_log('Function not found: getimagesize'); - return false; - } - return @getimagesize($file_path); - } - - protected function create_scaled_image($file_name, $version, $options) { - if ($this->options['image_library'] === 2) { - return $this->imagemagick_create_scaled_image($file_name, $version, $options); - } - if ($this->options['image_library'] && extension_loaded('imagick')) { - return $this->imagick_create_scaled_image($file_name, $version, $options); - } - return $this->gd_create_scaled_image($file_name, $version, $options); - } - - protected function destroy_image_object($file_path) { - if ($this->options['image_library'] && extension_loaded('imagick')) { - return $this->imagick_destroy_image_object($file_path); - } - } - - protected function is_valid_image_file($file_path) { - if (!preg_match($this->options['image_file_types'], $file_path)) { - return false; - } - if (function_exists('exif_imagetype')) { - return @exif_imagetype($file_path); - } - $image_info = $this->get_image_size($file_path); - return $image_info && $image_info[0] && $image_info[1]; - } - - protected function handle_image_file($file_path, $file) { - $failed_versions = array(); - foreach ($this->options['image_versions'] as $version => $options) { - if ($this->create_scaled_image($file->name, $version, $options)) { - if (!empty($version)) { - $file->{$version.'Url'} = $this->get_download_url( - $file->name, - $version - ); - } else { - $file->size = $this->get_file_size($file_path, true); - } - } else { - $failed_versions[] = $version ? $version : 'original'; - } - } - if (count($failed_versions)) { - $file->error = $this->get_error_message('image_resize') - .' ('.implode($failed_versions, ', ').')'; - } - // Free memory: - $this->destroy_image_object($file_path); - } - - protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, - $index = null, $content_range = null) { - $file = new \stdClass(); - $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error, - $index, $content_range); - $file->size = $this->fix_integer_overflow((int)$size); - $file->type = $type; - if ($this->validate($uploaded_file, $file, $error, $index)) { - $this->handle_form_data($file, $index); - $upload_dir = $this->get_upload_path(); - if (!is_dir($upload_dir)) { - mkdir($upload_dir, $this->options['mkdir_mode'], true); - } - $file_path = $this->get_upload_path($file->name); - $append_file = $content_range && is_file($file_path) && - $file->size > $this->get_file_size($file_path); - if ($uploaded_file && is_uploaded_file($uploaded_file)) { - // multipart/formdata uploads (POST method uploads) - if ($append_file) { - file_put_contents( - $file_path, - fopen($uploaded_file, 'r'), - FILE_APPEND - ); - } else { - move_uploaded_file($uploaded_file, $file_path); - } - } else { - // Non-multipart uploads (PUT method support) - file_put_contents( - $file_path, - fopen($this->options['input_stream'], 'r'), - $append_file ? FILE_APPEND : 0 - ); - } - $file_size = $this->get_file_size($file_path, $append_file); - if ($file_size === $file->size) { - $file->url = $this->get_download_url($file->name); - if ($this->is_valid_image_file($file_path)) { - $this->handle_image_file($file_path, $file); - } - } else { - $file->size = $file_size; - if (!$content_range && $this->options['discard_aborted_uploads']) { - unlink($file_path); - $file->error = $this->get_error_message('abort'); - } - } - $this->set_additional_file_properties($file); - } - return $file; - } - - protected function readfile($file_path) { - $file_size = $this->get_file_size($file_path); - $chunk_size = $this->options['readfile_chunk_size']; - if ($chunk_size && $file_size > $chunk_size) { - $handle = fopen($file_path, 'rb'); - while (!feof($handle)) { - echo fread($handle, $chunk_size); - @ob_flush(); - @flush(); - } - fclose($handle); - return $file_size; - } - return readfile($file_path); - } - - protected function body($str) { - echo $str; - } - - protected function header($str) { - header($str); - } - - protected function get_upload_data($id) { - return @$_FILES[$id]; - } - - protected function get_post_param($id) { - return @$_POST[$id]; - } - - protected function get_query_param($id) { - return @$_GET[$id]; - } - - protected function get_server_var($id) { - return @$_SERVER[$id]; - } - - protected function handle_form_data($file, $index) { - // Handle form data, e.g. $_POST['description'][$index] - } - - protected function get_version_param() { - return $this->basename(stripslashes($this->get_query_param('version'))); - } - - protected function get_singular_param_name() { - return substr($this->options['param_name'], 0, -1); - } - - protected function get_file_name_param() { - $name = $this->get_singular_param_name(); - return $this->basename(stripslashes($this->get_query_param($name))); - } - - protected function get_file_names_params() { - $params = $this->get_query_param($this->options['param_name']); - if (!$params) { - return null; - } - foreach ($params as $key => $value) { - $params[$key] = $this->basename(stripslashes($value)); - } - return $params; - } - - protected function get_file_type($file_path) { - switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) { - case 'jpeg': - case 'jpg': - return 'image/jpeg'; - case 'png': - return 'image/png'; - case 'gif': - return 'image/gif'; - default: - return ''; - } - } - - protected function download() { - switch ($this->options['download_via_php']) { - case 1: - $redirect_header = null; - break; - case 2: - $redirect_header = 'X-Sendfile'; - break; - case 3: - $redirect_header = 'X-Accel-Redirect'; - break; - default: - return $this->header('HTTP/1.1 403 Forbidden'); - } - $file_name = $this->get_file_name_param(); - if (!$this->is_valid_file_object($file_name)) { - return $this->header('HTTP/1.1 404 Not Found'); - } - if ($redirect_header) { - return $this->header( - $redirect_header.': '.$this->get_download_url( - $file_name, - $this->get_version_param(), - true - ) - ); - } - $file_path = $this->get_upload_path($file_name, $this->get_version_param()); - // Prevent browsers from MIME-sniffing the content-type: - $this->header('X-Content-Type-Options: nosniff'); - if (!preg_match($this->options['inline_file_types'], $file_name)) { - $this->header('Content-Type: application/octet-stream'); - $this->header('Content-Disposition: attachment; filename="'.$file_name.'"'); - } else { - $this->header('Content-Type: '.$this->get_file_type($file_path)); - $this->header('Content-Disposition: inline; filename="'.$file_name.'"'); - } - $this->header('Content-Length: '.$this->get_file_size($file_path)); - $this->header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path))); - $this->readfile($file_path); - } - - protected function send_content_type_header() { - $this->header('Vary: Accept'); - if (strpos($this->get_server_var('HTTP_ACCEPT'), 'application/json') !== false) { - $this->header('Content-type: application/json'); - } else { - $this->header('Content-type: text/plain'); - } - } - - protected function send_access_control_headers() { - $this->header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']); - $this->header('Access-Control-Allow-Credentials: ' - .($this->options['access_control_allow_credentials'] ? 'true' : 'false')); - $this->header('Access-Control-Allow-Methods: ' - .implode(', ', $this->options['access_control_allow_methods'])); - $this->header('Access-Control-Allow-Headers: ' - .implode(', ', $this->options['access_control_allow_headers'])); - } - - public function generate_response($content, $print_response = true) { - $this->response = $content; - if ($print_response) { - $json = json_encode($content); - $redirect = stripslashes($this->get_post_param('redirect')); - if ($redirect && preg_match($this->options['redirect_allow_target'], $redirect)) { - $this->header('Location: '.sprintf($redirect, rawurlencode($json))); - return; - } - $this->head(); - if ($this->get_server_var('HTTP_CONTENT_RANGE')) { - $files = isset($content[$this->options['param_name']]) ? - $content[$this->options['param_name']] : null; - if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) { - $this->header('Range: 0-'.( - $this->fix_integer_overflow((int)$files[0]->size) - 1 - )); - } - } - $this->body($json); - } - return $content; - } - - public function get_response () { - return $this->response; - } - - public function head() { - $this->header('Pragma: no-cache'); - $this->header('Cache-Control: no-store, no-cache, must-revalidate'); - $this->header('Content-Disposition: inline; filename="files.json"'); - // Prevent Internet Explorer from MIME-sniffing the content-type: - $this->header('X-Content-Type-Options: nosniff'); - if ($this->options['access_control_allow_origin']) { - $this->send_access_control_headers(); - } - $this->send_content_type_header(); - } - - public function get($print_response = true) { - if ($print_response && $this->get_query_param('download')) { - return $this->download(); - } - $file_name = $this->get_file_name_param(); - if ($file_name) { - $response = array( - $this->get_singular_param_name() => $this->get_file_object($file_name) - ); - } else { - $response = array( - $this->options['param_name'] => $this->get_file_objects() - ); - } - return $this->generate_response($response, $print_response); - } - - public function post($print_response = true) { - if ($this->get_query_param('_method') === 'DELETE') { - return $this->delete($print_response); - } - $upload = $this->get_upload_data($this->options['param_name']); - // Parse the Content-Disposition header, if available: - $content_disposition_header = $this->get_server_var('HTTP_CONTENT_DISPOSITION'); - $file_name = $content_disposition_header ? - rawurldecode(preg_replace( - '/(^[^"]+")|("$)/', - '', - $content_disposition_header - )) : null; - // Parse the Content-Range header, which has the following form: - // Content-Range: bytes 0-524287/2000000 - $content_range_header = $this->get_server_var('HTTP_CONTENT_RANGE'); - $content_range = $content_range_header ? - preg_split('/[^0-9]+/', $content_range_header) : null; - $size = $content_range ? $content_range[3] : null; - $files = array(); - if ($upload) { - if (is_array($upload['tmp_name'])) { - // param_name is an array identifier like "files[]", - // $upload is a multi-dimensional array: - foreach ($upload['tmp_name'] as $index => $value) { - $files[] = $this->handle_file_upload( - $upload['tmp_name'][$index], - $file_name ? $file_name : $upload['name'][$index], - $size ? $size : $upload['size'][$index], - $upload['type'][$index], - $upload['error'][$index], - $index, - $content_range - ); - } - } else { - // param_name is a single object identifier like "file", - // $upload is a one-dimensional array: - $files[] = $this->handle_file_upload( - isset($upload['tmp_name']) ? $upload['tmp_name'] : null, - $file_name ? $file_name : (isset($upload['name']) ? - $upload['name'] : null), - $size ? $size : (isset($upload['size']) ? - $upload['size'] : $this->get_server_var('CONTENT_LENGTH')), - isset($upload['type']) ? - $upload['type'] : $this->get_server_var('CONTENT_TYPE'), - isset($upload['error']) ? $upload['error'] : null, - null, - $content_range - ); - } - } - $response = array($this->options['param_name'] => $files); - return $this->generate_response($response, $print_response); - } - - public function delete($print_response = true) { - $file_names = $this->get_file_names_params(); - if (empty($file_names)) { - $file_names = array($this->get_file_name_param()); - } - $response = array(); - foreach ($file_names as $file_name) { - $file_path = $this->get_upload_path($file_name); - $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path); - if ($success) { - foreach ($this->options['image_versions'] as $version => $options) { - if (!empty($version)) { - $file = $this->get_upload_path($file_name, $version); - if (is_file($file)) { - unlink($file); - } - } - } - } - $response[$file_name] = $success; - } - return $this->generate_response($response, $print_response); - } - - protected function basename($filepath, $suffix = null) { - $splited = preg_split('/\//', rtrim ($filepath, '/ ')); - return substr(basename('X'.$splited[count($splited)-1], $suffix), 1); - } -} + 'The uploaded file exceeds the upload_max_filesize directive in php.ini', + 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', + 3 => 'The uploaded file was only partially uploaded', + 4 => 'No file was uploaded', + 6 => 'Missing a temporary folder', + 7 => 'Failed to write file to disk', + 8 => 'A PHP extension stopped the file upload', + 'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini', + 'max_file_size' => 'File is too big', + 'min_file_size' => 'File is too small', + 'accept_file_types' => 'Filetype not allowed', + 'max_number_of_files' => 'Maximum number of files exceeded', + 'max_width' => 'Image exceeds maximum width', + 'min_width' => 'Image requires a minimum width', + 'max_height' => 'Image exceeds maximum height', + 'min_height' => 'Image requires a minimum height', + 'abort' => 'File upload aborted', + 'image_resize' => 'Failed to resize image' + ); + + protected $image_objects = array(); + + public function __construct($options = null, $initialize = true, $error_messages = null) { + $this->response = array(); + $this->options = array( + 'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')), + 'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/', + 'upload_url' => $this->get_full_url().'/files/', + 'input_stream' => 'php://input', + 'user_dirs' => false, + 'mkdir_mode' => 0755, + 'param_name' => 'files', + // Set the following option to 'POST', if your server does not support + // DELETE requests. This is a parameter sent to the client: + 'delete_type' => 'DELETE', + 'access_control_allow_origin' => '*', + 'access_control_allow_credentials' => false, + 'access_control_allow_methods' => array( + 'OPTIONS', + 'HEAD', + 'GET', + 'POST', + 'PUT', + 'PATCH', + 'DELETE' + ), + 'access_control_allow_headers' => array( + 'Content-Type', + 'Content-Range', + 'Content-Disposition' + ), + // By default, allow redirects to the referer protocol+host: + 'redirect_allow_target' => '/^'.preg_quote( + parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_SCHEME) + .'://' + .parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_HOST) + .'/', // Trailing slash to not match subdomains by mistake + '/' // preg_quote delimiter param + ).'/', + // Enable to provide file downloads via GET requests to the PHP script: + // 1. Set to 1 to download files via readfile method through PHP + // 2. Set to 2 to send a X-Sendfile header for lighttpd/Apache + // 3. Set to 3 to send a X-Accel-Redirect header for nginx + // If set to 2 or 3, adjust the upload_url option to the base path of + // the redirect parameter, e.g. '/files/'. + 'download_via_php' => false, + // Read files in chunks to avoid memory limits when download_via_php + // is enabled, set to 0 to disable chunked reading of files: + 'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB + // Defines which files can be displayed inline when downloaded: + 'inline_file_types' => '/\.(gif|jpe?g|png)$/i', + // Defines which files (based on their names) are accepted for upload: + 'accept_file_types' => '/.+$/i', + // The php.ini settings upload_max_filesize and post_max_size + // take precedence over the following max_file_size setting: + 'max_file_size' => null, + 'min_file_size' => 1, + // The maximum number of files for the upload directory: + 'max_number_of_files' => null, + // Defines which files are handled as image files: + 'image_file_types' => '/\.(gif|jpe?g|png)$/i', + // Use exif_imagetype on all files to correct file extensions: + 'correct_image_extensions' => false, + // Image resolution restrictions: + 'max_width' => null, + 'max_height' => null, + 'min_width' => 1, + 'min_height' => 1, + // Set the following option to false to enable resumable uploads: + 'discard_aborted_uploads' => true, + // Set to 0 to use the GD library to scale and orient images, + // set to 1 to use imagick (if installed, falls back to GD), + // set to 2 to use the ImageMagick convert binary directly: + 'image_library' => 1, + // Uncomment the following to define an array of resource limits + // for imagick: + /* + 'imagick_resource_limits' => array( + imagick::RESOURCETYPE_MAP => 32, + imagick::RESOURCETYPE_MEMORY => 32 + ), + */ + // Command or path for to the ImageMagick convert binary: + 'convert_bin' => 'convert', + // Uncomment the following to add parameters in front of each + // ImageMagick convert call (the limit constraints seem only + // to have an effect if put in front): + /* + 'convert_params' => '-limit memory 32MiB -limit map 32MiB', + */ + // Command or path for to the ImageMagick identify binary: + 'identify_bin' => 'identify', + 'image_versions' => array( + // The empty image version key defines options for the original image. + // Keep in mind: these image manipulations are inherited by all other image versions from this point onwards. + // Also note that the property 'no_cache' is not inherited, since it's not a manipulation. + '' => array( + // Automatically rotate images based on EXIF meta data: + 'auto_orient' => true + ), + // You can add arrays to generate different versions. + // The name of the key is the name of the version (example: 'medium'). + // the array contains the options to apply. + /* + 'medium' => array( + 'max_width' => 800, + 'max_height' => 600 + ), + */ + 'thumbnail' => array( + // Uncomment the following to use a defined directory for the thumbnails + // instead of a subdirectory based on the version identifier. + // Make sure that this directory doesn't allow execution of files if you + // don't pose any restrictions on the type of uploaded files, e.g. by + // copying the .htaccess file from the files directory for Apache: + //'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/thumb/', + //'upload_url' => $this->get_full_url().'/thumb/', + // Uncomment the following to force the max + // dimensions and e.g. create square thumbnails: + // 'auto_orient' => true, + // 'crop' => true, + // 'jpeg_quality' => 70, + // 'no_cache' => true, (there's a caching option, but this remembers thumbnail sizes from a previous action!) + // 'strip' => true, (this strips EXIF tags, such as geolocation) + 'max_width' => 80, // either specify width, or set to 0. Then width is automatically adjusted - keeping aspect ratio to a specified max_height. + 'max_height' => 80 // either specify height, or set to 0. Then height is automatically adjusted - keeping aspect ratio to a specified max_width. + ) + ), + 'print_response' => true + ); + if ($options) { + $this->options = $options + $this->options; + } + if ($error_messages) { + $this->error_messages = $error_messages + $this->error_messages; + } + if ($initialize) { + $this->initialize(); + } + } + + protected function initialize() { + switch ($this->get_server_var('REQUEST_METHOD')) { + case 'OPTIONS': + case 'HEAD': + $this->head(); + break; + case 'GET': + $this->get($this->options['print_response']); + break; + case 'PATCH': + case 'PUT': + case 'POST': + $this->post($this->options['print_response']); + break; + case 'DELETE': + $this->delete($this->options['print_response']); + break; + default: + $this->header('HTTP/1.1 405 Method Not Allowed'); + } + } + + protected function get_full_url() { + $https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 || + !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && + strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0; + return + ($https ? 'https://' : 'http://'). + (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : ''). + (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME']. + ($https && $_SERVER['SERVER_PORT'] === 443 || + $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))). + substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/')); + } + + protected function get_user_id() { + @session_start(); + return session_id(); + } + + protected function get_user_path() { + if ($this->options['user_dirs']) { + return $this->get_user_id().'/'; + } + return ''; + } + + protected function get_upload_path($file_name = null, $version = null) { + $file_name = $file_name ? $file_name : ''; + if (empty($version)) { + $version_path = ''; + } else { + $version_dir = @$this->options['image_versions'][$version]['upload_dir']; + if ($version_dir) { + return $version_dir.$this->get_user_path().$file_name; + } + $version_path = $version.'/'; + } + return $this->options['upload_dir'].$this->get_user_path() + .$version_path.$file_name; + } + + protected function get_query_separator($url) { + return strpos($url, '?') === false ? '?' : '&'; + } + + protected function get_download_url($file_name, $version = null, $direct = false) { + if (!$direct && $this->options['download_via_php']) { + $url = $this->options['script_url'] + .$this->get_query_separator($this->options['script_url']) + .$this->get_singular_param_name() + .'='.rawurlencode($file_name); + if ($version) { + $url .= '&version='.rawurlencode($version); + } + return $url.'&download=1'; + } + if (empty($version)) { + $version_path = ''; + } else { + $version_url = @$this->options['image_versions'][$version]['upload_url']; + if ($version_url) { + return $version_url.$this->get_user_path().rawurlencode($file_name); + } + $version_path = rawurlencode($version).'/'; + } + return $this->options['upload_url'].$this->get_user_path() + .$version_path.rawurlencode($file_name); + } + + protected function set_additional_file_properties($file) { + $file->deleteUrl = $this->options['script_url'] + .$this->get_query_separator($this->options['script_url']) + .$this->get_singular_param_name() + .'='.rawurlencode($file->name); + $file->deleteType = $this->options['delete_type']; + if ($file->deleteType !== 'DELETE') { + $file->deleteUrl .= '&_method=DELETE'; + } + if ($this->options['access_control_allow_credentials']) { + $file->deleteWithCredentials = true; + } + } + + // Fix for overflowing signed 32 bit integers, + // works for sizes up to 2^32-1 bytes (4 GiB - 1): + protected function fix_integer_overflow($size) { + if ($size < 0) { + $size += 2.0 * (PHP_INT_MAX + 1); + } + return $size; + } + + protected function get_file_size($file_path, $clear_stat_cache = false) { + if ($clear_stat_cache) { + if (version_compare(PHP_VERSION, '5.3.0') >= 0) { + clearstatcache(true, $file_path); + } else { + clearstatcache(); + } + } + return $this->fix_integer_overflow(filesize($file_path)); + } + + protected function is_valid_file_object($file_name) { + $file_path = $this->get_upload_path($file_name); + if (is_file($file_path) && $file_name[0] !== '.') { + return true; + } + return false; + } + + protected function get_file_object($file_name) { + if ($this->is_valid_file_object($file_name)) { + $file = new \stdClass(); + $file->name = $file_name; + $file->size = $this->get_file_size( + $this->get_upload_path($file_name) + ); + $file->url = $this->get_download_url($file->name); + foreach ($this->options['image_versions'] as $version => $options) { + if (!empty($version)) { + if (is_file($this->get_upload_path($file_name, $version))) { + $file->{$version.'Url'} = $this->get_download_url( + $file->name, + $version + ); + } + } + } + $this->set_additional_file_properties($file); + return $file; + } + return null; + } + + protected function get_file_objects($iteration_method = 'get_file_object') { + $upload_dir = $this->get_upload_path(); + if (!is_dir($upload_dir)) { + return array(); + } + return array_values(array_filter(array_map( + array($this, $iteration_method), + scandir($upload_dir) + ))); + } + + protected function count_file_objects() { + return count($this->get_file_objects('is_valid_file_object')); + } + + protected function get_error_message($error) { + return isset($this->error_messages[$error]) ? + $this->error_messages[$error] : $error; + } + + public function get_config_bytes($val) { + $val = trim($val); + $last = strtolower($val[strlen($val)-1]); + $val = (int)$val; + switch ($last) { + case 'g': + $val *= 1024; + case 'm': + $val *= 1024; + case 'k': + $val *= 1024; + } + return $this->fix_integer_overflow($val); + } + + protected function validate($uploaded_file, $file, $error, $index) { + if ($error) { + $file->error = $this->get_error_message($error); + return false; + } + $content_length = $this->fix_integer_overflow( + (int)$this->get_server_var('CONTENT_LENGTH') + ); + $post_max_size = $this->get_config_bytes(ini_get('post_max_size')); + if ($post_max_size && ($content_length > $post_max_size)) { + $file->error = $this->get_error_message('post_max_size'); + return false; + } + if (!preg_match($this->options['accept_file_types'], $file->name)) { + $file->error = $this->get_error_message('accept_file_types'); + return false; + } + if ($uploaded_file && is_uploaded_file($uploaded_file)) { + $file_size = $this->get_file_size($uploaded_file); + } else { + $file_size = $content_length; + } + if ($this->options['max_file_size'] && ( + $file_size > $this->options['max_file_size'] || + $file->size > $this->options['max_file_size']) + ) { + $file->error = $this->get_error_message('max_file_size'); + return false; + } + if ($this->options['min_file_size'] && + $file_size < $this->options['min_file_size']) { + $file->error = $this->get_error_message('min_file_size'); + return false; + } + if (is_int($this->options['max_number_of_files']) && + ($this->count_file_objects() >= $this->options['max_number_of_files']) && + // Ignore additional chunks of existing files: + !is_file($this->get_upload_path($file->name))) { + $file->error = $this->get_error_message('max_number_of_files'); + return false; + } + $max_width = @$this->options['max_width']; + $max_height = @$this->options['max_height']; + $min_width = @$this->options['min_width']; + $min_height = @$this->options['min_height']; + if (($max_width || $max_height || $min_width || $min_height) + && preg_match($this->options['image_file_types'], $file->name)) { + list($img_width, $img_height) = $this->get_image_size($uploaded_file); + + // If we are auto rotating the image by default, do the checks on + // the correct orientation + if ( + @$this->options['image_versions']['']['auto_orient'] && + function_exists('exif_read_data') && + ($exif = @exif_read_data($uploaded_file)) && + (((int) @$exif['Orientation']) >= 5) + ) { + $tmp = $img_width; + $img_width = $img_height; + $img_height = $tmp; + unset($tmp); + } + + } + if (!empty($img_width)) { + if ($max_width && $img_width > $max_width) { + $file->error = $this->get_error_message('max_width'); + return false; + } + if ($max_height && $img_height > $max_height) { + $file->error = $this->get_error_message('max_height'); + return false; + } + if ($min_width && $img_width < $min_width) { + $file->error = $this->get_error_message('min_width'); + return false; + } + if ($min_height && $img_height < $min_height) { + $file->error = $this->get_error_message('min_height'); + return false; + } + } + return true; + } + + protected function upcount_name_callback($matches) { + $index = isset($matches[1]) ? ((int)$matches[1]) + 1 : 1; + $ext = isset($matches[2]) ? $matches[2] : ''; + return ' ('.$index.')'.$ext; + } + + protected function upcount_name($name) { + return preg_replace_callback( + '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', + array($this, 'upcount_name_callback'), + $name, + 1 + ); + } + + protected function get_unique_filename($file_path, $name, $size, $type, $error, + $index, $content_range) { + while(is_dir($this->get_upload_path($name))) { + $name = $this->upcount_name($name); + } + // Keep an existing filename if this is part of a chunked upload: + $uploaded_bytes = $this->fix_integer_overflow((int)$content_range[1]); + while (is_file($this->get_upload_path($name))) { + if ($uploaded_bytes === $this->get_file_size( + $this->get_upload_path($name))) { + break; + } + $name = $this->upcount_name($name); + } + return $name; + } + + protected function fix_file_extension($file_path, $name, $size, $type, $error, + $index, $content_range) { + // Add missing file extension for known image types: + if (strpos($name, '.') === false && + preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) { + $name .= '.'.$matches[1]; + } + if ($this->options['correct_image_extensions'] && + function_exists('exif_imagetype')) { + switch (@exif_imagetype($file_path)){ + case IMAGETYPE_JPEG: + $extensions = array('jpg', 'jpeg'); + break; + case IMAGETYPE_PNG: + $extensions = array('png'); + break; + case IMAGETYPE_GIF: + $extensions = array('gif'); + break; + } + // Adjust incorrect image file extensions: + if (!empty($extensions)) { + $parts = explode('.', $name); + $extIndex = count($parts) - 1; + $ext = strtolower(@$parts[$extIndex]); + if (!in_array($ext, $extensions)) { + $parts[$extIndex] = $extensions[0]; + $name = implode('.', $parts); + } + } + } + return $name; + } + + protected function trim_file_name($file_path, $name, $size, $type, $error, + $index, $content_range) { + // Remove path information and dots around the filename, to prevent uploading + // into different directories or replacing hidden system files. + // Also remove control characters and spaces (\x00..\x20) around the filename: + $name = trim($this->basename(stripslashes($name)), ".\x00..\x20"); + // Use a timestamp for empty filenames: + if (!$name) { + $name = str_replace('.', '-', microtime(true)); + } + return $name; + } + + protected function get_file_name($file_path, $name, $size, $type, $error, + $index, $content_range) { + $name = $this->trim_file_name($file_path, $name, $size, $type, $error, + $index, $content_range); + return $this->get_unique_filename( + $file_path, + $this->fix_file_extension($file_path, $name, $size, $type, $error, + $index, $content_range), + $size, + $type, + $error, + $index, + $content_range + ); + } + + protected function get_scaled_image_file_paths($file_name, $version) { + $file_path = $this->get_upload_path($file_name); + if (!empty($version)) { + $version_dir = $this->get_upload_path(null, $version); + if (!is_dir($version_dir)) { + mkdir($version_dir, $this->options['mkdir_mode'], true); + } + $new_file_path = $version_dir.'/'.$file_name; + } else { + $new_file_path = $file_path; + } + return array($file_path, $new_file_path); + } + + protected function gd_get_image_object($file_path, $func, $no_cache = false) { + if (empty($this->image_objects[$file_path]) || $no_cache) { + $this->gd_destroy_image_object($file_path); + $this->image_objects[$file_path] = $func($file_path); + } + return $this->image_objects[$file_path]; + } + + protected function gd_set_image_object($file_path, $image) { + $this->gd_destroy_image_object($file_path); + $this->image_objects[$file_path] = $image; + } + + protected function gd_destroy_image_object($file_path) { + $image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ; + return $image && imagedestroy($image); + } + + protected function gd_imageflip($image, $mode) { + if (function_exists('imageflip')) { + return imageflip($image, $mode); + } + $new_width = $src_width = imagesx($image); + $new_height = $src_height = imagesy($image); + $new_img = imagecreatetruecolor($new_width, $new_height); + $src_x = 0; + $src_y = 0; + switch ($mode) { + case '1': // flip on the horizontal axis + $src_y = $new_height - 1; + $src_height = -$new_height; + break; + case '2': // flip on the vertical axis + $src_x = $new_width - 1; + $src_width = -$new_width; + break; + case '3': // flip on both axes + $src_y = $new_height - 1; + $src_height = -$new_height; + $src_x = $new_width - 1; + $src_width = -$new_width; + break; + default: + return $image; + } + imagecopyresampled( + $new_img, + $image, + 0, + 0, + $src_x, + $src_y, + $new_width, + $new_height, + $src_width, + $src_height + ); + return $new_img; + } + + protected function gd_orient_image($file_path, $src_img) { + if (!function_exists('exif_read_data')) { + return false; + } + $exif = @exif_read_data($file_path); + if ($exif === false) { + return false; + } + $orientation = (int)@$exif['Orientation']; + if ($orientation < 2 || $orientation > 8) { + return false; + } + switch ($orientation) { + case 2: + $new_img = $this->gd_imageflip( + $src_img, + defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2 + ); + break; + case 3: + $new_img = imagerotate($src_img, 180, 0); + break; + case 4: + $new_img = $this->gd_imageflip( + $src_img, + defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1 + ); + break; + case 5: + $tmp_img = $this->gd_imageflip( + $src_img, + defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1 + ); + $new_img = imagerotate($tmp_img, 270, 0); + imagedestroy($tmp_img); + break; + case 6: + $new_img = imagerotate($src_img, 270, 0); + break; + case 7: + $tmp_img = $this->gd_imageflip( + $src_img, + defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2 + ); + $new_img = imagerotate($tmp_img, 270, 0); + imagedestroy($tmp_img); + break; + case 8: + $new_img = imagerotate($src_img, 90, 0); + break; + default: + return false; + } + $this->gd_set_image_object($file_path, $new_img); + return true; + } + + protected function gd_create_scaled_image($file_name, $version, $options) { + if (!function_exists('imagecreatetruecolor')) { + error_log('Function not found: imagecreatetruecolor'); + return false; + } + list($file_path, $new_file_path) = + $this->get_scaled_image_file_paths($file_name, $version); + $type = strtolower(substr(strrchr($file_name, '.'), 1)); + switch ($type) { + case 'jpg': + case 'jpeg': + $src_func = 'imagecreatefromjpeg'; + $write_func = 'imagejpeg'; + $image_quality = isset($options['jpeg_quality']) ? + $options['jpeg_quality'] : 75; + break; + case 'gif': + $src_func = 'imagecreatefromgif'; + $write_func = 'imagegif'; + $image_quality = null; + break; + case 'png': + $src_func = 'imagecreatefrompng'; + $write_func = 'imagepng'; + $image_quality = isset($options['png_quality']) ? + $options['png_quality'] : 9; + break; + default: + return false; + } + $src_img = $this->gd_get_image_object( + $file_path, + $src_func, + !empty($options['no_cache']) + ); + $image_oriented = false; + if (!empty($options['auto_orient']) && $this->gd_orient_image( + $file_path, + $src_img + )) { + $image_oriented = true; + $src_img = $this->gd_get_image_object( + $file_path, + $src_func + ); + } + $max_width = $img_width = imagesx($src_img); + $max_height = $img_height = imagesy($src_img); + if (!empty($options['max_width'])) { + $max_width = $options['max_width']; + } + if (!empty($options['max_height'])) { + $max_height = $options['max_height']; + } + $scale = min( + $max_width / $img_width, + $max_height / $img_height + ); + if ($scale >= 1) { + if ($image_oriented) { + return $write_func($src_img, $new_file_path, $image_quality); + } + if ($file_path !== $new_file_path) { + return copy($file_path, $new_file_path); + } + return true; + } + if (empty($options['crop'])) { + $new_width = $img_width * $scale; + $new_height = $img_height * $scale; + $dst_x = 0; + $dst_y = 0; + $new_img = imagecreatetruecolor($new_width, $new_height); + } else { + if (($img_width / $img_height) >= ($max_width / $max_height)) { + $new_width = $img_width / ($img_height / $max_height); + $new_height = $max_height; + } else { + $new_width = $max_width; + $new_height = $img_height / ($img_width / $max_width); + } + $dst_x = 0 - ($new_width - $max_width) / 2; + $dst_y = 0 - ($new_height - $max_height) / 2; + $new_img = imagecreatetruecolor($max_width, $max_height); + } + // Handle transparency in GIF and PNG images: + switch ($type) { + case 'gif': + case 'png': + imagecolortransparent($new_img, imagecolorallocate($new_img, 0, 0, 0)); + case 'png': + imagealphablending($new_img, false); + imagesavealpha($new_img, true); + break; + } + $success = imagecopyresampled( + $new_img, + $src_img, + $dst_x, + $dst_y, + 0, + 0, + $new_width, + $new_height, + $img_width, + $img_height + ) && $write_func($new_img, $new_file_path, $image_quality); + $this->gd_set_image_object($file_path, $new_img); + return $success; + } + + protected function imagick_get_image_object($file_path, $no_cache = false) { + if (empty($this->image_objects[$file_path]) || $no_cache) { + $this->imagick_destroy_image_object($file_path); + $image = new \Imagick(); + if (!empty($this->options['imagick_resource_limits'])) { + foreach ($this->options['imagick_resource_limits'] as $type => $limit) { + $image->setResourceLimit($type, $limit); + } + } + $image->readImage($file_path); + $this->image_objects[$file_path] = $image; + } + return $this->image_objects[$file_path]; + } + + protected function imagick_set_image_object($file_path, $image) { + $this->imagick_destroy_image_object($file_path); + $this->image_objects[$file_path] = $image; + } + + protected function imagick_destroy_image_object($file_path) { + $image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ; + return $image && $image->destroy(); + } + + protected function imagick_orient_image($image) { + $orientation = $image->getImageOrientation(); + $background = new \ImagickPixel('none'); + switch ($orientation) { + case \imagick::ORIENTATION_TOPRIGHT: // 2 + $image->flopImage(); // horizontal flop around y-axis + break; + case \imagick::ORIENTATION_BOTTOMRIGHT: // 3 + $image->rotateImage($background, 180); + break; + case \imagick::ORIENTATION_BOTTOMLEFT: // 4 + $image->flipImage(); // vertical flip around x-axis + break; + case \imagick::ORIENTATION_LEFTTOP: // 5 + $image->flopImage(); // horizontal flop around y-axis + $image->rotateImage($background, 270); + break; + case \imagick::ORIENTATION_RIGHTTOP: // 6 + $image->rotateImage($background, 90); + break; + case \imagick::ORIENTATION_RIGHTBOTTOM: // 7 + $image->flipImage(); // vertical flip around x-axis + $image->rotateImage($background, 270); + break; + case \imagick::ORIENTATION_LEFTBOTTOM: // 8 + $image->rotateImage($background, 270); + break; + default: + return false; + } + $image->setImageOrientation(\imagick::ORIENTATION_TOPLEFT); // 1 + return true; + } + + protected function imagick_create_scaled_image($file_name, $version, $options) { + list($file_path, $new_file_path) = + $this->get_scaled_image_file_paths($file_name, $version); + $image = $this->imagick_get_image_object( + $file_path, + !empty($options['crop']) || !empty($options['no_cache']) + ); + if ($image->getImageFormat() === 'GIF') { + // Handle animated GIFs: + $images = $image->coalesceImages(); + foreach ($images as $frame) { + $image = $frame; + $this->imagick_set_image_object($file_name, $image); + break; + } + } + $image_oriented = false; + if (!empty($options['auto_orient'])) { + $image_oriented = $this->imagick_orient_image($image); + } + + $image_resize = false; + $new_width = $max_width = $img_width = $image->getImageWidth(); + $new_height = $max_height = $img_height = $image->getImageHeight(); + + // use isset(). User might be setting max_width = 0 (auto in regular resizing). Value 0 would be considered empty when you use empty() + if (isset($options['max_width'])) { + $image_resize = true; + $new_width = $max_width = $options['max_width']; + } + if (isset($options['max_height'])) { + $image_resize = true; + $new_height = $max_height = $options['max_height']; + } + + $image_strip = (isset($options['strip']) ? $options['strip'] : false); + + if ( !$image_oriented && ($max_width >= $img_width) && ($max_height >= $img_height) && !$image_strip && empty($options["jpeg_quality"]) ) { + if ($file_path !== $new_file_path) { + return copy($file_path, $new_file_path); + } + return true; + } + $crop = (isset($options['crop']) ? $options['crop'] : false); + + if ($crop) { + $x = 0; + $y = 0; + if (($img_width / $img_height) >= ($max_width / $max_height)) { + $new_width = 0; // Enables proportional scaling based on max_height + $x = ($img_width / ($img_height / $max_height) - $max_width) / 2; + } else { + $new_height = 0; // Enables proportional scaling based on max_width + $y = ($img_height / ($img_width / $max_width) - $max_height) / 2; + } + } + $success = $image->resizeImage( + $new_width, + $new_height, + isset($options['filter']) ? $options['filter'] : \imagick::FILTER_LANCZOS, + isset($options['blur']) ? $options['blur'] : 1, + $new_width && $new_height // fit image into constraints if not to be cropped + ); + if ($success && $crop) { + $success = $image->cropImage( + $max_width, + $max_height, + $x, + $y + ); + if ($success) { + $success = $image->setImagePage($max_width, $max_height, 0, 0); + } + } + $type = strtolower(substr(strrchr($file_name, '.'), 1)); + switch ($type) { + case 'jpg': + case 'jpeg': + if (!empty($options['jpeg_quality'])) { + $image->setImageCompression(\imagick::COMPRESSION_JPEG); + $image->setImageCompressionQuality($options['jpeg_quality']); + } + break; + } + if ( $image_strip ) { + $image->stripImage(); + } + return $success && $image->writeImage($new_file_path); + } + + protected function imagemagick_create_scaled_image($file_name, $version, $options) { + list($file_path, $new_file_path) = + $this->get_scaled_image_file_paths($file_name, $version); + $resize = @$options['max_width'] + .(empty($options['max_height']) ? '' : 'X'.$options['max_height']); + if (!$resize && empty($options['auto_orient'])) { + if ($file_path !== $new_file_path) { + return copy($file_path, $new_file_path); + } + return true; + } + $cmd = $this->options['convert_bin']; + if (!empty($this->options['convert_params'])) { + $cmd .= ' '.$this->options['convert_params']; + } + $cmd .= ' '.escapeshellarg($file_path); + if (!empty($options['auto_orient'])) { + $cmd .= ' -auto-orient'; + } + if ($resize) { + // Handle animated GIFs: + $cmd .= ' -coalesce'; + if (empty($options['crop'])) { + $cmd .= ' -resize '.escapeshellarg($resize.'>'); + } else { + $cmd .= ' -resize '.escapeshellarg($resize.'^'); + $cmd .= ' -gravity center'; + $cmd .= ' -crop '.escapeshellarg($resize.'+0+0'); + } + // Make sure the page dimensions are correct (fixes offsets of animated GIFs): + $cmd .= ' +repage'; + } + if (!empty($options['convert_params'])) { + $cmd .= ' '.$options['convert_params']; + } + $cmd .= ' '.escapeshellarg($new_file_path); + exec($cmd, $output, $error); + if ($error) { + error_log(implode('\n', $output)); + return false; + } + return true; + } + + protected function get_image_size($file_path) { + if ($this->options['image_library']) { + if (extension_loaded('imagick')) { + $image = new \Imagick(); + try { + if (@$image->pingImage($file_path)) { + $dimensions = array($image->getImageWidth(), $image->getImageHeight()); + $image->destroy(); + return $dimensions; + } + return false; + } catch (\Exception $e) { + error_log($e->getMessage()); + } + } + if ($this->options['image_library'] === 2) { + $cmd = $this->options['identify_bin']; + $cmd .= ' -ping '.escapeshellarg($file_path); + exec($cmd, $output, $error); + if (!$error && !empty($output)) { + // image.jpg JPEG 1920x1080 1920x1080+0+0 8-bit sRGB 465KB 0.000u 0:00.000 + $infos = preg_split('/\s+/', substr($output[0], strlen($file_path))); + $dimensions = preg_split('/x/', $infos[2]); + return $dimensions; + } + return false; + } + } + if (!function_exists('getimagesize')) { + error_log('Function not found: getimagesize'); + return false; + } + return @getimagesize($file_path); + } + + protected function create_scaled_image($file_name, $version, $options) { + if ($this->options['image_library'] === 2) { + return $this->imagemagick_create_scaled_image($file_name, $version, $options); + } + if ($this->options['image_library'] && extension_loaded('imagick')) { + return $this->imagick_create_scaled_image($file_name, $version, $options); + } + return $this->gd_create_scaled_image($file_name, $version, $options); + } + + protected function destroy_image_object($file_path) { + if ($this->options['image_library'] && extension_loaded('imagick')) { + return $this->imagick_destroy_image_object($file_path); + } + } + + protected function is_valid_image_file($file_path) { + if (!preg_match($this->options['image_file_types'], $file_path)) { + return false; + } + if (function_exists('exif_imagetype')) { + return @exif_imagetype($file_path); + } + $image_info = $this->get_image_size($file_path); + return $image_info && $image_info[0] && $image_info[1]; + } + + protected function handle_image_file($file_path, $file) { + $failed_versions = array(); + foreach ($this->options['image_versions'] as $version => $options) { + if ($this->create_scaled_image($file->name, $version, $options)) { + if (!empty($version)) { + $file->{$version.'Url'} = $this->get_download_url( + $file->name, + $version + ); + } else { + $file->size = $this->get_file_size($file_path, true); + } + } else { + $failed_versions[] = $version ? $version : 'original'; + } + } + if (count($failed_versions)) { + $file->error = $this->get_error_message('image_resize') + .' ('.implode($failed_versions, ', ').')'; + } + // Free memory: + $this->destroy_image_object($file_path); + } + + protected function handle_file_upload($uploaded_file, $name, $size, $type, $error, + $index = null, $content_range = null) { + $file = new \stdClass(); + $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error, + $index, $content_range); + $file->size = $this->fix_integer_overflow((int)$size); + $file->type = $type; + if ($this->validate($uploaded_file, $file, $error, $index)) { + $this->handle_form_data($file, $index); + $upload_dir = $this->get_upload_path(); + if (!is_dir($upload_dir)) { + mkdir($upload_dir, $this->options['mkdir_mode'], true); + } + $file_path = $this->get_upload_path($file->name); + $append_file = $content_range && is_file($file_path) && + $file->size > $this->get_file_size($file_path); + if ($uploaded_file && is_uploaded_file($uploaded_file)) { + // multipart/formdata uploads (POST method uploads) + if ($append_file) { + file_put_contents( + $file_path, + fopen($uploaded_file, 'r'), + FILE_APPEND + ); + } else { + move_uploaded_file($uploaded_file, $file_path); + } + } else { + // Non-multipart uploads (PUT method support) + file_put_contents( + $file_path, + fopen($this->options['input_stream'], 'r'), + $append_file ? FILE_APPEND : 0 + ); + } + $file_size = $this->get_file_size($file_path, $append_file); + if ($file_size === $file->size) { + $file->url = $this->get_download_url($file->name); + if ($this->is_valid_image_file($file_path)) { + $this->handle_image_file($file_path, $file); + } + } else { + $file->size = $file_size; + if (!$content_range && $this->options['discard_aborted_uploads']) { + unlink($file_path); + $file->error = $this->get_error_message('abort'); + } + } + $this->set_additional_file_properties($file); + } + return $file; + } + + protected function readfile($file_path) { + $file_size = $this->get_file_size($file_path); + $chunk_size = $this->options['readfile_chunk_size']; + if ($chunk_size && $file_size > $chunk_size) { + $handle = fopen($file_path, 'rb'); + while (!feof($handle)) { + echo fread($handle, $chunk_size); + @ob_flush(); + @flush(); + } + fclose($handle); + return $file_size; + } + return readfile($file_path); + } + + protected function body($str) { + echo $str; + } + + protected function header($str) { + header($str); + } + + protected function get_upload_data($id) { + return @$_FILES[$id]; + } + + protected function get_post_param($id) { + return @$_POST[$id]; + } + + protected function get_query_param($id) { + return @$_GET[$id]; + } + + protected function get_server_var($id) { + return @$_SERVER[$id]; + } + + protected function handle_form_data($file, $index) { + // Handle form data, e.g. $_POST['description'][$index] + } + + protected function get_version_param() { + return $this->basename(stripslashes($this->get_query_param('version'))); + } + + protected function get_singular_param_name() { + return substr($this->options['param_name'], 0, -1); + } + + protected function get_file_name_param() { + $name = $this->get_singular_param_name(); + return $this->basename(stripslashes($this->get_query_param($name))); + } + + protected function get_file_names_params() { + $params = $this->get_query_param($this->options['param_name']); + if (!$params) { + return null; + } + foreach ($params as $key => $value) { + $params[$key] = $this->basename(stripslashes($value)); + } + return $params; + } + + protected function get_file_type($file_path) { + switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) { + case 'jpeg': + case 'jpg': + return 'image/jpeg'; + case 'png': + return 'image/png'; + case 'gif': + return 'image/gif'; + default: + return ''; + } + } + + protected function download() { + switch ($this->options['download_via_php']) { + case 1: + $redirect_header = null; + break; + case 2: + $redirect_header = 'X-Sendfile'; + break; + case 3: + $redirect_header = 'X-Accel-Redirect'; + break; + default: + return $this->header('HTTP/1.1 403 Forbidden'); + } + $file_name = $this->get_file_name_param(); + if (!$this->is_valid_file_object($file_name)) { + return $this->header('HTTP/1.1 404 Not Found'); + } + if ($redirect_header) { + return $this->header( + $redirect_header.': '.$this->get_download_url( + $file_name, + $this->get_version_param(), + true + ) + ); + } + $file_path = $this->get_upload_path($file_name, $this->get_version_param()); + // Prevent browsers from MIME-sniffing the content-type: + $this->header('X-Content-Type-Options: nosniff'); + if (!preg_match($this->options['inline_file_types'], $file_name)) { + $this->header('Content-Type: application/octet-stream'); + $this->header('Content-Disposition: attachment; filename="'.$file_name.'"'); + } else { + $this->header('Content-Type: '.$this->get_file_type($file_path)); + $this->header('Content-Disposition: inline; filename="'.$file_name.'"'); + } + $this->header('Content-Length: '.$this->get_file_size($file_path)); + $this->header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path))); + $this->readfile($file_path); + } + + protected function send_content_type_header() { + $this->header('Vary: Accept'); + if (strpos($this->get_server_var('HTTP_ACCEPT'), 'application/json') !== false) { + $this->header('Content-type: application/json'); + } else { + $this->header('Content-type: text/plain'); + } + } + + protected function send_access_control_headers() { + $this->header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']); + $this->header('Access-Control-Allow-Credentials: ' + .($this->options['access_control_allow_credentials'] ? 'true' : 'false')); + $this->header('Access-Control-Allow-Methods: ' + .implode(', ', $this->options['access_control_allow_methods'])); + $this->header('Access-Control-Allow-Headers: ' + .implode(', ', $this->options['access_control_allow_headers'])); + } + + public function generate_response($content, $print_response = true) { + $this->response = $content; + if ($print_response) { + $json = json_encode($content); + $redirect = stripslashes($this->get_post_param('redirect')); + if ($redirect && preg_match($this->options['redirect_allow_target'], $redirect)) { + $this->header('Location: '.sprintf($redirect, rawurlencode($json))); + return; + } + $this->head(); + if ($this->get_server_var('HTTP_CONTENT_RANGE')) { + $files = isset($content[$this->options['param_name']]) ? + $content[$this->options['param_name']] : null; + if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) { + $this->header('Range: 0-'.( + $this->fix_integer_overflow((int)$files[0]->size) - 1 + )); + } + } + $this->body($json); + } + return $content; + } + + public function get_response () { + return $this->response; + } + + public function head() { + $this->header('Pragma: no-cache'); + $this->header('Cache-Control: no-store, no-cache, must-revalidate'); + $this->header('Content-Disposition: inline; filename="files.json"'); + // Prevent Internet Explorer from MIME-sniffing the content-type: + $this->header('X-Content-Type-Options: nosniff'); + if ($this->options['access_control_allow_origin']) { + $this->send_access_control_headers(); + } + $this->send_content_type_header(); + } + + public function get($print_response = true) { + if ($print_response && $this->get_query_param('download')) { + return $this->download(); + } + $file_name = $this->get_file_name_param(); + if ($file_name) { + $response = array( + $this->get_singular_param_name() => $this->get_file_object($file_name) + ); + } else { + $response = array( + $this->options['param_name'] => $this->get_file_objects() + ); + } + return $this->generate_response($response, $print_response); + } + + public function post($print_response = true) { + if ($this->get_query_param('_method') === 'DELETE') { + return $this->delete($print_response); + } + $upload = $this->get_upload_data($this->options['param_name']); + // Parse the Content-Disposition header, if available: + $content_disposition_header = $this->get_server_var('HTTP_CONTENT_DISPOSITION'); + $file_name = $content_disposition_header ? + rawurldecode(preg_replace( + '/(^[^"]+")|("$)/', + '', + $content_disposition_header + )) : null; + // Parse the Content-Range header, which has the following form: + // Content-Range: bytes 0-524287/2000000 + $content_range_header = $this->get_server_var('HTTP_CONTENT_RANGE'); + $content_range = $content_range_header ? + preg_split('/[^0-9]+/', $content_range_header) : null; + $size = $content_range ? $content_range[3] : null; + $files = array(); + if ($upload) { + if (is_array($upload['tmp_name'])) { + // param_name is an array identifier like "files[]", + // $upload is a multi-dimensional array: + foreach ($upload['tmp_name'] as $index => $value) { + $files[] = $this->handle_file_upload( + $upload['tmp_name'][$index], + $file_name ? $file_name : $upload['name'][$index], + $size ? $size : $upload['size'][$index], + $upload['type'][$index], + $upload['error'][$index], + $index, + $content_range + ); + } + } else { + // param_name is a single object identifier like "file", + // $upload is a one-dimensional array: + $files[] = $this->handle_file_upload( + isset($upload['tmp_name']) ? $upload['tmp_name'] : null, + $file_name ? $file_name : (isset($upload['name']) ? + $upload['name'] : null), + $size ? $size : (isset($upload['size']) ? + $upload['size'] : $this->get_server_var('CONTENT_LENGTH')), + isset($upload['type']) ? + $upload['type'] : $this->get_server_var('CONTENT_TYPE'), + isset($upload['error']) ? $upload['error'] : null, + null, + $content_range + ); + } + } + $response = array($this->options['param_name'] => $files); + return $this->generate_response($response, $print_response); + } + + public function delete($print_response = true) { + $file_names = $this->get_file_names_params(); + if (empty($file_names)) { + $file_names = array($this->get_file_name_param()); + } + $response = array(); + foreach ($file_names as $file_name) { + $file_path = $this->get_upload_path($file_name); + $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path); + if ($success) { + foreach ($this->options['image_versions'] as $version => $options) { + if (!empty($version)) { + $file = $this->get_upload_path($file_name, $version); + if (is_file($file)) { + unlink($file); + } + } + } + } + $response[$file_name] = $success; + } + return $this->generate_response($response, $print_response); + } + + protected function basename($filepath, $suffix = null) { + $splited = preg_split('/\//', rtrim ($filepath, '/ ')); + return substr(basename('X'.$splited[count($splited)-1], $suffix), 1); + } +} diff --git a/web/bin/classes/simple_html_dom.php b/web/bin/classes/simple_html_dom.php index e1204fb..19f8944 100644 --- a/web/bin/classes/simple_html_dom.php +++ b/web/bin/classes/simple_html_dom.php @@ -1,975 +1,975 @@ - - Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/) - Contributions by: - Yousuke Kumakura (Attribute filters) - Vadim Voituk (Negative indexes supports of "find" method) - Antcs (Constructor with automatically load contents either text or file/url) - Licensed under The MIT License - Redistributions of files must retain the above copyright notice. - *******************************************************************************/ - - define('HDOM_TYPE_ELEMENT', 1); - define('HDOM_TYPE_COMMENT', 2); - define('HDOM_TYPE_TEXT', 3); - define('HDOM_TYPE_ENDTAG', 4); - define('HDOM_TYPE_ROOT', 5); - define('HDOM_TYPE_UNKNOWN', 6); - define('HDOM_QUOTE_DOUBLE', 0); - define('HDOM_QUOTE_SINGLE', 1); - define('HDOM_QUOTE_NO', 3); - define('HDOM_INFO_BEGIN', 0); - define('HDOM_INFO_END', 1); - define('HDOM_INFO_QUOTE', 2); - define('HDOM_INFO_SPACE', 3); - define('HDOM_INFO_TEXT', 4); - define('HDOM_INFO_INNER', 5); - define('HDOM_INFO_OUTER', 6); - define('HDOM_INFO_ENDSPACE',7); - -// helper functions -// ----------------------------------------------------------------------------- -// get html dom form file - function file_get_html() { - $dom = new simple_html_dom; - $args = func_get_args(); - $dom->load(call_user_func_array('file_get_contents', $args), true); - return $dom; - } - -// get html dom form string - function str_get_html($str, $lowercase=true) { - $dom = new simple_html_dom; - $dom->load($str, $lowercase); - return $dom; - } - -// dump html dom tree - function dump_html_tree($node, $show_attr=true, $deep=0) { - $lead = str_repeat(' ', $deep); - echo $lead.$node->tag; - if ($show_attr && count($node->attr)>0) { - echo '('; - foreach($node->attr as $k=>$v) - echo "[$k]=>\"".$node->$k.'", '; - echo ')'; - } - echo "\n"; - - foreach($node->nodes as $c) - dump_html_tree($c, $show_attr, $deep+1); - } - -// get dom form file (deprecated) - function file_get_dom() { - $dom = new simple_html_dom; - $args = func_get_args(); - $dom->load(call_user_func_array('file_get_contents', $args), true); - return $dom; - } - -// get dom form string (deprecated) - function str_get_dom($str, $lowercase=true) { - $dom = new simple_html_dom; - $dom->load($str, $lowercase); - return $dom; - } - -// simple html dom node -// ----------------------------------------------------------------------------- - class simple_html_dom_node { - public $nodetype = HDOM_TYPE_TEXT; - public $tag = 'text'; - public $attr = array(); - public $children = array(); - public $nodes = array(); - public $parent = null; - public $_ = array(); - private $dom = null; - - function __construct($dom) { - $this->dom = $dom; - $dom->nodes[] = $this; - } - - function __destruct() { - $this->clear(); - } - - function __toString() { - return $this->outertext(); - } - - // clean up memory due to php5 circular references memory leak... - function clear() { - $this->dom = null; - $this->nodes = null; - $this->parent = null; - $this->children = null; - } - - // dump node's tree - function dump($show_attr=true) { - dump_html_tree($this, $show_attr); - } - - // returns the parent of node - function parent() { - return $this->parent; - } - - // returns children of node - function children($idx=-1) { - if ($idx===-1) return $this->children; - if (isset($this->children[$idx])) return $this->children[$idx]; - return null; - } - - // returns the first child of node - function first_child() { - if (count($this->children)>0) return $this->children[0]; - return null; - } - - // returns the last child of node - function last_child() { - if (($count=count($this->children))>0) return $this->children[$count-1]; - return null; - } - - // returns the next sibling of node - function next_sibling() { - if ($this->parent===null) return null; - $idx = 0; - $count = count($this->parent->children); - while ($idx<$count && $this!==$this->parent->children[$idx]) - ++$idx; - if (++$idx>=$count) return null; - return $this->parent->children[$idx]; - } - - // returns the previous sibling of node - function prev_sibling() { - if ($this->parent===null) return null; - $idx = 0; - $count = count($this->parent->children); - while ($idx<$count && $this!==$this->parent->children[$idx]) - ++$idx; - if (--$idx<0) return null; - return $this->parent->children[$idx]; - } - - // get dom node's inner html - function innertext() { - if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER]; - if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); - - $ret = ''; - foreach($this->nodes as $n) - $ret .= $n->outertext(); - return $ret; - } - - // get dom node's outer text (with tag) - function outertext() { - if ($this->tag==='root') return $this->innertext(); - - // trigger callback - if ($this->dom->callback!==null) - call_user_func_array($this->dom->callback, array($this)); - - if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER]; - if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); - - // render begin tag - $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup(); - - // render inner text - if (isset($this->_[HDOM_INFO_INNER])) - $ret .= $this->_[HDOM_INFO_INNER]; - else { - foreach($this->nodes as $n) - $ret .= $n->outertext(); - } - - // render end tag - if(isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0) - $ret .= 'tag.'>'; - return $ret; - } - - // get dom node's plain text - function text() { - if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER]; - switch ($this->nodetype) { - case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); - case HDOM_TYPE_COMMENT: return ''; - case HDOM_TYPE_UNKNOWN: return ''; - } - if (strcasecmp($this->tag, 'script')===0) return ''; - if (strcasecmp($this->tag, 'style')===0) return ''; - - $ret = ''; - foreach($this->nodes as $n) - $ret .= $n->text(); - return $ret; - } - - function xmltext() { - $ret = $this->innertext(); - $ret = str_ireplace('', '', $ret); - return $ret; - } - - // build node's text with tag - function makeup() { - // text, comment, unknown - if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); - - $ret = '<'.$this->tag; - $i = -1; - - foreach($this->attr as $key=>$val) { - ++$i; - - // skip removed attribute - if ($val===null || $val===false) - continue; - - $ret .= $this->_[HDOM_INFO_SPACE][$i][0]; - //no value attr: nowrap, checked selected... - if ($val===true) - $ret .= $key; - else { - switch($this->_[HDOM_INFO_QUOTE][$i]) { - case HDOM_QUOTE_DOUBLE: $quote = '"'; break; - case HDOM_QUOTE_SINGLE: $quote = '\''; break; - default: $quote = ''; - } - $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote; - } - } - $ret = $this->dom->restore_noise($ret); - return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>'; - } - - // find elements by css selector - function find($selector, $idx=null) { - $selectors = $this->parse_selector($selector); - if (($count=count($selectors))===0) return array(); - $found_keys = array(); - - // find each selector - for ($c=0; $c<$count; ++$c) { - if (($levle=count($selectors[0]))===0) return array(); - if (!isset($this->_[HDOM_INFO_BEGIN])) return array(); - - $head = array($this->_[HDOM_INFO_BEGIN]=>1); - - // handle descendant selectors, no recursive! - for ($l=0; $l<$levle; ++$l) { - $ret = array(); - foreach($head as $k=>$v) { - $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k]; - $n->seek($selectors[$c][$l], $ret); - } - $head = $ret; - } - - foreach($head as $k=>$v) { - if (!isset($found_keys[$k])) - $found_keys[$k] = 1; - } - } - - // sort keys - ksort($found_keys); - - $found = array(); - foreach($found_keys as $k=>$v) - $found[] = $this->dom->nodes[$k]; - - // return nth-element or array - if (is_null($idx)) return $found; - else if ($idx<0) $idx = count($found) + $idx; - return (isset($found[$idx])) ? $found[$idx] : null; - } - - // seek for given conditions - protected function seek($selector, &$ret) { - list($tag, $key, $val, $exp, $no_key) = $selector; - - // xpath index - if ($tag && $key && is_numeric($key)) { - $count = 0; - foreach ($this->children as $c) { - if ($tag==='*' || $tag===$c->tag) { - if (++$count==$key) { - $ret[$c->_[HDOM_INFO_BEGIN]] = 1; - return; - } - } - } - return; - } - - $end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0; - if ($end==0) { - $parent = $this->parent; - while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) { - $end -= 1; - $parent = $parent->parent; - } - $end += $parent->_[HDOM_INFO_END]; - } - - for($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) { - $node = $this->dom->nodes[$i]; - $pass = true; - - if ($tag==='*' && !$key) { - if (in_array($node, $this->children, true)) - $ret[$i] = 1; - continue; - } - - // compare tag - if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;} - // compare key - if ($pass && $key) { - if ($no_key) { - if (isset($node->attr[$key])) $pass=false; - } - else if (!isset($node->attr[$key])) $pass=false; - } - // compare value - if ($pass && $key && $val && $val!=='*') { - $check = $this->match($exp, $val, $node->attr[$key]); - // handle multiple class - if (!$check && strcasecmp($key, 'class')===0) { - foreach(explode(' ',$node->attr[$key]) as $k) { - $check = $this->match($exp, $val, $k); - if ($check) break; - } - } - if (!$check) $pass = false; - } - if ($pass) $ret[$i] = 1; - unset($node); - } - } - - protected function match($exp, $pattern, $value) { - switch ($exp) { - case '=': - return ($value===$pattern); - case '!=': - return ($value!==$pattern); - case '^=': - return preg_match("/^".preg_quote($pattern,'/')."/", $value); - case '$=': - return preg_match("/".preg_quote($pattern,'/')."$/", $value); - case '*=': - if ($pattern[0]=='/') - return preg_match($pattern, $value); - return preg_match("/".$pattern."/i", $value); - } - return false; - } - - protected function parse_selector($selector_string) { - // pattern of CSS selectors, modified from mootools - $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is"; - preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER); - $selectors = array(); - $result = array(); - //print_r($matches); - - foreach ($matches as $m) { - $m[0] = trim($m[0]); - if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue; - // for borwser grnreated xpath - if ($m[1]==='tbody') continue; - - list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false); - if(!empty($m[2])) {$key='id'; $val=$m[2];} - if(!empty($m[3])) {$key='class'; $val=$m[3];} - if(!empty($m[4])) {$key=$m[4];} - if(!empty($m[5])) {$exp=$m[5];} - if(!empty($m[6])) {$val=$m[6];} - - // convert to lowercase - if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);} - //elements that do NOT have the specified attribute - if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;} - - $result[] = array($tag, $key, $val, $exp, $no_key); - if (trim($m[7])===',') { - $selectors[] = $result; - $result = array(); - } - } - if (count($result)>0) - $selectors[] = $result; - return $selectors; - } - - function __get($name) { - if (isset($this->attr[$name])) return $this->attr[$name]; - switch($name) { - case 'outertext': return $this->outertext(); - case 'innertext': return $this->innertext(); - case 'plaintext': return $this->text(); - case 'xmltext': return $this->xmltext(); - default: return array_key_exists($name, $this->attr); - } - } - - function __set($name, $value) { - switch($name) { - case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value; - case 'innertext': - if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value; - return $this->_[HDOM_INFO_INNER] = $value; - } - if (!isset($this->attr[$name])) { - $this->_[HDOM_INFO_SPACE][] = array(' ', '', ''); - $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE; - } - $this->attr[$name] = $value; - } - - function __isset($name) { - switch($name) { - case 'outertext': return true; - case 'innertext': return true; - case 'plaintext': return true; - } - //no value attr: nowrap, checked selected... - return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]); - } - - function __unset($name) { - if (isset($this->attr[$name])) - unset($this->attr[$name]); - } - - // camel naming conventions - function getAllAttributes() {return $this->attr;} - function getAttribute($name) {return $this->__get($name);} - function setAttribute($name, $value) {$this->__set($name, $value);} - function hasAttribute($name) {return $this->__isset($name);} - function removeAttribute($name) {$this->__set($name, null);} - function getElementById($id) {return $this->find("#$id", 0);} - function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);} - function getElementByTagName($name) {return $this->find($name, 0);} - function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);} - function parentNode() {return $this->parent();} - function childNodes($idx=-1) {return $this->children($idx);} - function firstChild() {return $this->first_child();} - function lastChild() {return $this->last_child();} - function nextSibling() {return $this->next_sibling();} - function previousSibling() {return $this->prev_sibling();} - } - -// simple html dom parser -// ----------------------------------------------------------------------------- - class simple_html_dom { - public $root = null; - public $nodes = array(); - public $callback = null; - public $lowercase = false; - protected $pos; - protected $doc; - protected $char; - protected $size; - protected $cursor; - protected $parent; - protected $noise = array(); - protected $token_blank = " \t\r\n"; - protected $token_equal = ' =/>'; - protected $token_slash = " />\r\n\t"; - protected $token_attr = ' >'; - // use isset instead of in_array, performance boost about 30%... - protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1); - protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1); - protected $optional_closing_tags = array( - 'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1), - 'th'=>array('th'=>1), - 'td'=>array('td'=>1), - 'li'=>array('li'=>1), - 'dt'=>array('dt'=>1, 'dd'=>1), - 'dd'=>array('dd'=>1, 'dt'=>1), - 'dl'=>array('dd'=>1, 'dt'=>1), - 'p'=>array('p'=>1), - 'nobr'=>array('nobr'=>1), - ); - - function __construct($str=null) { - if ($str) { - if (preg_match("/^http:\/\//i",$str) || is_file($str)) - $this->load_file($str); - else - $this->load($str); - } - } - - function __destruct() { - $this->clear(); - } - - // load html from string - function load($str, $lowercase=true) { - // prepare - $this->prepare($str, $lowercase); - // strip out comments - $this->remove_noise("''is"); - // strip out cdata - $this->remove_noise("''is", true); - // strip out -
- +query_one(array("idville" => (int)$idville)); + +$zoom = 5; +if (empty($arrV['latitudeVille']) || empty($arrV['longitudeVille'])) { + $arrV['latitudeVille'] = $arrV['longitudeVille'] = 0; + $zoom = 2; +} +?> + +
+ diff --git a/web/bin/idae/mdl/app/app_dev/debug_times.php b/web/bin/idae/mdl/app/app_dev/debug_times.php index 9e6c2f5..75be4d7 100644 --- a/web/bin/idae/mdl/app/app_dev/debug_times.php +++ b/web/bin/idae/mdl/app/app_dev/debug_times.php @@ -1,21 +1,21 @@ -get_session(); - - $configs = CommandeQueueConsole::get_times_config(); - - $HTMLSHOPS = $Idae->module('app_dev/debug_times_shops'); - -?> - - +get_session(); + + $configs = CommandeQueueConsole::get_times_config(); + + $HTMLSHOPS = $Idae->module('app_dev/debug_times_shops'); + +?> + + get_session(); - - $rs = $DB->find(['actifShop' => 1]); - - while ($arr = $rs->getNext()) { - ?> -
- "; - $configs = CommandeQueueConsole::consoleShop($arr['idshop']); - echo $configs->console_shop->get_templateHTML(); - echo "
"; - } +get_session(); + + $rs = $DB->find(['actifShop' => 1]); + + while ($arr = $rs->getNext()) { + ?> +
+ "; + $configs = CommandeQueueConsole::consoleShop($arr['idshop']); + echo $configs->console_shop->get_templateHTML(); + echo "
"; + } diff --git a/web/bin/idae/mdl/app/app_espace.php b/web/bin/idae/mdl/app/app_espace.php index 1735275..8713c68 100644 --- a/web/bin/idae/mdl/app/app_espace.php +++ b/web/bin/idae/mdl/app/app_espace.php @@ -1,22 +1,22 @@ -nomAppscheme; - $iconTable = $APP->iconAppscheme; - - $idae_liste = new Idae($table); - $table_ligne = $idae_liste->liste($vars); - $table_ligne = $idae_liste->module('liste',http_build_query($_POST)); - +nomAppscheme; + $iconTable = $APP->iconAppscheme; + + $idae_liste = new Idae($table); + $table_ligne = $idae_liste->liste($vars); + $table_ligne = $idae_liste->module('liste',http_build_query($_POST)); + echo $table_ligne; \ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche.php b/web/bin/idae/mdl/app/app_fiche.php index 54499f5..170a595 100644 --- a/web/bin/idae/mdl/app/app_fiche.php +++ b/web/bin/idae/mdl/app/app_fiche.php @@ -1,115 +1,115 @@ -module('app_custom/' . $table . '/' . $table . '_fiche', $this->HTTP_VARS); - - return; - } - - $APP = new App($table); - - $APP_TABLE = $APP->app_table_one; - $APPOBJ = $APP->appobj($table_value, $vars); - $ARR = $APP->findOne(["id$table" => (int)$table_value]); - // - $EXTRACTS_VARS = $APP->extract_vars($table_value, $vars); - extract($EXTRACTS_VARS, EXTR_OVERWRITE); - - $Idae = new Idae($table); - - $crypted_image_link = AppLink::liste_images($table, $table_value); - - $options = ['apply_droit' => [$type_session, - 'R'], - 'data_mode' => 'fiche', - 'scheme_field_view' => 'native', - 'field_draw_style' => 'draw_html_field', - 'scheme_field_view_groupby' => 'group', - 'fields_scheme_part' => 'all', - 'field_composition' => ['hide_field_icon' => 1, - 'hide_field_name' => 1, - 'hide_field_value' => 1]]; - - $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); - $Fabric->fetch_data(["id$table" => $table_value]); - $tplData = $Fabric->get_templateDataHTML(); - -?> -
-
- module('fiche_entete', ['table' => $table, - 'table_value' => $table_value]) ?> -
-
-
-
-
- -
- - -
-
- -
-
- -
-
- module('app_fiche_fields', ['table' => $table, - 'table_value' => $table_value, - 'titre' => 0, - 'show_empty' => 0]) ?> -
- - APP_TABLE['hasLigneScheme'])): ?> -
-
- module('app_fiche/fiche_ligne', ['table' => $table . '_ligne', - 'vars' => ["id$table" => $table_value]]) ?> -
-
- -
-
- -
- -
-
- -
- module('app_fiche_fk/app_fiche_fk_nongrouped', ['mode' => 'fiche', - 'table' => $table, - 'table_value' => $table_value]) ?>
-
-
- module('fiche_rfk', ['table' => $table, - 'table_value' => $table_value]) ?> -
-
-
-
-
- module('app_fiche/app_fiche_menu', ['table' => $table, - 'table_value' => $table_value]) ?> -
+module('app_custom/' . $table . '/' . $table . '_fiche', $this->HTTP_VARS); + + return; + } + + $APP = new App($table); + + $APP_TABLE = $APP->app_table_one; + $APPOBJ = $APP->appobj($table_value, $vars); + $ARR = $APP->findOne(["id$table" => (int)$table_value]); + // + $EXTRACTS_VARS = $APP->extract_vars($table_value, $vars); + extract($EXTRACTS_VARS, EXTR_OVERWRITE); + + $Idae = new Idae($table); + + $crypted_image_link = AppLink::liste_images($table, $table_value); + + $options = ['apply_droit' => [$type_session, + 'R'], + 'data_mode' => 'fiche', + 'scheme_field_view' => 'native', + 'field_draw_style' => 'draw_html_field', + 'scheme_field_view_groupby' => 'group', + 'fields_scheme_part' => 'all', + 'field_composition' => ['hide_field_icon' => 1, + 'hide_field_name' => 1, + 'hide_field_value' => 1]]; + + $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); + $Fabric->fetch_data(["id$table" => $table_value]); + $tplData = $Fabric->get_templateDataHTML(); + +?> +
+
+ module('fiche_entete', ['table' => $table, + 'table_value' => $table_value]) ?> +
+
+
+
+
+ +
+ + +
+
+ +
+
+ +
+
+ module('app_fiche_fields', ['table' => $table, + 'table_value' => $table_value, + 'titre' => 0, + 'show_empty' => 0]) ?> +
+ + APP_TABLE['hasLigneScheme'])): ?> +
+
+ module('app_fiche/fiche_ligne', ['table' => $table . '_ligne', + 'vars' => ["id$table" => $table_value]]) ?> +
+
+ +
+
+ +
+ +
+
+ +
+ module('app_fiche_fk/app_fiche_fk_nongrouped', ['mode' => 'fiche', + 'table' => $table, + 'table_value' => $table_value]) ?>
+
+
+ module('fiche_rfk', ['table' => $table, + 'table_value' => $table_value]) ?> +
+
+
+
+
+ module('app_fiche/app_fiche_menu', ['table' => $table, + 'table_value' => $table_value]) ?> +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche/app_fiche_fields_table.php b/web/bin/idae/mdl/app/app_fiche/app_fiche_fields_table.php index ec7118f..dbdd24a 100644 --- a/web/bin/idae/mdl/app/app_fiche/app_fiche_fields_table.php +++ b/web/bin/idae/mdl/app/app_fiche/app_fiche_fields_table.php @@ -1,59 +1,59 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - - $Idae = new Idae($table); - $ARR = $Idae->findOne(["id$table" => $table_value]); - $ARR_COLLECT = $Idae->get_table_fields($table_value, $this->HTTP_VARS); - - $COLLECT_FIELDS = []; - foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { - foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { - $COLLECT_FIELDS[] = $ARR_FIELD; - } - } - - $FK = $Idae->get_grille_fk(); -?> -
-
- $ARR_FIELD) { ?> -
-
-
- -
-
- -
-
- HTTP_VARS['edit_field']) ? $ARR_FIELD['value_html'] : $ARR_FIELD['value_input'] ?> -
-
-
- - $ARR_FK) { ?> -
-
-
- -
-
- - cf_output('color', $ARR, 'color' . ucfirst($ARR_FK['codeAppscheme'])); ?> -
-
cf_output('icon', $ARR, 'icon' . ucfirst($ARR_FK['codeAppscheme'])); ?> - cf_output('nom', $ARR, 'nom' . ucfirst($ARR_FK['codeAppscheme'])); ?> - cf_output('prenom', $ARR, 'prenom' . ucfirst($ARR_FK['codeAppscheme'])); ?> -
-
-
- -
+HTTP_VARS['table']; + $Table = ucfirst($table); + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + + $Idae = new Idae($table); + $ARR = $Idae->findOne(["id$table" => $table_value]); + $ARR_COLLECT = $Idae->get_table_fields($table_value, $this->HTTP_VARS); + + $COLLECT_FIELDS = []; + foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { + foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { + $COLLECT_FIELDS[] = $ARR_FIELD; + } + } + + $FK = $Idae->get_grille_fk(); +?> +
+
+ $ARR_FIELD) { ?> +
+
+
+ +
+
+ +
+
+ HTTP_VARS['edit_field']) ? $ARR_FIELD['value_html'] : $ARR_FIELD['value_input'] ?> +
+
+
+ + $ARR_FK) { ?> +
+
+
+ +
+
+ + cf_output('color', $ARR, 'color' . ucfirst($ARR_FK['codeAppscheme'])); ?> +
+
cf_output('icon', $ARR, 'icon' . ucfirst($ARR_FK['codeAppscheme'])); ?> + cf_output('nom', $ARR, 'nom' . ucfirst($ARR_FK['codeAppscheme'])); ?> + cf_output('prenom', $ARR, 'prenom' . ucfirst($ARR_FK['codeAppscheme'])); ?> +
+
+
+ +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche/app_fiche_fields_table_fk.php b/web/bin/idae/mdl/app/app_fiche/app_fiche_fields_table_fk.php index 573bf5d..ceb940f 100644 --- a/web/bin/idae/mdl/app/app_fiche/app_fiche_fields_table_fk.php +++ b/web/bin/idae/mdl/app/app_fiche/app_fiche_fields_table_fk.php @@ -1,43 +1,43 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - - $Idae = new Idae($table); - $ARR = $Idae->findOne(["id$table" => $table_value]); - $ARR_COLLECT = $Idae->get_table_fields($table_value, $this->HTTP_VARS); - - $COLLECT_FIELDS = []; - foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { - foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { - $COLLECT_FIELDS[] = $ARR_FIELD; - } - } - - $FK = $Idae->get_grille_fk(); -?> -
-
- $ARR_FK) { ?> -
-
-
- -
-
- - cf_output('color', $ARR, 'color' . ucfirst($ARR_FK['codeAppscheme'])); ?> -
-
cf_output('icon', $ARR, 'icon' . ucfirst($ARR_FK['codeAppscheme'])); ?> - cf_output('nom', $ARR, 'nom' . ucfirst($ARR_FK['codeAppscheme'])); ?> - cf_output('prenom', $ARR, 'prenom' . ucfirst($ARR_FK['codeAppscheme'])); ?> -
-
-
- -
+HTTP_VARS['table']; + $Table = ucfirst($table); + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + + $Idae = new Idae($table); + $ARR = $Idae->findOne(["id$table" => $table_value]); + $ARR_COLLECT = $Idae->get_table_fields($table_value, $this->HTTP_VARS); + + $COLLECT_FIELDS = []; + foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { + foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { + $COLLECT_FIELDS[] = $ARR_FIELD; + } + } + + $FK = $Idae->get_grille_fk(); +?> +
+
+ $ARR_FK) { ?> +
+
+
+ +
+
+ + cf_output('color', $ARR, 'color' . ucfirst($ARR_FK['codeAppscheme'])); ?> +
+
cf_output('icon', $ARR, 'icon' . ucfirst($ARR_FK['codeAppscheme'])); ?> + cf_output('nom', $ARR, 'nom' . ucfirst($ARR_FK['codeAppscheme'])); ?> + cf_output('prenom', $ARR, 'prenom' . ucfirst($ARR_FK['codeAppscheme'])); ?> +
+
+
+ +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche/app_fiche_ligne.php b/web/bin/idae/mdl/app/app_fiche/app_fiche_ligne.php index 029b52f..c5d70d6 100644 --- a/web/bin/idae/mdl/app/app_fiche/app_fiche_ligne.php +++ b/web/bin/idae/mdl/app/app_fiche/app_fiche_ligne.php @@ -1,62 +1,62 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - unset($vars['idlivreur']); - // - $APP_HAS_FIELD = new App('appscheme_has_field'); - $APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); - // - $APP = new App($table); - - $rs = $APP->find($vars); - $arr = iterator_to_array($rs); - - $RS_HAS_TABLE_FIELD = $APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$APP->idappscheme])->sort(['ordreAppscheme_has_table_field' => 1]); - $ARR_HAS_TABLE_FIELD = iterator_to_array($RS_HAS_TABLE_FIELD); - // has_totalAppscheme_field - $fields = $ARR_HAS_TABLE_FIELD; - $liste = $arr; - - // Helper::dump($vars); -?> -
- - - - $field) { ?> - - - - - - $row) { - $id = 'id' . $table ?> - - $field) { - $codeField = $field['codeAppscheme_field']; - ?> - - - - - -
- - -
- draw_field(['field_name_raw' => $field['codeAppscheme_has_table_field'], - 'table' => $table, - 'field_value' => $row[$field['codeAppscheme_has_table_field']]]); ?> - -
- - draw_field(['field_name_raw' => "description$Table", - 'table' => $table, - 'field_value' => nl2br($row["description$Table"])]); ?> -
- -
+HTTP_VARS['table']; + $Table = ucfirst($table); + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + unset($vars['idlivreur']); + // + $APP_HAS_FIELD = new App('appscheme_has_field'); + $APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); + // + $APP = new App($table); + + $rs = $APP->find($vars); + $arr = iterator_to_array($rs); + + $RS_HAS_TABLE_FIELD = $APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$APP->idappscheme])->sort(['ordreAppscheme_has_table_field' => 1]); + $ARR_HAS_TABLE_FIELD = iterator_to_array($RS_HAS_TABLE_FIELD); + // has_totalAppscheme_field + $fields = $ARR_HAS_TABLE_FIELD; + $liste = $arr; + + // Helper::dump($vars); +?> +
+ + + + $field) { ?> + + + + + + $row) { + $id = 'id' . $table ?> + + $field) { + $codeField = $field['codeAppscheme_field']; + ?> + + + + + +
+ + +
+ draw_field(['field_name_raw' => $field['codeAppscheme_has_table_field'], + 'table' => $table, + 'field_value' => $row[$field['codeAppscheme_has_table_field']]]); ?> + +
+ + draw_field(['field_name_raw' => "description$Table", + 'table' => $table, + 'field_value' => nl2br($row["description$Table"])]); ?> +
+ +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche/app_fiche_mail.php b/web/bin/idae/mdl/app/app_fiche/app_fiche_mail.php index c7d181e..15dfc49 100644 --- a/web/bin/idae/mdl/app/app_fiche/app_fiche_mail.php +++ b/web/bin/idae/mdl/app/app_fiche/app_fiche_mail.php @@ -1,139 +1,139 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - - // - $APP = new App($table); - $APP_TABLE = $APP->app_table_one; - $APPOBJ = $APP->appobj($table_value, $vars); - $ARR = $APP->findOne(["id$table" => (int)$table_value]); - - $Idae = new Idae($table); - $ARR_COLLECT = $Idae->get_table_fields($table_value); - - function draw_it($codeAppscheme_field, $ARR, $table = 'commande') { - $APP = new App($table); - $Table = ucfirst($table); - - $value = $ARR[$codeAppscheme_field . $Table]?: $ARR[$codeAppscheme_field]; - return $APP->draw_field(['field_name_raw' => $codeAppscheme_field, - 'table' => $table, - 'field_value' => $value]); - } - - $APP_HAS_FIELD = new App('appscheme_has_field'); - $APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); - $APP_LIGNE = new App('commande_ligne'); - - $rs_ligne = $APP_LIGNE->find(["id$table"=>$table_value]); - $arr_ligne = iterator_to_array($rs_ligne); - - $RS_HAS_TABLE_FIELD = $APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$APP_LIGNE->idappscheme])->sort(['ordreAppscheme_has_table_field' => 1]); - $ARR_HAS_TABLE_FIELD = iterator_to_array($RS_HAS_TABLE_FIELD); - - $fields = $ARR_HAS_TABLE_FIELD; - $liste = $arr_ligne; - -?> -
-
- module('fiche_entete', ['table' => $table, - 'table_value' => $table_value]) ?> -
-
- -
-
-
-
-
- - - - - -
- - - - - - - - - - - - - -
Code
Date
Heure
-
- - - - - - - - - - - - - -
Nom
Email
Adresse
-
-
-
-
-
- APP_TABLE['hasLigneScheme'])): ?> - - - - $field) { ?> - - - - - - $row) { - $id = 'id' . $table ?> - - $field) { - ?> - - - - - -
- - -
- -
- -
- module('fiche_rfk', ['table' => $table, - 'table_value' => $table_value]) ?> -
-
-
module('app_fiche_fk/app_fiche_fk', ['mode' => 'fiche', 'table' => $table, 'table_value' => $table_value]) ?>
-
-
+HTTP_VARS['table']; + $Table = ucfirst($table); + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + + // + $APP = new App($table); + $APP_TABLE = $APP->app_table_one; + $APPOBJ = $APP->appobj($table_value, $vars); + $ARR = $APP->findOne(["id$table" => (int)$table_value]); + + $Idae = new Idae($table); + $ARR_COLLECT = $Idae->get_table_fields($table_value); + + function draw_it($codeAppscheme_field, $ARR, $table = 'commande') { + $APP = new App($table); + $Table = ucfirst($table); + + $value = $ARR[$codeAppscheme_field . $Table]?: $ARR[$codeAppscheme_field]; + return $APP->draw_field(['field_name_raw' => $codeAppscheme_field, + 'table' => $table, + 'field_value' => $value]); + } + + $APP_HAS_FIELD = new App('appscheme_has_field'); + $APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); + $APP_LIGNE = new App('commande_ligne'); + + $rs_ligne = $APP_LIGNE->find(["id$table"=>$table_value]); + $arr_ligne = iterator_to_array($rs_ligne); + + $RS_HAS_TABLE_FIELD = $APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$APP_LIGNE->idappscheme])->sort(['ordreAppscheme_has_table_field' => 1]); + $ARR_HAS_TABLE_FIELD = iterator_to_array($RS_HAS_TABLE_FIELD); + + $fields = $ARR_HAS_TABLE_FIELD; + $liste = $arr_ligne; + +?> +
+
+ module('fiche_entete', ['table' => $table, + 'table_value' => $table_value]) ?> +
+
+ +
+
+
+
+
+ + + + + +
+ + + + + + + + + + + + + +
Code
Date
Heure
+
+ + + + + + + + + + + + + +
Nom
Email
Adresse
+
+
+
+
+
+ APP_TABLE['hasLigneScheme'])): ?> + + + + $field) { ?> + + + + + + $row) { + $id = 'id' . $table ?> + + $field) { + ?> + + + + + +
+ + +
+ +
+ +
+ module('fiche_rfk', ['table' => $table, + 'table_value' => $table_value]) ?> +
+
+
module('app_fiche_fk/app_fiche_fk', ['mode' => 'fiche', 'table' => $table, 'table_value' => $table_value]) ?>
+
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche/app_fiche_menu.php b/web/bin/idae/mdl/app/app_fiche/app_fiche_menu.php index e798bc8..18a26dc 100644 --- a/web/bin/idae/mdl/app/app_fiche/app_fiche_menu.php +++ b/web/bin/idae/mdl/app/app_fiche/app_fiche_menu.php @@ -1,162 +1,162 @@ -translate_vars($vars); - $groupBy = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; - // - $APP = new App($table); - $APP_TABLE = $APP->app_table_one; - $APPOBJ = $APP->appobj($table_value, $vars); - $ICON_COLOR = $APPOBJ->ICON_COLOR; - $ARR = $APPOBJ->ARR; - // - $name_id = 'id' . $table; - $nom = 'nom' . ucfirst($table); - - $arr_allowed_c = droit_table($type_session, 'C', $table); - $arr_allowed_r = droit_table($type_session, 'R', $table); - $arr_allowed_u = droit_table($type_session, 'U', $table); - $arr_allowed_d = droit_table($type_session, 'D', $table); - $arr_allowed_l = droit_table($type_session, 'L', $table); - - $white_COLOR = '#fff'; - $rand = uniqid(); - - $css_table = "fiche_$table"; - - $color = empty($APP->colorAppscheme) ? '#c4c4c4' : $APP->colorAppscheme; - $color_contrast = color_contrast($APP->colorAppscheme); - $color_inverse = color_inverse($APP->colorAppscheme); - - $crypted_create_link = AppLink::create($table, null, [$name_idtype_session => $idtype_session]); - $crypted_update_link = AppLink::update($table, $table_value); - $crypted_delete_link = AppLink::delete($table, $table_value); - $crypted_map_link = AppLink::map($table, $table_value); - $crypted_liste_link = AppLink::liste($table); - $crypted_liste_groupby_link = AppLink::liste_groupby($table); - $crypted_liste_calendar_link = AppLink::liste_calendrier($table); - -?> -
- -
-
- -
-
- - -
-
- -
-
- - has_field('adresse')) { ?> -
-
- -
-
- - has_field(['date', 'dateDebut'])) { ?> -
-
- -
-
- - -
-
- -
-
- - -
-
- -
-
- -
- \ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_entete.php b/web/bin/idae/mdl/app/app_fiche_entete.php index 53594c1..2370aab 100644 --- a/web/bin/idae/mdl/app/app_fiche_entete.php +++ b/web/bin/idae/mdl/app/app_fiche_entete.php @@ -1,77 +1,77 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - $query_str = http_build_query($this->HTTP_VARS); - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - // - $APP = new App($table); - $APP_TABLE = $APP->app_table_one; - $APPOBJ = $APP->appobj($table_value, $vars); - $ARR = $APPOBJ->ARR; - // - $EXTRACTS_VARS = $APP->extract_vars($table_value, $vars); - extract($EXTRACTS_VARS, EXTR_OVERWRITE); - // - // - $name_id = 'id' . $table; - - $arr_allowed_c = droit_table($type_session, 'C', $table); - $arr_allowed_r = droit_table($type_session, 'R', $table); - $arr_allowed_u = droit_table($type_session, 'U', $table); - $arr_allowed_d = droit_table($type_session, 'D', $table); - $arr_allowed_l = droit_table($type_session, 'L', $table); - - $html_fiche_link = 'back'; - $white_COLOR = '#fff'; - - if ($APP->has_field('adresse')) { - $html_map_link = 'table=' . $table . '&table_value=' . $table_value; - } - - $rand = uniqid(); - - $css_table = "fiche_$table"; - - $color = empty($APP->colorAppscheme) ? '#c4c4c4' : $APP->colorAppscheme; - $color_contrast = color_contrast($APP->colorAppscheme); - $color_inverse = color_inverse($APP->colorAppscheme); - - $fieldTypeShow = ($table=='commande')? 'code' : 'nom' ; -?> -
-
-
- HTTP_VARS['table_value'])): ?> -
-
- -
- -
- -
- -
-
-
- HTTP_VARS['table_value'])): ?> -

draw_field(['field_name_raw' => 'nom', - 'table' => $table, - 'field_value' => $ARR[$fieldTypeShow . $Table]]) ?> -

- -

nomAppscheme ?>

- -
-
-
+HTTP_VARS['table']; + $Table = ucfirst($table); + $query_str = http_build_query($this->HTTP_VARS); + + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + // + $APP = new App($table); + $APP_TABLE = $APP->app_table_one; + $APPOBJ = $APP->appobj($table_value, $vars); + $ARR = $APPOBJ->ARR; + // + $EXTRACTS_VARS = $APP->extract_vars($table_value, $vars); + extract($EXTRACTS_VARS, EXTR_OVERWRITE); + // + // + $name_id = 'id' . $table; + + $arr_allowed_c = droit_table($type_session, 'C', $table); + $arr_allowed_r = droit_table($type_session, 'R', $table); + $arr_allowed_u = droit_table($type_session, 'U', $table); + $arr_allowed_d = droit_table($type_session, 'D', $table); + $arr_allowed_l = droit_table($type_session, 'L', $table); + + $html_fiche_link = 'back'; + $white_COLOR = '#fff'; + + if ($APP->has_field('adresse')) { + $html_map_link = 'table=' . $table . '&table_value=' . $table_value; + } + + $rand = uniqid(); + + $css_table = "fiche_$table"; + + $color = empty($APP->colorAppscheme) ? '#c4c4c4' : $APP->colorAppscheme; + $color_contrast = color_contrast($APP->colorAppscheme); + $color_inverse = color_inverse($APP->colorAppscheme); + + $fieldTypeShow = ($table=='commande')? 'code' : 'nom' ; +?> +
+
+
+ HTTP_VARS['table_value'])): ?> +
+
+ +
+ +
+ +
+ +
+
+
+ HTTP_VARS['table_value'])): ?> +

draw_field(['field_name_raw' => 'nom', + 'table' => $table, + 'field_value' => $ARR[$fieldTypeShow . $Table]]) ?> +

+ +

nomAppscheme ?>

+ +
+
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_fields.php b/web/bin/idae/mdl/app/app_fiche_fields.php index 9896ede..eec9f85 100644 --- a/web/bin/idae/mdl/app/app_fiche_fields.php +++ b/web/bin/idae/mdl/app/app_fiche_fields.php @@ -1,59 +1,59 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - - $Idae = new Idae($table); - $ARR_COLLECT = $Idae->get_table_fields($table_value, $this->HTTP_VARS); - if ($Idae->has_field('adresse')) { - $html_map_link = 'table=' . $table . '&table_value=' . $table_value; - } -?> -
-
- $ARR_FIELD_GROUP) { - ?> - HTTP_VARS['titre'])) { ?> -
-
-
-
-
-
- - HTTP_VARS['cesure'])) { ?> -
- -
- $ARR_FIELD) { - - $html_edit_link = 'field_name_raw='.$ARR_FIELD['field_name_raw'].'&field_name='.$ARR_FIELD['field_name'].'&table=' . $table . '&table_value=' . $table_value; - - ?> -
-
-
- - -
-
- -
-
- HTTP_VARS['edit_field']) ? $ARR_FIELD['value_html'] : $ARR_FIELD['value_input'] ?> -
-
-
- -
- HTTP_VARS['titre'])) { ?> -
-
-
- - -
+HTTP_VARS['table']; + $Table = ucfirst($table); + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + + $Idae = new Idae($table); + $ARR_COLLECT = $Idae->get_table_fields($table_value, $this->HTTP_VARS); + if ($Idae->has_field('adresse')) { + $html_map_link = 'table=' . $table . '&table_value=' . $table_value; + } +?> +
+
+ $ARR_FIELD_GROUP) { + ?> + HTTP_VARS['titre'])) { ?> +
+
+
+
+
+
+ + HTTP_VARS['cesure'])) { ?> +
+ +
+ $ARR_FIELD) { + + $html_edit_link = 'field_name_raw='.$ARR_FIELD['field_name_raw'].'&field_name='.$ARR_FIELD['field_name'].'&table=' . $table . '&table_value=' . $table_value; + + ?> +
+
+
+ - +
+
+ +
+
+ HTTP_VARS['edit_field']) ? $ARR_FIELD['value_html'] : $ARR_FIELD['value_input'] ?> +
+
+
+ +
+ HTTP_VARS['titre'])) { ?> +
+
+
+ + +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk.php b/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk.php index 670ce6c..8954b12 100644 --- a/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk.php +++ b/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk.php @@ -1,63 +1,63 @@ -table; - $Table = ucfirst($table); - - $APP = new App($table); - if (sizeof($APP->get_grille_fk()) == 0) { return; } - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $mode = empty($this->HTTP_VARS['mode']) ? 'icone' : $this->HTTP_VARS['mode']; - - $name_id = 'id' . $table; - $ARR = $APP->findOne([$name_id => $table_value]); -?> -
- get_grille_fk() as $field): - // query for name - $table_fk = $field['table_fk']; - $Table_fk = ucfirst($table_fk); - - $arr_allowed_c = droit_table($type_session, 'R', $table_fk); - $arr_allowed_l = droit_table($type_session, 'L', $table_fk); - - $APP_TMP = new App($table_fk); - $TBL_TMP = $APP_TMP->app_table_one; - - $arr = $APP->plug($field['base_fk'], $table_fk)->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); - $dsp_fieldname = 'nom' . ucfirst($table_fk); - $dsp_fieldcode = 'code' . ucfirst($table_fk); - $dsp_name = $arr[$dsp_fieldname] ?: $arr[$dsp_fieldcode]; - if (empty($dsp_name)) { - $dsp_name = 'Aucun'; - } - - $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; - ?> -
-
-
-
-
-
nomAppscheme ?>
-
-
draw_field(['field_name_raw' => 'nom', 'field_name' => $dsp_fieldname, 'table' => $table, 'field_value' => $dsp_name]) ?>
-
cf_output('color', $ARR, "color$Table_fk"); ?>
-
cf_output('icon', $ARR, "icon$Table_fk"); ?>
-
-
-
- -
-
-
-
- +table; + $Table = ucfirst($table); + + $APP = new App($table); + if (sizeof($APP->get_grille_fk()) == 0) { return; } + + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $mode = empty($this->HTTP_VARS['mode']) ? 'icone' : $this->HTTP_VARS['mode']; + + $name_id = 'id' . $table; + $ARR = $APP->findOne([$name_id => $table_value]); +?> +
+ get_grille_fk() as $field): + // query for name + $table_fk = $field['table_fk']; + $Table_fk = ucfirst($table_fk); + + $arr_allowed_c = droit_table($type_session, 'R', $table_fk); + $arr_allowed_l = droit_table($type_session, 'L', $table_fk); + + $APP_TMP = new App($table_fk); + $TBL_TMP = $APP_TMP->app_table_one; + + $arr = $APP->plug($field['base_fk'], $table_fk)->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); + $dsp_fieldname = 'nom' . ucfirst($table_fk); + $dsp_fieldcode = 'code' . ucfirst($table_fk); + $dsp_name = $arr[$dsp_fieldname] ?: $arr[$dsp_fieldcode]; + if (empty($dsp_name)) { + $dsp_name = 'Aucun'; + } + + $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; + ?> +
+
+
+
+
+
nomAppscheme ?>
+
+
draw_field(['field_name_raw' => 'nom', 'field_name' => $dsp_fieldname, 'table' => $table, 'field_value' => $dsp_name]) ?>
+
cf_output('color', $ARR, "color$Table_fk"); ?>
+
cf_output('icon', $ARR, "icon$Table_fk"); ?>
+
+
+
+ +
+
+
+
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk_grouped.php b/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk_grouped.php index 2753e4e..0df8b70 100644 --- a/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk_grouped.php +++ b/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk_grouped.php @@ -1,63 +1,63 @@ -table; - $Table = ucfirst($table); - - $APP = new App($table); - if (sizeof($APP->get_grille_fk()) == 0) { return; } - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $mode = empty($this->HTTP_VARS['mode']) ? 'icone' : $this->HTTP_VARS['mode']; - - $name_id = 'id' . $table; - $ARR = $APP->findOne([$name_id => $table_value]); -?> -
- get_grille_fk_grouped() as $field): - // query for name - $table_fk = $field['table_fk']; - $Table_fk = ucfirst($table_fk); - - $arr_allowed_c = droit_table($type_session, 'R', $table_fk); - $arr_allowed_l = droit_table($type_session, 'L', $table_fk); - - $APP_TMP = new App($table_fk); - $TBL_TMP = $APP_TMP->app_table_one; - - $arr = $APP->plug($field['base_fk'], $table_fk)->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); - $dsp_fieldname = 'nom' . ucfirst($table_fk); - $dsp_fieldcode = 'code' . ucfirst($table_fk); - $dsp_name = $arr[$dsp_fieldname] ?: $arr[$dsp_fieldcode]; - if (empty($dsp_name)) { - $dsp_name = 'Aucun'; - } - - $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; - ?> -
-
-
-
-
-
nomAppscheme ?>
-
-
draw_field(['field_name_raw' => 'nom', 'field_name' => $dsp_fieldname, 'table' => $table, 'field_value' => $dsp_name]) ?>
-
cf_output('color', $ARR, "color$Table_fk"); ?>
-
cf_output('icon', $ARR, "icon$Table_fk"); ?>
-
-
-
- -
-
-
-
- +table; + $Table = ucfirst($table); + + $APP = new App($table); + if (sizeof($APP->get_grille_fk()) == 0) { return; } + + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $mode = empty($this->HTTP_VARS['mode']) ? 'icone' : $this->HTTP_VARS['mode']; + + $name_id = 'id' . $table; + $ARR = $APP->findOne([$name_id => $table_value]); +?> +
+ get_grille_fk_grouped() as $field): + // query for name + $table_fk = $field['table_fk']; + $Table_fk = ucfirst($table_fk); + + $arr_allowed_c = droit_table($type_session, 'R', $table_fk); + $arr_allowed_l = droit_table($type_session, 'L', $table_fk); + + $APP_TMP = new App($table_fk); + $TBL_TMP = $APP_TMP->app_table_one; + + $arr = $APP->plug($field['base_fk'], $table_fk)->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); + $dsp_fieldname = 'nom' . ucfirst($table_fk); + $dsp_fieldcode = 'code' . ucfirst($table_fk); + $dsp_name = $arr[$dsp_fieldname] ?: $arr[$dsp_fieldcode]; + if (empty($dsp_name)) { + $dsp_name = 'Aucun'; + } + + $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; + ?> +
+
+
+
+
+
nomAppscheme ?>
+
+
draw_field(['field_name_raw' => 'nom', 'field_name' => $dsp_fieldname, 'table' => $table, 'field_value' => $dsp_name]) ?>
+
cf_output('color', $ARR, "color$Table_fk"); ?>
+
cf_output('icon', $ARR, "icon$Table_fk"); ?>
+
+
+
+ +
+
+
+
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk_nongrouped.php b/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk_nongrouped.php index 7314428..869657a 100644 --- a/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk_nongrouped.php +++ b/web/bin/idae/mdl/app/app_fiche_fk/app_fiche_fk_nongrouped.php @@ -1,63 +1,63 @@ -table; - $Table = ucfirst($table); - - $APP = new App($table); - if (sizeof($APP->get_grille_fk()) == 0) { return; } - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $mode = empty($this->HTTP_VARS['mode']) ? 'icone' : $this->HTTP_VARS['mode']; - - $name_id = 'id' . $table; - $ARR = $APP->findOne([$name_id => $table_value]); -?> -
- get_grille_fk_nongrouped() as $field): - // query for name - $table_fk = $field['table_fk']; - $Table_fk = ucfirst($table_fk); - - $arr_allowed_c = droit_table($type_session, 'R', $table_fk); - $arr_allowed_l = droit_table($type_session, 'L', $table_fk); - - $APP_TMP = new App($table_fk); - $TBL_TMP = $APP_TMP->app_table_one; - - $arr = $APP->plug($field['base_fk'], $table_fk)->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); - $dsp_fieldname = 'nom' . ucfirst($table_fk); - $dsp_fieldcode = 'code' . ucfirst($table_fk); - $dsp_name = $arr[$dsp_fieldname] ?: $arr[$dsp_fieldcode]; - if (empty($dsp_name)) { - $dsp_name = 'Aucun'; - } - - $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; - ?> -
-
-
-
-
-
nomAppscheme ?>
-
-
draw_field(['field_name_raw' => 'nom', 'field_name' => $dsp_fieldname, 'table' => $table, 'field_value' => $dsp_name]) ?>
-
cf_output('color', $ARR, "color$Table_fk"); ?>
-
cf_output('icon', $ARR, "icon$Table_fk"); ?>
-
-
-
- -
-
-
-
- +table; + $Table = ucfirst($table); + + $APP = new App($table); + if (sizeof($APP->get_grille_fk()) == 0) { return; } + + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $mode = empty($this->HTTP_VARS['mode']) ? 'icone' : $this->HTTP_VARS['mode']; + + $name_id = 'id' . $table; + $ARR = $APP->findOne([$name_id => $table_value]); +?> +
+ get_grille_fk_nongrouped() as $field): + // query for name + $table_fk = $field['table_fk']; + $Table_fk = ucfirst($table_fk); + + $arr_allowed_c = droit_table($type_session, 'R', $table_fk); + $arr_allowed_l = droit_table($type_session, 'L', $table_fk); + + $APP_TMP = new App($table_fk); + $TBL_TMP = $APP_TMP->app_table_one; + + $arr = $APP->plug($field['base_fk'], $table_fk)->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); + $dsp_fieldname = 'nom' . ucfirst($table_fk); + $dsp_fieldcode = 'code' . ucfirst($table_fk); + $dsp_name = $arr[$dsp_fieldname] ?: $arr[$dsp_fieldcode]; + if (empty($dsp_name)) { + $dsp_name = 'Aucun'; + } + + $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; + ?> +
+
+
+
+
+
nomAppscheme ?>
+
+
draw_field(['field_name_raw' => 'nom', 'field_name' => $dsp_fieldname, 'table' => $table, 'field_value' => $dsp_name]) ?>
+
cf_output('color', $ARR, "color$Table_fk"); ?>
+
cf_output('icon', $ARR, "icon$Table_fk"); ?>
+
+
+
+ +
+
+
+
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_has.php b/web/bin/idae/mdl/app/app_fiche_has.php index 3353fac..3de4f9d 100644 --- a/web/bin/idae/mdl/app/app_fiche_has.php +++ b/web/bin/idae/mdl/app/app_fiche_has.php @@ -1,59 +1,59 @@ -app_table_one; - $APPOBJ = $APP->appobj($table_value, $vars); - $ARR = $APPOBJ->ARR; -?> -
- -
- $value): - $APPTMP = new App("$table" . "_" . "$value"); - - $Value = ucfirst($value); - $_table = $table . '_' . $value; - $_Table = ucfirst($_table); - $_id = 'id' . $_table; - $_nom = 'nom' . $_Table; - $_code = 'code' . $_Table; - $_icon = 'icon' . $_Table; - $_color = 'color' . $_Table; - if (!empty($ARR[$_nom])): ?> -
-
-
- draw_field(['field_name_raw' => 'color', - 'field_name' => $_color, - 'table' => $value, - 'field_value' => $ARR[$_color]]) ?> -
-
- draw_field(['field_name_raw' => 'icon', - 'field_name' => $_icon, - 'table' => $value, - 'field_value' => $ARR[$_icon]]) ?> -
-
-
-
draw_field(['field_name_raw' => 'nom', - 'field_name' => $_nom, - 'table' => $value, - 'field_value' => $ARR[$_nom]]) ?>
-
nomAppscheme) ?>
-
-
- - -
+app_table_one; + $APPOBJ = $APP->appobj($table_value, $vars); + $ARR = $APPOBJ->ARR; +?> +
+ +
+ $value): + $APPTMP = new App("$table" . "_" . "$value"); + + $Value = ucfirst($value); + $_table = $table . '_' . $value; + $_Table = ucfirst($_table); + $_id = 'id' . $_table; + $_nom = 'nom' . $_Table; + $_code = 'code' . $_Table; + $_icon = 'icon' . $_Table; + $_color = 'color' . $_Table; + if (!empty($ARR[$_nom])): ?> +
+
+
+ draw_field(['field_name_raw' => 'color', + 'field_name' => $_color, + 'table' => $value, + 'field_value' => $ARR[$_color]]) ?> +
+
+ draw_field(['field_name_raw' => 'icon', + 'field_name' => $_icon, + 'table' => $value, + 'field_value' => $ARR[$_icon]]) ?> +
+
+
+
draw_field(['field_name_raw' => 'nom', + 'field_name' => $_nom, + 'table' => $value, + 'field_value' => $ARR[$_nom]]) ?>
+
nomAppscheme) ?>
+
+
+ + +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map.php b/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map.php index 4fd8542..a10b8a9 100644 --- a/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map.php +++ b/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map.php @@ -1,133 +1,133 @@ -findOne([$name_id => (int)$value_id]); - - $zoom = 5; - if (empty($arrV[$lat_field]) || empty($arrV[$lng_field])) { - $arrV[$lat_field] = $arrV[$lng_field] = 0; - $zoom = 2; - } - - $adresse = $arrV["adresse$Table"] . ' ' . $arrV["codePostal$Table"] . ' ' . $arrV["ville$Table"]; - if (!empty($arrV['idshop'])) { - $APP_SHOP = new App('shop'); - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$arrV['idshop']]); - $address_shop = $ARR_SHOP['adresseShop'] . ' ' . $ARR_SHOP['codePostalShop'] . ' ' . $ARR_SHOP['nomVille']; - } -?> - -
-
- - - - - "> - "> -
-
- - - - - - - - - - - - - - - - - - - - - -
- nomAppscheme ?> - - "/> - - -
- - - - - - - -
-
-
-
-
-
-
-
-
- nomAppscheme ?> -
- -
-
-
-
- fiche_next_statut($table_value); ?> -
-
-
- +findOne([$name_id => (int)$value_id]); + + $zoom = 5; + if (empty($arrV[$lat_field]) || empty($arrV[$lng_field])) { + $arrV[$lat_field] = $arrV[$lng_field] = 0; + $zoom = 2; + } + + $adresse = $arrV["adresse$Table"] . ' ' . $arrV["codePostal$Table"] . ' ' . $arrV["ville$Table"]; + if (!empty($arrV['idshop'])) { + $APP_SHOP = new App('shop'); + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$arrV['idshop']]); + $address_shop = $ARR_SHOP['adresseShop'] . ' ' . $ARR_SHOP['codePostalShop'] . ' ' . $ARR_SHOP['nomVille']; + } +?> + +
+
+ + + + + "> + "> +
+
+ + + + + + + + + + + + + + + + + + + + + +
+ nomAppscheme ?> + + "/> + + +
+ + + + + + + +
+
+
+
+
+
+
+
+
+ nomAppscheme ?> +
+ +
+
+
+
+ fiche_next_statut($table_value); ?> +
+
+
+ diff --git a/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map_itineraire.php b/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map_itineraire.php index 63adeba..905e768 100644 --- a/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map_itineraire.php +++ b/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map_itineraire.php @@ -1,139 +1,139 @@ -findOne([$name_id => (int)$value_id]); - - $zoom = 5; - if (empty($arrV[$lat_field]) || empty($arrV[$lng_field])) { - $arrV[$lat_field] = $arrV[$lng_field] = 0; - $zoom = 2; - } - - $adresse = $arrV["adresse$Table"] . ' ' . $arrV["codePostal$Table"] . ' ' . $arrV["ville$Table"]; - if (!empty($arrV['idshop'])) { - $APP_SHOP = new App('shop'); - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$arrV['idshop']]); - $address_shop = $ARR_SHOP['adresseShop'] . ' ' . $ARR_SHOP['codePostalShop'] . ' ' . $ARR_SHOP['nomVille']; - } -?> - -
-
- - - - - "> - "> -
-
- - - - - - - - - - - - - - - - - - - - - -
- nomAppscheme ?> - - "/> - - -
- - - - - - - -
-
-
-
-
-
-
-
-
- nomAppscheme ?> -
- -
-
-
-
- fiche_next_statut($table_value); ?> -
-
-
- +findOne([$name_id => (int)$value_id]); + + $zoom = 5; + if (empty($arrV[$lat_field]) || empty($arrV[$lng_field])) { + $arrV[$lat_field] = $arrV[$lng_field] = 0; + $zoom = 2; + } + + $adresse = $arrV["adresse$Table"] . ' ' . $arrV["codePostal$Table"] . ' ' . $arrV["ville$Table"]; + if (!empty($arrV['idshop'])) { + $APP_SHOP = new App('shop'); + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$arrV['idshop']]); + $address_shop = $ARR_SHOP['adresseShop'] . ' ' . $ARR_SHOP['codePostalShop'] . ' ' . $ARR_SHOP['nomVille']; + } +?> + +
+
+ + + + + "> + "> +
+
+ + + + + + + + + + + + + + + + + + + + + +
+ nomAppscheme ?> + + "/> + + +
+ + + + + + + +
+
+
+
+
+
+
+
+
+ nomAppscheme ?> +
+ +
+
+
+
+ fiche_next_statut($table_value); ?> +
+
+
+ diff --git a/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map_mini.php b/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map_mini.php index 9662968..0f7bba8 100644 --- a/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map_mini.php +++ b/web/bin/idae/mdl/app/app_fiche_map/app_fiche_map_mini.php @@ -1,53 +1,53 @@ -findOne([$name_id => (int)$value_id]); - - $zoom = 5; - if (empty($arrV[$lat_field]) || empty($arrV[$lng_field])) { - $arrV[$lat_field] = $arrV[$lng_field] = 0; - $zoom = 2; - } - - $adresse = $arrV["adresse$Table"] . ' ' . $arrV["codePostal$Table"] . ' ' . $arrV["ville$Table"]; - if (!empty($arrV['idshop'])) { - $APP_SHOP = new App('shop'); - $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$arrV['idshop']]); - $address_shop = $ARR_SHOP['adresseShop'] . ' ' . $ARR_SHOP['codePostalShop'] . ' ' . $ARR_SHOP['nomVille']; - } -?> - -
-
- +findOne([$name_id => (int)$value_id]); + + $zoom = 5; + if (empty($arrV[$lat_field]) || empty($arrV[$lng_field])) { + $arrV[$lat_field] = $arrV[$lng_field] = 0; + $zoom = 2; + } + + $adresse = $arrV["adresse$Table"] . ' ' . $arrV["codePostal$Table"] . ' ' . $arrV["ville$Table"]; + if (!empty($arrV['idshop'])) { + $APP_SHOP = new App('shop'); + $ARR_SHOP = $APP_SHOP->findOne(['idshop' => (int)$arrV['idshop']]); + $address_shop = $ARR_SHOP['adresseShop'] . ' ' . $ARR_SHOP['codePostalShop'] . ' ' . $ARR_SHOP['nomVille']; + } +?> + +
+
+ diff --git a/web/bin/idae/mdl/app/app_fiche_micro.php b/web/bin/idae/mdl/app/app_fiche_micro.php index f0060fd..2764377 100644 --- a/web/bin/idae/mdl/app/app_fiche_micro.php +++ b/web/bin/idae/mdl/app/app_fiche_micro.php @@ -1,118 +1,118 @@ -HTTP_VARS['table']; - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - - $APP = new App($table); - $APPOBJ = $APP->appobj($table_value, $vars); - $APP_TABLE = $APP->app_table_one; - - // - $EXTRACTS_VARS = $APP->extract_vars($table_value, $vars); - extract($EXTRACTS_VARS, EXTR_OVERWRITE); - // - - $iconAppscheme = $APP->iconAppscheme; - - $html_edit_link = 'table=' . $table . '&table_value=' . $table_value; - - $Idae = new Idae($table); - - $html_table_statut = $Idae->fiche_next_statut($table_value, true); - $html_table_statut_has = $Idae->module('fiche_has', "table=$table&table_value=$table_value&table_type=statut"); - $ARR_COLLECT = $Idae->get_table_fields($table_value, ['codeAppscheme_field' => ['nom', 'code']]); - - $ARR_FIELDS = array_column($ARR_COLLECT, 'appscheme_fields'); - - $crypted_fiche_link = AppLink::fiche($table,$table_value ); - - $COLLECT_FIELDS = []; - foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { - foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { - $COLLECT_FIELDS[] = $ARR_FIELD; - } - } - - $options = ['apply_droit' => [$type_session, - 'R'], - 'data_mode' => 'fiche', - 'scheme_field_view' => 'short', - 'field_draw_style' => 'draw_html_field', - 'scheme_field_view_groupby' => 'group', - 'fields_scheme_part' => 'all', - 'show_field_name' => 0, - 'field_composition' => ['hide_field_icon' => 1, - 'hide_field_name' => 1, - 'hide_field_value' => 1]]; - - /* $Fabric = new AppDataSchemeFieldDrawerFabric($table, $options); - $Fabric->fetch_data(["id$table" => $table_value]); - $tplData = $Fabric->get_templateDataHTML();*/ -?> -
-
-
-
-
-
- HTTP_VARS['table_value'])): ?> -
- -
- -
- -
- -
-
-
-
- NAME_APP ?> -
-
-
-
-
- - $ARR_FIELD) { ?> -
-
-
-
-
- -
-
-
- -
-
-
-
-
- -
-
-
- -
-
-
-
- -
-
-
-
- - - -
-
+HTTP_VARS['table']; + + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + + $APP = new App($table); + $APPOBJ = $APP->appobj($table_value, $vars); + $APP_TABLE = $APP->app_table_one; + + // + $EXTRACTS_VARS = $APP->extract_vars($table_value, $vars); + extract($EXTRACTS_VARS, EXTR_OVERWRITE); + // + + $iconAppscheme = $APP->iconAppscheme; + + $html_edit_link = 'table=' . $table . '&table_value=' . $table_value; + + $Idae = new Idae($table); + + $html_table_statut = $Idae->fiche_next_statut($table_value, true); + $html_table_statut_has = $Idae->module('fiche_has', "table=$table&table_value=$table_value&table_type=statut"); + $ARR_COLLECT = $Idae->get_table_fields($table_value, ['codeAppscheme_field' => ['nom', 'code']]); + + $ARR_FIELDS = array_column($ARR_COLLECT, 'appscheme_fields'); + + $crypted_fiche_link = AppLink::fiche($table,$table_value ); + + $COLLECT_FIELDS = []; + foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { + foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { + $COLLECT_FIELDS[] = $ARR_FIELD; + } + } + + $options = ['apply_droit' => [$type_session, + 'R'], + 'data_mode' => 'fiche', + 'scheme_field_view' => 'short', + 'field_draw_style' => 'draw_html_field', + 'scheme_field_view_groupby' => 'group', + 'fields_scheme_part' => 'all', + 'show_field_name' => 0, + 'field_composition' => ['hide_field_icon' => 1, + 'hide_field_name' => 1, + 'hide_field_value' => 1]]; + + /* $Fabric = new AppDataSchemeFieldDrawerFabric($table, $options); + $Fabric->fetch_data(["id$table" => $table_value]); + $tplData = $Fabric->get_templateDataHTML();*/ +?> +
+
+
+
+
+
+ HTTP_VARS['table_value'])): ?> +
+ +
+ +
+ +
+ +
+
+
+
+ NAME_APP ?> +
+
+
+
+
+ + $ARR_FIELD) { ?> +
+
+
+
+
+ +
+
+
+ +
+
+
+
+
+ +
+
+
+ +
+
+
+
+ +
+
+
+
+ + + +
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_mini.php b/web/bin/idae/mdl/app/app_fiche_mini.php index 6184328..273fac5 100644 --- a/web/bin/idae/mdl/app/app_fiche_mini.php +++ b/web/bin/idae/mdl/app/app_fiche_mini.php @@ -1,93 +1,93 @@ -HTTP_VARS['table']; - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - - $APP = new App($table); - $Idae = new Idae($table); - $APPOBJ = $APP->appobj($table_value, $vars); - - /*$test_custom = Idae::module_exists('app_custom/' . $table . '/' . $table . '_fiche_mini'); - if (!empty($test_custom)) { - echo $Idae->module('app_custom/' . $table . '/' . $table . '_fiche_mini', $this->HTTP_VARS); - - return; - }*/ - - // - $EXTRACTS_VARS = $APP->extract_vars($table_value, $vars); - extract($EXTRACTS_VARS, EXTR_OVERWRITE); - // - $APP_TABLE = $APP->app_table_one; - - $iconAppscheme = $APP->iconAppscheme; - - $Idae = new Idae($table); - - $html_table_statut = $Idae->fiche_next_statut($table_value, true); - $html_table_statut_has = $Idae->module('fiche_has', "table=$table&table_value=$table_value&table_type=statut"); - - $module_link = in_array($table, ['livreur_affectation']) ? 'update' : 'fiche'; - $crypted_link = AppLink::$module_link($table, $table_value); - - $options = ['apply_droit' => [$type_session, - 'R'], - 'data_mode' => 'fiche', - 'scheme_field_view' => 'mini', - 'field_draw_style' => 'draw_html_field', - 'scheme_field_view_groupby' => null, - /*'field_group_type' => 'group',*/ - 'fields_scheme_part' => 'main', - 'hide_field_empty' => 1, - 'hide_field_icon' => 1, - 'hide_field_name' => 1, - 'hide_field_value' => 1, - 'field_composition' => ['hide_field_icon' => 1, - 'hide_field_name' => 1, - 'hide_field_value' => 1]]; - - $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); - $Fabric->fetch_data(["id$table" => $table_value]); - $tplData = $Fabric->get_templateData(); - -?> -
-
-
-
- HTTP_VARS['table_value'])): ?> -
-
- -
- -
- -
-
- -
-
- -
-
-
-
- -
-
- module('fiche_fields', ['table' => $table, - 'table_value' => $table_value, - 'in_mini_fiche' => 1]) ?> -
-
- - - -
+HTTP_VARS['table']; + + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + + $APP = new App($table); + $Idae = new Idae($table); + $APPOBJ = $APP->appobj($table_value, $vars); + + /*$test_custom = Idae::module_exists('app_custom/' . $table . '/' . $table . '_fiche_mini'); + if (!empty($test_custom)) { + echo $Idae->module('app_custom/' . $table . '/' . $table . '_fiche_mini', $this->HTTP_VARS); + + return; + }*/ + + // + $EXTRACTS_VARS = $APP->extract_vars($table_value, $vars); + extract($EXTRACTS_VARS, EXTR_OVERWRITE); + // + $APP_TABLE = $APP->app_table_one; + + $iconAppscheme = $APP->iconAppscheme; + + $Idae = new Idae($table); + + $html_table_statut = $Idae->fiche_next_statut($table_value, true); + $html_table_statut_has = $Idae->module('fiche_has', "table=$table&table_value=$table_value&table_type=statut"); + + $module_link = in_array($table, ['livreur_affectation']) ? 'update' : 'fiche'; + $crypted_link = AppLink::$module_link($table, $table_value); + + $options = ['apply_droit' => [$type_session, + 'R'], + 'data_mode' => 'fiche', + 'scheme_field_view' => 'mini', + 'field_draw_style' => 'draw_html_field', + 'scheme_field_view_groupby' => null, + /*'field_group_type' => 'group',*/ + 'fields_scheme_part' => 'main', + 'hide_field_empty' => 1, + 'hide_field_icon' => 1, + 'hide_field_name' => 1, + 'hide_field_value' => 1, + 'field_composition' => ['hide_field_icon' => 1, + 'hide_field_name' => 1, + 'hide_field_value' => 1]]; + + $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); + $Fabric->fetch_data(["id$table" => $table_value]); + $tplData = $Fabric->get_templateData(); + +?> +
+
+
+
+ HTTP_VARS['table_value'])): ?> +
+
+ +
+ +
+ +
+
+ +
+
+ +
+
+
+
+ +
+
+ module('fiche_fields', ['table' => $table, + 'table_value' => $table_value, + 'in_mini_fiche' => 1]) ?> +
+
+ + + +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_fiche_rfk.php b/web/bin/idae/mdl/app/app_fiche_rfk.php index 280eb92..8bc4d25 100644 --- a/web/bin/idae/mdl/app/app_fiche_rfk.php +++ b/web/bin/idae/mdl/app/app_fiche_rfk.php @@ -1,65 +1,65 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - $table_value = empty($this->HTTP_VARS['table_value']) ? '' : (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - - $arr_allowed_c = droit_table($type_session, 'C', $table); - $arr_allowed_r = droit_table($type_session, 'R', $table); - $arr_allowed_u = droit_table($type_session, 'U', $table); - $arr_allowed_d = droit_table($type_session, 'D', $table); - $arr_allowed_l = droit_table($type_session, 'L', $table); - - $id = 'id' . $table; - if (!empty($table_value)) $vars[$id] = (int)$table_value; - - $APP = new App($table); - $ARR = $APP->findOne($vars); - - $ARR_RFK = $APP->get_table_rfk($table_value); - - if (is_array($arr_allowed_c) && is_array($ARR_RFK)) { - $arr_allowed_c = droit_table($type_session, 'L'); - $ARR_RFK = array_intersect($arr_allowed_c, $ARR_RFK); - } - -?> -
$table_value]; - $vars_rfk['table'] = $table_rfk; - if ($APP_TMP->has_field_fk($type_session)) { - //$vars_rfk['vars'][$name_idtype_session] = $idtype_session; - } - $html_list_link = http_build_query($vars_rfk); - $ARR_RFK = $APP_TMP->findOne(["id$table_rfk" => (int)$ARR["id$table_rfk"]]); - $RS_TMP = $APP_TMP->find($vars_rfk['vars']); - $count = $RS_TMP->count(); - //if (empty($count)) continue; - ?> - - +HTTP_VARS['table']; + $Table = ucfirst($table); + $table_value = empty($this->HTTP_VARS['table_value']) ? '' : (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + + $arr_allowed_c = droit_table($type_session, 'C', $table); + $arr_allowed_r = droit_table($type_session, 'R', $table); + $arr_allowed_u = droit_table($type_session, 'U', $table); + $arr_allowed_d = droit_table($type_session, 'D', $table); + $arr_allowed_l = droit_table($type_session, 'L', $table); + + $id = 'id' . $table; + if (!empty($table_value)) $vars[$id] = (int)$table_value; + + $APP = new App($table); + $ARR = $APP->findOne($vars); + + $ARR_RFK = $APP->get_table_rfk($table_value); + + if (is_array($arr_allowed_c) && is_array($ARR_RFK)) { + $arr_allowed_c = droit_table($type_session, 'L'); + $ARR_RFK = array_intersect($arr_allowed_c, $ARR_RFK); + } + +?> +
$table_value]; + $vars_rfk['table'] = $table_rfk; + if ($APP_TMP->has_field_fk($type_session)) { + //$vars_rfk['vars'][$name_idtype_session] = $idtype_session; + } + $html_list_link = http_build_query($vars_rfk); + $ARR_RFK = $APP_TMP->findOne(["id$table_rfk" => (int)$ARR["id$table_rfk"]]); + $RS_TMP = $APP_TMP->find($vars_rfk['vars']); + $count = $RS_TMP->count(); + //if (empty($count)) continue; + ?> + +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_field_add.php b/web/bin/idae/mdl/app/app_field_add.php index 73adaa5..1a765ae 100644 --- a/web/bin/idae/mdl/app/app_field_add.php +++ b/web/bin/idae/mdl/app/app_field_add.php @@ -1,73 +1,73 @@ -translate_vars($vars); - if (empty($_POST['run'])): - ?> - -
- -
- - - - - - - - -
Ajouter -
- $value): - - ?> -   -
-
- - -
- -
- - - - - - - - - -
- - - -
- - translate_vars($vars); + if (empty($_POST['run'])): + ?> + +
+ +
+ + + + + + + + +
Ajouter +
+ $value): + + ?> +   +
+
+ + +
+ +
+ + + + + + + + + +
+ + + +
+ + HTTP_VARS['field_name']; - $field_name_raw = $this->HTTP_VARS['field_name_raw']; - $table = $this->HTTP_VARS['table']; - $Table = ucfirst($table); - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? array() : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $field_name_raw = empty($this->HTTP_VARS['field_name_raw']) ? '' : $this->HTTP_VARS['field_name_raw']; - $field_name = empty($this->HTTP_VARS['field_name']) ? $field_name_raw . $Table : $this->HTTP_VARS['field_name']; - - // - $APP = new App($table); - // - $APP_TABLE = $APP->app_table_one; - // - $GRILLE_FK = $APP->get_grille_fk($table); - $HTTP_VARS = $APP->translate_vars($vars); - $BASE_APP = $APP_TABLE['base']; - // - $id = 'id' . $table; - $ARR = $APP->query_one([$id => $table_value]); - // - $field_value = empty($this->HTTP_VARS['field_value']) ? $ARR[$field_name] : $this->HTTP_VARS['field_value']; - - -?> -
- - - - - -
-
- draw_field_input(['table'=>$table,'field_name_raw' => $field_name_raw,'field_value'=>$field_value]); ?> -
-
- - -
-
+HTTP_VARS['field_name']; + $field_name_raw = $this->HTTP_VARS['field_name_raw']; + $table = $this->HTTP_VARS['table']; + $Table = ucfirst($table); + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? array() : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $field_name_raw = empty($this->HTTP_VARS['field_name_raw']) ? '' : $this->HTTP_VARS['field_name_raw']; + $field_name = empty($this->HTTP_VARS['field_name']) ? $field_name_raw . $Table : $this->HTTP_VARS['field_name']; + + // + $APP = new App($table); + // + $APP_TABLE = $APP->app_table_one; + // + $GRILLE_FK = $APP->get_grille_fk($table); + $HTTP_VARS = $APP->translate_vars($vars); + $BASE_APP = $APP_TABLE['base']; + // + $id = 'id' . $table; + $ARR = $APP->query_one([$id => $table_value]); + // + $field_value = empty($this->HTTP_VARS['field_value']) ? $ARR[$field_name] : $this->HTTP_VARS['field_value']; + + +?> + + + + + + +
+
+ draw_field_input(['table'=>$table,'field_name_raw' => $field_name_raw,'field_value'=>$field_value]); ?> +
+
+ + +
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_gui/app_menu_home.php b/web/bin/idae/mdl/app/app_gui/app_menu_home.php index ca7aeb6..1e9bc11 100644 --- a/web/bin/idae/mdl/app/app_gui/app_menu_home.php +++ b/web/bin/idae/mdl/app/app_gui/app_menu_home.php @@ -1,115 +1,115 @@ -module('fiche_entete', "table=$type_session&table_value=" . $_SESSION["id$type_session"]); - $html_entete_fields = $IDAE_SELF->module('fiche_fields', "edit_field=true&codeAppscheme_field_type=bool&table=$type_session&table_value=" . $_SESSION["id$type_session"]); - - $arr_sch_type = $APP_SCH->distinct_all('idappscheme_type', ['codeAppscheme' => ['$in' => $arr_allowed_r]]); - $RS_TY = $APP_SCH_TY->find(['idappscheme_type' => ['$in' => $arr_sch_type]])->sort(['nomAppscheme_type' => 1]); - - $crypted_profil = AppLink::home($type_session, $idtype_session); - $crypted_console = AppLink::console('commande'); - -?> -
-
-
-
-
-
-
-
Start
-
-
-
- - getNext()) { - $idappscheme_type = (int)$ARR_TY['idappscheme_type']; - $RS_SCH = $APP_SCH->find(['idappscheme_type' => $idappscheme_type, 'codeAppscheme' => ['$in' => $arr_allowed_r]])->sort(['nomAppscheme' => 1]); - - $arr_fields = ['nom', 'code', 'color', 'icon']; - while ($ARR_SCH = $RS_SCH->getNext()) { - $table = $ARR_SCH['codeAppscheme']; - $extr = []; - foreach ($arr_fields as $key_f => $value_field) { - $extr[$value_field . '_table'] = $ARR_SCH[$value_field . 'Appscheme']; - } - extract($extr); // "nom_table icon_table ..." - $APP_SCH_TMP = new App($table); - $add_vars = ''; - $arr_vars = []; - if ($APP_SCH_TMP->has_field_fk($type_session)) { - if ($arr_allowed_l[$type_session]) { - // echo '.'; - $add_vars = "&vars[id$type_session]=$idtype_session"; - $arr_vars["id$type_session"] = $idtype_session; - } else { - // echo '..'; - $add_vars = "&vars[id$type_session]=$idtype_session"; - $arr_vars["id$type_session"] = $idtype_session; - } - } - // si commandes, on rajoute secteur pour livreur, idshop pour shop - // si statut plus que START : - // idlivreur pour livreur, idshop pour shop - if ($table == 'commande' && ($type_session == 'shop' || $type_session == 'livreur')) { - $add_vars = "&vars[id$type_session]=$idtype_session"; - $arr_vars["id$type_session"] = $idtype_session; - } - $crypted_app_liste = AppLink::liste($table, null,$arr_vars); - ?> -
-
-
-
-
-
-
-
- - - -
-
-
- \ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_gui/app_menu_left.php b/web/bin/idae/mdl/app/app_gui/app_menu_left.php index 7a7e0cc..d355247 100644 --- a/web/bin/idae/mdl/app/app_gui/app_menu_left.php +++ b/web/bin/idae/mdl/app/app_gui/app_menu_left.php @@ -1,183 +1,183 @@ -findOne([$name_idtype_session => $idtype_session]); - - $html_entete = $IDAE_SELF->module('fiche_entete', "table=$type_session&table_value=" . $_SESSION["id$type_session"]); - $html_entete_fields = $IDAE_SELF->module('fiche_fields', "edit_field=true&codeAppscheme_field_type=bool&table=$type_session&table_value=" . $_SESSION["id$type_session"]); - - $arr_sch_type = $APP_SCH->distinct_all('idappscheme_type', ['codeAppscheme' => ['$in' => $arr_allowed_r]]); - $RS_TY = $APP_SCH_TY->find(['idappscheme_type' => ['$in' => $arr_sch_type]])->sort(['nomAppscheme_type' => 1]); - - $crypted_console = AppLink::console('commande'); - -?> -
-
- -
-
- - getNext()) { - $idappscheme_type = (int)$ARR_TY['idappscheme_type']; - $RS_SCH = $APP_SCH->find(['idappscheme_type' => $idappscheme_type, 'codeAppscheme' => ['$in' => $arr_allowed_r]])->sort(['nomAppscheme' => 1]); - ?> -
-
- getNext()) { - $table = $ARR_SCH['codeAppscheme']; - $extr = []; - foreach ($arr_fields as $key_f => $value_field) { - $extr[$value_field . '_table'] = $ARR_SCH[$value_field . 'Appscheme']; - } - extract($extr); // "nom_table icon_table ..." - $APP_SCH_TMP = new App($table); - $add_vars = ''; - $arr_vars = []; - if ($APP_SCH_TMP->has_field_fk($type_session)) { - if ($arr_allowed_l[$type_session]) { - // echo '.'; - $add_vars = "&vars[id$type_session]=$idtype_session"; - $arr_vars["id$type_session"] = $idtype_session; - } else { - // echo '..'; - $add_vars = "&vars[id$type_session]=$idtype_session"; - $arr_vars["id$type_session"] = $idtype_session; - } - } - // si commandes, on rajoute secteur pour livreur, idshop pour shop - // si statut plus que START : - // idlivreur pour livreur, idshop pour shop - if ($table == 'commande' && ($type_session == 'shop' || $type_session == 'livreur')) { - $add_vars = "&vars[id$type_session]=$idtype_session"; - $arr_vars["id$type_session"] = $idtype_session; - } - - $crypted_liste = AppLink::liste($table, null, $arr_vars); - ?> - -
- find(); - - $Value = ucfirst($value); - $_table = $table . '_' . $value; - $_Table = ucfirst($_table); - $_id = 'id' . $_table; - $_nom = 'nom' . $_Table; - $_code = 'code' . $_Table; - $_icon = 'icon' . $_Table; - $_color = 'color' . $_Table; - while ($ARR_TMP = $RS_TMP->getNext()) { - $tpl_color = $APP->draw_field(['field_name_raw' => 'color', - 'field_name' => $_color, - 'table' => $value, - 'field_value' => $ARR_TMP[$_color]]); - $tpl_icon = $APP->draw_field(['field_name_raw' => 'icon', - 'field_name' => $_icon, - 'table' => $value, - 'field_value' => $ARR_TMP[$_icon]]); - $tpl_nom = $APP->draw_field(['field_name_raw' => 'nom', - 'field_name' => $_nom, - 'table' => $value, - 'field_value' => $ARR_TMP[$_nom]]); - - // si commandes, on rajoute secteur pour livreur, idshop pour shop - $ARR_SELF = $IDAE_SELF->findOne([$name_idtype_session => $idtype_session]); - // si statut plus que START : - // idlivreur pour livreur, idshop pour shop - $add_vars = ''; - if ($table == 'commande') { - if ($type_session == 'shop') { - $add_vars = "&type_liste=shop_pool_" . $ARR_TMP[$_code]; - } - if ($type_session == 'livreur') { - $add_vars = "&type_liste=livreur_pool_" . $ARR_TMP[$_code]; - } - } - $data_vars = "table=$table&vars[$_id]=$ARR_TMP[$_id]$add_vars"; - ?> -
-
-
-
- ="" data-idsecteur="" data-count="" data-table_value="" data-table="" class="ellipsis"> -
-
-
- -
- -
-
- -
- - - - -
- \ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_gui/app_menu_top.php b/web/bin/idae/mdl/app/app_gui/app_menu_top.php index 44b98b7..29c23f6 100644 --- a/web/bin/idae/mdl/app/app_gui/app_menu_top.php +++ b/web/bin/idae/mdl/app/app_gui/app_menu_top.php @@ -1,110 +1,110 @@ -get_session();*/ - - $type_session = $_SESSION['type_session']; - $Type_session = ucfirst($type_session); - $name_idtype_session = "id$type_session"; - $idtype_session = (int)$_SESSION[$name_idtype_session]; - - $APP = new App('appscheme'); - // - $arr_allowed_c = droit_table($type_session, 'C'); - $arr_allowed_r = droit_table($type_session, 'R'); - $arr_allowed_l = droit_table($type_session, 'L'); - // - $APP_SCH = new IdaeDB('appscheme'); - $APP_SCH_TY = new IdaeDB('appscheme_type'); - - $IDAE_SELF = new Idae($type_session); - $APPOBJ = $IDAE_SELF->appobj($idtype_session, $vars); - $ARR = $APPOBJ->ARR; - - - $table = $type_session; - - - $LIVREUR_DISPONIBLE_NB = null; - $LIVREUR_WORKING_NB = null; - $COMMAND_UNASSIGNED_NB = null; - $COMMAND_NB = null; - - if ($type_session == 'shop') { - - $configs = CommandeQueueConsole::consoleShop($idtype_session); - - $times_secteur = $configs->console_secteur_livreur->get_templateObjHTML(); - $times_shop = $configs->console_shop->get_templateObjHTML(); - - $LIVREUR_DISPONIBLE_NB = $times_secteur->LIVREUR_DISPONIBLE_NB; - $LIVREUR_WORKING_NB = $times_secteur->LIVREUR_WORKING_NB; - - $COMMAND_UNASSIGNED_NB = $times_shop->COMMAND_SHOP_WAITING_NB; - $COMMAND_NB = $times_shop->COMMAND_SHOP_SHIFT_NB; - } - - if ($type_session == 'livreur') { - $configs = CommandeQueueConsole::consoleLivreur($idtype_session); - $times_secteur_livreur = $configs->console_secteur_livreur->get_templateObjHTML(); - $times_secteur = $configs->console_secteur->get_templateObjHTML(); - - $LIVREUR_DISPONIBLE_NB = $times_secteur_livreur->LIVREUR_DISPONIBLE_NB; - $LIVREUR_WORKING_NB = $times_secteur_livreur->LIVREUR_WORKING_NB; - - $COMMAND_UNASSIGNED_NB = $times_secteur->COMMAND_SECTEUR_UNASSIGNED_NB; - $COMMAND_NB = $times_secteur->COMMAND_SECTEUR_NB; - } - -?> -
-
-
- -
-
-
-
-
-
- -
-
-
-
-
-
-
-
- - -
-
-
-
-
-
-
- -
- -
-
-
- -
-
- -
-
-
-
-
-
-
+get_session();*/ + + $type_session = $_SESSION['type_session']; + $Type_session = ucfirst($type_session); + $name_idtype_session = "id$type_session"; + $idtype_session = (int)$_SESSION[$name_idtype_session]; + + $APP = new App('appscheme'); + // + $arr_allowed_c = droit_table($type_session, 'C'); + $arr_allowed_r = droit_table($type_session, 'R'); + $arr_allowed_l = droit_table($type_session, 'L'); + // + $APP_SCH = new IdaeDB('appscheme'); + $APP_SCH_TY = new IdaeDB('appscheme_type'); + + $IDAE_SELF = new Idae($type_session); + $APPOBJ = $IDAE_SELF->appobj($idtype_session, $vars); + $ARR = $APPOBJ->ARR; + + + $table = $type_session; + + + $LIVREUR_DISPONIBLE_NB = null; + $LIVREUR_WORKING_NB = null; + $COMMAND_UNASSIGNED_NB = null; + $COMMAND_NB = null; + + if ($type_session == 'shop') { + + $configs = CommandeQueueConsole::consoleShop($idtype_session); + + $times_secteur = $configs->console_secteur_livreur->get_templateObjHTML(); + $times_shop = $configs->console_shop->get_templateObjHTML(); + + $LIVREUR_DISPONIBLE_NB = $times_secteur->LIVREUR_DISPONIBLE_NB; + $LIVREUR_WORKING_NB = $times_secteur->LIVREUR_WORKING_NB; + + $COMMAND_UNASSIGNED_NB = $times_shop->COMMAND_SHOP_WAITING_NB; + $COMMAND_NB = $times_shop->COMMAND_SHOP_SHIFT_NB; + } + + if ($type_session == 'livreur') { + $configs = CommandeQueueConsole::consoleLivreur($idtype_session); + $times_secteur_livreur = $configs->console_secteur_livreur->get_templateObjHTML(); + $times_secteur = $configs->console_secteur->get_templateObjHTML(); + + $LIVREUR_DISPONIBLE_NB = $times_secteur_livreur->LIVREUR_DISPONIBLE_NB; + $LIVREUR_WORKING_NB = $times_secteur_livreur->LIVREUR_WORKING_NB; + + $COMMAND_UNASSIGNED_NB = $times_secteur->COMMAND_SECTEUR_UNASSIGNED_NB; + $COMMAND_NB = $times_secteur->COMMAND_SECTEUR_NB; + } + +?> +
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+ + +
+
+
+
+
+
+
+ +
+ +
+
+
+ +
+
+ +
+
+
+
+
+
+
diff --git a/web/bin/idae/mdl/app/app_home.php b/web/bin/idae/mdl/app/app_home.php index b4e8dbd..c85a3f9 100644 --- a/web/bin/idae/mdl/app/app_home.php +++ b/web/bin/idae/mdl/app/app_home.php @@ -1,84 +1,84 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - // - $type_session = $_SESSION['type_session']; - $name_idtype_session = "id$type_session"; - $idtype_session = (int)$_SESSION[$name_idtype_session]; - // - $APP = new App($table); - $Idae = new Idae($table); - $APP_TABLE = $APP->app_table_one; - - $crypted_update = AppLink::update($table, $table_value); - $crypted_image_link = AppLink::liste_images($table, $table_value); - - $options = ['apply_droit' => [$type_session, - 'R'], - 'data_mode' => 'fiche', - 'scheme_field_view' => 'native', - 'field_draw_style' => 'draw_html_field', - 'scheme_field_view_groupby' => 'group', - 'fields_scheme_part' => 'main', - 'show_only_fields' => ['nom', 'password', 'mail', 'telephone', 'adresse', 'ville', 'codePostal', 'description','atout'], - 'field_composition' => ['hide_field_icon' => 1, - 'hide_field_name' => 1, - 'hide_field_value' => 1]]; - - $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); - $Fabric->fetch_data(["id$table" => $table_value]); - $tplData = $Fabric->get_templateData(); -?> -
-
- module('fiche_entete', ['table' => $table, - 'table_value' => $table_value]) ?> -
-
-
-
-
-
- - module('fiche_fields', ['table' => $table, - 'table_value' => $table_value, - 'titre' => 0, - 'codeAppscheme_field' => ['nom', 'password', 'mail', 'telephone', 'adresse', 'ville', 'codePostal', 'description']]) */?> -
-
- module('app_liste_rfk', ['table' => $table, - 'table_value' => $table_value]) ?> -
-
-
-
-
-
- -
-
- -
-
- - HTTP_VARS); - - ?> -
- -
- -
-
-
+HTTP_VARS['table']; + $Table = ucfirst($table); + + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + // + $type_session = $_SESSION['type_session']; + $name_idtype_session = "id$type_session"; + $idtype_session = (int)$_SESSION[$name_idtype_session]; + // + $APP = new App($table); + $Idae = new Idae($table); + $APP_TABLE = $APP->app_table_one; + + $crypted_update = AppLink::update($table, $table_value); + $crypted_image_link = AppLink::liste_images($table, $table_value); + + $options = ['apply_droit' => [$type_session, + 'R'], + 'data_mode' => 'fiche', + 'scheme_field_view' => 'native', + 'field_draw_style' => 'draw_html_field', + 'scheme_field_view_groupby' => 'group', + 'fields_scheme_part' => 'main', + 'show_only_fields' => ['nom', 'password', 'mail', 'telephone', 'adresse', 'ville', 'codePostal', 'description','atout'], + 'field_composition' => ['hide_field_icon' => 1, + 'hide_field_name' => 1, + 'hide_field_value' => 1]]; + + $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); + $Fabric->fetch_data(["id$table" => $table_value]); + $tplData = $Fabric->get_templateData(); +?> +
+
+ module('fiche_entete', ['table' => $table, + 'table_value' => $table_value]) ?> +
+
+
+
+
+
+ + module('fiche_fields', ['table' => $table, + 'table_value' => $table_value, + 'titre' => 0, + 'codeAppscheme_field' => ['nom', 'password', 'mail', 'telephone', 'adresse', 'ville', 'codePostal', 'description']]) */?> +
+
+ module('app_liste_rfk', ['table' => $table, + 'table_value' => $table_value]) ?> +
+
+
+
+
+
+ +
+
+ +
+
+ + HTTP_VARS); + + ?> +
+ +
+ +
+
+
diff --git a/web/bin/idae/mdl/app/app_img_dyn.php b/web/bin/idae/mdl/app/app_img_dyn.php index 97f129c..0efbdfa 100644 --- a/web/bin/idae/mdl/app/app_img_dyn.php +++ b/web/bin/idae/mdl/app/app_img_dyn.php @@ -1,55 +1,55 @@ -HTTP_VARS['table_value']; - $table = !empty($this->table) ? $this->table : $this->HTTP_VARS['table']; - $codeTailleImage = $this->HTTP_VARS['codeTailleImage']; - // - $data_attr = empty($this->HTTP_VARS['edit']) ? '' : ' data-button_image_uploader = ""'; - - $src = AppSite::imgApp($table, $table_value, $codeTailleImage); -?> -
-
-
- -
-
-
-
- -
-
- -
-
-
-
-
>
Modifier -
-
-
-
- -
-
-
- -
-
- -
-
-
+HTTP_VARS['table_value']; + $table = !empty($this->table) ? $this->table : $this->HTTP_VARS['table']; + $codeTailleImage = $this->HTTP_VARS['codeTailleImage']; + // + $data_attr = empty($this->HTTP_VARS['edit']) ? '' : ' data-button_image_uploader = ""'; + + $src = AppSite::imgApp($table, $table_value, $codeTailleImage); +?> +
+
+
+ +
+
+
+
+ +
+
+ +
+
+
+
+
>
Modifier +
+
+
+
+ +
+
+
+ +
+
+ +
+
+
diff --git a/web/bin/idae/mdl/app/app_img_liste.php b/web/bin/idae/mdl/app/app_img_liste.php index 4e2a862..c806225 100644 --- a/web/bin/idae/mdl/app/app_img_liste.php +++ b/web/bin/idae/mdl/app/app_img_liste.php @@ -1,52 +1,52 @@ -app_table_one; - - $arr = $APP->query_one([ $id => $table_value ]); - -?> -
-
- module('fiche_entete' , [ 'table' => $table , - 'table_value' => $table_value ]) ?> -
-
-
- $value) { - - if ( empty($APP_TABLE['hasImage' . $key . 'Scheme']) ) { - continue; - } - $vars = [ 'table' => $table , - 'table_value' => $table_value , - 'codeTailleImage' => $key , - 'needResize' => true ]; - $vars['show_info'] = true; - ?> -
- - module('app_img_dyn' , [ 'edit'=>true,'table' => $table , 'table_value' => $table_value , 'codeTailleImage' => $key ]); ?> -
- -
-
-
- module('app_fiche/app_fiche_menu', ['table' => $table, - 'table_value' => $table_value]) ?> -
+app_table_one; + + $arr = $APP->query_one([ $id => $table_value ]); + +?> +
+
+ module('fiche_entete' , [ 'table' => $table , + 'table_value' => $table_value ]) ?> +
+
+
+ $value) { + + if ( empty($APP_TABLE['hasImage' . $key . 'Scheme']) ) { + continue; + } + $vars = [ 'table' => $table , + 'table_value' => $table_value , + 'codeTailleImage' => $key , + 'needResize' => true ]; + $vars['show_info'] = true; + ?> +
+ + module('app_img_dyn' , [ 'edit'=>true,'table' => $table , 'table_value' => $table_value , 'codeTailleImage' => $key ]); ?> +
+ +
+
+
+ module('app_fiche/app_fiche_menu', ['table' => $table, + 'table_value' => $table_value]) ?> +
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_liste/app_liste.php b/web/bin/idae/mdl/app/app_liste/app_liste.php index afb4ea4..b61e728 100644 --- a/web/bin/idae/mdl/app/app_liste/app_liste.php +++ b/web/bin/idae/mdl/app/app_liste/app_liste.php @@ -1,189 +1,189 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - - if (empty($this->HTTP_VARS['groupBy'])) { - if ($table == 'livreur_affectation') { - $this->HTTP_VARS['groupBy'] = "dateDebut$Table"; - $field_raw_group_by = 'dateDebut'; - } - if ($table == 'shop_jours_shift') { - $this->HTTP_VARS['groupBy'] = 'shop_jours'; - } - if ($table == 'commande') { - $this->HTTP_VARS['groupBy'] = 'shop_jours_shift_run'; - } - if ($table == 'produit') { - $this->HTTP_VARS['groupBy'] = 'produit_categorie'; - } - } - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; - $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; - - $Idae = new Idae($table); - $APP = new App($table); - // - $APP_TABLE = $APP->app_table_one; - - $APPOBJ = $APP->appobj(null, $vars); - $name_id = "id$table"; - - $sortBy = empty($this->HTTP_VARS['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $APP->nomAppscheme : $APP_TABLE['sortFieldName'] : $this->HTTP_VARS['sortBy']; - $sortDir = empty($this->HTTP_VARS['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$this->HTTP_VARS['sortDir']; - $sortBySecond = empty($this->HTTP_VARS['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? 'dateCreation' . $Table : $APP_TABLE['sortFieldSecondName'] : $this->HTTP_VARS['sortBySecond']; - $sortDirSecond = empty($this->HTTP_VARS['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$this->HTTP_VARS['sortDirSecond']; - - $arr_sort_by = array_filter([$sortBy => $sortDir, $sortBySecond => $sortDirSecond]); - - //var_dump($vars); - - if (!empty($groupBy)): - if (!empty($APPOBJ->GRILLE_FK[$groupBy])) { - $APP_GROUPBY = new App($groupBy); - $rs_dist = $APP->distinct($groupBy, $vars, $nbRows); - $rs_distall = $APP->distinct_all("id$groupBy", $vars); - - $sortByGB = $APP_GROUPBY->app_table_one['sortFieldName']; - $sortDirGB = (int)$APP_GROUPBY->app_table_one['sortFieldOrder']; - $sortBySecondGB = $APP_GROUPBY->app_table_one['sortFieldSecondName']; - $sortDirSecondGB = (int)$APP_GROUPBY->app_table_one['sortFieldSecondOrder']; - - $arr_sort_groupby = array_filter([$sortByGB => $sortDirGB, $sortBySecondGB => $sortDirSecondGB]); - - $rsGroupBy = $APP_GROUPBY->find(["id$groupBy" => ['$in' => $rs_distall]])->sort($arr_sort_groupby)->limit(10); - $dist_count = $rs_dist->count(); - $dist_max_count = $rs_dist->count(true); - - } else { - $rs_dist = $APP->distinct_all($groupBy, array_merge($vars)); - $rsfetch = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); - $fetch = array_column(iterator_to_array($rsfetch), $groupBy); - $rsGroupBy = array_unique($fetch); - $dist_count = (sizeof($rs_dist) > $nbRows) ? $nbRows : sizeof($rs_dist); - $dist_max_count = sizeof($rs_dist); - - } - endif; - - $rs_app = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); - - $type_fiche = ($table == 'produit') ? 'fiche_mini' : 'fiche_micro'; - $type_fiche = ($table == 'livreur_affectation') ? 'fiche_mini' : $type_fiche; -?> -
-
- module('app_liste/app_liste_entete_search', $this->HTTP_VARS); ?> -
- - -
- HTTP_VARS['type_liste'])) { ?> - - $arr_groupby): - if (!empty($arr_groupby["id$groupBy"])) { - $vars["id$groupBy"] = (int)$arr_groupby["id$groupBy"]; // unset apres - $new_vars = array_merge($this->HTTP_VARS, ['vars' => ["id$groupBy" => $arr_groupby['id' . $groupBy]]]); - } else { - $vars["$groupBy"] = $arr_groupby; - $new_vars = array_merge($this->HTTP_VARS, ['vars' => ["$groupBy" => $arr_groupby]]); - - } - - if (!empty($arr_groupby["id$groupBy"])) { - echo $Idae->module('liste_groupby_entete', "table=$groupBy&table_value=" . $arr_groupby['id' . $groupBy]); - } else { - $titre=$APP->cf_output_icon($field_raw_group_by); - //$titre = (strpos($groupBy,'date')!==false)? '' : $groupBy ; - $text = (strpos($groupBy,'date')!==false)? function_prod::jourMoisDate_fr($arr_groupby) : $arr_groupby ; - echo '
'; - echo '

'; - echo $titre.' '.$text; - echo '

'; - echo '
'; - } - if (!empty($GRILLE_FK[$groupBy])) { - $vars['id' . $groupBy] = (int)$arr_groupby['id' . $groupBy]; // unset apres - } - echo "
"; - echo $Idae->module('app_liste/app_liste_inner', $new_vars); - echo "
"; - unset($vars['id' . $groupBy]); - unset($vars[$groupBy]); - - endforeach; - else: - - echo $Idae->module('app_liste/app_liste_inner', $this->HTTP_VARS); - endif; - ?> -
-
- module('app_liste/app_liste_menu', "table=$table&table_value=$value"); ?> -
-
+HTTP_VARS['table']; + $Table = ucfirst($table); + + if (empty($this->HTTP_VARS['groupBy'])) { + if ($table == 'livreur_affectation') { + $this->HTTP_VARS['groupBy'] = "dateDebut$Table"; + $field_raw_group_by = 'dateDebut'; + } + if ($table == 'shop_jours_shift') { + $this->HTTP_VARS['groupBy'] = 'shop_jours'; + } + if ($table == 'commande') { + $this->HTTP_VARS['groupBy'] = 'shop_jours_shift_run'; + } + if ($table == 'produit') { + $this->HTTP_VARS['groupBy'] = 'produit_categorie'; + } + } + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; + $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; + + $Idae = new Idae($table); + $APP = new App($table); + // + $APP_TABLE = $APP->app_table_one; + + $APPOBJ = $APP->appobj(null, $vars); + $name_id = "id$table"; + + $sortBy = empty($this->HTTP_VARS['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $APP->nomAppscheme : $APP_TABLE['sortFieldName'] : $this->HTTP_VARS['sortBy']; + $sortDir = empty($this->HTTP_VARS['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$this->HTTP_VARS['sortDir']; + $sortBySecond = empty($this->HTTP_VARS['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? 'dateCreation' . $Table : $APP_TABLE['sortFieldSecondName'] : $this->HTTP_VARS['sortBySecond']; + $sortDirSecond = empty($this->HTTP_VARS['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$this->HTTP_VARS['sortDirSecond']; + + $arr_sort_by = array_filter([$sortBy => $sortDir, $sortBySecond => $sortDirSecond]); + + //var_dump($vars); + + if (!empty($groupBy)): + if (!empty($APPOBJ->GRILLE_FK[$groupBy])) { + $APP_GROUPBY = new App($groupBy); + $rs_dist = $APP->distinct($groupBy, $vars, $nbRows); + $rs_distall = $APP->distinct_all("id$groupBy", $vars); + + $sortByGB = $APP_GROUPBY->app_table_one['sortFieldName']; + $sortDirGB = (int)$APP_GROUPBY->app_table_one['sortFieldOrder']; + $sortBySecondGB = $APP_GROUPBY->app_table_one['sortFieldSecondName']; + $sortDirSecondGB = (int)$APP_GROUPBY->app_table_one['sortFieldSecondOrder']; + + $arr_sort_groupby = array_filter([$sortByGB => $sortDirGB, $sortBySecondGB => $sortDirSecondGB]); + + $rsGroupBy = $APP_GROUPBY->find(["id$groupBy" => ['$in' => $rs_distall]])->sort($arr_sort_groupby)->limit(10); + $dist_count = $rs_dist->count(); + $dist_max_count = $rs_dist->count(true); + + } else { + $rs_dist = $APP->distinct_all($groupBy, array_merge($vars)); + $rsfetch = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); + $fetch = array_column(iterator_to_array($rsfetch), $groupBy); + $rsGroupBy = array_unique($fetch); + $dist_count = (sizeof($rs_dist) > $nbRows) ? $nbRows : sizeof($rs_dist); + $dist_max_count = sizeof($rs_dist); + + } + endif; + + $rs_app = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); + + $type_fiche = ($table == 'produit') ? 'fiche_mini' : 'fiche_micro'; + $type_fiche = ($table == 'livreur_affectation') ? 'fiche_mini' : $type_fiche; +?> +
+
+ module('app_liste/app_liste_entete_search', $this->HTTP_VARS); ?> +
+ + +
+ HTTP_VARS['type_liste'])) { ?> + + $arr_groupby): + if (!empty($arr_groupby["id$groupBy"])) { + $vars["id$groupBy"] = (int)$arr_groupby["id$groupBy"]; // unset apres + $new_vars = array_merge($this->HTTP_VARS, ['vars' => ["id$groupBy" => $arr_groupby['id' . $groupBy]]]); + } else { + $vars["$groupBy"] = $arr_groupby; + $new_vars = array_merge($this->HTTP_VARS, ['vars' => ["$groupBy" => $arr_groupby]]); + + } + + if (!empty($arr_groupby["id$groupBy"])) { + echo $Idae->module('liste_groupby_entete', "table=$groupBy&table_value=" . $arr_groupby['id' . $groupBy]); + } else { + $titre=$APP->cf_output_icon($field_raw_group_by); + //$titre = (strpos($groupBy,'date')!==false)? '' : $groupBy ; + $text = (strpos($groupBy,'date')!==false)? function_prod::jourMoisDate_fr($arr_groupby) : $arr_groupby ; + echo '
'; + echo '

'; + echo $titre.' '.$text; + echo '

'; + echo '
'; + } + if (!empty($GRILLE_FK[$groupBy])) { + $vars['id' . $groupBy] = (int)$arr_groupby['id' . $groupBy]; // unset apres + } + echo "
"; + echo $Idae->module('app_liste/app_liste_inner', $new_vars); + echo "
"; + unset($vars['id' . $groupBy]); + unset($vars[$groupBy]); + + endforeach; + else: + + echo $Idae->module('app_liste/app_liste_inner', $this->HTTP_VARS); + endif; + ?> +
+
+ module('app_liste/app_liste_menu', "table=$table&table_value=$value"); ?> +
+
diff --git a/web/bin/idae/mdl/app/app_liste/app_liste_entete.php b/web/bin/idae/mdl/app/app_liste/app_liste_entete.php index 491e3e6..bcc4ec7 100644 --- a/web/bin/idae/mdl/app/app_liste/app_liste_entete.php +++ b/web/bin/idae/mdl/app/app_liste/app_liste_entete.php @@ -1,61 +1,61 @@ -appobj($table_value, $vars); - - $rs_app = $APP->find($vars)->skip(($nbRows * $page))->limit($nbRows); - - $count_false = $rs_app->count(false); - $count_true = $rs_app->count(true); - // - $white_COLOR = '#ffffff'; - -?> -
-
-
-
-
-
-
-

nomAppscheme ?>

- -
liste_titre($_POST); ?>
-
-
-
- -
-
- -
- -
-
-
- \ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_liste/app_liste_entete_search.php b/web/bin/idae/mdl/app/app_liste/app_liste_entete_search.php index 2281ed5..6b3d497 100644 --- a/web/bin/idae/mdl/app/app_liste/app_liste_entete_search.php +++ b/web/bin/idae/mdl/app/app_liste/app_liste_entete_search.php @@ -1,74 +1,74 @@ -appobj($table_value, $vars); - - $rs_app = $APP->find($vars)->skip(($nbRows * $page))->limit($nbRows); - - $count_false = $rs_app->count(false); - $count_true = $rs_app->count(true); - // - $white_COLOR = '#ffffff'; - -?> -
-
" data-table_value="" style="overflow:hidden;position:sticky;top:0;z-index:200;"> -
-
-
-
-
-
-

nomAppscheme ?>

-
liste_titre($_POST); ?>
-
-
-
-
- -
-
-
-
-
- -
- -
-
-
- -
-
-
-
- \ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_liste/app_liste_groupby.php b/web/bin/idae/mdl/app/app_liste/app_liste_groupby.php index 482d5e4..e38b7fc 100644 --- a/web/bin/idae/mdl/app/app_liste/app_liste_groupby.php +++ b/web/bin/idae/mdl/app/app_liste/app_liste_groupby.php @@ -1,81 +1,81 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - - - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; - $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; - - $Idae = new Idae($table); - $APP = new App($table); - // - $APP_TABLE = $APP->app_table_one; - - $APPOBJ = $APP->appobj(null, $vars); - $name_id = "id$table"; - - $GRILLE_FK = $APP->get_grille_fk(); - - $ARR_RFK = $APP->get_table_rfk($table_value); - - if (is_array($arr_allowed_c) && is_array($ARR_RFK)) { - $arr_allowed_c = droit_table($type_session, 'L'); - $ARR_RFK = array_intersect($arr_allowed_c, $ARR_RFK); - } - -?> -
- -
- plug($ARR_FK['base_fk'], $table_fk)->findOne([$ARR_FK['idtable_fk'] => $ARR[$ARR_FK['idtable_fk']]]); - $dsp_code = $arr['code' . ucfirst($table_fk)]; - $dsp_fieldname = 'nom' . ucfirst($table_fk) ; - $dsp_name = $arr[$dsp_fieldname]; - if ( empty($dsp_name) ) { - $dsp_name = 'Aucun'; - } - - $html_fiche_link = 'table=' . $APP_TMP->codeAppscheme . '&table_value=' . $ARR[$field['idtable_fk']]; - - $arr_allowed_c = droit_table($type_session, 'R', $table_fk); - $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; - $html_attr = ($arr_allowed_c) ? "data-module_link='fiche' data-vars='$html_fiche_link'" : ''; - ?> -
- module('app_liste/app_liste_groupby_inner', "table=$table&groupBy=$table_fk&table_value=" . $arr_groupby['id' . $groupBy]); ?> -
- -
-
- module('app_liste/app_liste_menu', "table=$table&table_value=$value"); ?> -
-
+HTTP_VARS['table']; + $Table = ucfirst($table); + + + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; + $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; + + $Idae = new Idae($table); + $APP = new App($table); + // + $APP_TABLE = $APP->app_table_one; + + $APPOBJ = $APP->appobj(null, $vars); + $name_id = "id$table"; + + $GRILLE_FK = $APP->get_grille_fk(); + + $ARR_RFK = $APP->get_table_rfk($table_value); + + if (is_array($arr_allowed_c) && is_array($ARR_RFK)) { + $arr_allowed_c = droit_table($type_session, 'L'); + $ARR_RFK = array_intersect($arr_allowed_c, $ARR_RFK); + } + +?> +
+ +
+ plug($ARR_FK['base_fk'], $table_fk)->findOne([$ARR_FK['idtable_fk'] => $ARR[$ARR_FK['idtable_fk']]]); + $dsp_code = $arr['code' . ucfirst($table_fk)]; + $dsp_fieldname = 'nom' . ucfirst($table_fk) ; + $dsp_name = $arr[$dsp_fieldname]; + if ( empty($dsp_name) ) { + $dsp_name = 'Aucun'; + } + + $html_fiche_link = 'table=' . $APP_TMP->codeAppscheme . '&table_value=' . $ARR[$field['idtable_fk']]; + + $arr_allowed_c = droit_table($type_session, 'R', $table_fk); + $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; + $html_attr = ($arr_allowed_c) ? "data-module_link='fiche' data-vars='$html_fiche_link'" : ''; + ?> +
+ module('app_liste/app_liste_groupby_inner', "table=$table&groupBy=$table_fk&table_value=" . $arr_groupby['id' . $groupBy]); ?> +
+ +
+
+ module('app_liste/app_liste_menu', "table=$table&table_value=$value"); ?> +
+
diff --git a/web/bin/idae/mdl/app/app_liste/app_liste_groupby_inner.php b/web/bin/idae/mdl/app/app_liste/app_liste_groupby_inner.php index c040625..bcfee9f 100644 --- a/web/bin/idae/mdl/app/app_liste/app_liste_groupby_inner.php +++ b/web/bin/idae/mdl/app/app_liste/app_liste_groupby_inner.php @@ -1,136 +1,136 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - - if (empty($this->HTTP_VARS['groupBy'])) { - if ($table == 'livreur_affectation') { - $this->HTTP_VARS['groupBy'] = "dateDebut$Table"; - $field_raw_group_by = 'dateDebut'; - } - if ($table == 'shop_jours_shift') { - $this->HTTP_VARS['groupBy'] = 'shop_jours'; - } - if ($table == 'commande') { - $this->HTTP_VARS['groupBy'] = 'shop_jours_shift_run'; - } - if ($table == 'produit') { - $this->HTTP_VARS['groupBy'] = 'produit_categorie'; - } - } - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; - $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; - - $Idae = new Idae($table); - $APP = new App($table); - // - $APP_TABLE = $APP->app_table_one; - - $APPOBJ = $APP->appobj(null, $vars); - $name_id = "id$table"; - - $sortBy = empty($this->HTTP_VARS['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $APP->nomAppscheme : $APP_TABLE['sortFieldName'] : $this->HTTP_VARS['sortBy']; - $sortDir = empty($this->HTTP_VARS['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$this->HTTP_VARS['sortDir']; - $sortBySecond = empty($this->HTTP_VARS['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? 'dateCreation' . $Table : $APP_TABLE['sortFieldSecondName'] : $this->HTTP_VARS['sortBySecond']; - $sortDirSecond = empty($this->HTTP_VARS['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$this->HTTP_VARS['sortDirSecond']; - - $arr_sort_by = array_filter([$sortBy => $sortDir, $sortBySecond => $sortDirSecond]); - - if (!empty($groupBy)): - if (!empty($APPOBJ->GRILLE_FK[$groupBy])) { - $APP_GROUPBY = new App($groupBy); - $rs_dist = $APP->distinct($groupBy, $vars, $nbRows); - $rs_distall = $APP->distinct_all("id$groupBy", $vars); - - $sortByGB = $APP_GROUPBY->app_table_one['sortFieldName']; - $sortDirGB = (int)$APP_GROUPBY->app_table_one['sortFieldOrder']; - $sortBySecondGB = $APP_GROUPBY->app_table_one['sortFieldSecondName']; - $sortDirSecondGB = (int)$APP_GROUPBY->app_table_one['sortFieldSecondOrder']; - - $arr_sort_groupby = array_filter([$sortByGB => $sortDirGB, $sortBySecondGB => $sortDirSecondGB]); - - $rsGroupBy = $APP_GROUPBY->find(["id$groupBy" => ['$in' => $rs_distall]])->sort($arr_sort_groupby)->limit(10); - $dist_count = $rs_dist->count(); - $dist_max_count = $rs_dist->count(true); - - } else { - $rs_dist = $APP->distinct_all($groupBy, array_merge($vars)); - $rsfetch = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); - $fetch = array_column(iterator_to_array($rsfetch), $groupBy); - $rsGroupBy = array_unique($fetch); - $dist_count = (sizeof($rs_dist) > $nbRows) ? $nbRows : sizeof($rs_dist); - $dist_max_count = sizeof($rs_dist); - - } - endif; - - $rs_app = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); - - $type_fiche = ($table == 'produit') ? 'fiche_mini' : 'fiche_micro'; - $type_fiche = ($table == 'livreur_affectation') ? 'fiche_mini' : $type_fiche; -?> -
- -
-
- -
-
-
- $arr_groupby): - if (!empty($arr_groupby["id$groupBy"])) { - $vars["id$groupBy"] = (int)$arr_groupby["id$groupBy"]; // unset apres - $new_vars = array_merge($this->HTTP_VARS, ['vars' => ["id$groupBy" => $arr_groupby['id' . $groupBy]]]); - } else { - $vars["$groupBy"] = $arr_groupby; - $new_vars = array_merge($this->HTTP_VARS, ['vars' => ["$groupBy" => $arr_groupby]]); - - } - - if (!empty($arr_groupby["id$groupBy"])) { - echo $Idae->module('app_liste/app_liste_groupby_inner_entete', "table=$groupBy&table_value=" . $arr_groupby['id' . $groupBy]); - } else { - $titre = $APP->cf_output_icon($field_raw_group_by); - - $text = (strpos($groupBy, 'date') !== false) ? function_prod::jourMoisDate_fr($arr_groupby) : $arr_groupby; - echo '
'; - echo '

'; - echo $titre . ' ' . $text; - echo '

'; - echo '
'; - } - if (!empty($GRILLE_FK[$groupBy])) { - $vars['id' . $groupBy] = (int)$arr_groupby['id' . $groupBy]; // unset apres - } - - unset($vars['id' . $groupBy]); - unset($vars[$groupBy]); - - endforeach; - endif; - ?>
-
+HTTP_VARS['table']; + $Table = ucfirst($table); + + if (empty($this->HTTP_VARS['groupBy'])) { + if ($table == 'livreur_affectation') { + $this->HTTP_VARS['groupBy'] = "dateDebut$Table"; + $field_raw_group_by = 'dateDebut'; + } + if ($table == 'shop_jours_shift') { + $this->HTTP_VARS['groupBy'] = 'shop_jours'; + } + if ($table == 'commande') { + $this->HTTP_VARS['groupBy'] = 'shop_jours_shift_run'; + } + if ($table == 'produit') { + $this->HTTP_VARS['groupBy'] = 'produit_categorie'; + } + } + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; + $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; + + $Idae = new Idae($table); + $APP = new App($table); + // + $APP_TABLE = $APP->app_table_one; + + $APPOBJ = $APP->appobj(null, $vars); + $name_id = "id$table"; + + $sortBy = empty($this->HTTP_VARS['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $APP->nomAppscheme : $APP_TABLE['sortFieldName'] : $this->HTTP_VARS['sortBy']; + $sortDir = empty($this->HTTP_VARS['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$this->HTTP_VARS['sortDir']; + $sortBySecond = empty($this->HTTP_VARS['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? 'dateCreation' . $Table : $APP_TABLE['sortFieldSecondName'] : $this->HTTP_VARS['sortBySecond']; + $sortDirSecond = empty($this->HTTP_VARS['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$this->HTTP_VARS['sortDirSecond']; + + $arr_sort_by = array_filter([$sortBy => $sortDir, $sortBySecond => $sortDirSecond]); + + if (!empty($groupBy)): + if (!empty($APPOBJ->GRILLE_FK[$groupBy])) { + $APP_GROUPBY = new App($groupBy); + $rs_dist = $APP->distinct($groupBy, $vars, $nbRows); + $rs_distall = $APP->distinct_all("id$groupBy", $vars); + + $sortByGB = $APP_GROUPBY->app_table_one['sortFieldName']; + $sortDirGB = (int)$APP_GROUPBY->app_table_one['sortFieldOrder']; + $sortBySecondGB = $APP_GROUPBY->app_table_one['sortFieldSecondName']; + $sortDirSecondGB = (int)$APP_GROUPBY->app_table_one['sortFieldSecondOrder']; + + $arr_sort_groupby = array_filter([$sortByGB => $sortDirGB, $sortBySecondGB => $sortDirSecondGB]); + + $rsGroupBy = $APP_GROUPBY->find(["id$groupBy" => ['$in' => $rs_distall]])->sort($arr_sort_groupby)->limit(10); + $dist_count = $rs_dist->count(); + $dist_max_count = $rs_dist->count(true); + + } else { + $rs_dist = $APP->distinct_all($groupBy, array_merge($vars)); + $rsfetch = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); + $fetch = array_column(iterator_to_array($rsfetch), $groupBy); + $rsGroupBy = array_unique($fetch); + $dist_count = (sizeof($rs_dist) > $nbRows) ? $nbRows : sizeof($rs_dist); + $dist_max_count = sizeof($rs_dist); + + } + endif; + + $rs_app = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); + + $type_fiche = ($table == 'produit') ? 'fiche_mini' : 'fiche_micro'; + $type_fiche = ($table == 'livreur_affectation') ? 'fiche_mini' : $type_fiche; +?> +
+ +
+
+ +
+
+
+ $arr_groupby): + if (!empty($arr_groupby["id$groupBy"])) { + $vars["id$groupBy"] = (int)$arr_groupby["id$groupBy"]; // unset apres + $new_vars = array_merge($this->HTTP_VARS, ['vars' => ["id$groupBy" => $arr_groupby['id' . $groupBy]]]); + } else { + $vars["$groupBy"] = $arr_groupby; + $new_vars = array_merge($this->HTTP_VARS, ['vars' => ["$groupBy" => $arr_groupby]]); + + } + + if (!empty($arr_groupby["id$groupBy"])) { + echo $Idae->module('app_liste/app_liste_groupby_inner_entete', "table=$groupBy&table_value=" . $arr_groupby['id' . $groupBy]); + } else { + $titre = $APP->cf_output_icon($field_raw_group_by); + + $text = (strpos($groupBy, 'date') !== false) ? function_prod::jourMoisDate_fr($arr_groupby) : $arr_groupby; + echo '
'; + echo '

'; + echo $titre . ' ' . $text; + echo '

'; + echo '
'; + } + if (!empty($GRILLE_FK[$groupBy])) { + $vars['id' . $groupBy] = (int)$arr_groupby['id' . $groupBy]; // unset apres + } + + unset($vars['id' . $groupBy]); + unset($vars[$groupBy]); + + endforeach; + endif; + ?>
+
diff --git a/web/bin/idae/mdl/app/app_liste/app_liste_groupby_inner_entete.php b/web/bin/idae/mdl/app/app_liste/app_liste_groupby_inner_entete.php index 50f9c69..bb56f69 100644 --- a/web/bin/idae/mdl/app/app_liste/app_liste_groupby_inner_entete.php +++ b/web/bin/idae/mdl/app/app_liste/app_liste_groupby_inner_entete.php @@ -1,50 +1,50 @@ -get_table_fields($table_value, ['codeAppscheme_field' => ['nom', 'code', 'reference']]); - - $COLLECT_FIELDS = []; - foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { - foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { - $COLLECT_FIELDS[] = $ARR_FIELD; - } - } - - $color = empty($APP->colorAppscheme) ? '#c4c4c4' : $APP->colorAppscheme; - $color_contrast = color_contrast($APP->colorAppscheme); - $color_inverse = color_inverse($APP->colorAppscheme); -?> -
-
-
-
- -
-
-
-
- $ARR_FIELD) { ?> -
-
-
- HTTP_VARS['edit_field']) ? $ARR_FIELD['value_html'] : $ARR_FIELD['value_input'] ?> -
-
-
- -
-
-
+get_table_fields($table_value, ['codeAppscheme_field' => ['nom', 'code', 'reference']]); + + $COLLECT_FIELDS = []; + foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { + foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { + $COLLECT_FIELDS[] = $ARR_FIELD; + } + } + + $color = empty($APP->colorAppscheme) ? '#c4c4c4' : $APP->colorAppscheme; + $color_contrast = color_contrast($APP->colorAppscheme); + $color_inverse = color_inverse($APP->colorAppscheme); +?> +
+
+
+
+ +
+
+
+
+ $ARR_FIELD) { ?> +
+
+
+ HTTP_VARS['edit_field']) ? $ARR_FIELD['value_html'] : $ARR_FIELD['value_input'] ?> +
+
+
+ +
+
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_liste/app_liste_inner.php b/web/bin/idae/mdl/app/app_liste/app_liste_inner.php index 28d80e2..b5a09e0 100644 --- a/web/bin/idae/mdl/app/app_liste/app_liste_inner.php +++ b/web/bin/idae/mdl/app/app_liste/app_liste_inner.php @@ -1,77 +1,77 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; - $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; - - $Idae = new Idae($table); - $APP = new App($table); - // - $APP_TABLE = $APP->app_table_one; - - $APPOBJ = $APP->appobj(null, $vars); - $name_id = "id$table"; - - $sortBy = empty($this->HTTP_VARS['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $APP->nomAppscheme : $APP_TABLE['sortFieldName'] : $this->HTTP_VARS['sortBy']; - $sortDir = empty($this->HTTP_VARS['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$this->HTTP_VARS['sortDir']; - $sortBySecond = empty($this->HTTP_VARS['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? 'dateCreation' . $Table : $APP_TABLE['sortFieldSecondName'] : $this->HTTP_VARS['sortBySecond']; - $sortDirSecond = empty($this->HTTP_VARS['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$this->HTTP_VARS['sortDirSecond']; - - $arr_sort_by = array_filter([$sortBy => $sortDir, $sortBySecond => $sortDirSecond]); - $rs_app = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); - - $count_tot = $rs_app->count(); - $count_rows = $rs_app->count(true); - $nbPage = ceil($count_tot / $nbRows); - - $type_fiche = (!empty($groupBy)) ? 'fiche_micro' : 'fiche_mini' ; - $type_fiche = ($table == 'produit') ? 'fiche_mini' : 'fiche_micro'; - $type_fiche = ($table == 'shop_jours_shift') ? 'fiche_mini' : 'fiche_micro'; - $type_fiche = ($table == 'shop_jours') ? 'fiche_micro' : $type_fiche; - $type_fiche = ($table == 'livreur_affectation') ? 'fiche_mini' : $type_fiche; - $type_fiche = ($table == 'commande_facture') ? 'fiche_mini' : $type_fiche; - ?> -
- getNext()) { - $value = $arr_app[$name_id]; - echo $Idae->module($type_fiche, "table=$table&table_value=$value"); - } - ?> -
-HTTP_VARS['page'] = $page + 1; - ?> -
-
- -
-
-
-
- HTTP_VARS['table']; + $Table = ucfirst($table); + + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; + $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; + + $Idae = new Idae($table); + $APP = new App($table); + // + $APP_TABLE = $APP->app_table_one; + + $APPOBJ = $APP->appobj(null, $vars); + $name_id = "id$table"; + + $sortBy = empty($this->HTTP_VARS['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $APP->nomAppscheme : $APP_TABLE['sortFieldName'] : $this->HTTP_VARS['sortBy']; + $sortDir = empty($this->HTTP_VARS['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$this->HTTP_VARS['sortDir']; + $sortBySecond = empty($this->HTTP_VARS['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? 'dateCreation' . $Table : $APP_TABLE['sortFieldSecondName'] : $this->HTTP_VARS['sortBySecond']; + $sortDirSecond = empty($this->HTTP_VARS['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$this->HTTP_VARS['sortDirSecond']; + + $arr_sort_by = array_filter([$sortBy => $sortDir, $sortBySecond => $sortDirSecond]); + $rs_app = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); + + $count_tot = $rs_app->count(); + $count_rows = $rs_app->count(true); + $nbPage = ceil($count_tot / $nbRows); + + $type_fiche = (!empty($groupBy)) ? 'fiche_micro' : 'fiche_mini' ; + $type_fiche = ($table == 'produit') ? 'fiche_mini' : 'fiche_micro'; + $type_fiche = ($table == 'shop_jours_shift') ? 'fiche_mini' : 'fiche_micro'; + $type_fiche = ($table == 'shop_jours') ? 'fiche_micro' : $type_fiche; + $type_fiche = ($table == 'livreur_affectation') ? 'fiche_mini' : $type_fiche; + $type_fiche = ($table == 'commande_facture') ? 'fiche_mini' : $type_fiche; + ?> +
+ getNext()) { + $value = $arr_app[$name_id]; + echo $Idae->module($type_fiche, "table=$table&table_value=$value"); + } + ?> +
+HTTP_VARS['page'] = $page + 1; + ?> +
+
+ +
+
+
+
+ HTTP_VARS['table']; - $Table = ucfirst($table); - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; - $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; - // - $APP = new App($table); - $Idae = new Idae($table); - $APPOBJ = $APP->appobj($table_value, $vars); - // - $white_COLOR = '#ffffff'; - - $arr_allowed_c = droit_table($type_session, 'C', $table); - $arr_allowed_r = droit_table($type_session, 'R', $table); - $arr_allowed_u = droit_table($type_session, 'U', $table); - $arr_allowed_d = droit_table($type_session, 'D', $table); - $arr_allowed_l = droit_table($type_session, 'L', $table); - - $html_attr_create = ''; - $html_attr = 'table=' . $table; - $html_create_link = $html_attr; - $html_create_link .= '&' . http_build_query($this->HTTP_VARS); - if ($APP->has_field_fk($type_session)) { - $html_create_link .= "&vars[$name_idtype_session]=$idtype_session"; - } - - $crypted_create_link = AppLink::create($table,$table_value,[$name_idtype_session=>$idtype_session]); - $crypted_liste_link = AppLink::liste($table); - $crypted_liste_groupby_link = AppLink::liste_groupby($table); - $crypted_liste_calendar_link = AppLink::liste_calendrier($table); - -?> -
- -
-
- -
-
- - -
-
- -
-
-
-
- -
-
- - has_field(['date', 'dateDebut']) && $arr_allowed_l) { ?> -
-
- -
-
- -
- \ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_liste/app_liste_mini.php b/web/bin/idae/mdl/app/app_liste/app_liste_mini.php index d3186dc..28a6b3a 100644 --- a/web/bin/idae/mdl/app/app_liste/app_liste_mini.php +++ b/web/bin/idae/mdl/app/app_liste/app_liste_mini.php @@ -1,79 +1,79 @@ -HTTP_VARS['table']; - $Table = ucfirst($table); - - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; - $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; - - $Idae = new Idae($table); - $APP = new App($table); - // - $APP_TABLE = $APP->app_table_one; - - $APPOBJ = $APP->appobj(null, $vars); - $name_id = "id$table"; - - $sortBy = empty($this->HTTP_VARS['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $APP->nomAppscheme : $APP_TABLE['sortFieldName'] : $this->HTTP_VARS['sortBy']; - $sortDir = empty($this->HTTP_VARS['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$this->HTTP_VARS['sortDir']; - $sortBySecond = empty($this->HTTP_VARS['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? 'dateCreation' . $Table : $APP_TABLE['sortFieldSecondName'] : $this->HTTP_VARS['sortBySecond']; - $sortDirSecond = empty($this->HTTP_VARS['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$this->HTTP_VARS['sortDirSecond']; - - $arr_sort_by = array_filter([$sortBy => $sortDir, $sortBySecond => $sortDirSecond]); - $rs_app = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); - - $count_tot = $rs_app->count(); - $count_rows = $rs_app->count(true); - $nbPage = ceil($count_tot / $nbRows); - - $type_fiche = ($table == 'produit') ? 'fiche_mini' : 'fiche_micro'; - $type_fiche = ($table == 'shop_jours_shift') ? 'fiche_mini' : 'fiche_micro'; - $type_fiche = ($table == 'livreur_affectation') ? 'fiche_mini' : $type_fiche; - $type_fiche = 'app_fiche/app_fiche_fields_table'; - ?> -
- getNext()) { - $value = $arr_app[$name_id]; - ?> -
-
- module($type_fiche, "table=$table&table_value=$value");?> -
-
- -
-HTTP_VARS['page'] = $page + 1; - ?> -
-
- -
-
-
-
- HTTP_VARS['table']; + $Table = ucfirst($table); + + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $page = (!isset($this->HTTP_VARS['page'])) ? 0 : $this->HTTP_VARS['page']; + $nbRows = (empty($this->HTTP_VARS['nbRows'])) ? empty($settings_nbRows) ? 10 : (int)$settings_nbRows : $this->HTTP_VARS['nbRows']; + + $Idae = new Idae($table); + $APP = new App($table); + // + $APP_TABLE = $APP->app_table_one; + + $APPOBJ = $APP->appobj(null, $vars); + $name_id = "id$table"; + + $sortBy = empty($this->HTTP_VARS['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $APP->nomAppscheme : $APP_TABLE['sortFieldName'] : $this->HTTP_VARS['sortBy']; + $sortDir = empty($this->HTTP_VARS['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$this->HTTP_VARS['sortDir']; + $sortBySecond = empty($this->HTTP_VARS['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? 'dateCreation' . $Table : $APP_TABLE['sortFieldSecondName'] : $this->HTTP_VARS['sortBySecond']; + $sortDirSecond = empty($this->HTTP_VARS['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$this->HTTP_VARS['sortDirSecond']; + + $arr_sort_by = array_filter([$sortBy => $sortDir, $sortBySecond => $sortDirSecond]); + $rs_app = $APP->find($vars)->sort($arr_sort_by)->skip(($nbRows * $page))->limit($nbRows); + + $count_tot = $rs_app->count(); + $count_rows = $rs_app->count(true); + $nbPage = ceil($count_tot / $nbRows); + + $type_fiche = ($table == 'produit') ? 'fiche_mini' : 'fiche_micro'; + $type_fiche = ($table == 'shop_jours_shift') ? 'fiche_mini' : 'fiche_micro'; + $type_fiche = ($table == 'livreur_affectation') ? 'fiche_mini' : $type_fiche; + $type_fiche = 'app_fiche/app_fiche_fields_table'; + ?> +
+ getNext()) { + $value = $arr_app[$name_id]; + ?> +
+
+ module($type_fiche, "table=$table&table_value=$value");?> +
+
+ +
+HTTP_VARS['page'] = $page + 1; + ?> +
+
+ +
+
+
+
+ get_table_fields($table_value, ['codeAppscheme_field' => ['nom', 'code', 'reference']]); - - $COLLECT_FIELDS = []; - foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { - foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { - $COLLECT_FIELDS[] = $ARR_FIELD; - } - } - -?> -
-
-
-
- -
-
-
-
- $ARR_FIELD) { ?> -
-
-
- -
-
- HTTP_VARS['edit_field']) ? $ARR_FIELD['value_html'] : $ARR_FIELD['value_input'] ?> -
-
-
- -
-
nomAppscheme ?>
-
-
+get_table_fields($table_value, ['codeAppscheme_field' => ['nom', 'code', 'reference']]); + + $COLLECT_FIELDS = []; + foreach ($ARR_COLLECT as $key => $ARR_FIELD_GROUP) { + foreach ($ARR_FIELD_GROUP['appscheme_fields'] as $CODE_ARR_FIELD => $ARR_FIELD) { + $COLLECT_FIELDS[] = $ARR_FIELD; + } + } + +?> +
+
+
+
+ +
+
+
+
+ $ARR_FIELD) { ?> +
+
+
+ +
+
+ HTTP_VARS['edit_field']) ? $ARR_FIELD['value_html'] : $ARR_FIELD['value_input'] ?> +
+
+
+ +
+
nomAppscheme ?>
+
+
\ No newline at end of file diff --git a/web/bin/idae/mdl/app/app_liste_rfk.php b/web/bin/idae/mdl/app/app_liste_rfk.php index 7dbe4c9..46ab7d3 100644 --- a/web/bin/idae/mdl/app/app_liste_rfk.php +++ b/web/bin/idae/mdl/app/app_liste_rfk.php @@ -1,113 +1,113 @@ -extract_vars($table_value , $vars); - extract($EXTRACTS_VARS , EXTR_OVERWRITE); - - $BASE_APP = $APP_TABLE['codeAppscheme_base']; - // - $id = 'id' . $table; - if ( !empty($table_value) ) { - $vars[$id] = (int)$table_value; - } - - $ARR = $APP->query_one($vars); - // - // - - if ( sizeof($R_FK) != 0 ): - foreach ($R_FK as $arr_fk): - $final_rfk[$arr_fk['scope']][] = $arr_fk; - endforeach; - - //if (sizeof($final_rfk) == 0) return; - ?> -
- $arr_final): - ?> -
-
- (int)$table_value ]; - //$vars_rfk['table_value'] = $ARR['id' . $arr_fk['table']]; - $vars_rfk['table'] = $arr_fk['table']; - $count = $arr_fk['count']; - $html_list_link = http_build_query($vars_rfk); - // - $sortByGB = $APP_TMP->app_table_one['sortFieldName']; - $sortDirGB = (int)$APP_TMP->app_table_one['sortFieldOrder']; - $sortBySecondGB = $APP_TMP->app_table_one['sortFieldSecondName']; - $sortDirSecondGB = (int)$APP_TMP->app_table_one['sortFieldSecondOrder']; - - $arr_sort_groupby = array_filter([ $sortByGB => $sortDirGB , $sortBySecondGB => $sortDirSecondGB ]); - - $RS_TMP = $APP_TMP->find($vars_rfk['vars'])->sort($arr_sort_groupby)->limit(3); - - ?> -
-
-
- -
-
- getNext()) { - $value = $arr_app[$name_id_fk]; - // echo $Idae_tmp->module('fiche_fields' , "table=$table_fk&table_value=$value"); - } - ?> -
-
-
-
-
- -
-
- -
- - - +extract_vars($table_value , $vars); + extract($EXTRACTS_VARS , EXTR_OVERWRITE); + + $BASE_APP = $APP_TABLE['codeAppscheme_base']; + // + $id = 'id' . $table; + if ( !empty($table_value) ) { + $vars[$id] = (int)$table_value; + } + + $ARR = $APP->query_one($vars); + // + // + + if ( sizeof($R_FK) != 0 ): + foreach ($R_FK as $arr_fk): + $final_rfk[$arr_fk['scope']][] = $arr_fk; + endforeach; + + //if (sizeof($final_rfk) == 0) return; + ?> +
+ $arr_final): + ?> +
+
+ (int)$table_value ]; + //$vars_rfk['table_value'] = $ARR['id' . $arr_fk['table']]; + $vars_rfk['table'] = $arr_fk['table']; + $count = $arr_fk['count']; + $html_list_link = http_build_query($vars_rfk); + // + $sortByGB = $APP_TMP->app_table_one['sortFieldName']; + $sortDirGB = (int)$APP_TMP->app_table_one['sortFieldOrder']; + $sortBySecondGB = $APP_TMP->app_table_one['sortFieldSecondName']; + $sortDirSecondGB = (int)$APP_TMP->app_table_one['sortFieldSecondOrder']; + + $arr_sort_groupby = array_filter([ $sortByGB => $sortDirGB , $sortBySecondGB => $sortDirSecondGB ]); + + $RS_TMP = $APP_TMP->find($vars_rfk['vars'])->sort($arr_sort_groupby)->limit(3); + + ?> +
+
+
+ +
+
+ getNext()) { + $value = $arr_app[$name_id_fk]; + // echo $Idae_tmp->module('fiche_fields' , "table=$table_fk&table_value=$value"); + } + ?> +
+
+
+
+
+ +
+
+ +
+ + + diff --git a/web/bin/idae/mdl/app/app_select.php b/web/bin/idae/mdl/app/app_select.php index 9453748..bb91643 100644 --- a/web/bin/idae/mdl/app/app_select.php +++ b/web/bin/idae/mdl/app/app_select.php @@ -1,72 +1,72 @@ - $value_vars): - $value_vars['$in'] = json_decode($value_vars['$in']); - $vars[$key_vars] = $value_vars; - endforeach; - } - // vardump($vars); - $HTTP_VARS = $APP->translate_vars($vars); - $APP_TABLE = $APP->app_table_one; - $ARR_FIELDS = $APP->get_field_list(); - - $add = [ ]; - - $sortBy = empty($APP->app_table_one['sortFieldName']) ? $nom : $APP->app_table_one['sortFieldName']; - $sortDir = empty($APP->app_table_one['sortFieldOrder']) ? 1 : (int)$APP->app_table_one['sortFieldOrder']; - $sortBySecond = empty($APP->app_table_one['sortFieldSecondName']) ? null : $APP->app_table_one['sortFieldSecondName']; - $sortDirSecond = empty($APP->app_table_one['sortFieldSecondOrder']) ? 1 : (int)$APP->app_table_one['sortFieldSecondOrder']; - $sortByThird = empty($APP->app_table_one['sortFieldThirdName']) ? null : $APP->app_table_one['sortFieldThirdName']; - $sortDirThird = empty($APP->app_table_one['sortFieldThirdOrder']) ? 1 : (int)$APP->app_table_one['sortFieldThirdOrder']; - - $sort_fields = [$sortBy => $sortDir]; - if ($sortBySecond) { - $sort_fields = array_merge($sort_fields,[$sortBySecond => $sortDirSecond]); - } - // - if ( !empty($_POST['search']) ): - $search = trim($_POST['search']); - $arrSearch = explode(' ' , trim($search)); - foreach ($arrSearch as $key => $value) { - // $out[] = new MongoRegex("/.*" . (string)$arrSearch[$key] . "*./i"); - } - $out[] = new MongoRegex("/" . (string)$search . "/i"); - if ( sizeof($out) == 1 ) { - $add = [ '$or' => [ [ $nom => [ '$all' => $out ] ] , [ $id => (int)$_POST['search'] ] , [ 'code' . $Table => [ '$in' => $out ] ] , [ $prenom => [ '$in' => $out ] ] ] ]; - } - if ( is_int($_POST['search']) ): - $add['$or'][] = [ $id => (int)$_POST['search'] ]; - endif; - $rs = $APP->find($vars + $add)->sort([ 'nom' . $Table => 1 , 'ordre' . $Table => - 1 ])->limit(250); - // vardump_async(array_merge( $vars , $add),true); - else: - $rs = $APP->find($vars)->sort($sort_fields)->limit(250); - endif; - - - -?> - + $value_vars): + $value_vars['$in'] = json_decode($value_vars['$in']); + $vars[$key_vars] = $value_vars; + endforeach; + } + // vardump($vars); + $HTTP_VARS = $APP->translate_vars($vars); + $APP_TABLE = $APP->app_table_one; + $ARR_FIELDS = $APP->get_field_list(); + + $add = [ ]; + + $sortBy = empty($APP->app_table_one['sortFieldName']) ? $nom : $APP->app_table_one['sortFieldName']; + $sortDir = empty($APP->app_table_one['sortFieldOrder']) ? 1 : (int)$APP->app_table_one['sortFieldOrder']; + $sortBySecond = empty($APP->app_table_one['sortFieldSecondName']) ? null : $APP->app_table_one['sortFieldSecondName']; + $sortDirSecond = empty($APP->app_table_one['sortFieldSecondOrder']) ? 1 : (int)$APP->app_table_one['sortFieldSecondOrder']; + $sortByThird = empty($APP->app_table_one['sortFieldThirdName']) ? null : $APP->app_table_one['sortFieldThirdName']; + $sortDirThird = empty($APP->app_table_one['sortFieldThirdOrder']) ? 1 : (int)$APP->app_table_one['sortFieldThirdOrder']; + + $sort_fields = [$sortBy => $sortDir]; + if ($sortBySecond) { + $sort_fields = array_merge($sort_fields,[$sortBySecond => $sortDirSecond]); + } + // + if ( !empty($_POST['search']) ): + $search = trim($_POST['search']); + $arrSearch = explode(' ' , trim($search)); + foreach ($arrSearch as $key => $value) { + // $out[] = new MongoRegex("/.*" . (string)$arrSearch[$key] . "*./i"); + } + $out[] = new MongoRegex("/" . (string)$search . "/i"); + if ( sizeof($out) == 1 ) { + $add = [ '$or' => [ [ $nom => [ '$all' => $out ] ] , [ $id => (int)$_POST['search'] ] , [ 'code' . $Table => [ '$in' => $out ] ] , [ $prenom => [ '$in' => $out ] ] ] ]; + } + if ( is_int($_POST['search']) ): + $add['$or'][] = [ $id => (int)$_POST['search'] ]; + endif; + $rs = $APP->find($vars + $add)->sort([ 'nom' . $Table => 1 , 'ordre' . $Table => - 1 ])->limit(250); + // vardump_async(array_merge( $vars , $add),true); + else: + $rs = $APP->find($vars)->sort($sort_fields)->limit(250); + endif; + + + +?> + diff --git a/web/bin/idae/mdl/app/app_select_line.php b/web/bin/idae/mdl/app/app_select_line.php index 7cdb382..0566172 100644 --- a/web/bin/idae/mdl/app/app_select_line.php +++ b/web/bin/idae/mdl/app/app_select_line.php @@ -1,104 +1,104 @@ -HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $vars = array_filter($vars); - $table = $this->HTTP_VARS['table']; - $table_value = empty($this->HTTP_VARS['table_value']) ? null : (int)$this->HTTP_VARS['table_value']; - $table_from = $this->HTTP_VARS['table_from']; - $table_value_from = empty($this->HTTP_VARS['table_value_from']) ? null : (int)$this->HTTP_VARS['table_value_from']; - - $arr_allowed_r = droit_table($type_session, 'R', $table); - - $id = 'id' . $this->HTTP_VARS['table']; - $Table = ucfirst($table); - $nom = 'nom' . ucfirst($table); - $prenom = 'prenom' . ucfirst($table); - $code = 'code' . ucfirst($table); - // - // - $APP = new App($table); - $Idae = new Idae($table_from); - if (!empty($this->HTTP_VARS['vars_in'])) { - foreach ($this->HTTP_VARS['vars_in'] as $key_vars => $value_vars): - $value_vars['$in'] = json_decode($value_vars['$in']); - $vars[$key_vars] = $value_vars; - endforeach; - } - // vardump($vars); - $HTTP_VARS = $APP->translate_vars($vars); - $APP_TABLE = $APP->app_table_one; - $ARR_FIELDS = $APP->get_field_list(); - - $add = []; - - // - if (!empty($this->HTTP_VARS['search'])): - $search = trim($this->HTTP_VARS['search']); - $arrSearch = explode(' ', trim($search)); - foreach ($arrSearch as $key => $value) { - // $out[] = new MongoRegex("/.*" . (string)$arrSearch[$key] . "*./i"); - } - $out[] = new MongoRegex("/" . (string)$search . "/i"); - if (sizeof($out) == 1) { - $add = ['$or' => [[$nom => ['$all' => $out]], - [$id => (int)$this->HTTP_VARS['search']], - ['code' . $Table => ['$in' => $out]], - [$prenom => ['$in' => $out]]]]; - } - if (is_int($this->HTTP_VARS['search'])): - $add['$or'][] = [$id => (int)$this->HTTP_VARS['search']]; - endif; - $rs = $APP->find($vars + $add)->sort(['nom' . $Table => 1, - 'ordre' . $Table => -1])->limit(250); - // vardump_async(array_merge( $vars , $add),true); - else: - $rs = $APP->find($vars)->sort(['nom' . $Table => 1, - 'ordre' . $Table => -1])->limit(250); - endif; - - /*$options = ['apply_droit' => [$type_session, - 'U'], - 'data_mode' => 'liste', - 'scheme_field_view' => 'short', - 'field_draw_style' => 'draw_html_field', - 'fields_scheme_part' => 'all', - 'field_composition' => ['hide_field_icon' => 0, - 'hide_field_name' => 0, - 'hide_field_value' => 0]]; - - $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); - $Fabric->fetch_query($rs, 'find'); - $tplData = $Fabric->get_templateDataFields();*/ - -?> -
-
- module('fiche_entete', ['table' => $table]) ?> -
-
-
- - getNext()) { ?> -
> -
-
- - - - -
-
- -
-
-
- - -
- -
-
+HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $vars = array_filter($vars); + $table = $this->HTTP_VARS['table']; + $table_value = empty($this->HTTP_VARS['table_value']) ? null : (int)$this->HTTP_VARS['table_value']; + $table_from = $this->HTTP_VARS['table_from']; + $table_value_from = empty($this->HTTP_VARS['table_value_from']) ? null : (int)$this->HTTP_VARS['table_value_from']; + + $arr_allowed_r = droit_table($type_session, 'R', $table); + + $id = 'id' . $this->HTTP_VARS['table']; + $Table = ucfirst($table); + $nom = 'nom' . ucfirst($table); + $prenom = 'prenom' . ucfirst($table); + $code = 'code' . ucfirst($table); + // + // + $APP = new App($table); + $Idae = new Idae($table_from); + if (!empty($this->HTTP_VARS['vars_in'])) { + foreach ($this->HTTP_VARS['vars_in'] as $key_vars => $value_vars): + $value_vars['$in'] = json_decode($value_vars['$in']); + $vars[$key_vars] = $value_vars; + endforeach; + } + // vardump($vars); + $HTTP_VARS = $APP->translate_vars($vars); + $APP_TABLE = $APP->app_table_one; + $ARR_FIELDS = $APP->get_field_list(); + + $add = []; + + // + if (!empty($this->HTTP_VARS['search'])): + $search = trim($this->HTTP_VARS['search']); + $arrSearch = explode(' ', trim($search)); + foreach ($arrSearch as $key => $value) { + // $out[] = new MongoRegex("/.*" . (string)$arrSearch[$key] . "*./i"); + } + $out[] = new MongoRegex("/" . (string)$search . "/i"); + if (sizeof($out) == 1) { + $add = ['$or' => [[$nom => ['$all' => $out]], + [$id => (int)$this->HTTP_VARS['search']], + ['code' . $Table => ['$in' => $out]], + [$prenom => ['$in' => $out]]]]; + } + if (is_int($this->HTTP_VARS['search'])): + $add['$or'][] = [$id => (int)$this->HTTP_VARS['search']]; + endif; + $rs = $APP->find($vars + $add)->sort(['nom' . $Table => 1, + 'ordre' . $Table => -1])->limit(250); + // vardump_async(array_merge( $vars , $add),true); + else: + $rs = $APP->find($vars)->sort(['nom' . $Table => 1, + 'ordre' . $Table => -1])->limit(250); + endif; + + /*$options = ['apply_droit' => [$type_session, + 'U'], + 'data_mode' => 'liste', + 'scheme_field_view' => 'short', + 'field_draw_style' => 'draw_html_field', + 'fields_scheme_part' => 'all', + 'field_composition' => ['hide_field_icon' => 0, + 'hide_field_name' => 0, + 'hide_field_value' => 0]]; + + $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); + $Fabric->fetch_query($rs, 'find'); + $tplData = $Fabric->get_templateDataFields();*/ + +?> +
+
+ module('fiche_entete', ['table' => $table]) ?> +
+
+
+ + getNext()) { ?> +
> +
+
+ + + + +
+
+ +
+
+
+ + +
+ +
+
diff --git a/web/bin/idae/mdl/app/app_update/app_update.php b/web/bin/idae/mdl/app/app_update/app_update.php index ab561d9..30ad26d 100644 --- a/web/bin/idae/mdl/app/app_update/app_update.php +++ b/web/bin/idae/mdl/app/app_update/app_update.php @@ -1,152 +1,152 @@ -HTTP_VARS['table']; - $Table = ucfirst($this->HTTP_VARS['table']); - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $type_session = $_SESSION['type_session']; - $name_idtype_session = "id$type_session"; - - // - $APP = new App($table); - $Idae = new Idae($table); - - $test_custom = Idae::module_exists('app_custom/' . $table . '/' . $table . '_update'); - if (!empty($test_custom)) { - echo $Idae->module('app_custom/' . $table . '/' . $table . '_update', $this->HTTP_VARS); - - return; - } - - $GRILLE_FK = $APP->get_grille_fk(); - // - // - $id = 'id' . $table; - $ARR = $APP->findOne([$id => $table_value]); - - $Idae = new Idae($table); - - $crypted_image_link = AppLink::liste_images($table, $table_value); - - $options = ['apply_droit' => [$type_session, - 'U'], - 'data_mode' => 'fiche', - 'scheme_field_view' => 'native', - 'field_draw_style' => 'draw_html_input', - 'scheme_field_view_groupby' => 'group', - 'fields_scheme_part' => 'all', - 'hide_field_empty' => 0, - 'hide_field_icon' => 0, - 'hide_field_name' => 0, - 'hide_field_value' => 0, - 'field_composition' => ['hide_field_icon' => 0, - 'hide_field_name' => 0, - 'hide_field_value' => 0]]; - - $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); - $Fabric->fetch_data(["id$table" => $table_value]); - $tplData = $Fabric->get_templateData(); -?> -
-
- module('app_fiche_entete', ['table' => $table, - 'table_value' => $table_value]) ?> -
-
-
- - - - - - - - -
-
-
- -
-
- -
-
-
- -
- module('app_update_fk', ['table' => $table, - 'table_value' => $table_value, - 'edit_field' => 1, - 'titre' => 0, - 'show_empty' => 0]) ?> - -
-
- $field): - $APP_TMP = new App($field['table_fk']); - $GRILLE_FK_TMP = $APP_TMP->get_grille_fk($field['table_fk']); - $id = 'id' . $field['table_fk']; - $arr = $APP_TMP->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); - - if (!empty($vars[$id])) { - continue; - } - - $arr_extends = array_intersect(array_keys($GRILLE_FK), array_keys($GRILLE_FK_TMP)); - $http_add_vars = ''; - $add_vars = []; - if (sizeof($arr_extends) != 0) { - foreach ($arr_extends as $key_ext => $table_ext) { - $idtable_ext = 'id' . $table_ext; - if (!empty($ARR[$idtable_ext])) { - $add_vars[$idtable_ext] = (int)$ARR[$idtable_ext]; - } - } - if (!empty($add_vars)) { - $http_add_vars = $APP->translate_vars($add_vars); - } - } - if ($table == 'produit_tarif_gamme' && $field['table_fk'] == 'transport_gamme') { - $APP_TMP = new App('produit'); - $arr = $APP_TMP->findOne(['idproduit' => $ARR['idproduit']]); - } - $select = AppSocket::cf_module('app/app_select', ['vars' => $add_vars, - 'table' => $field['table_fk'], - 'table_value' => $ARR[$field['idtable_fk']]], 1235); - - ?> -
-
-
-
- -
-
- -
-
-
- -
-
-
- -
-
-
-
- -
-
-
-
-
-
+HTTP_VARS['table']; + $Table = ucfirst($this->HTTP_VARS['table']); + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $type_session = $_SESSION['type_session']; + $name_idtype_session = "id$type_session"; + + // + $APP = new App($table); + $Idae = new Idae($table); + + $test_custom = Idae::module_exists('app_custom/' . $table . '/' . $table . '_update'); + if (!empty($test_custom)) { + echo $Idae->module('app_custom/' . $table . '/' . $table . '_update', $this->HTTP_VARS); + + return; + } + + $GRILLE_FK = $APP->get_grille_fk(); + // + // + $id = 'id' . $table; + $ARR = $APP->findOne([$id => $table_value]); + + $Idae = new Idae($table); + + $crypted_image_link = AppLink::liste_images($table, $table_value); + + $options = ['apply_droit' => [$type_session, + 'U'], + 'data_mode' => 'fiche', + 'scheme_field_view' => 'native', + 'field_draw_style' => 'draw_html_input', + 'scheme_field_view_groupby' => 'group', + 'fields_scheme_part' => 'all', + 'hide_field_empty' => 0, + 'hide_field_icon' => 0, + 'hide_field_name' => 0, + 'hide_field_value' => 0, + 'field_composition' => ['hide_field_icon' => 0, + 'hide_field_name' => 0, + 'hide_field_value' => 0]]; + + $Fabric = new IdaeDataSchemeFieldDrawerFabric($table, $options); + $Fabric->fetch_data(["id$table" => $table_value]); + $tplData = $Fabric->get_templateData(); +?> +
+
+ module('app_fiche_entete', ['table' => $table, + 'table_value' => $table_value]) ?> +
+
+
+ + + + + + + + +
+
+
+ +
+
+ +
+
+
+ +
+ module('app_update_fk', ['table' => $table, + 'table_value' => $table_value, + 'edit_field' => 1, + 'titre' => 0, + 'show_empty' => 0]) ?> + +
+
+ $field): + $APP_TMP = new App($field['table_fk']); + $GRILLE_FK_TMP = $APP_TMP->get_grille_fk($field['table_fk']); + $id = 'id' . $field['table_fk']; + $arr = $APP_TMP->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); + + if (!empty($vars[$id])) { + continue; + } + + $arr_extends = array_intersect(array_keys($GRILLE_FK), array_keys($GRILLE_FK_TMP)); + $http_add_vars = ''; + $add_vars = []; + if (sizeof($arr_extends) != 0) { + foreach ($arr_extends as $key_ext => $table_ext) { + $idtable_ext = 'id' . $table_ext; + if (!empty($ARR[$idtable_ext])) { + $add_vars[$idtable_ext] = (int)$ARR[$idtable_ext]; + } + } + if (!empty($add_vars)) { + $http_add_vars = $APP->translate_vars($add_vars); + } + } + if ($table == 'produit_tarif_gamme' && $field['table_fk'] == 'transport_gamme') { + $APP_TMP = new App('produit'); + $arr = $APP_TMP->findOne(['idproduit' => $ARR['idproduit']]); + } + $select = AppSocket::cf_module('app/app_select', ['vars' => $add_vars, + 'table' => $field['table_fk'], + 'table_value' => $ARR[$field['idtable_fk']]], 1235); + + ?> +
+
+
+
+ +
+
+ +
+
+
+ +
+
+
+ +
+
+
+
+ +
+
+
+
+
+
diff --git a/web/bin/idae/mdl/app/app_update_fk.php b/web/bin/idae/mdl/app/app_update_fk.php index 18abfac..9b292ed 100644 --- a/web/bin/idae/mdl/app/app_update_fk.php +++ b/web/bin/idae/mdl/app/app_update_fk.php @@ -1,90 +1,90 @@ -table; - $Table = ucfirst($table); - - $table_value = (int)$this->HTTP_VARS['table_value']; - $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); - $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; - $mode = empty($this->HTTP_VARS['mode']) ? 'icone' : $this->HTTP_VARS['mode']; - - $APP = new App($table); - - if (sizeof($APP->get_grille_fk()) == 0) { - return; - } - - $name_id = 'id' . $table; - $ARR = $APP->findOne([$name_id => $table_value]); -?> -
- get_grille_fk() as $field): - $APP_TMP = new App($field['table_fk']); - $GRILLE_FK_TMP = $APP_TMP->get_grille_fk($field['table_fk']); - - $arr_extends = array_intersect(array_keys($APP->get_grille_fk()), array_keys($GRILLE_FK_TMP)); - - // query for name - $table_fk = $field['table_fk']; - $APP_TMP = new App($table_fk); - $arr = $APP->plug($field['base_fk'], $table_fk)->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); - $dsp_code = $arr['code' . ucfirst($table_fk)]; - $dsp_fieldname = 'nom' . ucfirst($table_fk); - $dsp_name = $arr[$dsp_fieldname]; - if (empty($dsp_name)) { - $dsp_name = 'Aucun'; - } - - $html_fiche_link = 'table=' . $APP_TMP->codeAppscheme . '&table_value=' . $ARR[$field['idtable_fk']]; - $data_vars = "table=$table_fk&table_value_from=$table_value&table_from=$table"; - - $arr_allowed_c = droit_table($type_session, 'R', $table_fk); - $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; - $html_attr = ($arr_allowed_c) ? "data-module_link='app_select_line' data-vars='$data_vars'" : ''; - $add_vars = []; - if (sizeof($arr_extends) != 0) { - foreach ($arr_extends as $key_ext => $table_ext) { - $idtable_ext = 'id' . $table_ext; - if (!empty($ARR[$idtable_ext])) { - $add_vars[$idtable_ext] = (int)$ARR[$idtable_ext]; - } - } - if (!empty($add_vars)) { - $http_add_vars = $APP->translate_vars($add_vars); - } - // vardump($arr_extends); - } - - $select = AppSocket::cf_module('app/app_select', ['vars' => $add_vars, - 'table' => $field['table_fk'], - 'table_value' => $ARR[$field['idtable_fk']]], 1235); - $html_attr = "data-module_link='app_select_line' data-vars='$data_vars'" ; - ?> -
-
-
data-module_link="app_select_line" - data-target_flyout="true" - class="flex_h flex_align_middle borderb"> -
-
-
-
- draw_field(['field_name_raw' => 'nom', - 'field_name' => $dsp_fieldname, - 'table' => $table, - 'field_value' => $dsp_name]) ?> -
- -
-
-
-
- +table; + $Table = ucfirst($table); + + $table_value = (int)$this->HTTP_VARS['table_value']; + $vars = empty($this->HTTP_VARS['vars']) ? [] : function_prod::cleanPostMongo($this->HTTP_VARS['vars'], 1); + $groupBy = empty($this->HTTP_VARS['groupBy']) ? '' : $this->HTTP_VARS['groupBy']; + $mode = empty($this->HTTP_VARS['mode']) ? 'icone' : $this->HTTP_VARS['mode']; + + $APP = new App($table); + + if (sizeof($APP->get_grille_fk()) == 0) { + return; + } + + $name_id = 'id' . $table; + $ARR = $APP->findOne([$name_id => $table_value]); +?> +
+ get_grille_fk() as $field): + $APP_TMP = new App($field['table_fk']); + $GRILLE_FK_TMP = $APP_TMP->get_grille_fk($field['table_fk']); + + $arr_extends = array_intersect(array_keys($APP->get_grille_fk()), array_keys($GRILLE_FK_TMP)); + + // query for name + $table_fk = $field['table_fk']; + $APP_TMP = new App($table_fk); + $arr = $APP->plug($field['base_fk'], $table_fk)->findOne([$field['idtable_fk'] => $ARR[$field['idtable_fk']]]); + $dsp_code = $arr['code' . ucfirst($table_fk)]; + $dsp_fieldname = 'nom' . ucfirst($table_fk); + $dsp_name = $arr[$dsp_fieldname]; + if (empty($dsp_name)) { + $dsp_name = 'Aucun'; + } + + $html_fiche_link = 'table=' . $APP_TMP->codeAppscheme . '&table_value=' . $ARR[$field['idtable_fk']]; + $data_vars = "table=$table_fk&table_value_from=$table_value&table_from=$table"; + + $arr_allowed_c = droit_table($type_session, 'R', $table_fk); + $css_cursor = ($arr_allowed_c) ? 'cursor' : ''; + $html_attr = ($arr_allowed_c) ? "data-module_link='app_select_line' data-vars='$data_vars'" : ''; + $add_vars = []; + if (sizeof($arr_extends) != 0) { + foreach ($arr_extends as $key_ext => $table_ext) { + $idtable_ext = 'id' . $table_ext; + if (!empty($ARR[$idtable_ext])) { + $add_vars[$idtable_ext] = (int)$ARR[$idtable_ext]; + } + } + if (!empty($add_vars)) { + $http_add_vars = $APP->translate_vars($add_vars); + } + // vardump($arr_extends); + } + + $select = AppSocket::cf_module('app/app_select', ['vars' => $add_vars, + 'table' => $field['table_fk'], + 'table_value' => $ARR[$field['idtable_fk']]], 1235); + $html_attr = "data-module_link='app_select_line' data-vars='$data_vars'" ; + ?> +
+
+
data-module_link="app_select_line" + data-target_flyout="true" + class="flex_h flex_align_middle borderb"> +
+
+
+
+ draw_field(['field_name_raw' => 'nom', + 'field_name' => $dsp_fieldname, + 'table' => $table, + 'field_value' => $dsp_name]) ?> +
+ +
+
+
+
+
\ No newline at end of file diff --git a/web/bin/node/app_https/app_https_main.js b/web/bin/node/app_https/app_https_main.js index 6d52f91..6085267 100644 --- a/web/bin/node/app_https/app_https_main.js +++ b/web/bin/node/app_https/app_https_main.js @@ -1,12 +1,12 @@ -/// 3007 preproduction -/// 3008 production - -var port = ('/var/www/tac-tac.shop.mydde.fr/web/bin/node/app_https' == __dirname) ? '3007' : '3008'; - -var appsocket = require('./app_https_socket.js'); -var cron = require('./app_cron.js'); - -console.log(port); - -appsocket.socket_start(port); - +/// 3007 preproduction +/// 3008 production + +var port = ('/var/www/tac-tac.shop.mydde.fr/web/bin/node/app_https' == __dirname) ? '3007' : '3008'; + +var appsocket = require('./app_https_socket.js'); +var cron = require('./app_cron.js'); + +console.log(port); + +appsocket.socket_start(port); + diff --git a/web/bin/node/app_https/app_https_middleware.js b/web/bin/node/app_https/app_https_middleware.js index d9f32ee..9c41c8f 100644 --- a/web/bin/node/app_https/app_https_middleware.js +++ b/web/bin/node/app_https/app_https_middleware.js @@ -1,167 +1,167 @@ -/** - * Created by Mydde on 28/09/2016. - */ - - - var http = require('http') - , connect = require('connect') - , fs = require('fs') - , qs = require('qs') - , url = require('url') - , request = require('request') ; - -// var io; - -function http_handler(req, res) { - // - console.log('http_handler : '); - - if (req.url === '/favicon.ico') { - res.writeHead(200, {'Content-Type': 'image/x-icon'} ); - res.end(); - return; - } - var path = url.parse(req.url).pathname; - - switch (path){ - case '/postScope': - // DOCUMENTDOMAIN - var fullBody = ''; - req.on('data', function(chunk) { - fullBody += chunk.toString(); - if (fullBody.length > 1e6) { - req.connection.destroy(); - } - }); - req.on('end', function() { - data = qs.parse(fullBody); - // - reloadVars={scope:data.scope,value:data.value} - if(data.vars) reloadVars.vars = qs.stringify(data.vars) - if(data.scope && data.value){ - io.sockets.emit('reloadScope',reloadVars); - } - res.writeHead(200, {'Content-Type': 'text/html'}) - res.end(); - }); - break; - case "/run": - var fullBody = ''; - req.on('data', function(chunk) { - fullBody += chunk.toString(); - if (fullBody.length > 1e6) { - req.connection.destroy(); - } - }); - req.on('end', function() { - data = qs.parse(fullBody); - - data.vars = data.vars || '' - data.options = data.options || {} - data.vars.defer = ''; - SESSID = data.SESSID || ''; - PHPSESSID = data.PHPSESSID || 'none'; - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN; - // - var url = 'http://'+DOCUMENTDOMAIN+'/'+data.mdl+'.php' - - request.post({ - url : url , - method: 'POST', - headers:{'Cookie':'PHPSESSID='+PHPSESSID+'; path=/','content-type': 'application/x-www-form-urlencoded'}, - body: qs.stringify(data.vars) - },function(err,res,body){ - // console.log('run ',body); - }); - }) - - break; - case '/runModule': - var fullBody = ''; - req.on('data', function(chunk) { - fullBody += chunk.toString(); - if (fullBody.length > 1e6) { - req.connection.destroy(); - } - }); - req.on('end', function() { - data = qs.parse(fullBody); - // - vars = data.vars || ''; - title = data.title || ''; - mdl = data.mdl || ''; - SESSID = data.SESSID || ''; - PHPSESSID = data.PHPSESSID || ''; - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; - // - request.post({ - uri:'http://'+DOCUMENTDOMAIN+'/mdl/'+data.mdl+'.php', - headers:{'Cookie':'PHPSESSID='+PHPSESSID+'; path=/','content-type': 'application/x-www-form-urlencoded'}, - body: qs.stringify(vars) - },function(err,res,body){ - console.log('rumModule',mdl,body); - io.sockets.emit('act_run',{body:body}) - - }); - res.writeHead(200, {'Content-Type': 'text/html'}) - res.end(); - }); - - - break; - case '/postReload': // => middleware ici - // DOCUMENTDOMAIN - var fullBody = ''; - - req.on('data', function(chunk) { - fullBody += chunk.toString(); - // console.log(fullBody,fullBody.length,1e6) - if (fullBody.length > 1e6) { - console.log('destroy ',fullBody.length) - req.connection.destroy(); - } - }); - req.on('end', function() { - - - var data = qs.parse(fullBody); - - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end(); - // - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || ''; - reloadVars={module:data.module,value:data.value || ''}; - // - - console.log( 'Type postReload ', typeof(data.vars)); - - if(data.cmd && data.vars){ - if(data.OWN){ - io.sockets.to(data.OWN).emit('receive_cmd',data); - }else{ - io.sockets.to(DOCUMENTDOMAIN).emit('receive_cmd',data); - } - } - if(data.vars){ - if(typeof(data.vars)=='object') reloadVars.vars = qs.stringify(data.vars) - } - if(data.module && data.value){ - io.sockets.emit('reloadModule',reloadVars); - } - }); - break; - } -} - - -module.exports = function(ioobj){ - console.log('middle !!! ') - middleware_start = function (ioobj) { - // - console.log('middleware starts') - var io = ioobj; - var http = require('http').createServer(http_handler); - return http; - } - -} +/** + * Created by Mydde on 28/09/2016. + */ + + + var http = require('http') + , connect = require('connect') + , fs = require('fs') + , qs = require('qs') + , url = require('url') + , request = require('request') ; + +// var io; + +function http_handler(req, res) { + // + console.log('http_handler : '); + + if (req.url === '/favicon.ico') { + res.writeHead(200, {'Content-Type': 'image/x-icon'} ); + res.end(); + return; + } + var path = url.parse(req.url).pathname; + + switch (path){ + case '/postScope': + // DOCUMENTDOMAIN + var fullBody = ''; + req.on('data', function(chunk) { + fullBody += chunk.toString(); + if (fullBody.length > 1e6) { + req.connection.destroy(); + } + }); + req.on('end', function() { + data = qs.parse(fullBody); + // + reloadVars={scope:data.scope,value:data.value} + if(data.vars) reloadVars.vars = qs.stringify(data.vars) + if(data.scope && data.value){ + io.sockets.emit('reloadScope',reloadVars); + } + res.writeHead(200, {'Content-Type': 'text/html'}) + res.end(); + }); + break; + case "/run": + var fullBody = ''; + req.on('data', function(chunk) { + fullBody += chunk.toString(); + if (fullBody.length > 1e6) { + req.connection.destroy(); + } + }); + req.on('end', function() { + data = qs.parse(fullBody); + + data.vars = data.vars || '' + data.options = data.options || {} + data.vars.defer = ''; + SESSID = data.SESSID || ''; + PHPSESSID = data.PHPSESSID || 'none'; + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN; + // + var url = 'http://'+DOCUMENTDOMAIN+'/'+data.mdl+'.php' + + request.post({ + url : url , + method: 'POST', + headers:{'Cookie':'PHPSESSID='+PHPSESSID+'; path=/','content-type': 'application/x-www-form-urlencoded'}, + body: qs.stringify(data.vars) + },function(err,res,body){ + // console.log('run ',body); + }); + }) + + break; + case '/runModule': + var fullBody = ''; + req.on('data', function(chunk) { + fullBody += chunk.toString(); + if (fullBody.length > 1e6) { + req.connection.destroy(); + } + }); + req.on('end', function() { + data = qs.parse(fullBody); + // + vars = data.vars || ''; + title = data.title || ''; + mdl = data.mdl || ''; + SESSID = data.SESSID || ''; + PHPSESSID = data.PHPSESSID || ''; + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; + // + request.post({ + uri:'http://'+DOCUMENTDOMAIN+'/mdl/'+data.mdl+'.php', + headers:{'Cookie':'PHPSESSID='+PHPSESSID+'; path=/','content-type': 'application/x-www-form-urlencoded'}, + body: qs.stringify(vars) + },function(err,res,body){ + console.log('rumModule',mdl,body); + io.sockets.emit('act_run',{body:body}) + + }); + res.writeHead(200, {'Content-Type': 'text/html'}) + res.end(); + }); + + + break; + case '/postReload': // => middleware ici + // DOCUMENTDOMAIN + var fullBody = ''; + + req.on('data', function(chunk) { + fullBody += chunk.toString(); + // console.log(fullBody,fullBody.length,1e6) + if (fullBody.length > 1e6) { + console.log('destroy ',fullBody.length) + req.connection.destroy(); + } + }); + req.on('end', function() { + + + var data = qs.parse(fullBody); + + res.writeHead(200, {'Content-Type': 'text/html'}); + res.end(); + // + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || ''; + reloadVars={module:data.module,value:data.value || ''}; + // + + console.log( 'Type postReload ', typeof(data.vars)); + + if(data.cmd && data.vars){ + if(data.OWN){ + io.sockets.to(data.OWN).emit('receive_cmd',data); + }else{ + io.sockets.to(DOCUMENTDOMAIN).emit('receive_cmd',data); + } + } + if(data.vars){ + if(typeof(data.vars)=='object') reloadVars.vars = qs.stringify(data.vars) + } + if(data.module && data.value){ + io.sockets.emit('reloadModule',reloadVars); + } + }); + break; + } +} + + +module.exports = function(ioobj){ + console.log('middle !!! ') + middleware_start = function (ioobj) { + // + console.log('middleware starts') + var io = ioobj; + var http = require('http').createServer(http_handler); + return http; + } + +} diff --git a/web/bin/node/app_https/app_https_socket.js b/web/bin/node/app_https/app_https_socket.js index d7e893b..0259af9 100644 --- a/web/bin/node/app_https/app_https_socket.js +++ b/web/bin/node/app_https/app_https_socket.js @@ -1,533 +1,533 @@ -/** - * Created by lebru_000 on 25/12/14. - */ - -process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0; -NODE_TLS_REJECT_UNAUTHORIZED = 0; - -var fs = require('fs'); -var mongo_url; - -if ('/var/www/tac-tac.shop.mydde.fr/web/bin/node/app_https' == __dirname) { - - var ssl_opt = { - key: fs.readFileSync('/etc/letsencrypt/live/tac-tac.shop.mydde.fr/privkey.pem'), - cert: fs.readFileSync('/etc/letsencrypt/live/tac-tac.shop.mydde.fr/fullchain.pem'), - ca: fs.readFileSync('/etc/letsencrypt/live/tac-tac.shop.mydde.fr/chain.pem'), - ciphers: 'ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM', - honorCipherOrder: true, - requestCert: true, - rejectUnauthorized: false - } -} else if ('/var/www/www.tac-tac-city.fr/web/bin/node/app_https' == __dirname) { - var ssl_opt = { - key: fs.readFileSync('/etc/letsencrypt/live/www.tac-tac-city.fr/privkey.pem'), - cert: fs.readFileSync('/etc/letsencrypt/live/www.tac-tac-city.fr/fullchain.pem'), - ca: fs.readFileSync('/etc/letsencrypt/live/www.tac-tac-city.fr/chain.pem'), - ciphers: 'ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM', - honorCipherOrder: true, - requestCert: true, - rejectUnauthorized: false - } - -} - -var https = require('https'); -var http = require('http'); -var app = http.createServer(http_handler); -var io = require('socket.io')(app); -var url = require('url'); -var qs = require('qs'); -var request = require('request'); -var cookieParser = require('socket.io-cookie'); -var mongoClient = require('mongodb').MongoClient; - -var socket_array = {}; - - -build_header = function (data) { - - if (!data.DOCUMENTDOMAIN) { - return ''; - } - data.vars = data.vars || ''; - var SESSID = data.SESSID || '', - PHPSESSID = data.PHPSESSID || '', - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'appgem.destinationsreve.com'; - - var headers = { - 'Cookie': 'PHPSESSID=' + PHPSESSID + '; path=/', - 'content-type': 'application/x-www-form-urlencoded' - }; - - return headers; -}; -build_vars = function (data) { - if (!data.DOCUMENTDOMAIN) { - return ''; - } - data.vars = data.vars || ''; - - return data.vars; -}; - -function http_handler(req, res) { - - var arr_delay = []; - if (!req.url) { - return; - } - - if (req.url === '/favicon.ico') { - res.writeHead(200, {'Content-Type': 'image/x-icon'}); - res.end(); - return; - } - var path = url.parse(req.url).pathname; - - // - var fullBody = ''; - - req.on('data', function (chunk) { - fullBody += chunk.toString(); - if (fullBody.length > 1e6) { - req.connection.destroy(); - } - }); - - // - switch (path) { - case '/postScope': - - req.on('end', function () { - data = qs.parse(fullBody); - // - reloadVars = {scope: data.scope, value: data.value}; - if (data.vars) { - reloadVars.vars = qs.stringify(data.vars); - } - if (data.scope && data.value) { - io.sockets.emit('reloadScope', reloadVars); - } - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end(); - }); - break; - case "/run": - - req.on('end', function () { - var reqbody = qs.parse(fullBody); - - var vars = reqbody.vars || ''; - var options = vars.vars || {}, - route = vars.route || '', - delay = vars.delay || 0, - delay_name = vars.delay_name || false, - method = vars.method || 'POST'; - - var SESSID = reqbody.SESSID || '', - PHPSESSID = reqbody.PHPSESSID || 'none', - DOCUMENTDOMAIN = reqbody.DOCUMENTDOMAIN; - // - var url = 'https://' + DOCUMENTDOMAIN + '/' + route; - - var post_params = { - url: url, - method: method, - headers: build_header(reqbody), - body: qs.stringify(options) - }; - - if (vars.delay_name && arr_delay[vars.delay_name]) { - arr_delay[vars.delay_name] = true; - clearTimeout(arr_delay[vars.delay_name]); - arr_delay[vars.delay_name] = setTimeout(function () { - request.post(post_params, function (err, res, body) { - if (vars.delay_name && arr_delay[vars.delay_name]) { - clearTimeout(arr_delay[vars.delay_name]); - } - }); - }, delay); - - } else { - setTimeout(function () { - request.post(post_params, function (err, res, body) { - if (vars.delay_name && arr_delay[vars.delay_name]) { - delete arr_delay[vars.delay_name]; - } - }); - - }, delay); - } - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end(); - }); - - break; - case '/runModule': - - req.on('end', function () { - data = qs.parse(fullBody); - // - vars = data.vars || ''; - title = data.title || ''; - mdl = data.mdl || ''; - SESSID = data.SESSID || ''; - PHPSESSID = data.PHPSESSID || ''; - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; - // - request.post({ - uri: 'http://' + DOCUMENTDOMAIN + '/mdl/' + data.mdl + '.php', - headers: { - 'Cookie': 'PHPSESSID=' + PHPSESSID + '; path=/', - 'content-type': 'application/x-www-form-urlencoded' - }, - body: qs.stringify(vars) - }, function (err, res, body) { - // console.log('rumModule', mdl, body); - io.sockets.in(DOCUMENTDOMAIN).emit('act_run', {body: body}) - - }); - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end(); - }); - - break; - case '/postGrantIn': - req.on('end', function () { - var data = qs.parse(fullBody); - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end(); - - if (data.vars && data.vars.room) { - var ids = Object.keys(io.sockets.connected); - // console.log (io.sockets.connected); - ids.forEach(function (id) { - var socket_da = io.sockets.connected[id]; - if (socket_da['PHPSESSID'] == data.PHPSESSID) { - socket_da.join(data.vars.room); - if (data.DOCUMENTDOMAIN) { - socket_da.join(data.DOCUMENTDOMAIN); - } - } - - }); - - } - - }); - break; - case '/postReload': // => middleware, most happen here - - req.on('end', function () { - var data = qs.parse(fullBody); - //console.log('postReload',data) - res.writeHead(200, {'Content-Type': 'text/html'}); - res.end(); - - // - var DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || '', - reloadVars = {module: data.module, value: data.value || ''}; - // - - if (data.cmd && data.vars) { - if (data.OWN) { - // console.log('postReload', DOCUMENTDOMAIN, data.OWN, typeof(data.OWN)) - switch (typeof(data.OWN)) { - case 'string': - io.sockets.to(data.OWN).emit('receive_cmd', data); - break; - case 'object': - data.OWN.forEach(function (item, index) { - io.sockets.to(item).emit('receive_cmd', data); - }); - break; - } - } else { - //console.log ('reload to DOCUMENTDOMAIN ', DOCUMENTDOMAIN); - - io.sockets.to(DOCUMENTDOMAIN).emit('receive_cmd', data); - } - } - if (data.vars) { - if (typeof(data.vars) == 'object') { - reloadVars.vars = qs.stringify(data.vars) - } - } - if (data.module && data.value) { - io.sockets.emit('reloadModule', reloadVars); - } - }); - break; - } -} - -function init_app() { - io.use(cookieParser); - io.use(authorization); - socket_onconnection(); -} -// -function authorization(socket, next) { - // console.log('auth', socket.handshake.headers); - if (socket.request.headers.cookie) { - var cookie = socket.request.headers.cookie; - // PHPSESSID TEST - if (!cookie.PHPSESSID) { - next(new Error('not authorized')); //; - return false; - } - - socket.PHPSESSID = cookie.PHPSESSID; - socket.join(socket.PHPSESSID); - next(); - authorization_ok(socket); - } else { - { - if (socket.handshake) { - // console.log('Echec .request', socket.request.headers); - } - next(new Error('not authorized')); - return false; - } - } -} - - -declare_db = function (host) { - - if (host == null) { - return false; - } - switch (host) { - case 'http://idaertys.mydde.fr': - prefix = 'idaenext'; - break; - case 'http://idaertys-preprod.mydde.fr': - prefix = 'idaenext'; - break; - case 'http://tactac_idae.preprod.mydde.fr': - prefix = 'tactac'; - break; - case 'https://tac-tac.shop.mydde.fr': - prefix = 'tactac'; - break; - case 'https://tac-tac.city.fr': - prefix = 'tactac'; - break; - case 'https://tac-tac.lan': - prefix = 'tactac'; - break; - } -}; - -authorization_ok = function (socket) { - declare_db(socket.request.headers.origin); - socket.emit('ask_grantIn'); -}; - - -function socket_onconnection() { - - console.log('socket is listening') - io.on('connection', function (socket) { - - if (socket.PHPSESSID) { - socket.join(socket.PHPSESSID); - } - - // HEARTBEAT - var sender = setInterval(function () { - socket.emit('heartbeat_app', [new Date().getTime(), socket.PHPSESSID]); - }, 15000); - - socket.on('disconnect', function (data) { - - }); - // - socket.on('grantIn', function (data, fn) { - var sess = {}; - sess.sessionId = socket.id; - sess.DOCUMENTDOMAIN = data.DOCUMENTDOMAIN; - sess.SESSID = data.SESSID; - sess.PHPSESSID = data.PHPSESSID; - // sess.SSSAVEPATH = data.SSSAVEPATH; - // - if (data.DOCUMENTDOMAIN) { - socket.join(data.DOCUMENTDOMAIN); - } - if (data.ROOM) { - socket.join(data.ROOM); - } - if (socket_array) { - // socket_array[socket.id] = sess; - } - // - io.sockets.to(data.DOCUMENTDOMAIN).send('user connected'); - // socket.broadcast.send('user connected'); - if (data.SESSID) { - if (fn) { - fn(true); - } - } - }); - // - socket.on('message', function (message) { - // console.log(message) // socket.send('cool'); - }); - socket.on('reloadModule', function (data) { - socket.broadcast.emit('reloadModule', data); - }); - socket.on('reloadScope', function (data) { - // console.log(data); - if (!data) { - return; - } - if (!data.scope) { - return; - } - reloadVars = {scope: data.scope, value: data.value}; - if (data.vars) { - reloadVars.vars = qs.stringify(data.vars); - } - if (data.scope && data.value) { - io.sockets.emit('reloadScope', reloadVars); - } - }); - // loadModule - socket.on('loadModule', function (data, func) { - var fn = func || null, - vars = data.vars || '', - title = data.title || '', - mdl = data.mdl || '', - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; - - if (DOCUMENTDOMAIN) { - socket.join(DOCUMENTDOMAIN) - } else { - return false; - } - - request.post({ - uri: 'http://' + DOCUMENTDOMAIN + '/mdl/' + data.mdl + '.php', - headers: build_header(data), - body: qs.stringify(vars) - }, function (err, res, body) { - socket.to(DOCUMENTDOMAIN).emit('loadModule', {body: body, vars: vars, mdl: mdl, title: title}) - }); - }); - - socket.on('socketModule', function (data, fun) { - var fn = fun || null; - - data.vars = data.vars || ''; - data.options = data.options || {}; - data.vars.defer = ''; - - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'appgem.destinationsreve.com'; - // - if (DOCUMENTDOMAIN) { - socket.join(DOCUMENTDOMAIN); - } - // - var url = 'http://' + DOCUMENTDOMAIN + '/mdl/' + data.file + '.php'; - - request.post({ - url: url, - method: 'POST', - headers: build_header(data), - body: data.vars - }, function (err, res, body) { - socket.to(DOCUMENTDOMAIN).emit('socketModule', {body: body, out: data}); - if (fn) { - fn({body: body, data: data}); - } - }); - }); - socket.on('upd_data', function (data) { - vars = data.vars || ''; - title = data.title || ''; - mdl = data.mdl || ''; - - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; - // - request.post({ - uri: 'http://' + DOCUMENTDOMAIN + '/services/json_data_table_row.php', - headers: build_header(data), - body: qs.stringify(vars) - }, function (err, res, body) { - io.sockets.in(DOCUMENTDOMAIN).emit('upd_data', {body: body, vars: vars, mdl: mdl, title: title}); - // socket.emit('upd_data',{body:body,vars:vars,mdl:mdl,title:title}) - }); - }); - - socket.on('get_data', function (data, options, fn) { - var vars = data.vars || '', - options = options || {}, - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; - - var directory = (data.directory) ? data.directory : 'bin/services'; - var extension = (data.extension) ? data.extension : 'php'; - // - var url = 'http://' + DOCUMENTDOMAIN + '/' + directory + '/' + data.mdl + '.' + extension; - - - if (socket.PHPSESSID !== undefined) { - request.get({ - url: url, - method: 'GET', - headers: build_header(data), - qs: vars - }, function (err, res, body) { - fn(body, options) - }); - } - }); - - var runningRunModule = {}; - - socket.on('runModule', function (data) { - - data.vars = data.vars || ''; - data.options = data.options || {}; - data.vars.defer = ''; - var SESSID = data.SESSID || '', - DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'appgem.destinationsreve.com'; - - var url = 'http://' + DOCUMENTDOMAIN + '/' + data.file + '.php'; - - key = SESSID + data.file + data.vars; - - request.post({ - url: url, - method: 'POST', - headers: build_header(data), - body: data.vars - }, function (err, res, body) { - - }); - - }); - }) - -} - -module.exports = { - - init_app: function (port) { - - }, - socket_start: function (port) { - // - console.log('socket started on port ' + port); - - app.listen(port); - init_app(); - - }, - io: io, - bar: function () { - // whatever - } - +/** + * Created by lebru_000 on 25/12/14. + */ + +process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0; +NODE_TLS_REJECT_UNAUTHORIZED = 0; + +var fs = require('fs'); +var mongo_url; + +if ('/var/www/tac-tac.shop.mydde.fr/web/bin/node/app_https' == __dirname) { + + var ssl_opt = { + key: fs.readFileSync('/etc/letsencrypt/live/tac-tac.shop.mydde.fr/privkey.pem'), + cert: fs.readFileSync('/etc/letsencrypt/live/tac-tac.shop.mydde.fr/fullchain.pem'), + ca: fs.readFileSync('/etc/letsencrypt/live/tac-tac.shop.mydde.fr/chain.pem'), + ciphers: 'ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM', + honorCipherOrder: true, + requestCert: true, + rejectUnauthorized: false + } +} else if ('/var/www/www.tac-tac-city.fr/web/bin/node/app_https' == __dirname) { + var ssl_opt = { + key: fs.readFileSync('/etc/letsencrypt/live/www.tac-tac-city.fr/privkey.pem'), + cert: fs.readFileSync('/etc/letsencrypt/live/www.tac-tac-city.fr/fullchain.pem'), + ca: fs.readFileSync('/etc/letsencrypt/live/www.tac-tac-city.fr/chain.pem'), + ciphers: 'ECDHE-RSA-AES256-SHA:AES256-SHA:RC4-SHA:RC4:HIGH:!MD5:!aNULL:!EDH:!AESGCM', + honorCipherOrder: true, + requestCert: true, + rejectUnauthorized: false + } + +} + +var https = require('https'); +var http = require('http'); +var app = http.createServer(http_handler); +var io = require('socket.io')(app); +var url = require('url'); +var qs = require('qs'); +var request = require('request'); +var cookieParser = require('socket.io-cookie'); +var mongoClient = require('mongodb').MongoClient; + +var socket_array = {}; + + +build_header = function (data) { + + if (!data.DOCUMENTDOMAIN) { + return ''; + } + data.vars = data.vars || ''; + var SESSID = data.SESSID || '', + PHPSESSID = data.PHPSESSID || '', + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'appgem.destinationsreve.com'; + + var headers = { + 'Cookie': 'PHPSESSID=' + PHPSESSID + '; path=/', + 'content-type': 'application/x-www-form-urlencoded' + }; + + return headers; +}; +build_vars = function (data) { + if (!data.DOCUMENTDOMAIN) { + return ''; + } + data.vars = data.vars || ''; + + return data.vars; +}; + +function http_handler(req, res) { + + var arr_delay = []; + if (!req.url) { + return; + } + + if (req.url === '/favicon.ico') { + res.writeHead(200, {'Content-Type': 'image/x-icon'}); + res.end(); + return; + } + var path = url.parse(req.url).pathname; + + // + var fullBody = ''; + + req.on('data', function (chunk) { + fullBody += chunk.toString(); + if (fullBody.length > 1e6) { + req.connection.destroy(); + } + }); + + // + switch (path) { + case '/postScope': + + req.on('end', function () { + data = qs.parse(fullBody); + // + reloadVars = {scope: data.scope, value: data.value}; + if (data.vars) { + reloadVars.vars = qs.stringify(data.vars); + } + if (data.scope && data.value) { + io.sockets.emit('reloadScope', reloadVars); + } + res.writeHead(200, {'Content-Type': 'text/html'}); + res.end(); + }); + break; + case "/run": + + req.on('end', function () { + var reqbody = qs.parse(fullBody); + + var vars = reqbody.vars || ''; + var options = vars.vars || {}, + route = vars.route || '', + delay = vars.delay || 0, + delay_name = vars.delay_name || false, + method = vars.method || 'POST'; + + var SESSID = reqbody.SESSID || '', + PHPSESSID = reqbody.PHPSESSID || 'none', + DOCUMENTDOMAIN = reqbody.DOCUMENTDOMAIN; + // + var url = 'https://' + DOCUMENTDOMAIN + '/' + route; + + var post_params = { + url: url, + method: method, + headers: build_header(reqbody), + body: qs.stringify(options) + }; + + if (vars.delay_name && arr_delay[vars.delay_name]) { + arr_delay[vars.delay_name] = true; + clearTimeout(arr_delay[vars.delay_name]); + arr_delay[vars.delay_name] = setTimeout(function () { + request.post(post_params, function (err, res, body) { + if (vars.delay_name && arr_delay[vars.delay_name]) { + clearTimeout(arr_delay[vars.delay_name]); + } + }); + }, delay); + + } else { + setTimeout(function () { + request.post(post_params, function (err, res, body) { + if (vars.delay_name && arr_delay[vars.delay_name]) { + delete arr_delay[vars.delay_name]; + } + }); + + }, delay); + } + res.writeHead(200, {'Content-Type': 'text/html'}); + res.end(); + }); + + break; + case '/runModule': + + req.on('end', function () { + data = qs.parse(fullBody); + // + vars = data.vars || ''; + title = data.title || ''; + mdl = data.mdl || ''; + SESSID = data.SESSID || ''; + PHPSESSID = data.PHPSESSID || ''; + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; + // + request.post({ + uri: 'http://' + DOCUMENTDOMAIN + '/mdl/' + data.mdl + '.php', + headers: { + 'Cookie': 'PHPSESSID=' + PHPSESSID + '; path=/', + 'content-type': 'application/x-www-form-urlencoded' + }, + body: qs.stringify(vars) + }, function (err, res, body) { + // console.log('rumModule', mdl, body); + io.sockets.in(DOCUMENTDOMAIN).emit('act_run', {body: body}) + + }); + res.writeHead(200, {'Content-Type': 'text/html'}); + res.end(); + }); + + break; + case '/postGrantIn': + req.on('end', function () { + var data = qs.parse(fullBody); + res.writeHead(200, {'Content-Type': 'text/html'}); + res.end(); + + if (data.vars && data.vars.room) { + var ids = Object.keys(io.sockets.connected); + // console.log (io.sockets.connected); + ids.forEach(function (id) { + var socket_da = io.sockets.connected[id]; + if (socket_da['PHPSESSID'] == data.PHPSESSID) { + socket_da.join(data.vars.room); + if (data.DOCUMENTDOMAIN) { + socket_da.join(data.DOCUMENTDOMAIN); + } + } + + }); + + } + + }); + break; + case '/postReload': // => middleware, most happen here + + req.on('end', function () { + var data = qs.parse(fullBody); + //console.log('postReload',data) + res.writeHead(200, {'Content-Type': 'text/html'}); + res.end(); + + // + var DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || '', + reloadVars = {module: data.module, value: data.value || ''}; + // + + if (data.cmd && data.vars) { + if (data.OWN) { + // console.log('postReload', DOCUMENTDOMAIN, data.OWN, typeof(data.OWN)) + switch (typeof(data.OWN)) { + case 'string': + io.sockets.to(data.OWN).emit('receive_cmd', data); + break; + case 'object': + data.OWN.forEach(function (item, index) { + io.sockets.to(item).emit('receive_cmd', data); + }); + break; + } + } else { + //console.log ('reload to DOCUMENTDOMAIN ', DOCUMENTDOMAIN); + + io.sockets.to(DOCUMENTDOMAIN).emit('receive_cmd', data); + } + } + if (data.vars) { + if (typeof(data.vars) == 'object') { + reloadVars.vars = qs.stringify(data.vars) + } + } + if (data.module && data.value) { + io.sockets.emit('reloadModule', reloadVars); + } + }); + break; + } +} + +function init_app() { + io.use(cookieParser); + io.use(authorization); + socket_onconnection(); +} +// +function authorization(socket, next) { + // console.log('auth', socket.handshake.headers); + if (socket.request.headers.cookie) { + var cookie = socket.request.headers.cookie; + // PHPSESSID TEST + if (!cookie.PHPSESSID) { + next(new Error('not authorized')); //; + return false; + } + + socket.PHPSESSID = cookie.PHPSESSID; + socket.join(socket.PHPSESSID); + next(); + authorization_ok(socket); + } else { + { + if (socket.handshake) { + // console.log('Echec .request', socket.request.headers); + } + next(new Error('not authorized')); + return false; + } + } +} + + +declare_db = function (host) { + + if (host == null) { + return false; + } + switch (host) { + case 'http://idaertys.mydde.fr': + prefix = 'idaenext'; + break; + case 'http://idaertys-preprod.mydde.fr': + prefix = 'idaenext'; + break; + case 'http://tactac_idae.preprod.mydde.fr': + prefix = 'tactac'; + break; + case 'https://tac-tac.shop.mydde.fr': + prefix = 'tactac'; + break; + case 'https://tac-tac.city.fr': + prefix = 'tactac'; + break; + case 'https://tac-tac.lan': + prefix = 'tactac'; + break; + } +}; + +authorization_ok = function (socket) { + declare_db(socket.request.headers.origin); + socket.emit('ask_grantIn'); +}; + + +function socket_onconnection() { + + console.log('socket is listening') + io.on('connection', function (socket) { + + if (socket.PHPSESSID) { + socket.join(socket.PHPSESSID); + } + + // HEARTBEAT + var sender = setInterval(function () { + socket.emit('heartbeat_app', [new Date().getTime(), socket.PHPSESSID]); + }, 15000); + + socket.on('disconnect', function (data) { + + }); + // + socket.on('grantIn', function (data, fn) { + var sess = {}; + sess.sessionId = socket.id; + sess.DOCUMENTDOMAIN = data.DOCUMENTDOMAIN; + sess.SESSID = data.SESSID; + sess.PHPSESSID = data.PHPSESSID; + // sess.SSSAVEPATH = data.SSSAVEPATH; + // + if (data.DOCUMENTDOMAIN) { + socket.join(data.DOCUMENTDOMAIN); + } + if (data.ROOM) { + socket.join(data.ROOM); + } + if (socket_array) { + // socket_array[socket.id] = sess; + } + // + io.sockets.to(data.DOCUMENTDOMAIN).send('user connected'); + // socket.broadcast.send('user connected'); + if (data.SESSID) { + if (fn) { + fn(true); + } + } + }); + // + socket.on('message', function (message) { + // console.log(message) // socket.send('cool'); + }); + socket.on('reloadModule', function (data) { + socket.broadcast.emit('reloadModule', data); + }); + socket.on('reloadScope', function (data) { + // console.log(data); + if (!data) { + return; + } + if (!data.scope) { + return; + } + reloadVars = {scope: data.scope, value: data.value}; + if (data.vars) { + reloadVars.vars = qs.stringify(data.vars); + } + if (data.scope && data.value) { + io.sockets.emit('reloadScope', reloadVars); + } + }); + // loadModule + socket.on('loadModule', function (data, func) { + var fn = func || null, + vars = data.vars || '', + title = data.title || '', + mdl = data.mdl || '', + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; + + if (DOCUMENTDOMAIN) { + socket.join(DOCUMENTDOMAIN) + } else { + return false; + } + + request.post({ + uri: 'http://' + DOCUMENTDOMAIN + '/mdl/' + data.mdl + '.php', + headers: build_header(data), + body: qs.stringify(vars) + }, function (err, res, body) { + socket.to(DOCUMENTDOMAIN).emit('loadModule', {body: body, vars: vars, mdl: mdl, title: title}) + }); + }); + + socket.on('socketModule', function (data, fun) { + var fn = fun || null; + + data.vars = data.vars || ''; + data.options = data.options || {}; + data.vars.defer = ''; + + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'appgem.destinationsreve.com'; + // + if (DOCUMENTDOMAIN) { + socket.join(DOCUMENTDOMAIN); + } + // + var url = 'http://' + DOCUMENTDOMAIN + '/mdl/' + data.file + '.php'; + + request.post({ + url: url, + method: 'POST', + headers: build_header(data), + body: data.vars + }, function (err, res, body) { + socket.to(DOCUMENTDOMAIN).emit('socketModule', {body: body, out: data}); + if (fn) { + fn({body: body, data: data}); + } + }); + }); + socket.on('upd_data', function (data) { + vars = data.vars || ''; + title = data.title || ''; + mdl = data.mdl || ''; + + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; + // + request.post({ + uri: 'http://' + DOCUMENTDOMAIN + '/services/json_data_table_row.php', + headers: build_header(data), + body: qs.stringify(vars) + }, function (err, res, body) { + io.sockets.in(DOCUMENTDOMAIN).emit('upd_data', {body: body, vars: vars, mdl: mdl, title: title}); + // socket.emit('upd_data',{body:body,vars:vars,mdl:mdl,title:title}) + }); + }); + + socket.on('get_data', function (data, options, fn) { + var vars = data.vars || '', + options = options || {}, + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'app.destinationsreve.com'; + + var directory = (data.directory) ? data.directory : 'bin/services'; + var extension = (data.extension) ? data.extension : 'php'; + // + var url = 'http://' + DOCUMENTDOMAIN + '/' + directory + '/' + data.mdl + '.' + extension; + + + if (socket.PHPSESSID !== undefined) { + request.get({ + url: url, + method: 'GET', + headers: build_header(data), + qs: vars + }, function (err, res, body) { + fn(body, options) + }); + } + }); + + var runningRunModule = {}; + + socket.on('runModule', function (data) { + + data.vars = data.vars || ''; + data.options = data.options || {}; + data.vars.defer = ''; + var SESSID = data.SESSID || '', + DOCUMENTDOMAIN = data.DOCUMENTDOMAIN || 'appgem.destinationsreve.com'; + + var url = 'http://' + DOCUMENTDOMAIN + '/' + data.file + '.php'; + + key = SESSID + data.file + data.vars; + + request.post({ + url: url, + method: 'POST', + headers: build_header(data), + body: data.vars + }, function (err, res, body) { + + }); + + }); + }) + +} + +module.exports = { + + init_app: function (port) { + + }, + socket_start: function (port) { + // + console.log('socket started on port ' + port); + + app.listen(port); + init_app(); + + }, + io: io, + bar: function () { + // whatever + } + }; \ No newline at end of file diff --git a/web/bin/node/app_https/daemon/tactacmainservice.err.log b/web/bin/node/app_https/daemon/tactacmainservice.err.log index 495f137..dcc48ca 100644 --- a/web/bin/node/app_https/daemon/tactacmainservice.err.log +++ b/web/bin/node/app_https/daemon/tactacmainservice.err.log @@ -1,59 +1,59 @@ -module.js:487 - throw err; - ^ - -Error: Cannot find module 'socket.io' - at Function.Module._resolveFilename (module.js:485:15) - at Function.Module._load (module.js:437:25) - at Module.require (module.js:513:17) - at require (internal/module.js:11:18) - at Object. (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_socket.js:38:20) - at Module._compile (module.js:569:30) - at Object.Module._extensions..js (module.js:580:10) - at Module.load (module.js:503:32) - at tryModuleLoad (module.js:466:12) - at Function.Module._load (module.js:458:3) -module.js:487 - throw err; - ^ - -Error: Cannot find module 'socket.io' - at Function.Module._resolveFilename (module.js:485:15) - at Function.Module._load (module.js:437:25) - at Module.require (module.js:513:17) - at require (internal/module.js:11:18) - at Object. (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_socket.js:38:20) - at Module._compile (module.js:569:30) - at Object.Module._extensions..js (module.js:580:10) - at Module.load (module.js:503:32) - at tryModuleLoad (module.js:466:12) - at Function.Module._load (module.js:458:3) -module.js:487 - throw err; - ^ - -Error: Cannot find module 'socket.io' - at Function.Module._resolveFilename (module.js:485:15) - at Function.Module._load (module.js:437:25) - at Module.require (module.js:513:17) - at require (internal/module.js:11:18) - at Object. (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_socket.js:38:20) - at Module._compile (module.js:569:30) - at Object.Module._extensions..js (module.js:580:10) - at Module.load (module.js:503:32) - at tryModuleLoad (module.js:466:12) - at Function.Module._load (module.js:458:3) -D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js:177 - child.send('shutdown'); - ^ - -TypeError: Cannot read property 'send' of null - at process.killkid (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js:177:10) - at emitOne (events.js:115:13) - at process.emit (events.js:210:7) - at process.exit (internal/process.js:154:15) - at monitor (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js:99:17) - at ChildProcess. (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js:170:5) - at emitTwo (events.js:125:13) - at ChildProcess.emit (events.js:213:7) - at Process.ChildProcess._handle.onexit (internal/child_process.js:197:12) +module.js:487 + throw err; + ^ + +Error: Cannot find module 'socket.io' + at Function.Module._resolveFilename (module.js:485:15) + at Function.Module._load (module.js:437:25) + at Module.require (module.js:513:17) + at require (internal/module.js:11:18) + at Object. (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_socket.js:38:20) + at Module._compile (module.js:569:30) + at Object.Module._extensions..js (module.js:580:10) + at Module.load (module.js:503:32) + at tryModuleLoad (module.js:466:12) + at Function.Module._load (module.js:458:3) +module.js:487 + throw err; + ^ + +Error: Cannot find module 'socket.io' + at Function.Module._resolveFilename (module.js:485:15) + at Function.Module._load (module.js:437:25) + at Module.require (module.js:513:17) + at require (internal/module.js:11:18) + at Object. (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_socket.js:38:20) + at Module._compile (module.js:569:30) + at Object.Module._extensions..js (module.js:580:10) + at Module.load (module.js:503:32) + at tryModuleLoad (module.js:466:12) + at Function.Module._load (module.js:458:3) +module.js:487 + throw err; + ^ + +Error: Cannot find module 'socket.io' + at Function.Module._resolveFilename (module.js:485:15) + at Function.Module._load (module.js:437:25) + at Module.require (module.js:513:17) + at require (internal/module.js:11:18) + at Object. (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_socket.js:38:20) + at Module._compile (module.js:569:30) + at Object.Module._extensions..js (module.js:580:10) + at Module.load (module.js:503:32) + at tryModuleLoad (module.js:466:12) + at Function.Module._load (module.js:458:3) +D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js:177 + child.send('shutdown'); + ^ + +TypeError: Cannot read property 'send' of null + at process.killkid (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js:177:10) + at emitOne (events.js:115:13) + at process.emit (events.js:210:7) + at process.exit (internal/process.js:154:15) + at monitor (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js:99:17) + at ChildProcess. (D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js:170:5) + at emitTwo (events.js:125:13) + at ChildProcess.emit (events.js:213:7) + at Process.ChildProcess._handle.onexit (internal/child_process.js:197:12) diff --git a/web/bin/node/app_https/daemon/tactacmainservice.wrapper.log b/web/bin/node/app_https/daemon/tactacmainservice.wrapper.log index 7e5c9f6..ebfdd55 100644 --- a/web/bin/node/app_https/daemon/tactacmainservice.wrapper.log +++ b/web/bin/node/app_https/daemon/tactacmainservice.wrapper.log @@ -1,152 +1,152 @@ -2018-10-03 22:22:40 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-03 22:22:40 - Started 13080 -2018-10-03 22:24:42 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-03 22:24:42 - Started 20916 -2018-10-04 20:48:24 - Stopping tactacmainservice.exe -2018-10-04 20:48:24 - ProcessKill 20916 +2018-10-03 22:22:40 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-03 22:22:40 - Started 13080 +2018-10-03 22:24:42 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-03 22:24:42 - Started 20916 +2018-10-04 20:48:24 - Stopping tactacmainservice.exe +2018-10-04 20:48:24 - ProcessKill 20916 2018-10-04 20:48:29 - Shutdown exception Message:Un arrêt système est en cours. (Exception de HRESULT : 0x8007045B) -Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) - à System.Management.ManagementScope.InitializeGuts(Object o) - à System.Management.ManagementScope.Initialize() - à System.Management.ManagementObjectSearcher.Initialize() - à System.Management.ManagementObjectSearcher.Get() - à winsw.WrapperService.GetChildPids(Int32 pid) - à winsw.WrapperService.StopProcessAndChildren(Int32 pid) - à winsw.WrapperService.StopIt() - à winsw.WrapperService.OnShutdown() -2018-10-04 20:51:52 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-04 20:51:52 - Started 8340 -2018-10-05 17:34:30 - Stopping tactacmainservice.exe -2018-10-05 17:34:30 - ProcessKill 8340 +Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) + à System.Management.ManagementScope.InitializeGuts(Object o) + à System.Management.ManagementScope.Initialize() + à System.Management.ManagementObjectSearcher.Initialize() + à System.Management.ManagementObjectSearcher.Get() + à winsw.WrapperService.GetChildPids(Int32 pid) + à winsw.WrapperService.StopProcessAndChildren(Int32 pid) + à winsw.WrapperService.StopIt() + à winsw.WrapperService.OnShutdown() +2018-10-04 20:51:52 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-04 20:51:52 - Started 8340 +2018-10-05 17:34:30 - Stopping tactacmainservice.exe +2018-10-05 17:34:30 - ProcessKill 8340 2018-10-05 17:34:33 - Shutdown exception Message:Un arrêt système est en cours. (Exception de HRESULT : 0x8007045B) -Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) - à System.Management.ManagementScope.InitializeGuts(Object o) - à System.Management.ManagementScope.Initialize() - à System.Management.ManagementObjectSearcher.Initialize() - à System.Management.ManagementObjectSearcher.Get() - à winsw.WrapperService.GetChildPids(Int32 pid) - à winsw.WrapperService.StopProcessAndChildren(Int32 pid) - à winsw.WrapperService.StopIt() - à winsw.WrapperService.OnShutdown() -2018-10-05 17:41:34 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-05 17:41:34 - Started 8172 -2018-10-17 20:16:18 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-17 20:16:18 - Started 8088 -2018-10-17 20:46:35 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-17 20:46:35 - Started 8428 -2018-10-25 11:11:54 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-25 11:11:54 - Started 7384 -2018-10-25 11:17:02 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-25 11:17:03 - Started 7416 -2018-10-25 18:12:31 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-25 18:12:31 - Started 7452 -2018-10-31 21:39:07 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-10-31 21:39:07 - Started 7772 -2018-11-02 20:51:47 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-02 20:51:48 - Started 5832 -2018-11-02 21:06:29 - Stopping tactacmainservice.exe -2018-11-02 21:06:29 - ProcessKill 5832 -2018-11-02 21:06:29 - Found child process: 5884 Name: conhost.exe -2018-11-02 21:06:29 - Found child process: 6420 Name: node.exe -2018-11-02 21:06:29 - Stopping process 5884 -2018-11-02 21:06:29 - Send SIGINT 5884 -2018-11-02 21:06:29 - SIGINT to 5884 failed - Killing as fallback -2018-11-02 21:06:29 - Stopping process 6420 -2018-11-02 21:06:29 - Send SIGINT 6420 -2018-11-02 21:06:29 - SIGINT to 6420 failed - Killing as fallback -2018-11-02 21:06:29 - Stopping process 5832 -2018-11-02 21:06:29 - Send SIGINT 5832 -2018-11-02 21:06:29 - SIGINT to 5832 failed - Killing as fallback -2018-11-02 21:06:29 - Finished tactacmainservice.exe -2018-11-02 21:27:29 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-02 21:27:30 - Started 6680 -2018-11-02 21:33:44 - Stopping tactacmainservice.exe -2018-11-02 21:33:44 - ProcessKill 6680 +Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) + à System.Management.ManagementScope.InitializeGuts(Object o) + à System.Management.ManagementScope.Initialize() + à System.Management.ManagementObjectSearcher.Initialize() + à System.Management.ManagementObjectSearcher.Get() + à winsw.WrapperService.GetChildPids(Int32 pid) + à winsw.WrapperService.StopProcessAndChildren(Int32 pid) + à winsw.WrapperService.StopIt() + à winsw.WrapperService.OnShutdown() +2018-10-05 17:41:34 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-05 17:41:34 - Started 8172 +2018-10-17 20:16:18 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-17 20:16:18 - Started 8088 +2018-10-17 20:46:35 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-17 20:46:35 - Started 8428 +2018-10-25 11:11:54 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-25 11:11:54 - Started 7384 +2018-10-25 11:17:02 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-25 11:17:03 - Started 7416 +2018-10-25 18:12:31 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-25 18:12:31 - Started 7452 +2018-10-31 21:39:07 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-10-31 21:39:07 - Started 7772 +2018-11-02 20:51:47 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-02 20:51:48 - Started 5832 +2018-11-02 21:06:29 - Stopping tactacmainservice.exe +2018-11-02 21:06:29 - ProcessKill 5832 +2018-11-02 21:06:29 - Found child process: 5884 Name: conhost.exe +2018-11-02 21:06:29 - Found child process: 6420 Name: node.exe +2018-11-02 21:06:29 - Stopping process 5884 +2018-11-02 21:06:29 - Send SIGINT 5884 +2018-11-02 21:06:29 - SIGINT to 5884 failed - Killing as fallback +2018-11-02 21:06:29 - Stopping process 6420 +2018-11-02 21:06:29 - Send SIGINT 6420 +2018-11-02 21:06:29 - SIGINT to 6420 failed - Killing as fallback +2018-11-02 21:06:29 - Stopping process 5832 +2018-11-02 21:06:29 - Send SIGINT 5832 +2018-11-02 21:06:29 - SIGINT to 5832 failed - Killing as fallback +2018-11-02 21:06:29 - Finished tactacmainservice.exe +2018-11-02 21:27:29 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-02 21:27:30 - Started 6680 +2018-11-02 21:33:44 - Stopping tactacmainservice.exe +2018-11-02 21:33:44 - ProcessKill 6680 2018-11-02 21:33:49 - Shutdown exception Message:Un arrêt système est en cours. (Exception de HRESULT : 0x8007045B) -Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) - à System.Management.ManagementScope.InitializeGuts(Object o) - à System.Management.ManagementScope.Initialize() - à System.Management.ManagementObjectSearcher.Initialize() - à System.Management.ManagementObjectSearcher.Get() - à winsw.WrapperService.GetChildPids(Int32 pid) - à winsw.WrapperService.StopProcessAndChildren(Int32 pid) - à winsw.WrapperService.StopIt() - à winsw.WrapperService.OnShutdown() -2018-11-02 21:41:40 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-02 21:41:41 - Started 3308 -2018-11-05 08:39:08 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-05 08:39:09 - Started 6740 -2018-11-07 13:38:44 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-07 13:38:45 - Started 7192 -2018-11-07 16:04:22 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-07 16:04:22 - Started 7452 -2018-11-09 21:35:29 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-09 21:35:29 - Started 7428 -2018-11-12 08:40:24 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-12 08:40:24 - Started 7588 -2018-11-13 20:13:04 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-13 20:13:04 - Started 7452 -2018-11-13 20:16:42 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-13 20:16:42 - Started 7216 -2018-11-13 20:41:02 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-13 20:41:02 - Started 7644 -2018-11-13 20:50:52 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-13 20:50:52 - Started 7632 -2018-11-14 20:12:45 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-14 20:12:45 - Started 6960 -2018-11-16 19:28:16 - Stopping tactacmainservice.exe -2018-11-16 19:28:16 - ProcessKill 6960 +Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) + à System.Management.ManagementScope.InitializeGuts(Object o) + à System.Management.ManagementScope.Initialize() + à System.Management.ManagementObjectSearcher.Initialize() + à System.Management.ManagementObjectSearcher.Get() + à winsw.WrapperService.GetChildPids(Int32 pid) + à winsw.WrapperService.StopProcessAndChildren(Int32 pid) + à winsw.WrapperService.StopIt() + à winsw.WrapperService.OnShutdown() +2018-11-02 21:41:40 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-02 21:41:41 - Started 3308 +2018-11-05 08:39:08 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-05 08:39:09 - Started 6740 +2018-11-07 13:38:44 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-07 13:38:45 - Started 7192 +2018-11-07 16:04:22 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-07 16:04:22 - Started 7452 +2018-11-09 21:35:29 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-09 21:35:29 - Started 7428 +2018-11-12 08:40:24 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-12 08:40:24 - Started 7588 +2018-11-13 20:13:04 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-13 20:13:04 - Started 7452 +2018-11-13 20:16:42 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-13 20:16:42 - Started 7216 +2018-11-13 20:41:02 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-13 20:41:02 - Started 7644 +2018-11-13 20:50:52 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-13 20:50:52 - Started 7632 +2018-11-14 20:12:45 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-14 20:12:45 - Started 6960 +2018-11-16 19:28:16 - Stopping tactacmainservice.exe +2018-11-16 19:28:16 - ProcessKill 6960 2018-11-16 19:28:17 - Shutdown exception Message:Un arrêt système est en cours. (Exception de HRESULT : 0x8007045B) -Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) - à System.Management.ManagementScope.InitializeGuts(Object o) - à System.Management.ManagementScope.Initialize() - à System.Management.ManagementObjectSearcher.Initialize() - à System.Management.ManagementObjectSearcher.Get() - à winsw.WrapperService.GetChildPids(Int32 pid) - à winsw.WrapperService.StopProcessAndChildren(Int32 pid) - à winsw.WrapperService.StopIt() - à winsw.WrapperService.OnShutdown() -2018-11-16 19:30:16 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-16 19:30:16 - Started 7628 -2018-11-19 20:30:11 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-19 20:30:11 - Started 7560 -2018-11-20 19:56:18 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-20 19:56:18 - Started 7492 -2018-11-29 08:42:53 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-11-29 08:42:53 - Started 7936 -2018-11-29 17:33:00 - Stopping tactacmainservice.exe -2018-11-29 17:33:00 - ProcessKill 7936 +Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) + à System.Management.ManagementScope.InitializeGuts(Object o) + à System.Management.ManagementScope.Initialize() + à System.Management.ManagementObjectSearcher.Initialize() + à System.Management.ManagementObjectSearcher.Get() + à winsw.WrapperService.GetChildPids(Int32 pid) + à winsw.WrapperService.StopProcessAndChildren(Int32 pid) + à winsw.WrapperService.StopIt() + à winsw.WrapperService.OnShutdown() +2018-11-16 19:30:16 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-16 19:30:16 - Started 7628 +2018-11-19 20:30:11 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-19 20:30:11 - Started 7560 +2018-11-20 19:56:18 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-20 19:56:18 - Started 7492 +2018-11-29 08:42:53 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-11-29 08:42:53 - Started 7936 +2018-11-29 17:33:00 - Stopping tactacmainservice.exe +2018-11-29 17:33:00 - ProcessKill 7936 2018-11-29 17:33:03 - Shutdown exception Message:Un arrêt système est en cours. (Exception de HRESULT : 0x8007045B) -Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) - à System.Management.ManagementScope.InitializeGuts(Object o) - à System.Management.ManagementScope.Initialize() - à System.Management.ManagementObjectSearcher.Initialize() - à System.Management.ManagementObjectSearcher.Get() - à winsw.WrapperService.GetChildPids(Int32 pid) - à winsw.WrapperService.StopProcessAndChildren(Int32 pid) - à winsw.WrapperService.StopIt() - à winsw.WrapperService.OnShutdown() -2018-12-31 11:05:31 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-12-31 11:05:31 - Started 11556 -2018-12-31 19:33:20 - Stopping tactacmainservice.exe -2018-12-31 19:33:20 - ProcessKill 11556 +Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) + à System.Management.ManagementScope.InitializeGuts(Object o) + à System.Management.ManagementScope.Initialize() + à System.Management.ManagementObjectSearcher.Initialize() + à System.Management.ManagementObjectSearcher.Get() + à winsw.WrapperService.GetChildPids(Int32 pid) + à winsw.WrapperService.StopProcessAndChildren(Int32 pid) + à winsw.WrapperService.StopIt() + à winsw.WrapperService.OnShutdown() +2018-12-31 11:05:31 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-12-31 11:05:31 - Started 11556 +2018-12-31 19:33:20 - Stopping tactacmainservice.exe +2018-12-31 19:33:20 - ProcessKill 11556 2018-12-31 19:33:20 - Shutdown exception Message:Un arrêt système est en cours. (Exception de HRESULT : 0x8007045B) -Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) - à System.Management.ManagementScope.InitializeGuts(Object o) - à System.Management.ManagementScope.Initialize() - à System.Management.ManagementObjectSearcher.Initialize() - à System.Management.ManagementObjectSearcher.Get() - à winsw.WrapperService.GetChildPids(Int32 pid) - à winsw.WrapperService.StopProcessAndChildren(Int32 pid) - à winsw.WrapperService.StopIt() - à winsw.WrapperService.OnShutdown() -2018-12-31 19:38:07 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2018-12-31 19:38:07 - Started 10072 -2019-01-04 21:10:08 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined -2019-01-04 21:10:08 - Started 12936 +Stacktrace: à System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo) + à System.Management.ManagementScope.InitializeGuts(Object o) + à System.Management.ManagementScope.Initialize() + à System.Management.ManagementObjectSearcher.Initialize() + à System.Management.ManagementObjectSearcher.Get() + à winsw.WrapperService.GetChildPids(Int32 pid) + à winsw.WrapperService.StopProcessAndChildren(Int32 pid) + à winsw.WrapperService.StopIt() + à winsw.WrapperService.OnShutdown() +2018-12-31 19:38:07 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2018-12-31 19:38:07 - Started 10072 +2019-01-04 21:10:08 - Starting C:\Program Files\nodejs\node.exe --harmony D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js --file D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js --log "tac-tac-main-service wrapper" --grow 0.25 --wait 1 --maxrestarts 3 --abortonerror n --stopparentfirst undefined +2019-01-04 21:10:08 - Started 12936 diff --git a/web/bin/node/app_https/daemon/tactacmainservice.xml b/web/bin/node/app_https/daemon/tactacmainservice.xml index 4c8b852..2e9b471 100644 --- a/web/bin/node/app_https/daemon/tactacmainservice.xml +++ b/web/bin/node/app_https/daemon/tactacmainservice.xml @@ -1,25 +1,25 @@ - - tactacmainservice.exe - tac-tac-main-service - tac-tac-main-service - C:\Program Files\nodejs\node.exe - rotate - --harmony - D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js - --file - D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js - --log - tac-tac-main-service wrapper - --grow - 0.25 - --wait - 1 - --maxrestarts - 3 - --abortonerror - n - --stopparentfirst - undefined - 30sec - D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service + + tactacmainservice.exe + tac-tac-main-service + tac-tac-main-service + C:\Program Files\nodejs\node.exe + rotate + --harmony + D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service\node_modules\node-windows\lib\wrapper.js + --file + D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\app_https\app_https_main.js + --log + tac-tac-main-service wrapper + --grow + 0.25 + --wait + 1 + --maxrestarts + 3 + --abortonerror + n + --stopparentfirst + undefined + 30sec + D:\boulot\UwAmp\www\tac-tac.lan\web\bin\node\windows_service \ No newline at end of file diff --git a/web/bin/node/app_https/package.json b/web/bin/node/app_https/package.json index cfe16fd..2298fa3 100644 --- a/web/bin/node/app_https/package.json +++ b/web/bin/node/app_https/package.json @@ -1,32 +1,32 @@ -{ - "name": "app_idae", - "version": "0.0.1", - "description": "idae socket connector", - "dependencies": { - "connect": "3.3.3", - "cron": "1.3.0", - "fs": "0.0.2", - "http": "0.0.0", - "https": "^1.0.0", - "mongodb": "2.2.10", - "path": "0.12.7", - "qs": "6.2.1", - "reinstall": "^2.0.0", - "request": "2.75.0", - "socket.io": "^1.4.8", - "socket.io-cookie": "0.0.1", - "socket.io-cookie-parser": "1.0.0", - "url": "0.11.0" - }, - "author": "Mydde", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [ - "base", - "module", - "for", - "idae" - ], - "license": "ISC" -} +{ + "name": "app_idae", + "version": "0.0.1", + "description": "idae socket connector", + "dependencies": { + "connect": "3.3.3", + "cron": "1.3.0", + "fs": "0.0.2", + "http": "0.0.0", + "https": "^1.0.0", + "mongodb": "2.2.10", + "path": "0.12.7", + "qs": "6.2.1", + "reinstall": "^2.0.0", + "request": "2.75.0", + "socket.io": "^1.4.8", + "socket.io-cookie": "0.0.1", + "socket.io-cookie-parser": "1.0.0", + "url": "0.11.0" + }, + "author": "Mydde", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [ + "base", + "module", + "for", + "idae" + ], + "license": "ISC" +} diff --git a/web/bin/phpunit.xml b/web/bin/phpunit.xml index fd4113c..86ba5af 100644 --- a/web/bin/phpunit.xml +++ b/web/bin/phpunit.xml @@ -1,11 +1,11 @@ - - - - - tests/unit - - - tests/integration - - - + + + + + tests/unit + + + tests/integration + + + diff --git a/web/bin/route.php b/web/bin/route.php index 91788bc..038e449 100644 --- a/web/bin/route.php +++ b/web/bin/route.php @@ -1,32 +1,32 @@ -parse($_REQUEST); +parse($_REQUEST); diff --git a/web/bin/services/json_data_search.php b/web/bin/services/json_data_search.php index c35a21c..b68296f 100644 --- a/web/bin/services/json_data_search.php +++ b/web/bin/services/json_data_search.php @@ -1,264 +1,264 @@ -findOne(['private_key' => $_SESSION[$type_session]], ['_id' => 0]); - $_POST['vars'][$name_idtype_session] = $arr_shop[$name_idtype_session]; - } - // - $uniqid = uniqid(); - // - $APP = new App('appscheme'); - // - $SEARCH_SCH_QY = !empty($_POST['table']) ? ['codeAppscheme' => $_POST['table']] : []; - $RSSCHEME = $APP->find($SEARCH_SCH_QY); // 'codeAppscheme_base'=>'sitebase_base' - // - $vars = empty($_POST['vars']) ? [] : function_prod::cleanPostMongo(array_filter($_POST['vars']), 1); - $groupBy = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; - $sortBy = empty($_POST['sortBy']) ? empty($settings_sortBy) ? $nom : $settings_sortBy : $_POST['sortBy']; - $sortDir = empty($_POST['sortDir']) ? empty($settings_sortDir) ? 1 : (int)$settings_sortDir : (int)$_POST['sortDir']; - $page = (!isset($_POST['page'])) ? 0 : $_POST['page']; - $nbRows = 25; //(empty($_POST['nbRows'])) ? empty($settings_nbRows) ? 250 : (int)$settings_nbRows : $_POST['nbRows']; - // vars_date - if (!empty($_POST['vars_date'])): - $key_date = $_POST['vars_date'] ['name_key']; - $vars[$key_date] = $_POST['vars_date'][$key_date]; - endif; - // - $arrFieldsBool = $APP->get_array_field_bool(); - // - - // MAIN_DATA - - $data_main = []; - $strm = []; - - $i = 0; - $nb_res = 0; - $SEARCH = trim(strip_tags($_POST['search'])); - $SEARCH_QY = !empty($_POST['table']) ? trim($_POST['table']) : new MongoRegex("/$SEARCH/i"); - - $RSSCHEME_SEARCH = $APP->find(['codeAppscheme' => $SEARCH_QY]); - // $RSSCHEME_SEARCH = $APP->find(['codeAppscheme' => new MongoRegex("/$SEARCH/i")] ); - $maxcount = $RSSCHEME_SEARCH->count(); - $count = $RSSCHEME_SEARCH->count(true); - - // - if ($RSSCHEME_SEARCH->count() != 0) { - // $data_main[] = ['groupBy' => 'appscheme', 'html' => ' Espaces']; - - } - - while ($ARR_SCh = $RSSCHEME_SEARCH->getNext()) { - continue; - $table = $ARR_SCh['codeAppscheme']; - $nom = $ARR_SCh['nomAppscheme']; - $icon = $ARR_SCh['iconAppscheme']; - $color = $ARR_SCh['colorAppscheme']; - - /*if (!droit_table($_SESSION['idagent'], 'L', $table)) continue; - if (!droit_table($_SESSION['idagent'], 'R', $table)) continue;*/ - - $in = ''; - //if (droit_table($_SESSION['idagent'], 'C', $table)) $in .= ''; - - $data_out['nom'] = ''; - $data_out['nom_fk'] = ''; - - $data_main[] = ['html' => $data_out, 'value' => '$arr[$id]', 'name_id' => '$id', 'table' => 'appscheme']; - - $out_model = ['data_main' => $data_main, 'maxcount' => $maxcount]; - $strm_vars = ['stream_to' => $stream_to, 'data' => $out_model, 'data_size' => sizeof($data_main)]; - AppSocket::send_cmd('act_stream_to', json_decode(json_encode($strm_vars)), session_id()); - $data_main = []; - - } - - foreach ($RSSCHEME as $arr_dist): - // - $table = $arr_dist['codeAppscheme']; - //if ($APP->get_settings($_SESSION['idagent'], 'app_search_' . $table) != 'true') continue; - //if (!droit_table($_SESSION['idagent'], 'R', $table)) continue; - //if(!droit_table($type_session,'R',$table)) continue; - $out = []; - $APPSC = new App($table); - $where = []; - if ($APPSC->has_field_fk($type_session)) { - $where[$name_idtype_session] = $idtype_session; - }; - $GRILLE_FK = $APPSC->get_grille_fk(); - $APP_TABLE = $APPSC->app_table_one; - $i++; - // - $color = $APPSC->colorAppscheme; - $Table = ucfirst($table); - $id = 'id' . $table; - $nom = 'nom' . $Table; - $prenom = 'prenom' . $Table; - $email = 'email' . $Table; - $code = 'code' . $Table; - $telephone = 'telephone' . $Table; - $icon = $arr_dist['iconAppscheme']; - $icon_css = ''; // - - if (!empty($_POST['search'])) { - if (!is_int($_POST['search'])): - $regexp = new MongoRegex("/$SEARCH/i"); - $tmp_or = []; - $where['$and'] = []; - foreach (['nom', 'prenom', 'email', 'code', 'telephone', 'ville'] as $in_key => $val_key) { - $tmp_or['$or'][] = [$val_key . $Table => $regexp]; - //$where['$and'][] = ['$or']; - if ($APPSC->has_field($val_key)) { - //$where['$or'][] = [$val_key . $Table => $regexp]; - $where['$and'][] = $tmp_or; - } - // if ($APPSC->has_field($val_key)) $where['$or'][] = [$val_key . $Table => $regexp]; - } - /* if ($APPSC->has_field('nom')) $where['$and']['$or'][] = [$nom => $regexp]; - if ($APPSC->has_field('prenom')) $where['$and']['$or'][] = [$prenom => $regexp]; - if ($APPSC->has_field('email')) $where['$and']['$or'][] = [$email => $regexp]; - if ($APPSC->has_field('code')) $where['$and']['$or'][] = [$code => $regexp]; - if ($APPSC->has_field('telephone')) $where['$and']['$or'][] = [$telephone => $regexp];*/ - /*$tmp_or['$or'][] = [$id => (int)$_POST['search']];; - $where['$and'][] = $tmp_or; - $where['$or'][] = [$id => (int)$_POST['search']];;*/ - else : - $where[$id] = (int)$_POST['search']; - endif; - } - - //vardump($where); - /*if ($APPSC->has_agent() && !droit_table($_SESSION['idagent'], 'CONF', $table)) { - $where['idagent'] = (int)$_SESSION['idagent']; - };*/ - - $rssc = $APPSC->query([$id => ['$ne' => 0]] + $vars + $where)->sort([$nom => 1])->limit($nbRows)->skip($page * $nbRows); - $rssc_count = $rssc->count(); - - if ($rssc->count() != 0): - $rss_html = "
$icon_css
" . ucfirst($arr_dist['nomAppscheme']) . " - $rssc_count
"; - - $data_main[] = $strm[] = ['groupBy' => $table, 'html' => '$rss_html']; - endif; - - while ($arr = $rssc->getNext()) { - // sleep(1); - $i++; - $nb_res++; - $data_out = []; - // - $data_out['chk'] = ''; - $data_out[$id] = $arr[$id]; - - $name = ucfirst(strtolower($arr[$nom] . ' ' . $arr[$prenom])); - - $data_out['nom_fk'] = []; - $data_out['nom_fk_large'] = []; - - foreach ($GRILLE_FK as $field): - $code = $BASE_APP . $table . $field['table_fk'] . $arr[$id]; - $id_fk = $field['idtable_fk']; - // - $arrq = $APP->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => (int)$arr[$id_fk]], [$field['idtable_fk'] => 1, $field['nomtable_fk'] => 1]); - $dsp_name = $arrq['nom' . ucfirst($field['table_fk'])]; - // - if (!empty($dsp_name)) { - $data_out['nom_fk'][] = "" . strtolower($dsp_name) . ""; - $data_out['nom_fk_large'][] = "
" . ucfirst($field['nomAppscheme']) . "
" . $dsp_name . "
"; - } - endforeach; - - $onclick = '';//fonctionsJs::app_fiche($table, $arr[$id]); - - if ($rssc_count == 1) { - $in = '
' . $table . '
'; - $Idae = new Idae($table); - $data_out['nom'] = //$Idae->module('fiche_mini', http_build_query(['table' => $table, 'table_value' => $arr[$id]])); - $data_out['nom_fk'] = ''; - } elseif ($rssc_count <= 3) { - $Idae = new Idae($table); - $data_out['nom'] =// $Idae->module('fiche_mini', http_build_query(['table' => $table, 'table_value' => $arr[$id]])); - - //$data_out['nom'] = $arr[$nom]; - $data_out['nom_fk'] = ''; - } else { - $Idae = new Idae($table); - $data_out['nom'] = // $Idae->module('fiche_mini', http_build_query(['table' => $table, 'table_value' => $arr[$id]])); - $data_out['nom_fk'] = '';//implode(', ', $data_out['nom_fk']); - } - - if ($rssc_count == 1) { - } else { - - } - - $data_main[] = ['html' => '$data_out', 'value' => $arr[$id],'table_value' => $arr[$id], 'name_id' => $id, 'table' => $table] + $arr ; - $strm[] = ['html' => '$data_out', 'value' => $arr[$id],'table_value' => $arr[$id], 'name_id' => $id, 'table' => $table] + $arr ; - - // stream - if ($i == 1 || ($i % 2) == 0 || !$rssc->hasNext()) { - if (!empty($stream_to)): - $out_model = ['data_main' => $strm, 'maxcount' => $maxcount]; - $strm_vars = ['stream_to' => $stream_to, 'data' => $out_model, 'data_size' => sizeof($strm)]; - AppSocket::send_cmd('act_stream_to', json_decode(json_encode($strm_vars)), session_id()); - $strm = []; - endif; - } - - } - // - endforeach; - - if ($nb_res == 0): - $data_main[] = ['groupBy' => 'fin ...', 'html' => '
-
Aucun résultat pour "' . $_POST['search'] . '"
']; - - $out_model = ['data_main' => $data_main, 'maxcount' => $maxcount]; - $strm_vars = ['stream_to' => $stream_to, 'data' => $out_model, 'data_size' => sizeof($strm)]; - AppSocket::send_cmd('act_stream_to', json_decode(json_encode($strm_vars)), session_id()); - - endif; - if ($nb_res != 0): - $APP_SA = new APP('agent_recherche'); - $idagent_recherche = $APP_SA->create_update(['quantiteAgent_recherche' => $nb_res, 'codeAgent_recherche' => $_POST['search']], ['dateCreationAgent_recherche' => date('Y-m-d'), 'heureCreationAgent_recherche' => date('H:i:s'), 'timeAgent_recherche' => time(), 'nomAgent_recherche' => $_POST['search'], 'idagent' => (int)$_SESSION['idagent']]); - $APP_SA->update_inc(['idagent_recherche' => $idagent_recherche], 'valeurAgent_recherche'); - AppSocket::reloadModule('app/app_gui/app_gui_start_search_last', $_SESSION['idagent']); - endif; - // - $out_model = ['data_main' => $data_main, 'maxcount' => $maxcount]; - // - if (empty($stream_to)): - echo trim(json_encode($out_model)); - endif; - - function dotr($arr) { - +findOne(['private_key' => $_SESSION[$type_session]], ['_id' => 0]); + $_POST['vars'][$name_idtype_session] = $arr_shop[$name_idtype_session]; + } + // + $uniqid = uniqid(); + // + $APP = new App('appscheme'); + // + $SEARCH_SCH_QY = !empty($_POST['table']) ? ['codeAppscheme' => $_POST['table']] : []; + $RSSCHEME = $APP->find($SEARCH_SCH_QY); // 'codeAppscheme_base'=>'sitebase_base' + // + $vars = empty($_POST['vars']) ? [] : function_prod::cleanPostMongo(array_filter($_POST['vars']), 1); + $groupBy = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; + $sortBy = empty($_POST['sortBy']) ? empty($settings_sortBy) ? $nom : $settings_sortBy : $_POST['sortBy']; + $sortDir = empty($_POST['sortDir']) ? empty($settings_sortDir) ? 1 : (int)$settings_sortDir : (int)$_POST['sortDir']; + $page = (!isset($_POST['page'])) ? 0 : $_POST['page']; + $nbRows = 25; //(empty($_POST['nbRows'])) ? empty($settings_nbRows) ? 250 : (int)$settings_nbRows : $_POST['nbRows']; + // vars_date + if (!empty($_POST['vars_date'])): + $key_date = $_POST['vars_date'] ['name_key']; + $vars[$key_date] = $_POST['vars_date'][$key_date]; + endif; + // + $arrFieldsBool = $APP->get_array_field_bool(); + // + + // MAIN_DATA + + $data_main = []; + $strm = []; + + $i = 0; + $nb_res = 0; + $SEARCH = trim(strip_tags($_POST['search'])); + $SEARCH_QY = !empty($_POST['table']) ? trim($_POST['table']) : new MongoRegex("/$SEARCH/i"); + + $RSSCHEME_SEARCH = $APP->find(['codeAppscheme' => $SEARCH_QY]); + // $RSSCHEME_SEARCH = $APP->find(['codeAppscheme' => new MongoRegex("/$SEARCH/i")] ); + $maxcount = $RSSCHEME_SEARCH->count(); + $count = $RSSCHEME_SEARCH->count(true); + + // + if ($RSSCHEME_SEARCH->count() != 0) { + // $data_main[] = ['groupBy' => 'appscheme', 'html' => ' Espaces']; + + } + + while ($ARR_SCh = $RSSCHEME_SEARCH->getNext()) { + continue; + $table = $ARR_SCh['codeAppscheme']; + $nom = $ARR_SCh['nomAppscheme']; + $icon = $ARR_SCh['iconAppscheme']; + $color = $ARR_SCh['colorAppscheme']; + + /*if (!droit_table($_SESSION['idagent'], 'L', $table)) continue; + if (!droit_table($_SESSION['idagent'], 'R', $table)) continue;*/ + + $in = ''; + //if (droit_table($_SESSION['idagent'], 'C', $table)) $in .= ''; + + $data_out['nom'] = ''; + $data_out['nom_fk'] = ''; + + $data_main[] = ['html' => $data_out, 'value' => '$arr[$id]', 'name_id' => '$id', 'table' => 'appscheme']; + + $out_model = ['data_main' => $data_main, 'maxcount' => $maxcount]; + $strm_vars = ['stream_to' => $stream_to, 'data' => $out_model, 'data_size' => sizeof($data_main)]; + AppSocket::send_cmd('act_stream_to', json_decode(json_encode($strm_vars)), session_id()); + $data_main = []; + + } + + foreach ($RSSCHEME as $arr_dist): + // + $table = $arr_dist['codeAppscheme']; + //if ($APP->get_settings($_SESSION['idagent'], 'app_search_' . $table) != 'true') continue; + //if (!droit_table($_SESSION['idagent'], 'R', $table)) continue; + //if(!droit_table($type_session,'R',$table)) continue; + $out = []; + $APPSC = new App($table); + $where = []; + if ($APPSC->has_field_fk($type_session)) { + $where[$name_idtype_session] = $idtype_session; + }; + $GRILLE_FK = $APPSC->get_grille_fk(); + $APP_TABLE = $APPSC->app_table_one; + $i++; + // + $color = $APPSC->colorAppscheme; + $Table = ucfirst($table); + $id = 'id' . $table; + $nom = 'nom' . $Table; + $prenom = 'prenom' . $Table; + $email = 'email' . $Table; + $code = 'code' . $Table; + $telephone = 'telephone' . $Table; + $icon = $arr_dist['iconAppscheme']; + $icon_css = ''; // + + if (!empty($_POST['search'])) { + if (!is_int($_POST['search'])): + $regexp = new MongoRegex("/$SEARCH/i"); + $tmp_or = []; + $where['$and'] = []; + foreach (['nom', 'prenom', 'email', 'code', 'telephone', 'ville'] as $in_key => $val_key) { + $tmp_or['$or'][] = [$val_key . $Table => $regexp]; + //$where['$and'][] = ['$or']; + if ($APPSC->has_field($val_key)) { + //$where['$or'][] = [$val_key . $Table => $regexp]; + $where['$and'][] = $tmp_or; + } + // if ($APPSC->has_field($val_key)) $where['$or'][] = [$val_key . $Table => $regexp]; + } + /* if ($APPSC->has_field('nom')) $where['$and']['$or'][] = [$nom => $regexp]; + if ($APPSC->has_field('prenom')) $where['$and']['$or'][] = [$prenom => $regexp]; + if ($APPSC->has_field('email')) $where['$and']['$or'][] = [$email => $regexp]; + if ($APPSC->has_field('code')) $where['$and']['$or'][] = [$code => $regexp]; + if ($APPSC->has_field('telephone')) $where['$and']['$or'][] = [$telephone => $regexp];*/ + /*$tmp_or['$or'][] = [$id => (int)$_POST['search']];; + $where['$and'][] = $tmp_or; + $where['$or'][] = [$id => (int)$_POST['search']];;*/ + else : + $where[$id] = (int)$_POST['search']; + endif; + } + + //vardump($where); + /*if ($APPSC->has_agent() && !droit_table($_SESSION['idagent'], 'CONF', $table)) { + $where['idagent'] = (int)$_SESSION['idagent']; + };*/ + + $rssc = $APPSC->query([$id => ['$ne' => 0]] + $vars + $where)->sort([$nom => 1])->limit($nbRows)->skip($page * $nbRows); + $rssc_count = $rssc->count(); + + if ($rssc->count() != 0): + $rss_html = "
$icon_css
" . ucfirst($arr_dist['nomAppscheme']) . " - $rssc_count
"; + + $data_main[] = $strm[] = ['groupBy' => $table, 'html' => '$rss_html']; + endif; + + while ($arr = $rssc->getNext()) { + // sleep(1); + $i++; + $nb_res++; + $data_out = []; + // + $data_out['chk'] = ''; + $data_out[$id] = $arr[$id]; + + $name = ucfirst(strtolower($arr[$nom] . ' ' . $arr[$prenom])); + + $data_out['nom_fk'] = []; + $data_out['nom_fk_large'] = []; + + foreach ($GRILLE_FK as $field): + $code = $BASE_APP . $table . $field['table_fk'] . $arr[$id]; + $id_fk = $field['idtable_fk']; + // + $arrq = $APP->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => (int)$arr[$id_fk]], [$field['idtable_fk'] => 1, $field['nomtable_fk'] => 1]); + $dsp_name = $arrq['nom' . ucfirst($field['table_fk'])]; + // + if (!empty($dsp_name)) { + $data_out['nom_fk'][] = "" . strtolower($dsp_name) . ""; + $data_out['nom_fk_large'][] = "
" . ucfirst($field['nomAppscheme']) . "
" . $dsp_name . "
"; + } + endforeach; + + $onclick = '';//fonctionsJs::app_fiche($table, $arr[$id]); + + if ($rssc_count == 1) { + $in = '
' . $table . '
'; + $Idae = new Idae($table); + $data_out['nom'] = //$Idae->module('fiche_mini', http_build_query(['table' => $table, 'table_value' => $arr[$id]])); + $data_out['nom_fk'] = ''; + } elseif ($rssc_count <= 3) { + $Idae = new Idae($table); + $data_out['nom'] =// $Idae->module('fiche_mini', http_build_query(['table' => $table, 'table_value' => $arr[$id]])); + + //$data_out['nom'] = $arr[$nom]; + $data_out['nom_fk'] = ''; + } else { + $Idae = new Idae($table); + $data_out['nom'] = // $Idae->module('fiche_mini', http_build_query(['table' => $table, 'table_value' => $arr[$id]])); + $data_out['nom_fk'] = '';//implode(', ', $data_out['nom_fk']); + } + + if ($rssc_count == 1) { + } else { + + } + + $data_main[] = ['html' => '$data_out', 'value' => $arr[$id],'table_value' => $arr[$id], 'name_id' => $id, 'table' => $table] + $arr ; + $strm[] = ['html' => '$data_out', 'value' => $arr[$id],'table_value' => $arr[$id], 'name_id' => $id, 'table' => $table] + $arr ; + + // stream + if ($i == 1 || ($i % 2) == 0 || !$rssc->hasNext()) { + if (!empty($stream_to)): + $out_model = ['data_main' => $strm, 'maxcount' => $maxcount]; + $strm_vars = ['stream_to' => $stream_to, 'data' => $out_model, 'data_size' => sizeof($strm)]; + AppSocket::send_cmd('act_stream_to', json_decode(json_encode($strm_vars)), session_id()); + $strm = []; + endif; + } + + } + // + endforeach; + + if ($nb_res == 0): + $data_main[] = ['groupBy' => 'fin ...', 'html' => '
+
Aucun résultat pour "' . $_POST['search'] . '"
']; + + $out_model = ['data_main' => $data_main, 'maxcount' => $maxcount]; + $strm_vars = ['stream_to' => $stream_to, 'data' => $out_model, 'data_size' => sizeof($strm)]; + AppSocket::send_cmd('act_stream_to', json_decode(json_encode($strm_vars)), session_id()); + + endif; + if ($nb_res != 0): + $APP_SA = new APP('agent_recherche'); + $idagent_recherche = $APP_SA->create_update(['quantiteAgent_recherche' => $nb_res, 'codeAgent_recherche' => $_POST['search']], ['dateCreationAgent_recherche' => date('Y-m-d'), 'heureCreationAgent_recherche' => date('H:i:s'), 'timeAgent_recherche' => time(), 'nomAgent_recherche' => $_POST['search'], 'idagent' => (int)$_SESSION['idagent']]); + $APP_SA->update_inc(['idagent_recherche' => $idagent_recherche], 'valeurAgent_recherche'); + AppSocket::reloadModule('app/app_gui/app_gui_start_search_last', $_SESSION['idagent']); + endif; + // + $out_model = ['data_main' => $data_main, 'maxcount' => $maxcount]; + // + if (empty($stream_to)): + echo trim(json_encode($out_model)); + endif; + + function dotr($arr) { + } \ No newline at end of file diff --git a/web/bin/services/json_data_table.php b/web/bin/services/json_data_table.php index ff39245..69ecd55 100644 --- a/web/bin/services/json_data_table.php +++ b/web/bin/services/json_data_table.php @@ -1,622 +1,622 @@ - 'Agent non connecté', 'options' => $_GET + ['mdl' => 'app/app_login/app_login', 'sticky' => 1, 'id' => 'json_debug']], session_id()); - //return; - } - // skelMdl::send_cmd('act_notify',['msg'=>'Agent non connecté '.session_id('d4uuh6a4jca153fk9rphfl0l27'),'options'=> ['mdl'=>'app/app_login/app_login','sticky'=>1]],"d4uuh6a4jca153fk9rphfl0l27"); - - $DEBUG = false; - - /*ini_set('output_buffering', 'off'); - ini_set('zlib.output_compression', false); - header('Content-Type: text/event-stream'); - header('Cache-Control: no-cache'); - header('Content-Encoding: none;'); - ob_end_flush(); - flush();*/ - - $_POST = array_merge($_GET, $_POST); - // - if (droit('DEV') && $DEBUG) { - skelMdl::send_cmd('act_notify', ['msg' => '__________________
  POST  => ' . json_encode($_POST, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); - } - // - if (droit('DEV') && $DEBUG) { - parse_str($_POST['url_data'], $out_url); - skelMdl::send_cmd('act_notify', ['msg' => '
url_data => ' . json_encode($out_url, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); - } - - // keep url_data - if (!empty($_POST['url_data'])) { - parse_str($_POST['url_data'], $arr_data); - if (empty($arr_data['vars'])) { - $arr_data['vars'] = []; - } - if (!empty($arr_data['vars_search_fk'])) { - $arr_data['vars_search_fk'] = array_filter($arr_data['vars_search_fk']); - } - unset($arr_data['stream_to'], $arr_data['PHPSESSID'], $arr_data['SESSID']); - $url_data = http_build_query($arr_data); - } else { - $tppost = $_POST; - unset($tppost['PHPSESSID'], $tppost['SESSID'], $tppost['stream_to'], $tppost['url_data']); - $url_data = http_build_query($tppost); - } - // - if (empty($_POST['table'])) { - return; - } - if (!empty($_POST['stream_to'])) { - if (!empty($_POST['url_data'])) { - $_POST['url_data'] .= '&stream_to=' . $_POST['stream_to']; - } - } - if (!empty($_POST['url_data'])) { - parse_str($_POST['url_data'], $_POST); - } - $uniqid = uniqid(); - // - $table = $_POST['table']; - $Table = ucfirst($_POST['table']); - // - $APP = new App($table); - // - if (!empty($_SESSION['idagent'])) { - $vars_hist['table'] = $_POST['table']; - $vars_hist['groupBy'] = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; - $vars_hist['search'] = empty($_POST['search']) ? '' : $_POST['search']; - $uid = md5(http_build_query($vars_hist)); - $APP->set_hist($_SESSION['idagent'], ['uid' => $uid] + ['vars' => $vars_hist]); - } - // - $id = 'id' . $table; - $nom = 'nom' . ucfirst($table); - $id_type = 'id' . $table . '_type'; - $nom_type = 'nom' . ucfirst($table) . '_type'; - $top = 'estTop' . ucfirst($table); - $actif = 'estActif' . ucfirst($table); - $visible = 'estVisible' . ucfirst($table); - - // - $vars = empty($_POST['vars']) ? [] : fonctionsProduction::cleanPostMongo(array_filter($_POST['vars'], "my_array_filter_fn"), 1); - $vars_search = empty($_POST['vars_search']) ? [] : fonctionsProduction::cleanPostMongo(array_filter($_POST['vars_search'], "my_array_filter_fn"), 1); - $vars_search_fk = empty($_POST['vars_search_fk']) ? [] : fonctionsProduction::cleanPostMongo(array_filter($_POST['vars_search_fk'], "my_array_filter_fn"), 1); - $vars_search_rfk = empty($_POST['vars_search_rfk']) ? [] : fonctionsProduction::cleanPostMongo(array_filter($_POST['vars_search_rfk'], "my_array_filter_fn"), 1); - - if (droit('DEV') && $DEBUG) { - skelMdl::send_cmd('act_notify', ['msg' => '
  $vars after INIT=> ' . json_encode($vars, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); - } - - if (!droit_table($_SESSION['idagent'], 'CONF', $table) && $APP->has_agent()): - $vars['idagent'] = (int)$_SESSION['idagent']; - endif; - if (!droit_table($_SESSION['idagent'], 'R', $table) && droit_table($_SESSION['idagent'], 'L', $table) && !$APP->has_agent()): - $_POST['vars']['idagent'] = (int)$_SESSION['idagent']; - endif; - // - $APP_TABLE = $APP->app_table_one; - $GRILLE_FK = $APP->get_grille_fk(); - $GRILLE_COUNT = $APP->get_grille_count($table); - $HTTP_VARS = $APP->translate_vars($vars); - $arrFieldsBool = $APP->get_array_field_bool(); - $arrFields_all = $APP->get_field_list(); - // - $groupBy = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; - $sortBy = empty($_POST['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $nom : $APP_TABLE['sortFieldName'] : $_POST['sortBy']; - $sortDir = empty($_POST['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$_POST['sortDir']; - $sortBySecond = empty($_POST['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? $nom : $APP_TABLE['sortFieldSecondName'] : $_POST['sortBySecond']; - $sortDirSecond = empty($_POST['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$_POST['sortDirSecond']; - - $page = (!isset($_POST['page'])) ? 0 : $_POST['page']; - $nbRows = (empty($_POST['nbRows'])) ? empty($settings_nbRows) ? 500 : (int)$settings_nbRows : $_POST['nbRows']; - // - $MDL = empty($_POST['mdl']) ? '' : $_POST['mdl']; - $strem_chunk_size = empty($MDL) ? 20 : 15; - - // $in => tableau - foreach ($vars as $key_vars => $value_vars): - if ($key_vars == 'ne') continue; - if (is_array($value_vars) && $key_vars != 'gte' && $key_vars != 'lte' && $key_vars != 'ne' && sizeof(array_values($value_vars)) != 0) $vars[$key_vars] = ['$in' => array_values($value_vars)]; - endforeach; - - // vars_date - if (!empty($_POST['vars_date'])): - array_walk_recursive($_POST, 'CleanStr', $_POST['vars_date']); - foreach ($_POST['vars_date'] as $dt => $dv): - $vars[$dt] = $dv; - endforeach; - endif; - if (!empty($_POST['vars_in'])) { - foreach ($_POST['vars_in'] as $key_vars => $value_vars): - $value_vars['$in'] = json_decode($value_vars['$in']); - $vars[$key_vars] = $value_vars; - endforeach; - } - // - if (!empty($_POST['vars']['gte'])) { - foreach ($_POST['vars']['gte'] as $key_vars => $value_vars): - $vars[$key_vars]['$gte'] = is_int($value_vars) ? (int)$value_vars : $value_vars; - endforeach; - unset($vars['gte']); - } - if (!empty($_POST['vars']['lte'])) { - foreach ($_POST['vars']['lte'] as $key_vars => $value_vars): - $vars[$key_vars]['$lte'] = is_int($value_vars) ? (int)$value_vars : $value_vars; - endforeach; - unset($vars['lte']); - } - if (!empty($_POST['vars']['ne'])) { - foreach ($_POST['vars']['ne'] as $key_vars => $value_vars): - $vars[$key_vars]['$ne'] = is_int($value_vars) ? (int)$value_vars : $value_vars; - endforeach; - unset($vars['ne']); - } - - // SETTINGS ne pas faire ici mais par javascript .... - // $APP->set_settings($_SESSION['idagent'], ['sortBy_' . $table => $sortBy, 'sortDir_' . $table => $sortDir, 'groupBy_' . $table => $groupBy, 'nbRows_' . $table => $nbRows]); - // - - $APP_SOCKET = $APP->plug('sitebase_sockets', 'stream_to'); - - // - $where = []; - - # champ = 'null' - - foreach ($vars as $key_vars => $value_vars): - if (strtolower($value_vars) == 'null') { - unset($vars[$key_vars]); - $where['$or'][] = [$key_vars => ['$exists' => false]]; - $where[$key_vars]['$in'] = [null, '']; - - } - - endforeach; - - if (!empty($_POST['search'])) { // un champ de recherche unique - $regexp = new MongoRegex("/" . $_POST['search'] . "/i"); - - if (is_int($_POST['search'])) $where['$or'][] = [$id => (int)$_POST['search']]; - /*$out[] = new MongoRegex("/" . (string)$_POST['search'] . "/i"); - if (sizeof($out) == 1) { - $where = array('$or' => array(array($nom => array('$all' => $out)), array('code' . $Table => array('$in' => $out)))); - }*/ - - if ($APP->has_field('nom')) $where['$or'][] = ['nom' . $Table => $regexp]; - if ($APP->has_field('prenom')) $where['$or'][] = ['prenom' . $Table => $regexp]; - if ($APP->has_field('email')) $where['$or'][] = ['email' . $Table => $regexp]; - if ($APP->has_field('code')) $where['$or'][] = ['code' . $Table => $regexp]; - if ($APP->has_field('reference')) $where['$or'][] = ['reference' . $Table => $regexp]; - if ($APP->has_field('telephone')) $where['$or'][] = ['telephone' . $Table => new MongoRegex("/" . cleanTel($_POST['search']) . "/i")]; - - // tourne ds fk - if (sizeof($GRILLE_FK) != 0) { - foreach ($GRILLE_FK as $field): - $code_fk = 'nom' . ucfirst($field['codeAppscheme']); - $nom_fk = 'nom' . ucfirst($field['nomAppscheme']); - //$regexp = new MongoRegex("/" . $nom_fk . "/i"); - $where['$or'][] = [$code_fk => $regexp]; - $where['$or'][] = [$nom_fk => $regexp]; - endforeach; - } - - // vardump($where);exit; - } - - if (!empty($_POST['search_start'])) { - $regexp = new MongoRegex("/^" . $_POST['search_start'] . "./i"); - // $where['$or'][] = [$nom => $regexp]; - if ($APP->has_field('nom')) { - $vars[$nom] = $regexp; - } else { - $vars[$code] = $regexp; - } - } - - if (!empty($vars_search)) { // vars_search est un array, avec des noms de table - foreach ($vars_search as $key_field => $field_value): - if (empty($field_value)) continue; - // tourne ds fields - $regexp = new MongoRegex("/" . $field_value . "/i"); - $where['$or'][] = [$key_field => $regexp]; - - endforeach; - } - if (!empty($vars_search_fk)) { // vars_search est un array, avec des noms de table - $vars_search_fk = array_filter($vars_search_fk); - if (droit('DEV') && $DEBUG) { - skelMdl::send_cmd('act_notify', ['msg' => '
 $vars_search_fk' . json_encode($vars_search_fk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); - } - foreach ($vars_search_fk as $table_key => $val_search): - if (empty($val_search)) continue; - $testid = substr(trim($table_key), 0, 2);; - if ($testid == 'id') { - $table_key = substr($table_key, -strlen($table_key) + 2); - - if (is_array($val_search)) { - $vars['id' . $table_key] = ['$in' => $val_search]; - } else { - $vars['id' . $table_key] = (int)$val_search; - } - continue; - } - - $where_fk = []; - // => on devrait tourner dans tout les champs de la table vars_search - $APPKEY = new App($table_key); - $APP_TABLE_SCHEME = $APPKEY->get_field_list(); - - // tourne ds fields - foreach ($APP_TABLE_SCHEME as $key_field => $field_scheme): - $tmp_name = $field_scheme['field_name']; - $regexp = new MongoRegex("/" . $val_search . "/i"); - $where_fk['$or'][] = [$tmp_name => $regexp]; - endforeach; - // query distinct id - $rs = $APPKEY->distinct($table_key, $where_fk, 200, 'no_full'); - $vars['id' . $table_key] = ['$in' => array_values($rs)]; - endforeach; - if (droit('DEV') && $DEBUG) { - skelMdl::send_cmd('act_notify', ['msg' => '$where_fk
' . json_encode($where_fk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); - } - } - - if (!empty($vars_search_rfk)) { // vars_search est un array, avec des noms de table - if (droit('DEV') && $DEBUG) { - skelMdl::send_cmd('act_notify', ['msg' => '$vars_search_rfk
' . json_encode($vars_search_rfk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); - } - foreach ($vars_search_rfk as $table_key => $val_search): - $where_rfk = []; - $testid = substr(trim($table_key), 0, 2);; - if ($testid == 'id') $table_key = substr($table_key, -strlen($table_key) + 2); - // => on devrait tourner dans tout les champs de la table vars_search - $APPKEY = new App($table_key); - $APP_TABLE_SCHEME = $APPKEY->get_display_fields($table_key); - - // tourne ds fields - if ($testid == 'id'): - $where_rfk['id' . $table_key] = (int)$val_search; - endif; - foreach ($APP_TABLE_SCHEME as $key_field => $field_scheme): - if ($testid == 'id') continue; - $tmp_name = $field_scheme['nomAppscheme_field']; - $tmp_name_raw = $field_scheme['codeAppscheme_field']; - $regexp = new MongoRegex("/" . $val_search . "/i"); - $where_rfk['$or'][] = [$tmp_name => $regexp]; - if ($tmp_name_raw == 'adresse') { - $where_rfk['$or'][] = ['adresse1' . ucfirst($table_key) => $regexp]; - $where_rfk['$or'][] = ['codePostal' . ucfirst($table_key) => $regexp]; - $where_rfk['$or'][] = ['ville' . ucfirst($table_key) => $regexp]; - } - endforeach; - // query distinct id - - $rs = $APPKEY->distinct($table, $where_rfk, 200, 'no_full'); - - $vars['id' . $table] = ['$in' => array_values($rs)]; - - endforeach; - } - - if (!empty($_POST['console_mode']) && !empty($APP_TABLE['hasStatutScheme'])) { - // statut END, last ? - $APP_STATUT = new App($table . '_statut'); - $ARR_STATUT = $APP_STATUT->findOne(['code' . $Table . '_statut' => 'END']); - if (empty($ARR_STATUT['id' . $table . '_statut'])) { - $RS_STATUT = $APP_STATUT->find()->sort(['ordre' . $Table . '_statut' => -1]); - $ARR_STATUT = $RS_STATUT->getNext(); - } - if (!empty($ARR_STATUT['id' . $table . '_statut'])) { - echo $idnostatut = (int)$ARR_STATUT['id' . $table . '_statut']; - // {dateDebutIntervention:'2015-11-23',idintervention_statut:{'$ne':4}} - // {dateDebutIntervention:{'$ne':'2015-11-23'},idintervention_statut:4} - - $dist1 = $APP->distinct($table, ['dateDebut' . $Table => date('Y-m-d')], 30, 'nofull'); - $dist2 = $APP->distinct($table, ['dateDebut' . $Table => ['$ne' => date('Y-m-d')], 'id' . $table . '_statut' => ['$ne' => $idnostatut]], 30, 'nofull'); - - $where[$id] = ['$in' => $dist1 + $dist2]; - } - } - - $rs = $APP->find($vars + $where)->sort([$sortBy => $sortDir, $sortBySecond => $sortDirSecond])->skip(($nbRows * $page))->limit($nbRows); - $count = $rs->count(); - $maxcount = $rs->count(false); - $count = ($count > $nbRows) ? $nbRows : $count; - // - if (droit('DEV') && $DEBUG) { - skelMdl::send_cmd('act_notify', ['msg' => '
 DATA QUERY 
' . $count . ' : ' . vardump($vars + $where, true) . '/ ' . $sortBySecond . " => " . $sortDirSecond . ' / ' . $page . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); - } - // ACT COUNT - if (!empty($_POST['piece']) && $_POST['piece'] == 'count'): - $data_count = ['count_id' => $_POST['count_id'], 'count' => $rs->count(), 'maxcount' => $maxcount, 'table' => $table]; - skelMdl::send_cmd('act_count', json_decode(json_encode($data_count, JSON_FORCE_OBJECT)), session_id()); - endif; - - if (!empty($_POST['verify'])): - $iter = iterator_to_array($rs1, true); - $key = array_search($_POST['verify'], array_column($iter, 'id' . $table)); - echo ($key === false) ? 'NULL' : $key; - - return; - endif; - - if (!empty($groupBy)): - if (!empty($GRILLE_FK[$groupBy])) { - $rs_dist = $APP->distinct($groupBy, $vars + $where, 50); - $dist_count = $rs_dist->count(); - $dist_max_count = $rs_dist->count(true); - - } else { - $rs_dist = $APP->distinct_all($groupBy, array_merge($vars, $where)); - $dist_count = (sizeof($rs_dist) > 50) ? 50 : sizeof($rs_dist); - $dist_max_count = sizeof($rs_dist); - - } - endif; - // MAIN_DATA - - if (!empty($groupBy)): - $data_main = []; - $strm = []; - - $i = 0; - - foreach ($rs_dist as $arr_dist): - $i++; - if (!empty($GRILLE_FK[$groupBy])) { - $vars['id' . $groupBy] = (int)$arr_dist['id' . $groupBy]; // unset apres - } - $rs = $APP->query($vars + $where)->sort([$sortBy => $sortDir]); - // - $vars_rfk['vars'] = ['id' . $table => $table_value]; - $vars_rfk['table'] = $arr_fk['table']; - $vars_rfk['table_value'] = $arr_fk['table_value']; - - $vars_rfk['vars'] = ['id' . $groupBy => $arr_dist['id' . $groupBy]]; - - $vars_rfk['table'] = $table; - $vars_rfk['table_value'] = $arr_dist['id' . $groupBy]; - $vars_rfk['groupBy'] = $groupBy; - - $data_out = []; - /// datas du groupby colspan - $z = skelMdl::cf_module('app/app/app_fiche_entete_group', ['groupBy' => $groupBy, 'vars' => $vars_rfk, 'table' => $groupBy, 'table_value' => $arr_dist['id' . $groupBy]]); - - $data_main[] = ['html' => $z, 'table' => $groupBy, 'table_value' => $arr_dist['id' . $groupBy], 'vars' => $vars_rfk, 'groupBy' => 1, 'maxcount' => $dist_max_count, 'count' => $dist_count]; - - $count_frag = 0; - $count_frag_test = 0; - - $count_groupBy = $rs->count(); - $count_groupBy_max = $rs->count(true); - - while ($arr = $rs->getNext()) { - if (empty($arr[$id])) continue; - $APP->consolidate_scheme($arr[$id]); - $count_frag++; - $count_frag_test++; - - if (!empty($_POST['stream_to'])): - $arr_allow_stream = $APP_SOCKET->findOne(['nomStream_to' => $_POST['stream_to']]); - if (!empty($arr_allow_stream['stop'])): - exit; - endif; - endif; - $i++; - $data_out = [];//$arr; - - $data_row = dotr($table, $arr); - $data_main[] = array_merge($data_row, ['chunk' => $count_frag_test, 'maxcount' => $dist_max_count, 'count' => $dist_count]); - - // progress - if ($i == 1 || ($i % 100) == 0 || !$rs->hasNext()) { - $progress_vars = ['progress_name' => 'progress_' . $table, 'progress_value' => ($nbRows * $page) + $i, 'progress_max' => $rs_dist->count()]; - skelMdl::send_cmd('act_progress', $progress_vars, session_id()); - } - // stream - if (($i % $strem_chunk_size) == 0 || !$rs->hasNext()) { - if (!empty($_POST['stream_to'])): - $arr_allow_stream = $APP_SOCKET->findOne(['nomStream_to' => $_POST['stream_to']]); - if (!empty($arr_allow_stream['stop'])): - exit; - endif; - - $out_model = ['data_main' => $data_main, 'maxcount' => $dist_max_count, 'url_data' => $url_data, 'table' => $table];// 'columnModel' => $columnModel, - $strm_vars = ['stream_to' => $_POST['stream_to'], 'data' => $out_model, 'data_size' => sizeof($data_main)]; - - skelMdl::send_cmd('act_stream_to', json_decode(json_encode($strm_vars, JSON_FORCE_OBJECT)), session_id()); - unset($data_main); - $count_frag_test++; - endif; - } - } - unset($vars['id' . $groupBy]); - endforeach; - // pas dans distinc : sans groupBy - $data_main = $strm = []; - $vars_rfk = []; - $rs_noGroupBy = $APP->find($vars + $where + ['id' . $groupBy => ['$exists' => false]])->sort([$sortBy => $sortDir])->skip($page)->limit($nbRows); - if ($rs_noGroupBy->count() != 0): - $z = '
Sans ' . $groupBy . '
' . $rs_noGroupBy->count() . '
';//skelMdl::cf_module('app/app/app_fiche_entete_group', ['groupBy' => $groupBy, 'vars' => $vars_rfk, 'table' => $groupBy, 'table_value' => '0']); - $data_main[] = ['html' => $z, 'vars' => $vars_rfk, 'groupBy' => 1]; - $strm[] = ['html' => $z, 'table' => $groupBy, 'table_value' => '', 'vars' => $vars_rfk, 'groupBy' => 1]; - - if (!empty($_POST['stream_to'])): - - $out_model = ['data_main' => $strm, 'maxcount' => $maxcount, 'url_data' => $url_data, 'table' => $table]; // 'columnModel' => $columnModel, - $strm_vars = ['stream_to' => $_POST['stream_to'], 'data' => $out_model, 'data_size' => sizeof($strm)]; - - skelMdl::send_cmd('act_stream_to', json_decode(json_encode($strm_vars, JSON_FORCE_OBJECT)), session_id()); - unset($strm); - endif; - endif; - $rs = $APP->find($vars + $where + ['id' . $groupBy => ['$exists' => false]])->sort([$sortBy => $sortDir])->skip($page)->limit($nbRows); - $count = $rs->count(); - $count = ($count > $nbRows) ? $nbRows : $count; - unset($groupBy); - - endif; - // NORMAL - if ($rs->count() == 0) { - $z = " Pas de résultats"; - - $strm_vars = ['stream_to' => $_POST['stream_to'], - 'data_size' => sizeof($strm), - 'table' => $table, - 'data' => ['data_main' => ['html' => $z, 'table' => $table, 'vars' => $vars, 'groupBy' => 1], - 'maxcount' => $maxcount, - 'url_data' => $url_data, - 'table' => $table] - ]; - - skelMdl::send_cmd('act_stream_to', $strm_vars, session_id()); - } - if (empty($groupBy)): - $data_main = []; - $i = 0; - $modulo = 0; - $count_frag = 0; - $count_frag_test = 0; - $count_prog = 0; - // si demande stream_count - if (!empty($_POST['stream_count'])): - $stream_count[] = ['count' => $count, 'ids' => $trvars, 'value' => $arr[$id], 'table_value' => $arr[$id], 'table' => $table, 'maxcount' => $maxcount, 'count' => $count]; - endif; - // - while ($arr = $rs->getNext()) { - - if (empty($arr[$id])) continue; - $APP->consolidate_scheme($arr[$id]); - $i++; - $count_frag++; - $count_prog++; - - $data_row = dotr($table, $arr); - - $data_main[] = array_merge($data_row, ['chunk' => $count_frag_test, 'maxcount' => $maxcount, 'count' => $count]); - - // PROGRESS - if ($count_prog == 40 || !$rs->hasNext()) { - $progress_vars = ['progress_name' => 'progress_' . $table, 'progress_value' => $i, 'progress_max' => $count]; - skelMdl::send_cmd('act_progress', $progress_vars, session_id()); - $count_prog = 0; - } - - if (!empty($_POST['stream_to'])): - - if (($count_frag % $strem_chunk_size) == 0 || !$rs->hasNext()) { - $out_model = ['data_main' => $data_main, - 'maxcount' => $maxcount, - 'url_data' => $url_data, - 'table' => $table]; - // - $strm_vars = ['stream_to' => $_POST['stream_to'], 'data_size' => sizeof($data_main), - 'table' => $table, - 'data' => $out_model]; - - skelMdl::send_cmd('act_stream_to', $strm_vars, session_id()); - - unset($data_main); - $count_frag = 0; - $count_frag_test++; - } - endif; - - $modulo++; - } - - endif; - // - $out_model = ['data_main' => $data_main, 'maxcount' => $maxcount]; - // - if (empty($_POST['stream_to'])): - echo trim(json_encode($out_model)); - endif; - if (!empty($_POST['csv_export'])): - // - foreach ($data_main as $key => $value) { - array_walk($value['html'], 'strip_tags'); - $csv_main[] = $value['html']; - } - // - $db_tmp = $APP->plug('sitebase_tmp', 'tmp'); - $db_tmp->insert(['uniqid' => $uniqid, 'data' => $csv_main, 'table' => $table, 'vars' => $vars]); - // - skelMdl::send_cmd('act_gui', ['title' => 'Télécharger le csv', 'mdl' => 'app/app_prod/app_prod_csv', 'vars' => 'uniqid=' . $uniqid], session_id()); - - endif; - // - // - function dotr($table, $arr) { - - global $APP, $APP_TABLE, $arrFields_all, $GRILLE_FK, $BASE_APP, $GRILLE_COUNT, $sortBy, $key_date, $MDL; - $out = []; - $id = 'id' . $table; - // variables pour le mdl_tr => vars - $trvars['id' . $table] = $arr[$id]; - $trvars['_id'] = (string)$arr['_id']; - $trvars['table'] = $table; - $trvars['table_value'] = $arr[$id]; - $trvars['sortBy'] = $sortBy; - $trvars['key_date'] = $key_date; - // - $out_more = ['icon' => $APP_TABLE['iconAppscheme'], 'value' => $arr[$id], 'table_value' => $arr[$id], 'table' => $table]; - - foreach ($arrFields_all as $key_f => $value_f): - $field_name = $value_f['field_name']; - $field_value = is_array($arr[$field_name]) ? explode(',', $arr[$field_name]) : $arr[$field_name]; - $field_name_raw = $value_f['field_name_raw']; - $codeAppscheme_field_type = $value_f['codeAppscheme_field_type']; - // if (is_array($arr[$field_name])) unset($arr[$field_name]); - // Integralité des champs // cast - $arr_cast = ['field_name' => $field_name, 'field_name_raw' => $field_name_raw, 'field_value' => $field_value, 'codeAppscheme_field_type' => $codeAppscheme_field_type]; - $arr_cast['table'] = $table; - $arr_cast['table_value'] = $arr[$id]; - $out[$field_name] = $APP->cast_field($arr_cast); - if ($codeAppscheme_field_type == 'bool') { - $set_value = empty($field_value) ? 1 : 0; - $uri = "table=$table&table_value=$arr[$id]&vars[$field_name]="; - $out[$field_name] = "$out[$field_name]"; - } - endforeach; - foreach ($GRILLE_FK as $field): - $code = $BASE_APP . $table . $field['table_fk'] . $arr[$id]; - $id_fk = $field['idtable_fk']; - // - $arrq = $APP->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => (int)$arr[$id_fk]]); - unset($arrq['_id']); - $dsp_name = $arrq['nom' . ucfirst($field['table_fk'])]; - // - $out['id' . $field['table_fk']] = (int)$arr[$id_fk]; - $out['nom' . ucfirst($field['table_fk'])] = $dsp_name; - $out['grille_FK'][$field['table_fk']] = $arrq; - endforeach; - foreach ($GRILLE_COUNT as $key_count => $field): - $APP_TMP = new App($key_count); - $RS_TMP = $APP_TMP->find([$id => $arr[$id]], [$id => 1]); - $link = fonctionsJs::app_liste($key_count, '', ['vars' => [$id => $arr[$id]]]); - $attr = " data-count='data-count' data-table='$key_count' data-vars='vars[$id]=$arr[$id]' "; - $count_grille = (empty($RS_TMP->count())) ? '' : $RS_TMP->count(); - $out['count_' . $key_count] = '' . $count_grille . '' . ((!empty($RS_TMP->count())) ? " $key_count" : ''); - endforeach; - - if (!empty($key_date)): - $out[$key_date] = ''; - endif; - - if (!empty($MDL)) $out_more['mdl'] = skelMdl::cf_module($MDL, ['table' => $table, 'table_value' => $arr[$id]]);; - - if (droit('DEV') && $table == 'ville') { - if (empty($arr['nomVille']) && !empty($arr['codeVille'])) { - skelMdl::send_cmd('act_notify', ['msg' => '
' . $APP->codeAppscheme . ' ' . $arr['codeVille'] . ' => ' . $arr['nomVille'], 'options' => ['sticky' => 1], 'id' => 'json_debug'], session_id()); - $APP->update(['id' . $APP->codeAppscheme => (int)$arr['id' . $APP->codeAppscheme]], ['nomVille' => ucfirst(strtolower($arr['codeVille']))]); - - } - } - - return array_merge(['html' => $out, 'vars' => $trvars], $out_more); - } + 'Agent non connecté', 'options' => $_GET + ['mdl' => 'app/app_login/app_login', 'sticky' => 1, 'id' => 'json_debug']], session_id()); + //return; + } + // skelMdl::send_cmd('act_notify',['msg'=>'Agent non connecté '.session_id('d4uuh6a4jca153fk9rphfl0l27'),'options'=> ['mdl'=>'app/app_login/app_login','sticky'=>1]],"d4uuh6a4jca153fk9rphfl0l27"); + + $DEBUG = false; + + /*ini_set('output_buffering', 'off'); + ini_set('zlib.output_compression', false); + header('Content-Type: text/event-stream'); + header('Cache-Control: no-cache'); + header('Content-Encoding: none;'); + ob_end_flush(); + flush();*/ + + $_POST = array_merge($_GET, $_POST); + // + if (droit('DEV') && $DEBUG) { + skelMdl::send_cmd('act_notify', ['msg' => '__________________
  POST  => ' . json_encode($_POST, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); + } + // + if (droit('DEV') && $DEBUG) { + parse_str($_POST['url_data'], $out_url); + skelMdl::send_cmd('act_notify', ['msg' => '
url_data => ' . json_encode($out_url, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); + } + + // keep url_data + if (!empty($_POST['url_data'])) { + parse_str($_POST['url_data'], $arr_data); + if (empty($arr_data['vars'])) { + $arr_data['vars'] = []; + } + if (!empty($arr_data['vars_search_fk'])) { + $arr_data['vars_search_fk'] = array_filter($arr_data['vars_search_fk']); + } + unset($arr_data['stream_to'], $arr_data['PHPSESSID'], $arr_data['SESSID']); + $url_data = http_build_query($arr_data); + } else { + $tppost = $_POST; + unset($tppost['PHPSESSID'], $tppost['SESSID'], $tppost['stream_to'], $tppost['url_data']); + $url_data = http_build_query($tppost); + } + // + if (empty($_POST['table'])) { + return; + } + if (!empty($_POST['stream_to'])) { + if (!empty($_POST['url_data'])) { + $_POST['url_data'] .= '&stream_to=' . $_POST['stream_to']; + } + } + if (!empty($_POST['url_data'])) { + parse_str($_POST['url_data'], $_POST); + } + $uniqid = uniqid(); + // + $table = $_POST['table']; + $Table = ucfirst($_POST['table']); + // + $APP = new App($table); + // + if (!empty($_SESSION['idagent'])) { + $vars_hist['table'] = $_POST['table']; + $vars_hist['groupBy'] = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; + $vars_hist['search'] = empty($_POST['search']) ? '' : $_POST['search']; + $uid = md5(http_build_query($vars_hist)); + $APP->set_hist($_SESSION['idagent'], ['uid' => $uid] + ['vars' => $vars_hist]); + } + // + $id = 'id' . $table; + $nom = 'nom' . ucfirst($table); + $id_type = 'id' . $table . '_type'; + $nom_type = 'nom' . ucfirst($table) . '_type'; + $top = 'estTop' . ucfirst($table); + $actif = 'estActif' . ucfirst($table); + $visible = 'estVisible' . ucfirst($table); + + // + $vars = empty($_POST['vars']) ? [] : fonctionsProduction::cleanPostMongo(array_filter($_POST['vars'], "my_array_filter_fn"), 1); + $vars_search = empty($_POST['vars_search']) ? [] : fonctionsProduction::cleanPostMongo(array_filter($_POST['vars_search'], "my_array_filter_fn"), 1); + $vars_search_fk = empty($_POST['vars_search_fk']) ? [] : fonctionsProduction::cleanPostMongo(array_filter($_POST['vars_search_fk'], "my_array_filter_fn"), 1); + $vars_search_rfk = empty($_POST['vars_search_rfk']) ? [] : fonctionsProduction::cleanPostMongo(array_filter($_POST['vars_search_rfk'], "my_array_filter_fn"), 1); + + if (droit('DEV') && $DEBUG) { + skelMdl::send_cmd('act_notify', ['msg' => '
  $vars after INIT=> ' . json_encode($vars, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); + } + + if (!droit_table($_SESSION['idagent'], 'CONF', $table) && $APP->has_agent()): + $vars['idagent'] = (int)$_SESSION['idagent']; + endif; + if (!droit_table($_SESSION['idagent'], 'R', $table) && droit_table($_SESSION['idagent'], 'L', $table) && !$APP->has_agent()): + $_POST['vars']['idagent'] = (int)$_SESSION['idagent']; + endif; + // + $APP_TABLE = $APP->app_table_one; + $GRILLE_FK = $APP->get_grille_fk(); + $GRILLE_COUNT = $APP->get_grille_count($table); + $HTTP_VARS = $APP->translate_vars($vars); + $arrFieldsBool = $APP->get_array_field_bool(); + $arrFields_all = $APP->get_field_list(); + // + $groupBy = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; + $sortBy = empty($_POST['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $nom : $APP_TABLE['sortFieldName'] : $_POST['sortBy']; + $sortDir = empty($_POST['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$_POST['sortDir']; + $sortBySecond = empty($_POST['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? $nom : $APP_TABLE['sortFieldSecondName'] : $_POST['sortBySecond']; + $sortDirSecond = empty($_POST['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$_POST['sortDirSecond']; + + $page = (!isset($_POST['page'])) ? 0 : $_POST['page']; + $nbRows = (empty($_POST['nbRows'])) ? empty($settings_nbRows) ? 500 : (int)$settings_nbRows : $_POST['nbRows']; + // + $MDL = empty($_POST['mdl']) ? '' : $_POST['mdl']; + $strem_chunk_size = empty($MDL) ? 20 : 15; + + // $in => tableau + foreach ($vars as $key_vars => $value_vars): + if ($key_vars == 'ne') continue; + if (is_array($value_vars) && $key_vars != 'gte' && $key_vars != 'lte' && $key_vars != 'ne' && sizeof(array_values($value_vars)) != 0) $vars[$key_vars] = ['$in' => array_values($value_vars)]; + endforeach; + + // vars_date + if (!empty($_POST['vars_date'])): + array_walk_recursive($_POST, 'CleanStr', $_POST['vars_date']); + foreach ($_POST['vars_date'] as $dt => $dv): + $vars[$dt] = $dv; + endforeach; + endif; + if (!empty($_POST['vars_in'])) { + foreach ($_POST['vars_in'] as $key_vars => $value_vars): + $value_vars['$in'] = json_decode($value_vars['$in']); + $vars[$key_vars] = $value_vars; + endforeach; + } + // + if (!empty($_POST['vars']['gte'])) { + foreach ($_POST['vars']['gte'] as $key_vars => $value_vars): + $vars[$key_vars]['$gte'] = is_int($value_vars) ? (int)$value_vars : $value_vars; + endforeach; + unset($vars['gte']); + } + if (!empty($_POST['vars']['lte'])) { + foreach ($_POST['vars']['lte'] as $key_vars => $value_vars): + $vars[$key_vars]['$lte'] = is_int($value_vars) ? (int)$value_vars : $value_vars; + endforeach; + unset($vars['lte']); + } + if (!empty($_POST['vars']['ne'])) { + foreach ($_POST['vars']['ne'] as $key_vars => $value_vars): + $vars[$key_vars]['$ne'] = is_int($value_vars) ? (int)$value_vars : $value_vars; + endforeach; + unset($vars['ne']); + } + + // SETTINGS ne pas faire ici mais par javascript .... + // $APP->set_settings($_SESSION['idagent'], ['sortBy_' . $table => $sortBy, 'sortDir_' . $table => $sortDir, 'groupBy_' . $table => $groupBy, 'nbRows_' . $table => $nbRows]); + // + + $APP_SOCKET = $APP->plug('sitebase_sockets', 'stream_to'); + + // + $where = []; + + # champ = 'null' + + foreach ($vars as $key_vars => $value_vars): + if (strtolower($value_vars) == 'null') { + unset($vars[$key_vars]); + $where['$or'][] = [$key_vars => ['$exists' => false]]; + $where[$key_vars]['$in'] = [null, '']; + + } + + endforeach; + + if (!empty($_POST['search'])) { // un champ de recherche unique + $regexp = new MongoRegex("/" . $_POST['search'] . "/i"); + + if (is_int($_POST['search'])) $where['$or'][] = [$id => (int)$_POST['search']]; + /*$out[] = new MongoRegex("/" . (string)$_POST['search'] . "/i"); + if (sizeof($out) == 1) { + $where = array('$or' => array(array($nom => array('$all' => $out)), array('code' . $Table => array('$in' => $out)))); + }*/ + + if ($APP->has_field('nom')) $where['$or'][] = ['nom' . $Table => $regexp]; + if ($APP->has_field('prenom')) $where['$or'][] = ['prenom' . $Table => $regexp]; + if ($APP->has_field('email')) $where['$or'][] = ['email' . $Table => $regexp]; + if ($APP->has_field('code')) $where['$or'][] = ['code' . $Table => $regexp]; + if ($APP->has_field('reference')) $where['$or'][] = ['reference' . $Table => $regexp]; + if ($APP->has_field('telephone')) $where['$or'][] = ['telephone' . $Table => new MongoRegex("/" . cleanTel($_POST['search']) . "/i")]; + + // tourne ds fk + if (sizeof($GRILLE_FK) != 0) { + foreach ($GRILLE_FK as $field): + $code_fk = 'nom' . ucfirst($field['codeAppscheme']); + $nom_fk = 'nom' . ucfirst($field['nomAppscheme']); + //$regexp = new MongoRegex("/" . $nom_fk . "/i"); + $where['$or'][] = [$code_fk => $regexp]; + $where['$or'][] = [$nom_fk => $regexp]; + endforeach; + } + + // vardump($where);exit; + } + + if (!empty($_POST['search_start'])) { + $regexp = new MongoRegex("/^" . $_POST['search_start'] . "./i"); + // $where['$or'][] = [$nom => $regexp]; + if ($APP->has_field('nom')) { + $vars[$nom] = $regexp; + } else { + $vars[$code] = $regexp; + } + } + + if (!empty($vars_search)) { // vars_search est un array, avec des noms de table + foreach ($vars_search as $key_field => $field_value): + if (empty($field_value)) continue; + // tourne ds fields + $regexp = new MongoRegex("/" . $field_value . "/i"); + $where['$or'][] = [$key_field => $regexp]; + + endforeach; + } + if (!empty($vars_search_fk)) { // vars_search est un array, avec des noms de table + $vars_search_fk = array_filter($vars_search_fk); + if (droit('DEV') && $DEBUG) { + skelMdl::send_cmd('act_notify', ['msg' => '
 $vars_search_fk' . json_encode($vars_search_fk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); + } + foreach ($vars_search_fk as $table_key => $val_search): + if (empty($val_search)) continue; + $testid = substr(trim($table_key), 0, 2);; + if ($testid == 'id') { + $table_key = substr($table_key, -strlen($table_key) + 2); + + if (is_array($val_search)) { + $vars['id' . $table_key] = ['$in' => $val_search]; + } else { + $vars['id' . $table_key] = (int)$val_search; + } + continue; + } + + $where_fk = []; + // => on devrait tourner dans tout les champs de la table vars_search + $APPKEY = new App($table_key); + $APP_TABLE_SCHEME = $APPKEY->get_field_list(); + + // tourne ds fields + foreach ($APP_TABLE_SCHEME as $key_field => $field_scheme): + $tmp_name = $field_scheme['field_name']; + $regexp = new MongoRegex("/" . $val_search . "/i"); + $where_fk['$or'][] = [$tmp_name => $regexp]; + endforeach; + // query distinct id + $rs = $APPKEY->distinct($table_key, $where_fk, 200, 'no_full'); + $vars['id' . $table_key] = ['$in' => array_values($rs)]; + endforeach; + if (droit('DEV') && $DEBUG) { + skelMdl::send_cmd('act_notify', ['msg' => '$where_fk
' . json_encode($where_fk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); + } + } + + if (!empty($vars_search_rfk)) { // vars_search est un array, avec des noms de table + if (droit('DEV') && $DEBUG) { + skelMdl::send_cmd('act_notify', ['msg' => '$vars_search_rfk
' . json_encode($vars_search_rfk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); + } + foreach ($vars_search_rfk as $table_key => $val_search): + $where_rfk = []; + $testid = substr(trim($table_key), 0, 2);; + if ($testid == 'id') $table_key = substr($table_key, -strlen($table_key) + 2); + // => on devrait tourner dans tout les champs de la table vars_search + $APPKEY = new App($table_key); + $APP_TABLE_SCHEME = $APPKEY->get_display_fields($table_key); + + // tourne ds fields + if ($testid == 'id'): + $where_rfk['id' . $table_key] = (int)$val_search; + endif; + foreach ($APP_TABLE_SCHEME as $key_field => $field_scheme): + if ($testid == 'id') continue; + $tmp_name = $field_scheme['nomAppscheme_field']; + $tmp_name_raw = $field_scheme['codeAppscheme_field']; + $regexp = new MongoRegex("/" . $val_search . "/i"); + $where_rfk['$or'][] = [$tmp_name => $regexp]; + if ($tmp_name_raw == 'adresse') { + $where_rfk['$or'][] = ['adresse1' . ucfirst($table_key) => $regexp]; + $where_rfk['$or'][] = ['codePostal' . ucfirst($table_key) => $regexp]; + $where_rfk['$or'][] = ['ville' . ucfirst($table_key) => $regexp]; + } + endforeach; + // query distinct id + + $rs = $APPKEY->distinct($table, $where_rfk, 200, 'no_full'); + + $vars['id' . $table] = ['$in' => array_values($rs)]; + + endforeach; + } + + if (!empty($_POST['console_mode']) && !empty($APP_TABLE['hasStatutScheme'])) { + // statut END, last ? + $APP_STATUT = new App($table . '_statut'); + $ARR_STATUT = $APP_STATUT->findOne(['code' . $Table . '_statut' => 'END']); + if (empty($ARR_STATUT['id' . $table . '_statut'])) { + $RS_STATUT = $APP_STATUT->find()->sort(['ordre' . $Table . '_statut' => -1]); + $ARR_STATUT = $RS_STATUT->getNext(); + } + if (!empty($ARR_STATUT['id' . $table . '_statut'])) { + echo $idnostatut = (int)$ARR_STATUT['id' . $table . '_statut']; + // {dateDebutIntervention:'2015-11-23',idintervention_statut:{'$ne':4}} + // {dateDebutIntervention:{'$ne':'2015-11-23'},idintervention_statut:4} + + $dist1 = $APP->distinct($table, ['dateDebut' . $Table => date('Y-m-d')], 30, 'nofull'); + $dist2 = $APP->distinct($table, ['dateDebut' . $Table => ['$ne' => date('Y-m-d')], 'id' . $table . '_statut' => ['$ne' => $idnostatut]], 30, 'nofull'); + + $where[$id] = ['$in' => $dist1 + $dist2]; + } + } + + $rs = $APP->find($vars + $where)->sort([$sortBy => $sortDir, $sortBySecond => $sortDirSecond])->skip(($nbRows * $page))->limit($nbRows); + $count = $rs->count(); + $maxcount = $rs->count(false); + $count = ($count > $nbRows) ? $nbRows : $count; + // + if (droit('DEV') && $DEBUG) { + skelMdl::send_cmd('act_notify', ['msg' => '
 DATA QUERY 
' . $count . ' : ' . vardump($vars + $where, true) . '/ ' . $sortBySecond . " => " . $sortDirSecond . ' / ' . $page . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); + } + // ACT COUNT + if (!empty($_POST['piece']) && $_POST['piece'] == 'count'): + $data_count = ['count_id' => $_POST['count_id'], 'count' => $rs->count(), 'maxcount' => $maxcount, 'table' => $table]; + skelMdl::send_cmd('act_count', json_decode(json_encode($data_count, JSON_FORCE_OBJECT)), session_id()); + endif; + + if (!empty($_POST['verify'])): + $iter = iterator_to_array($rs1, true); + $key = array_search($_POST['verify'], array_column($iter, 'id' . $table)); + echo ($key === false) ? 'NULL' : $key; + + return; + endif; + + if (!empty($groupBy)): + if (!empty($GRILLE_FK[$groupBy])) { + $rs_dist = $APP->distinct($groupBy, $vars + $where, 50); + $dist_count = $rs_dist->count(); + $dist_max_count = $rs_dist->count(true); + + } else { + $rs_dist = $APP->distinct_all($groupBy, array_merge($vars, $where)); + $dist_count = (sizeof($rs_dist) > 50) ? 50 : sizeof($rs_dist); + $dist_max_count = sizeof($rs_dist); + + } + endif; + // MAIN_DATA + + if (!empty($groupBy)): + $data_main = []; + $strm = []; + + $i = 0; + + foreach ($rs_dist as $arr_dist): + $i++; + if (!empty($GRILLE_FK[$groupBy])) { + $vars['id' . $groupBy] = (int)$arr_dist['id' . $groupBy]; // unset apres + } + $rs = $APP->query($vars + $where)->sort([$sortBy => $sortDir]); + // + $vars_rfk['vars'] = ['id' . $table => $table_value]; + $vars_rfk['table'] = $arr_fk['table']; + $vars_rfk['table_value'] = $arr_fk['table_value']; + + $vars_rfk['vars'] = ['id' . $groupBy => $arr_dist['id' . $groupBy]]; + + $vars_rfk['table'] = $table; + $vars_rfk['table_value'] = $arr_dist['id' . $groupBy]; + $vars_rfk['groupBy'] = $groupBy; + + $data_out = []; + /// datas du groupby colspan + $z = skelMdl::cf_module('app/app/app_fiche_entete_group', ['groupBy' => $groupBy, 'vars' => $vars_rfk, 'table' => $groupBy, 'table_value' => $arr_dist['id' . $groupBy]]); + + $data_main[] = ['html' => $z, 'table' => $groupBy, 'table_value' => $arr_dist['id' . $groupBy], 'vars' => $vars_rfk, 'groupBy' => 1, 'maxcount' => $dist_max_count, 'count' => $dist_count]; + + $count_frag = 0; + $count_frag_test = 0; + + $count_groupBy = $rs->count(); + $count_groupBy_max = $rs->count(true); + + while ($arr = $rs->getNext()) { + if (empty($arr[$id])) continue; + $APP->consolidate_scheme($arr[$id]); + $count_frag++; + $count_frag_test++; + + if (!empty($_POST['stream_to'])): + $arr_allow_stream = $APP_SOCKET->findOne(['nomStream_to' => $_POST['stream_to']]); + if (!empty($arr_allow_stream['stop'])): + exit; + endif; + endif; + $i++; + $data_out = [];//$arr; + + $data_row = dotr($table, $arr); + $data_main[] = array_merge($data_row, ['chunk' => $count_frag_test, 'maxcount' => $dist_max_count, 'count' => $dist_count]); + + // progress + if ($i == 1 || ($i % 100) == 0 || !$rs->hasNext()) { + $progress_vars = ['progress_name' => 'progress_' . $table, 'progress_value' => ($nbRows * $page) + $i, 'progress_max' => $rs_dist->count()]; + skelMdl::send_cmd('act_progress', $progress_vars, session_id()); + } + // stream + if (($i % $strem_chunk_size) == 0 || !$rs->hasNext()) { + if (!empty($_POST['stream_to'])): + $arr_allow_stream = $APP_SOCKET->findOne(['nomStream_to' => $_POST['stream_to']]); + if (!empty($arr_allow_stream['stop'])): + exit; + endif; + + $out_model = ['data_main' => $data_main, 'maxcount' => $dist_max_count, 'url_data' => $url_data, 'table' => $table];// 'columnModel' => $columnModel, + $strm_vars = ['stream_to' => $_POST['stream_to'], 'data' => $out_model, 'data_size' => sizeof($data_main)]; + + skelMdl::send_cmd('act_stream_to', json_decode(json_encode($strm_vars, JSON_FORCE_OBJECT)), session_id()); + unset($data_main); + $count_frag_test++; + endif; + } + } + unset($vars['id' . $groupBy]); + endforeach; + // pas dans distinc : sans groupBy + $data_main = $strm = []; + $vars_rfk = []; + $rs_noGroupBy = $APP->find($vars + $where + ['id' . $groupBy => ['$exists' => false]])->sort([$sortBy => $sortDir])->skip($page)->limit($nbRows); + if ($rs_noGroupBy->count() != 0): + $z = '
Sans ' . $groupBy . '
' . $rs_noGroupBy->count() . '
';//skelMdl::cf_module('app/app/app_fiche_entete_group', ['groupBy' => $groupBy, 'vars' => $vars_rfk, 'table' => $groupBy, 'table_value' => '0']); + $data_main[] = ['html' => $z, 'vars' => $vars_rfk, 'groupBy' => 1]; + $strm[] = ['html' => $z, 'table' => $groupBy, 'table_value' => '', 'vars' => $vars_rfk, 'groupBy' => 1]; + + if (!empty($_POST['stream_to'])): + + $out_model = ['data_main' => $strm, 'maxcount' => $maxcount, 'url_data' => $url_data, 'table' => $table]; // 'columnModel' => $columnModel, + $strm_vars = ['stream_to' => $_POST['stream_to'], 'data' => $out_model, 'data_size' => sizeof($strm)]; + + skelMdl::send_cmd('act_stream_to', json_decode(json_encode($strm_vars, JSON_FORCE_OBJECT)), session_id()); + unset($strm); + endif; + endif; + $rs = $APP->find($vars + $where + ['id' . $groupBy => ['$exists' => false]])->sort([$sortBy => $sortDir])->skip($page)->limit($nbRows); + $count = $rs->count(); + $count = ($count > $nbRows) ? $nbRows : $count; + unset($groupBy); + + endif; + // NORMAL + if ($rs->count() == 0) { + $z = " Pas de résultats"; + + $strm_vars = ['stream_to' => $_POST['stream_to'], + 'data_size' => sizeof($strm), + 'table' => $table, + 'data' => ['data_main' => ['html' => $z, 'table' => $table, 'vars' => $vars, 'groupBy' => 1], + 'maxcount' => $maxcount, + 'url_data' => $url_data, + 'table' => $table] + ]; + + skelMdl::send_cmd('act_stream_to', $strm_vars, session_id()); + } + if (empty($groupBy)): + $data_main = []; + $i = 0; + $modulo = 0; + $count_frag = 0; + $count_frag_test = 0; + $count_prog = 0; + // si demande stream_count + if (!empty($_POST['stream_count'])): + $stream_count[] = ['count' => $count, 'ids' => $trvars, 'value' => $arr[$id], 'table_value' => $arr[$id], 'table' => $table, 'maxcount' => $maxcount, 'count' => $count]; + endif; + // + while ($arr = $rs->getNext()) { + + if (empty($arr[$id])) continue; + $APP->consolidate_scheme($arr[$id]); + $i++; + $count_frag++; + $count_prog++; + + $data_row = dotr($table, $arr); + + $data_main[] = array_merge($data_row, ['chunk' => $count_frag_test, 'maxcount' => $maxcount, 'count' => $count]); + + // PROGRESS + if ($count_prog == 40 || !$rs->hasNext()) { + $progress_vars = ['progress_name' => 'progress_' . $table, 'progress_value' => $i, 'progress_max' => $count]; + skelMdl::send_cmd('act_progress', $progress_vars, session_id()); + $count_prog = 0; + } + + if (!empty($_POST['stream_to'])): + + if (($count_frag % $strem_chunk_size) == 0 || !$rs->hasNext()) { + $out_model = ['data_main' => $data_main, + 'maxcount' => $maxcount, + 'url_data' => $url_data, + 'table' => $table]; + // + $strm_vars = ['stream_to' => $_POST['stream_to'], 'data_size' => sizeof($data_main), + 'table' => $table, + 'data' => $out_model]; + + skelMdl::send_cmd('act_stream_to', $strm_vars, session_id()); + + unset($data_main); + $count_frag = 0; + $count_frag_test++; + } + endif; + + $modulo++; + } + + endif; + // + $out_model = ['data_main' => $data_main, 'maxcount' => $maxcount]; + // + if (empty($_POST['stream_to'])): + echo trim(json_encode($out_model)); + endif; + if (!empty($_POST['csv_export'])): + // + foreach ($data_main as $key => $value) { + array_walk($value['html'], 'strip_tags'); + $csv_main[] = $value['html']; + } + // + $db_tmp = $APP->plug('sitebase_tmp', 'tmp'); + $db_tmp->insert(['uniqid' => $uniqid, 'data' => $csv_main, 'table' => $table, 'vars' => $vars]); + // + skelMdl::send_cmd('act_gui', ['title' => 'Télécharger le csv', 'mdl' => 'app/app_prod/app_prod_csv', 'vars' => 'uniqid=' . $uniqid], session_id()); + + endif; + // + // + function dotr($table, $arr) { + + global $APP, $APP_TABLE, $arrFields_all, $GRILLE_FK, $BASE_APP, $GRILLE_COUNT, $sortBy, $key_date, $MDL; + $out = []; + $id = 'id' . $table; + // variables pour le mdl_tr => vars + $trvars['id' . $table] = $arr[$id]; + $trvars['_id'] = (string)$arr['_id']; + $trvars['table'] = $table; + $trvars['table_value'] = $arr[$id]; + $trvars['sortBy'] = $sortBy; + $trvars['key_date'] = $key_date; + // + $out_more = ['icon' => $APP_TABLE['iconAppscheme'], 'value' => $arr[$id], 'table_value' => $arr[$id], 'table' => $table]; + + foreach ($arrFields_all as $key_f => $value_f): + $field_name = $value_f['field_name']; + $field_value = is_array($arr[$field_name]) ? explode(',', $arr[$field_name]) : $arr[$field_name]; + $field_name_raw = $value_f['field_name_raw']; + $codeAppscheme_field_type = $value_f['codeAppscheme_field_type']; + // if (is_array($arr[$field_name])) unset($arr[$field_name]); + // Integralité des champs // cast + $arr_cast = ['field_name' => $field_name, 'field_name_raw' => $field_name_raw, 'field_value' => $field_value, 'codeAppscheme_field_type' => $codeAppscheme_field_type]; + $arr_cast['table'] = $table; + $arr_cast['table_value'] = $arr[$id]; + $out[$field_name] = $APP->cast_field($arr_cast); + if ($codeAppscheme_field_type == 'bool') { + $set_value = empty($field_value) ? 1 : 0; + $uri = "table=$table&table_value=$arr[$id]&vars[$field_name]="; + $out[$field_name] = "$out[$field_name]"; + } + endforeach; + foreach ($GRILLE_FK as $field): + $code = $BASE_APP . $table . $field['table_fk'] . $arr[$id]; + $id_fk = $field['idtable_fk']; + // + $arrq = $APP->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => (int)$arr[$id_fk]]); + unset($arrq['_id']); + $dsp_name = $arrq['nom' . ucfirst($field['table_fk'])]; + // + $out['id' . $field['table_fk']] = (int)$arr[$id_fk]; + $out['nom' . ucfirst($field['table_fk'])] = $dsp_name; + $out['grille_FK'][$field['table_fk']] = $arrq; + endforeach; + foreach ($GRILLE_COUNT as $key_count => $field): + $APP_TMP = new App($key_count); + $RS_TMP = $APP_TMP->find([$id => $arr[$id]], [$id => 1]); + $link = fonctionsJs::app_liste($key_count, '', ['vars' => [$id => $arr[$id]]]); + $attr = " data-count='data-count' data-table='$key_count' data-vars='vars[$id]=$arr[$id]' "; + $count_grille = (empty($RS_TMP->count())) ? '' : $RS_TMP->count(); + $out['count_' . $key_count] = '' . $count_grille . '' . ((!empty($RS_TMP->count())) ? " $key_count" : ''); + endforeach; + + if (!empty($key_date)): + $out[$key_date] = ''; + endif; + + if (!empty($MDL)) $out_more['mdl'] = skelMdl::cf_module($MDL, ['table' => $table, 'table_value' => $arr[$id]]);; + + if (droit('DEV') && $table == 'ville') { + if (empty($arr['nomVille']) && !empty($arr['codeVille'])) { + skelMdl::send_cmd('act_notify', ['msg' => '
' . $APP->codeAppscheme . ' ' . $arr['codeVille'] . ' => ' . $arr['nomVille'], 'options' => ['sticky' => 1], 'id' => 'json_debug'], session_id()); + $APP->update(['id' . $APP->codeAppscheme => (int)$arr['id' . $APP->codeAppscheme]], ['nomVille' => ucfirst(strtolower($arr['codeVille']))]); + + } + } + + return array_merge(['html' => $out, 'vars' => $trvars], $out_more); + } diff --git a/web/bin/services/json_data_table_migrate.php b/web/bin/services/json_data_table_migrate.php index 9d70dc9..5c5ca9f 100644 --- a/web/bin/services/json_data_table_migrate.php +++ b/web/bin/services/json_data_table_migrate.php @@ -1,653 +1,653 @@ -app_table_one; - $GRILLE_FK = $APP->get_grille_fk();// $APP->get_fk_tables($table); - $GRILLE_COUNT = $APP->get_grille_count($table); - $arrFields_all = $APP->get_field_list(); - // - $groupBy = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; - $sortBy = empty($_POST['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $nom : $APP_TABLE['sortFieldName'] : $_POST['sortBy']; - $sortDir = empty($_POST['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$_POST['sortDir']; - $sortBySecond = empty($_POST['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? $nom : $APP_TABLE['sortFieldSecondName'] : $_POST['sortBySecond']; - $sortDirSecond = empty($_POST['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$_POST['sortDirSecond']; - - $page = (!isset($_POST['page'])) ? 0 : $_POST['page']; - $nbRows = (empty($_POST['nbRows'])) ? empty($settings_nbRows) ? 150 : (int)$settings_nbRows : $_POST['nbRows']; - // - $MDL = empty($_POST['mdl']) ? '' : $_POST['mdl']; - $strem_chunk_size = empty($MDL) ? 20 : 15; - - // $in => tableau - foreach ($vars as $key_vars => $value_vars): - if ($key_vars == 'ne') continue; - if (is_array($value_vars) && $key_vars != 'gte' && $key_vars != 'lte' && $key_vars != 'ne' && sizeof(array_values($value_vars)) != 0) $vars[$key_vars] = ['$in' => array_values($value_vars)]; - endforeach; - - // vars_date - if (!empty($_POST['vars_date'])): - array_walk_recursive($_POST, 'CleanStr', $_POST['vars_date']); - foreach ($_POST['vars_date'] as $dt => $dv): - $vars[$dt] = $dv; - endforeach; - endif; - if (!empty($_POST['vars_in'])) { - foreach ($_POST['vars_in'] as $key_vars => $value_vars): - $value_vars['$in'] = json_decode($value_vars['$in']); - $vars[$key_vars] = $value_vars; - endforeach; - } - // - if (!empty($_POST['vars']['gte'])) { - foreach ($_POST['vars']['gte'] as $key_vars => $value_vars): - $vars[$key_vars]['$gte'] = is_int($value_vars) ? (int)$value_vars : $value_vars; - endforeach; - unset($vars['gte']); - } - if (!empty($_POST['vars']['lte'])) { - foreach ($_POST['vars']['lte'] as $key_vars => $value_vars): - $vars[$key_vars]['$lte'] = is_int($value_vars) ? (int)$value_vars : $value_vars; - endforeach; - unset($vars['lte']); - } - if (!empty($_POST['vars']['ne'])) { - foreach ($_POST['vars']['ne'] as $key_vars => $value_vars): - $vars[$key_vars]['$ne'] = is_int($value_vars) ? (int)$value_vars : $value_vars; - endforeach; - unset($vars['ne']); - } - - - $APP_SOCKET = $APP->plug('sitebase_sockets', 'stream_to'); - // - - // - $where = []; - - # champ = 'null' - - foreach ($vars as $key_vars => $value_vars): - if (strtolower($value_vars) == 'null') { - unset($vars[$key_vars]); - $where['$or'][] = [$key_vars => ['$exists' => false]]; - $where[$key_vars]['$in'] = [null, '']; - - } - - endforeach; - - if (!empty($_POST['search'])) { // un champ de recherche unique - $regexp = new MongoRegex("/" . $_POST['search'] . "/i"); - - if (is_int($_POST['search'])) $where['$or'][] = [$id => (int)$_POST['search']]; - - if ($APP->has_field('nom')) $where['$or'][] = ['nom' . $Table => $regexp]; - if ($APP->has_field('prenom')) $where['$or'][] = ['prenom' . $Table => $regexp]; - if ($APP->has_field('email')) $where['$or'][] = ['email' . $Table => $regexp]; - if ($APP->has_field('code')) $where['$or'][] = ['code' . $Table => $regexp]; - if ($APP->has_field('reference')) $where['$or'][] = ['reference' . $Table => $regexp]; - if ($APP->has_field('telephone')) $where['$or'][] = ['telephone' . $Table => new MongoRegex("/" . cleanTel($_POST['search']) . "/i")]; - - // tourne ds fk - if (sizeof($GRILLE_FK) != 0) { - foreach ($GRILLE_FK as $field): - $code_fk = 'nom' . ucfirst($field['codeAppscheme']); - $nom_fk = 'nom' . ucfirst($field['nomAppscheme']); - //$regexp = new MongoRegex("/" . $nom_fk . "/i"); - $where['$or'][] = [$code_fk => $regexp]; - $where['$or'][] = [$nom_fk => $regexp]; - endforeach; - } - - // vardump($where);exit; - } - - if (!empty($_POST['search_start'])) { - $regexp = new MongoRegex("/^" . $_POST['search_start'] . "./i"); - // $where['$or'][] = [$nom => $regexp]; - if ($APP->has_field('nom')) { - $vars[$nom] = $regexp; - } else { - $vars[$code] = $regexp; - } - } - - if (!empty($vars_search)) { // vars_search est un array, avec des noms de table - foreach ($vars_search as $key_field => $field_value): - if (empty($field_value)) continue; - // tourne ds fields - $regexp = new MongoRegex("/" . $field_value . "/i"); - $where['$or'][] = [$key_field => $regexp]; - - endforeach; - } - if (!empty($vars_search_fk)) { // vars_search est un array, avec des noms de table - $vars_search_fk = array_filter($vars_search_fk); - if ($DEBUG && droit('DEV')) { - skelMdl::send_cmd('act_notify', ['msg' => '
 $vars_search_fk' . json_encode($vars_search_fk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); - } - foreach ($vars_search_fk as $table_key => $val_search): - if (empty($val_search)) continue; - $testid = substr(trim($table_key), 0, 2);; - if ($testid == 'id') { - $table_key = substr($table_key, -strlen($table_key) + 2); - - if (is_array($val_search)) { - $vars['id' . $table_key] = ['$in' => $val_search]; - } else { - $vars['id' . $table_key] = (int)$val_search; - } - continue; - } - - $where_fk = []; - // => on devrait tourner dans tout les champs de la table vars_search - $APPKEY = new App($table_key); - $APP_TABLE_SCHEME = $APPKEY->get_field_list(); - - // tourne ds fields - foreach ($APP_TABLE_SCHEME as $key_field => $field_scheme): - $tmp_name = $field_scheme['field_name']; - $regexp = new MongoRegex("/" . $val_search . "/i"); - $where_fk['$or'][] = [$tmp_name => $regexp]; - endforeach; - // query distinct id - $rs = $APPKEY->distinct($table_key, $where_fk, 200, 'no_full'); - $vars['id' . $table_key] = ['$in' => array_values($rs)]; - endforeach; - if ($DEBUG && droit('DEV')) { - skelMdl::send_cmd('act_notify', ['msg' => '$where_fk
' . json_encode($where_fk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); - } - } - - if (!empty($vars_search_rfk)) { // vars_search est un array, avec des noms de table - - foreach ($vars_search_rfk as $table_key => $val_search): - $where_rfk = []; - $testid = substr(trim($table_key), 0, 2);; - if ($testid == 'id') $table_key = substr($table_key, -strlen($table_key) + 2); - // => on devrait tourner dans tout les champs de la table vars_search - $APPKEY = new App($table_key); - $APP_TABLE_SCHEME = $APPKEY->get_display_fields($table_key); - - // tourne ds fields - if ($testid == 'id'): - $where_rfk['id' . $table_key] = (int)$val_search; - endif; - foreach ($APP_TABLE_SCHEME as $key_field => $field_scheme): - if ($testid == 'id') continue; - $tmp_name = $field_scheme['nomAppscheme_field']; - $tmp_name_raw = $field_scheme['codeAppscheme_field']; - $regexp = new MongoRegex("/" . $val_search . "/i"); - $where_rfk['$or'][] = [$tmp_name => $regexp]; - if ($tmp_name_raw == 'adresse') { - $where_rfk['$or'][] = ['adresse1' . ucfirst($table_key) => $regexp]; - $where_rfk['$or'][] = ['codePostal' . ucfirst($table_key) => $regexp]; - $where_rfk['$or'][] = ['ville' . ucfirst($table_key) => $regexp]; - } - endforeach; - // query distinct id - - $rs = $APPKEY->distinct($table, $where_rfk, 200, 'no_full'); - - $vars['id' . $table] = ['$in' => array_values($rs)]; - - endforeach; - } - - if (!empty($_POST['console_mode']) && !empty($APP_TABLE['hasStatutScheme'])) { - // statut END, last ? - $APP_STATUT = new App($table . '_statut'); - $ARR_STATUT = $APP_STATUT->findOne(['code' . $Table . '_statut' => 'END']); - if (empty($ARR_STATUT['id' . $table . '_statut'])) { - $RS_STATUT = $APP_STATUT->find()->sort(['ordre' . $Table . '_statut' => -1]); - $ARR_STATUT = $RS_STATUT->getNext(); - } - if (!empty($ARR_STATUT['id' . $table . '_statut'])) { - echo $idnostatut = (int)$ARR_STATUT['id' . $table . '_statut']; - // {dateDebutIntervention:'2015-11-23',idintervention_statut:{'$ne':4}} - // {dateDebutIntervention:{'$ne':'2015-11-23'},idintervention_statut:4} - - $dist1 = $APP->distinct($table, ['dateDebut' . $Table => date('Y-m-d')], 30, 'nofull'); - $dist2 = $APP->distinct($table, ['dateDebut' . $Table => ['$ne' => date('Y-m-d')], 'id' . $table . '_statut' => ['$ne' => $idnostatut]], 30, 'nofull'); - - $where[$id] = ['$in' => $dist1 + $dist2]; - } - } - - $rs = $APP->find($vars + $where)->sort([$sortBy => $sortDir, $sortBySecond => $sortDirSecond])->skip(($nbRows * $page))->limit($nbRows); - $count = $rs->count(); - $maxcount = $rs->count(false); - $count = ($count > $nbRows) ? $nbRows : $count; - // - if ($DEBUG && droit('DEV')) { - //skelMdl::send_cmd('act_notify', ['msg' => '
 DATA QUERY 
' . $count . ' : ' . json_encode($vars + $where) . '/ ' . $sortBySecond . " => " . $sortDirSecond . ' / ' . $page . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); - } - // ACT COUNT - if (!empty($_POST['piece']) && $_POST['piece'] == 'count'): - $data_count = ['count_id' => $_POST['count_id'], 'count' => $rs->count(), 'maxcount' => $maxcount, 'table' => $table]; - //skelMdl::send_cmd('act_count', json_decode(json_encode($data_count, JSON_FORCE_OBJECT)), session_id()); - endif; - - if (!empty($_POST['verify'])): - $iter = iterator_to_array($rs1, true); - $key = array_search($_POST['verify'], array_column($iter, 'id' . $table)); - echo ($key === false) ? 'NULL' : $key; - - return; - endif; - - if (!empty($groupBy)): - if (!empty($GRILLE_FK[$groupBy])) { - $rs_dist = $APP->distinct($groupBy, $vars + $where, 50); - $dist_count = $rs_dist->count(); - $dist_max_count = $rs_dist->count(true); - $rs_dist = iterator_to_array($rs_dist); - $groupBy_field = "id$groupBy"; - $groupBy_values = array_column($rs_dist, $groupBy_field); - $groupBy_mode = "grille"; - $APP_GROUP = new App($groupBy); - $APP_TGR = $APP_GROUP->app_table_one; - $RS_GROUP = $APP_GROUP->find([$groupBy_field => ['$in' => $groupBy_values]])->sort([$APP_TGR['sortFieldName'] => $APP_TGR['sortFieldOrder']]); - - } else { - $rs_dist = array_filter($APP->distinct_all($groupBy, array_merge($vars, $where))); - $dist_count = (sizeof($rs_dist) > 50) ? 50 : sizeof($rs_dist); - $dist_max_count = sizeof($rs_dist); - $groupBy_field = $groupBy; - $groupBy_mode = "field"; - // date - nombre - - - } - /*if ($DEBUG && droit('DEV')) { - skelMdl::send_cmd('act_notify', ['msg' => '
 groupBy 
' . $groupBy . '/' . $groupBy_field . ' : ' . $groupBy_mode . sizeof($rs_dist) . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); - }*/ - endif; - // MAIN_DATA - - if (!empty($groupBy) && !empty($rs_dist) && !empty($groupBy_field)): - $data_main = []; - - $i = 0; - switch ($groupBy_mode): - case 'grille': - $rs_dist = array_filter($rs_dist); - break; - case 'field': - // date ? string ? int ? - if (strpos($groupBy_field, 'date') !== false) { - $rs_dist = array_map(function ($value) { - return substr($value, 0, 7); - }, $rs_dist); - $groupBy_mode = 'date'; - } else if (strpos($groupBy_field, 'email') !== false) { - $rs_dist = array_map(function ($value) { - return end(explode('@', $value)); - }, $rs_dist); - $groupBy_mode = 'email'; - } else if (is_string(reset($rs_dist))) { - $rs_dist = array_map(function ($value) { - return substr($value, 0, 2); - }, $rs_dist); - $groupBy_mode = 'string'; - } else { - $groupBy_mode = 'integer'; - } - $rs_dist = array_filter($rs_dist); - break; - endswitch; - - foreach ($rs_dist as $key_dist => $arr_dist): - $i++; - $vars_groupBy = []; - switch ($groupBy_mode): - case 'grille': - $vars_groupBy[$groupBy_field] = (int)$arr_dist[$groupBy_field]; // unset apres - $table_value = $arr_dist[$groupBy_field]; - break; - case 'date': - $vars_groupBy[$groupBy_field] = new MongoRegex("/^" . $arr_dist . "/i"); - $table_value = $arr_dist; - break; - case 'email': - $vars_groupBy[$groupBy_field] = new MongoRegex("/" . $arr_dist . "/i");; - $table_value = $arr_dist; - break; - case 'field': - case 'integer': - case 'string': - $vars_groupBy[$groupBy_field] = new MongoRegex("/^" . $arr_dist . "/i");; - $table_value = $arr_dist; - break; - endswitch; - $rs = $APP->find(array_merge($vars_groupBy, $vars, $where))->limit($nbRows / sizeof($rs_dist))->sort([$sortBy => $sortDir]); - /*if ($DEBUG && droit('DEV')) { - skelMdl::send_cmd('act_notify', ['msg' => '
Group 
' . $groupBy_mode . ' ' . $table_value . ' : ' . vardump(array_merge($vars_groupBy, $vars, $where), true) . ' total : ' . $rs->count() . '
', - 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); - }*/ - $count_groupBy = $rs->count(); - if ($count_groupBy == 0) continue; - - $vars_rfk['groupBy'] = $groupBy; - switch ($groupBy_mode): - case 'grille': - $vars_rfk['vars'] = ['id' . $groupBy => $arr_dist['id' . $groupBy]]; - $vars_rfk['table_value'] = $arr_dist['id' . $groupBy]; - break; - case 'date': - case 'email': - case 'field': - case 'integer': - case 'string': - $vars_rfk['vars'] = [$groupBy => $arr_dist[$groupBy]]; - break; - endswitch; - - switch ($groupBy_mode): - case 'grille': - $groupBy_key = 'groupby_' . $groupBy . '_' . $arr_dist['id' . $groupBy]; - $z = skelMdl::cf_module('app/app/app_fiche_entete_group', ['groupBy' => $groupBy, 'vars' => $vars_rfk, 'table' => $groupBy, 'table_value' => $arr_dist['id' . $groupBy]]); - - break; - case 'date': - case 'email': - case 'field': - case 'integer': - case 'string': - $groupBy_key = 'groupby_' . $groupBy . '_idx_' . $i; - $z = "
" . $table_value . ' ' . "$groupBy
"; - break; - endswitch; - - $data_main[] = ['groupBy_key' => $groupBy_key, 'data' => $z, 'md5' => md5($z), 'order' => $i, 'table' => $groupBy, 'table_value' => $table_value, 'vars' => $vars_rfk, 'groupBy' => 1, 'maxcount' => $dist_max_count, 'count' => $dist_count]; - - $count_frag = 0; - $count_frag_test = 1; - - while ($arr = $rs->getNext()) { - if (empty($arr[$id])) continue; - $APP->consolidate_scheme($arr[$id]); - $count_frag++; - $count_frag_test++; - - if (!empty($_POST['stream_to'])): - $arr_allow_stream = $APP_SOCKET->findOne(['nomStream_to' => $_POST['stream_to']]); - if (!empty($arr_allow_stream['stop'])): - exit; - endif; - endif; - $i++; - - $data_row = dotr($table, $arr); - $data_main[] = array_merge($data_row, ['order' => $i, 'chunk' => $count_frag_test, 'chunks' => ceil($count_groupBy / $count_frag_test), 'maxcount' => $dist_max_count, 'count' => $dist_count]); - // stream - if (($i % $strem_chunk_size) == 0 || !$rs->hasNext()) { - if (!empty($_POST['stream_to'])): - $arr_allow_stream = $APP_SOCKET->findOne(['nomStream_to' => $_POST['stream_to']]); - if (!empty($arr_allow_stream['stop'])): - exit; - endif; - - $out_model = ['data_main' => $data_main, 'maxcount' => $dist_max_count, 'url_data' => $url_data, 'table' => $table];// 'columnModel' => $columnModel, - $strm_vars = ['stream_to' => $_POST['stream_to'], 'data' => $out_model, 'data_size' => sizeof($data_main)]; - - // skelMdl::send_cmd('act_stream_to', json_decode(json_encode($strm_vars, JSON_FORCE_OBJECT)), session_id()); - unset($data_main); - $count_frag_test++; - endif; - } - } - unset($vars['id' . $groupBy]); - unset($vars[$groupBy]); - endforeach; - // pas dans distinc : sans groupBy - $data_main = $strm = []; - $vars_rfk = []; - $rs_noGroupBy = $APP->find($vars + $where + ['id' . $groupBy => ['$exists' => false]])->sort([$sortBy => $sortDir])->skip($page)->limit($nbRows); - if ($rs_noGroupBy->count() != 0): - $z = '
Sans ' . $groupBy . '
' . $rs_noGroupBy->count() . '
';//skelMdl::cf_module('app/app/app_fiche_entete_group', ['groupBy' => $groupBy, 'vars' => $vars_rfk, 'table' => $groupBy, 'table_value' => '0']); - $groupBy_key = 'groupby_' . $groupBy . '_idx_' . $i; - $data_main[] = ['data' => $z, 'vars' => $vars_rfk, 'groupBy_key' => $groupBy_key, 'groupBy' => 1]; - $strm[] = ['data' => $z, 'table' => $groupBy, 'groupBy_key' => $groupBy_key, 'table_value' => 'no_group', 'vars' => $vars_rfk, 'groupBy' => 1]; - - if (!empty($_POST['stream_to'])): - - $out_model = ['data_main' => $strm, 'maxcount' => $maxcount, 'url_data' => $url_data, 'table' => $table]; // 'columnModel' => $columnModel, - $strm_vars = ['stream_to' => $_POST['stream_to'], 'data' => $out_model, 'data_size' => sizeof($strm)]; - - //skelMdl::send_cmd('act_stream_to', json_decode(json_encode($strm_vars, JSON_FORCE_OBJECT)), session_id()); - unset($strm); - endif; - endif; - $rs = $APP->find($vars + $where + ['id' . $groupBy => ['$exists' => false]])->sort([$sortBy => $sortDir])->skip($page)->limit($nbRows); - $count = $rs->count(); - $count = ($count > $nbRows) ? $nbRows : $count; - unset($groupBy); - - endif; - // NORMAL - if ($rs->count() == 0) { - $z = " Pas de résultats"; - - $strm_vars = ['stream_to' => $_POST['stream_to'], - 'data_size' => sizeof($strm), - 'table' => $table, - 'data' => ['data_main' => ['data' => $z, 'table' => $table, 'vars' => $vars, 'groupBy' => 1], - 'maxcount' => $maxcount, - 'url_data' => $url_data, - 'table' => $table]]; - - //skelMdl::send_cmd('act_stream_to', $strm_vars, session_id()); - } - if (empty($groupBy)): - $data_main = []; - $i = 0; - $modulo = 0; - $count_frag = 0; - $count_frag_test = 1; - $count_prog = 0; - // si demande stream_count - if (!empty($_POST['stream_count'])): - $stream_count[] = ['count' => $count, 'ids' => $trvars, 'value' => $arr[$id], 'table_value' => $arr[$id], 'table' => $table, 'maxcount' => $maxcount, 'count' => $count]; - endif; - // - - while ($arr = $rs->getNext()) { - if (!empty($_POST['count'])) { - continue; - } - if (empty($arr[$id])) continue; - //$APP->consolidate_scheme($arr[$id]); - //$IDBC->consolidate_scheme($arr[$id]); - $i++; - $count_frag++; - $count_prog++; - - $data_row = dotr($table, $arr); - - $data_main[$arr[$id]] = $data_row;//$data_row;//array_merge($data_row, ['order' => $i, 'chunk' => $count_frag_test, 'chunks' => ceil($count / $strem_chunk_size), 'maxcount' => $maxcount, 'count' => $count]); - - // PROGRESS - if ($count_prog == 40 || !$rs->hasNext()) { - $progress_vars = ['progress_name' => 'progress_' . $table, 'progress_value' => $i, 'progress_max' => $count]; - // AppSocket::send_cmd('act_progress', $progress_vars, session_id()); - $count_prog = 0; - } - - if (!empty($_POST['stream_to'])): - - if (($count_frag % $strem_chunk_size) == 0 || !$rs->hasNext()) { - $out_model = ['data_main' => $data_main, - 'maxcount' => $maxcount, - 'url_data' => $url_data, - 'table' => $table]; - // - $strm_vars = ['stream_to' => $_POST['stream_to'], - 'data_size' => sizeof($data_main), - 'table' => $table, - 'data' => $out_model]; - - // AppSocket::send_cmd('act_stream_to', $strm_vars, session_id()); - - unset($data_main); - $count_frag = 0; - $count_frag_test++; - } - endif; - - $modulo++; - } - - endif; - // - $out_model = ['data_main' => $data_main, 'count' => $maxcount, 'pagecount' => $count]; - // - if (empty($_POST['stream_to'])): - echo trim(json_encode($out_model)); - endif; - if (!empty($_POST['csv_export'])): - // - foreach ($data_main as $key => $value) { - array_walk($value['data'], 'strip_tags'); - $csv_main[] = $value['data']; - } - // - $db_tmp = $APP->plug('sitebase_tmp', 'tmp'); - $db_tmp->insert(['uniqid' => $uniqid, 'data' => $csv_main, 'table' => $table, 'vars' => $vars]); - // - //AppSocket::send_cmd('act_gui', ['title' => 'Télécharger le csv', 'mdl' => 'app/app_prod/app_prod_csv', 'vars' => 'uniqid=' . $uniqid], session_id()); - - endif; - // - // - function dotr($table, $arr) { - - global $APP, $APP_TABLE, $arrFields_all, $GRILLE_FK, $BASE_APP, $GRILLE_COUNT, $sortBy, $key_date, $MDL; - $out = []; - $id = 'id' . $table; - // variables pour le mdl_tr => vars - $trvars['id' . $table] = $arr[$id]; - $trvars['_id'] = (string)$arr['_id']; - $trvars['table'] = $table; - $trvars['table_value'] = $arr[$id]; - $trvars['sortBy'] = $sortBy; - $trvars['key_date'] = $key_date; - // - $out_more = ['icon' => $APP_TABLE['iconAppscheme'], 'value' => $arr[$id], 'table_value' => $arr[$id], 'table' => $table]; - - foreach ($arrFields_all as $key_f => $value_f): - $field_name = $value_f['field_name']; - $field_value = is_array($arr[$field_name]) ? explode(',', $arr[$field_name]) : $arr[$field_name]; - $field_name_raw = $value_f['field_name_raw']; - $codeAppscheme_field_type = $value_f['codeAppscheme_field_type']; - // if (is_array($arr[$field_name])) unset($arr[$field_name]); - // Integralité des champs // cast - $arr_cast = ['field_name' => $field_name, 'field_name_raw' => $field_name_raw, 'field_value' => $field_value, 'codeAppscheme_field_type' => $codeAppscheme_field_type]; - $arr_cast['table'] = $table; - $arr_cast['table_value'] = $arr[$id]; - $out[$field_name] = $arr[$field_name];//$APP->cast_field($arr_cast); - if ($codeAppscheme_field_type == 'bool') { - $set_value = empty($field_value) ? 1 : 0; - $uri = "table=$table&table_value=$arr[$id]&vars[$field_name]="; - $out[$field_name] = "$field_value"; - } - endforeach; - foreach ($GRILLE_FK as $field): - $code = $BASE_APP . $table . $field['table_fk'] . $arr[$id]; - $id_fk = $field['idtable_fk']; - // - $arrq = $APP->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => (int)$arr[$id_fk]]); - unset($arrq['_id']); - $dsp_name = $arrq['nom' . ucfirst($field['table_fk'])]; - // we need default fields here !!! - $out['id' . $field['table_fk']] = (int)$arr[$id_fk]; - $out['nom' . ucfirst($field['table_fk'])] = $dsp_name; - $out['grilleFK'][$field['table_fk']] = $arrq ?: []; - endforeach; - foreach ($GRILLE_COUNT as $key_count => $field): - $APP_TMP = new App($key_count); - $RS_TMP = $APP_TMP->find([$id => $arr[$id]], [$id => 1, "id$key_count" => 1]); - $count_ct = $RS_TMP->count(); - //$link = fonctionsJs::app_liste($key_count, '', ['vars' => [$id => $arr[$id]]]); - /*if ($count_ct == 1) { - $ARR_TMP = $RS_TMP->getNext(); - $link = fonctionsJs::app_fiche($key_count, $ARR_TMP["id$key_count"], ['vars' => [$id => $arr[$id]]]); - }*/ - $attr = " data-count='data-count' data-table='$key_count' data-vars='vars[$id]=$arr[$id]' "; - $count_grille = (empty($count_ct)) ? '' : $count_ct; - //$out['count_' . $key_count] = '' . $count_grille . '' . ((!empty($count_ct)) ? " $key_count" : ''); - $out['count_' . $key_count] = $count_grille; - endforeach; - - if (!empty($key_date)): - $out[$key_date] = ''; - endif; - - if (!empty($MDL)) $out_more['mdl'] = skelMdl::cf_module($MDL, ['table' => $table, 'table_value' => $arr[$id]]);; - - if (droit('DEV') && $table == 'ville') { - if (empty($arr['nomVille']) && !empty($arr['codeVille'])) { - skelMdl::send_cmd('act_notify', ['msg' => '
' . $APP->codeAppscheme . ' ' . $arr['codeVille'] . ' => ' . $arr['nomVille'], 'options' => ['sticky' => 1], 'id' => 'json_debug'], session_id()); - $APP->update(['id' . $APP->codeAppscheme => (int)$arr['id' . $APP->codeAppscheme]], ['nomVille' => ucfirst(strtolower($arr['codeVille']))]); - - } - } - - return array_merge($out, $out_more); // array_merge(['data' => $out, 'md5' => md5(json_encode($out)), 'vars' => $trvars], $out_more); - } +app_table_one; + $GRILLE_FK = $APP->get_grille_fk();// $APP->get_fk_tables($table); + $GRILLE_COUNT = $APP->get_grille_count($table); + $arrFields_all = $APP->get_field_list(); + // + $groupBy = empty($_POST['groupBy']) ? '' : $_POST['groupBy']; + $sortBy = empty($_POST['sortBy']) ? empty($APP_TABLE['sortFieldName']) ? $nom : $APP_TABLE['sortFieldName'] : $_POST['sortBy']; + $sortDir = empty($_POST['sortDir']) ? empty($APP_TABLE['sortFieldOrder']) ? 1 : (int)$APP_TABLE['sortFieldOrder'] : (int)$_POST['sortDir']; + $sortBySecond = empty($_POST['sortBySecond']) ? empty($APP_TABLE['sortFieldSecondName']) ? $nom : $APP_TABLE['sortFieldSecondName'] : $_POST['sortBySecond']; + $sortDirSecond = empty($_POST['sortDirSecond']) ? empty($APP_TABLE['sortFieldSecondOrder']) ? 1 : (int)$APP_TABLE['sortFieldSecondOrder'] : (int)$_POST['sortDirSecond']; + + $page = (!isset($_POST['page'])) ? 0 : $_POST['page']; + $nbRows = (empty($_POST['nbRows'])) ? empty($settings_nbRows) ? 150 : (int)$settings_nbRows : $_POST['nbRows']; + // + $MDL = empty($_POST['mdl']) ? '' : $_POST['mdl']; + $strem_chunk_size = empty($MDL) ? 20 : 15; + + // $in => tableau + foreach ($vars as $key_vars => $value_vars): + if ($key_vars == 'ne') continue; + if (is_array($value_vars) && $key_vars != 'gte' && $key_vars != 'lte' && $key_vars != 'ne' && sizeof(array_values($value_vars)) != 0) $vars[$key_vars] = ['$in' => array_values($value_vars)]; + endforeach; + + // vars_date + if (!empty($_POST['vars_date'])): + array_walk_recursive($_POST, 'CleanStr', $_POST['vars_date']); + foreach ($_POST['vars_date'] as $dt => $dv): + $vars[$dt] = $dv; + endforeach; + endif; + if (!empty($_POST['vars_in'])) { + foreach ($_POST['vars_in'] as $key_vars => $value_vars): + $value_vars['$in'] = json_decode($value_vars['$in']); + $vars[$key_vars] = $value_vars; + endforeach; + } + // + if (!empty($_POST['vars']['gte'])) { + foreach ($_POST['vars']['gte'] as $key_vars => $value_vars): + $vars[$key_vars]['$gte'] = is_int($value_vars) ? (int)$value_vars : $value_vars; + endforeach; + unset($vars['gte']); + } + if (!empty($_POST['vars']['lte'])) { + foreach ($_POST['vars']['lte'] as $key_vars => $value_vars): + $vars[$key_vars]['$lte'] = is_int($value_vars) ? (int)$value_vars : $value_vars; + endforeach; + unset($vars['lte']); + } + if (!empty($_POST['vars']['ne'])) { + foreach ($_POST['vars']['ne'] as $key_vars => $value_vars): + $vars[$key_vars]['$ne'] = is_int($value_vars) ? (int)$value_vars : $value_vars; + endforeach; + unset($vars['ne']); + } + + + $APP_SOCKET = $APP->plug('sitebase_sockets', 'stream_to'); + // + + // + $where = []; + + # champ = 'null' + + foreach ($vars as $key_vars => $value_vars): + if (strtolower($value_vars) == 'null') { + unset($vars[$key_vars]); + $where['$or'][] = [$key_vars => ['$exists' => false]]; + $where[$key_vars]['$in'] = [null, '']; + + } + + endforeach; + + if (!empty($_POST['search'])) { // un champ de recherche unique + $regexp = new MongoRegex("/" . $_POST['search'] . "/i"); + + if (is_int($_POST['search'])) $where['$or'][] = [$id => (int)$_POST['search']]; + + if ($APP->has_field('nom')) $where['$or'][] = ['nom' . $Table => $regexp]; + if ($APP->has_field('prenom')) $where['$or'][] = ['prenom' . $Table => $regexp]; + if ($APP->has_field('email')) $where['$or'][] = ['email' . $Table => $regexp]; + if ($APP->has_field('code')) $where['$or'][] = ['code' . $Table => $regexp]; + if ($APP->has_field('reference')) $where['$or'][] = ['reference' . $Table => $regexp]; + if ($APP->has_field('telephone')) $where['$or'][] = ['telephone' . $Table => new MongoRegex("/" . cleanTel($_POST['search']) . "/i")]; + + // tourne ds fk + if (sizeof($GRILLE_FK) != 0) { + foreach ($GRILLE_FK as $field): + $code_fk = 'nom' . ucfirst($field['codeAppscheme']); + $nom_fk = 'nom' . ucfirst($field['nomAppscheme']); + //$regexp = new MongoRegex("/" . $nom_fk . "/i"); + $where['$or'][] = [$code_fk => $regexp]; + $where['$or'][] = [$nom_fk => $regexp]; + endforeach; + } + + // vardump($where);exit; + } + + if (!empty($_POST['search_start'])) { + $regexp = new MongoRegex("/^" . $_POST['search_start'] . "./i"); + // $where['$or'][] = [$nom => $regexp]; + if ($APP->has_field('nom')) { + $vars[$nom] = $regexp; + } else { + $vars[$code] = $regexp; + } + } + + if (!empty($vars_search)) { // vars_search est un array, avec des noms de table + foreach ($vars_search as $key_field => $field_value): + if (empty($field_value)) continue; + // tourne ds fields + $regexp = new MongoRegex("/" . $field_value . "/i"); + $where['$or'][] = [$key_field => $regexp]; + + endforeach; + } + if (!empty($vars_search_fk)) { // vars_search est un array, avec des noms de table + $vars_search_fk = array_filter($vars_search_fk); + if ($DEBUG && droit('DEV')) { + skelMdl::send_cmd('act_notify', ['msg' => '
 $vars_search_fk' . json_encode($vars_search_fk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); + } + foreach ($vars_search_fk as $table_key => $val_search): + if (empty($val_search)) continue; + $testid = substr(trim($table_key), 0, 2);; + if ($testid == 'id') { + $table_key = substr($table_key, -strlen($table_key) + 2); + + if (is_array($val_search)) { + $vars['id' . $table_key] = ['$in' => $val_search]; + } else { + $vars['id' . $table_key] = (int)$val_search; + } + continue; + } + + $where_fk = []; + // => on devrait tourner dans tout les champs de la table vars_search + $APPKEY = new App($table_key); + $APP_TABLE_SCHEME = $APPKEY->get_field_list(); + + // tourne ds fields + foreach ($APP_TABLE_SCHEME as $key_field => $field_scheme): + $tmp_name = $field_scheme['field_name']; + $regexp = new MongoRegex("/" . $val_search . "/i"); + $where_fk['$or'][] = [$tmp_name => $regexp]; + endforeach; + // query distinct id + $rs = $APPKEY->distinct($table_key, $where_fk, 200, 'no_full'); + $vars['id' . $table_key] = ['$in' => array_values($rs)]; + endforeach; + if ($DEBUG && droit('DEV')) { + skelMdl::send_cmd('act_notify', ['msg' => '$where_fk
' . json_encode($where_fk, JSON_PRETTY_PRINT) . '
', 'options' => ['sticky' => 0]], session_id()); + } + } + + if (!empty($vars_search_rfk)) { // vars_search est un array, avec des noms de table + + foreach ($vars_search_rfk as $table_key => $val_search): + $where_rfk = []; + $testid = substr(trim($table_key), 0, 2);; + if ($testid == 'id') $table_key = substr($table_key, -strlen($table_key) + 2); + // => on devrait tourner dans tout les champs de la table vars_search + $APPKEY = new App($table_key); + $APP_TABLE_SCHEME = $APPKEY->get_display_fields($table_key); + + // tourne ds fields + if ($testid == 'id'): + $where_rfk['id' . $table_key] = (int)$val_search; + endif; + foreach ($APP_TABLE_SCHEME as $key_field => $field_scheme): + if ($testid == 'id') continue; + $tmp_name = $field_scheme['nomAppscheme_field']; + $tmp_name_raw = $field_scheme['codeAppscheme_field']; + $regexp = new MongoRegex("/" . $val_search . "/i"); + $where_rfk['$or'][] = [$tmp_name => $regexp]; + if ($tmp_name_raw == 'adresse') { + $where_rfk['$or'][] = ['adresse1' . ucfirst($table_key) => $regexp]; + $where_rfk['$or'][] = ['codePostal' . ucfirst($table_key) => $regexp]; + $where_rfk['$or'][] = ['ville' . ucfirst($table_key) => $regexp]; + } + endforeach; + // query distinct id + + $rs = $APPKEY->distinct($table, $where_rfk, 200, 'no_full'); + + $vars['id' . $table] = ['$in' => array_values($rs)]; + + endforeach; + } + + if (!empty($_POST['console_mode']) && !empty($APP_TABLE['hasStatutScheme'])) { + // statut END, last ? + $APP_STATUT = new App($table . '_statut'); + $ARR_STATUT = $APP_STATUT->findOne(['code' . $Table . '_statut' => 'END']); + if (empty($ARR_STATUT['id' . $table . '_statut'])) { + $RS_STATUT = $APP_STATUT->find()->sort(['ordre' . $Table . '_statut' => -1]); + $ARR_STATUT = $RS_STATUT->getNext(); + } + if (!empty($ARR_STATUT['id' . $table . '_statut'])) { + echo $idnostatut = (int)$ARR_STATUT['id' . $table . '_statut']; + // {dateDebutIntervention:'2015-11-23',idintervention_statut:{'$ne':4}} + // {dateDebutIntervention:{'$ne':'2015-11-23'},idintervention_statut:4} + + $dist1 = $APP->distinct($table, ['dateDebut' . $Table => date('Y-m-d')], 30, 'nofull'); + $dist2 = $APP->distinct($table, ['dateDebut' . $Table => ['$ne' => date('Y-m-d')], 'id' . $table . '_statut' => ['$ne' => $idnostatut]], 30, 'nofull'); + + $where[$id] = ['$in' => $dist1 + $dist2]; + } + } + + $rs = $APP->find($vars + $where)->sort([$sortBy => $sortDir, $sortBySecond => $sortDirSecond])->skip(($nbRows * $page))->limit($nbRows); + $count = $rs->count(); + $maxcount = $rs->count(false); + $count = ($count > $nbRows) ? $nbRows : $count; + // + if ($DEBUG && droit('DEV')) { + //skelMdl::send_cmd('act_notify', ['msg' => '
 DATA QUERY 
' . $count . ' : ' . json_encode($vars + $where) . '/ ' . $sortBySecond . " => " . $sortDirSecond . ' / ' . $page . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); + } + // ACT COUNT + if (!empty($_POST['piece']) && $_POST['piece'] == 'count'): + $data_count = ['count_id' => $_POST['count_id'], 'count' => $rs->count(), 'maxcount' => $maxcount, 'table' => $table]; + //skelMdl::send_cmd('act_count', json_decode(json_encode($data_count, JSON_FORCE_OBJECT)), session_id()); + endif; + + if (!empty($_POST['verify'])): + $iter = iterator_to_array($rs1, true); + $key = array_search($_POST['verify'], array_column($iter, 'id' . $table)); + echo ($key === false) ? 'NULL' : $key; + + return; + endif; + + if (!empty($groupBy)): + if (!empty($GRILLE_FK[$groupBy])) { + $rs_dist = $APP->distinct($groupBy, $vars + $where, 50); + $dist_count = $rs_dist->count(); + $dist_max_count = $rs_dist->count(true); + $rs_dist = iterator_to_array($rs_dist); + $groupBy_field = "id$groupBy"; + $groupBy_values = array_column($rs_dist, $groupBy_field); + $groupBy_mode = "grille"; + $APP_GROUP = new App($groupBy); + $APP_TGR = $APP_GROUP->app_table_one; + $RS_GROUP = $APP_GROUP->find([$groupBy_field => ['$in' => $groupBy_values]])->sort([$APP_TGR['sortFieldName'] => $APP_TGR['sortFieldOrder']]); + + } else { + $rs_dist = array_filter($APP->distinct_all($groupBy, array_merge($vars, $where))); + $dist_count = (sizeof($rs_dist) > 50) ? 50 : sizeof($rs_dist); + $dist_max_count = sizeof($rs_dist); + $groupBy_field = $groupBy; + $groupBy_mode = "field"; + // date - nombre - + + } + /*if ($DEBUG && droit('DEV')) { + skelMdl::send_cmd('act_notify', ['msg' => '
 groupBy 
' . $groupBy . '/' . $groupBy_field . ' : ' . $groupBy_mode . sizeof($rs_dist) . '
', 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); + }*/ + endif; + // MAIN_DATA + + if (!empty($groupBy) && !empty($rs_dist) && !empty($groupBy_field)): + $data_main = []; + + $i = 0; + switch ($groupBy_mode): + case 'grille': + $rs_dist = array_filter($rs_dist); + break; + case 'field': + // date ? string ? int ? + if (strpos($groupBy_field, 'date') !== false) { + $rs_dist = array_map(function ($value) { + return substr($value, 0, 7); + }, $rs_dist); + $groupBy_mode = 'date'; + } else if (strpos($groupBy_field, 'email') !== false) { + $rs_dist = array_map(function ($value) { + return end(explode('@', $value)); + }, $rs_dist); + $groupBy_mode = 'email'; + } else if (is_string(reset($rs_dist))) { + $rs_dist = array_map(function ($value) { + return substr($value, 0, 2); + }, $rs_dist); + $groupBy_mode = 'string'; + } else { + $groupBy_mode = 'integer'; + } + $rs_dist = array_filter($rs_dist); + break; + endswitch; + + foreach ($rs_dist as $key_dist => $arr_dist): + $i++; + $vars_groupBy = []; + switch ($groupBy_mode): + case 'grille': + $vars_groupBy[$groupBy_field] = (int)$arr_dist[$groupBy_field]; // unset apres + $table_value = $arr_dist[$groupBy_field]; + break; + case 'date': + $vars_groupBy[$groupBy_field] = new MongoRegex("/^" . $arr_dist . "/i"); + $table_value = $arr_dist; + break; + case 'email': + $vars_groupBy[$groupBy_field] = new MongoRegex("/" . $arr_dist . "/i");; + $table_value = $arr_dist; + break; + case 'field': + case 'integer': + case 'string': + $vars_groupBy[$groupBy_field] = new MongoRegex("/^" . $arr_dist . "/i");; + $table_value = $arr_dist; + break; + endswitch; + $rs = $APP->find(array_merge($vars_groupBy, $vars, $where))->limit($nbRows / sizeof($rs_dist))->sort([$sortBy => $sortDir]); + /*if ($DEBUG && droit('DEV')) { + skelMdl::send_cmd('act_notify', ['msg' => '
Group 
' . $groupBy_mode . ' ' . $table_value . ' : ' . vardump(array_merge($vars_groupBy, $vars, $where), true) . ' total : ' . $rs->count() . '
', + 'options' => ['sticky' => 1, 'id' => 'json_debug']], session_id()); + }*/ + $count_groupBy = $rs->count(); + if ($count_groupBy == 0) continue; + + $vars_rfk['groupBy'] = $groupBy; + switch ($groupBy_mode): + case 'grille': + $vars_rfk['vars'] = ['id' . $groupBy => $arr_dist['id' . $groupBy]]; + $vars_rfk['table_value'] = $arr_dist['id' . $groupBy]; + break; + case 'date': + case 'email': + case 'field': + case 'integer': + case 'string': + $vars_rfk['vars'] = [$groupBy => $arr_dist[$groupBy]]; + break; + endswitch; + + switch ($groupBy_mode): + case 'grille': + $groupBy_key = 'groupby_' . $groupBy . '_' . $arr_dist['id' . $groupBy]; + $z = skelMdl::cf_module('app/app/app_fiche_entete_group', ['groupBy' => $groupBy, 'vars' => $vars_rfk, 'table' => $groupBy, 'table_value' => $arr_dist['id' . $groupBy]]); + + break; + case 'date': + case 'email': + case 'field': + case 'integer': + case 'string': + $groupBy_key = 'groupby_' . $groupBy . '_idx_' . $i; + $z = "
" . $table_value . ' ' . "$groupBy
"; + break; + endswitch; + + $data_main[] = ['groupBy_key' => $groupBy_key, 'data' => $z, 'md5' => md5($z), 'order' => $i, 'table' => $groupBy, 'table_value' => $table_value, 'vars' => $vars_rfk, 'groupBy' => 1, 'maxcount' => $dist_max_count, 'count' => $dist_count]; + + $count_frag = 0; + $count_frag_test = 1; + + while ($arr = $rs->getNext()) { + if (empty($arr[$id])) continue; + $APP->consolidate_scheme($arr[$id]); + $count_frag++; + $count_frag_test++; + + if (!empty($_POST['stream_to'])): + $arr_allow_stream = $APP_SOCKET->findOne(['nomStream_to' => $_POST['stream_to']]); + if (!empty($arr_allow_stream['stop'])): + exit; + endif; + endif; + $i++; + + $data_row = dotr($table, $arr); + $data_main[] = array_merge($data_row, ['order' => $i, 'chunk' => $count_frag_test, 'chunks' => ceil($count_groupBy / $count_frag_test), 'maxcount' => $dist_max_count, 'count' => $dist_count]); + // stream + if (($i % $strem_chunk_size) == 0 || !$rs->hasNext()) { + if (!empty($_POST['stream_to'])): + $arr_allow_stream = $APP_SOCKET->findOne(['nomStream_to' => $_POST['stream_to']]); + if (!empty($arr_allow_stream['stop'])): + exit; + endif; + + $out_model = ['data_main' => $data_main, 'maxcount' => $dist_max_count, 'url_data' => $url_data, 'table' => $table];// 'columnModel' => $columnModel, + $strm_vars = ['stream_to' => $_POST['stream_to'], 'data' => $out_model, 'data_size' => sizeof($data_main)]; + + // skelMdl::send_cmd('act_stream_to', json_decode(json_encode($strm_vars, JSON_FORCE_OBJECT)), session_id()); + unset($data_main); + $count_frag_test++; + endif; + } + } + unset($vars['id' . $groupBy]); + unset($vars[$groupBy]); + endforeach; + // pas dans distinc : sans groupBy + $data_main = $strm = []; + $vars_rfk = []; + $rs_noGroupBy = $APP->find($vars + $where + ['id' . $groupBy => ['$exists' => false]])->sort([$sortBy => $sortDir])->skip($page)->limit($nbRows); + if ($rs_noGroupBy->count() != 0): + $z = '
Sans ' . $groupBy . '
' . $rs_noGroupBy->count() . '
';//skelMdl::cf_module('app/app/app_fiche_entete_group', ['groupBy' => $groupBy, 'vars' => $vars_rfk, 'table' => $groupBy, 'table_value' => '0']); + $groupBy_key = 'groupby_' . $groupBy . '_idx_' . $i; + $data_main[] = ['data' => $z, 'vars' => $vars_rfk, 'groupBy_key' => $groupBy_key, 'groupBy' => 1]; + $strm[] = ['data' => $z, 'table' => $groupBy, 'groupBy_key' => $groupBy_key, 'table_value' => 'no_group', 'vars' => $vars_rfk, 'groupBy' => 1]; + + if (!empty($_POST['stream_to'])): + + $out_model = ['data_main' => $strm, 'maxcount' => $maxcount, 'url_data' => $url_data, 'table' => $table]; // 'columnModel' => $columnModel, + $strm_vars = ['stream_to' => $_POST['stream_to'], 'data' => $out_model, 'data_size' => sizeof($strm)]; + + //skelMdl::send_cmd('act_stream_to', json_decode(json_encode($strm_vars, JSON_FORCE_OBJECT)), session_id()); + unset($strm); + endif; + endif; + $rs = $APP->find($vars + $where + ['id' . $groupBy => ['$exists' => false]])->sort([$sortBy => $sortDir])->skip($page)->limit($nbRows); + $count = $rs->count(); + $count = ($count > $nbRows) ? $nbRows : $count; + unset($groupBy); + + endif; + // NORMAL + if ($rs->count() == 0) { + $z = " Pas de résultats"; + + $strm_vars = ['stream_to' => $_POST['stream_to'], + 'data_size' => sizeof($strm), + 'table' => $table, + 'data' => ['data_main' => ['data' => $z, 'table' => $table, 'vars' => $vars, 'groupBy' => 1], + 'maxcount' => $maxcount, + 'url_data' => $url_data, + 'table' => $table]]; + + //skelMdl::send_cmd('act_stream_to', $strm_vars, session_id()); + } + if (empty($groupBy)): + $data_main = []; + $i = 0; + $modulo = 0; + $count_frag = 0; + $count_frag_test = 1; + $count_prog = 0; + // si demande stream_count + if (!empty($_POST['stream_count'])): + $stream_count[] = ['count' => $count, 'ids' => $trvars, 'value' => $arr[$id], 'table_value' => $arr[$id], 'table' => $table, 'maxcount' => $maxcount, 'count' => $count]; + endif; + // + + while ($arr = $rs->getNext()) { + if (!empty($_POST['count'])) { + continue; + } + if (empty($arr[$id])) continue; + //$APP->consolidate_scheme($arr[$id]); + //$IDBC->consolidate_scheme($arr[$id]); + $i++; + $count_frag++; + $count_prog++; + + $data_row = dotr($table, $arr); + + $data_main[$arr[$id]] = $data_row;//$data_row;//array_merge($data_row, ['order' => $i, 'chunk' => $count_frag_test, 'chunks' => ceil($count / $strem_chunk_size), 'maxcount' => $maxcount, 'count' => $count]); + + // PROGRESS + if ($count_prog == 40 || !$rs->hasNext()) { + $progress_vars = ['progress_name' => 'progress_' . $table, 'progress_value' => $i, 'progress_max' => $count]; + // AppSocket::send_cmd('act_progress', $progress_vars, session_id()); + $count_prog = 0; + } + + if (!empty($_POST['stream_to'])): + + if (($count_frag % $strem_chunk_size) == 0 || !$rs->hasNext()) { + $out_model = ['data_main' => $data_main, + 'maxcount' => $maxcount, + 'url_data' => $url_data, + 'table' => $table]; + // + $strm_vars = ['stream_to' => $_POST['stream_to'], + 'data_size' => sizeof($data_main), + 'table' => $table, + 'data' => $out_model]; + + // AppSocket::send_cmd('act_stream_to', $strm_vars, session_id()); + + unset($data_main); + $count_frag = 0; + $count_frag_test++; + } + endif; + + $modulo++; + } + + endif; + // + $out_model = ['data_main' => $data_main, 'count' => $maxcount, 'pagecount' => $count]; + // + if (empty($_POST['stream_to'])): + echo trim(json_encode($out_model)); + endif; + if (!empty($_POST['csv_export'])): + // + foreach ($data_main as $key => $value) { + array_walk($value['data'], 'strip_tags'); + $csv_main[] = $value['data']; + } + // + $db_tmp = $APP->plug('sitebase_tmp', 'tmp'); + $db_tmp->insert(['uniqid' => $uniqid, 'data' => $csv_main, 'table' => $table, 'vars' => $vars]); + // + //AppSocket::send_cmd('act_gui', ['title' => 'Télécharger le csv', 'mdl' => 'app/app_prod/app_prod_csv', 'vars' => 'uniqid=' . $uniqid], session_id()); + + endif; + // + // + function dotr($table, $arr) { + + global $APP, $APP_TABLE, $arrFields_all, $GRILLE_FK, $BASE_APP, $GRILLE_COUNT, $sortBy, $key_date, $MDL; + $out = []; + $id = 'id' . $table; + // variables pour le mdl_tr => vars + $trvars['id' . $table] = $arr[$id]; + $trvars['_id'] = (string)$arr['_id']; + $trvars['table'] = $table; + $trvars['table_value'] = $arr[$id]; + $trvars['sortBy'] = $sortBy; + $trvars['key_date'] = $key_date; + // + $out_more = ['icon' => $APP_TABLE['iconAppscheme'], 'value' => $arr[$id], 'table_value' => $arr[$id], 'table' => $table]; + + foreach ($arrFields_all as $key_f => $value_f): + $field_name = $value_f['field_name']; + $field_value = is_array($arr[$field_name]) ? explode(',', $arr[$field_name]) : $arr[$field_name]; + $field_name_raw = $value_f['field_name_raw']; + $codeAppscheme_field_type = $value_f['codeAppscheme_field_type']; + // if (is_array($arr[$field_name])) unset($arr[$field_name]); + // Integralité des champs // cast + $arr_cast = ['field_name' => $field_name, 'field_name_raw' => $field_name_raw, 'field_value' => $field_value, 'codeAppscheme_field_type' => $codeAppscheme_field_type]; + $arr_cast['table'] = $table; + $arr_cast['table_value'] = $arr[$id]; + $out[$field_name] = $arr[$field_name];//$APP->cast_field($arr_cast); + if ($codeAppscheme_field_type == 'bool') { + $set_value = empty($field_value) ? 1 : 0; + $uri = "table=$table&table_value=$arr[$id]&vars[$field_name]="; + $out[$field_name] = "$field_value"; + } + endforeach; + foreach ($GRILLE_FK as $field): + $code = $BASE_APP . $table . $field['table_fk'] . $arr[$id]; + $id_fk = $field['idtable_fk']; + // + $arrq = $APP->plug($field['base_fk'], $field['table_fk'])->findOne([$field['idtable_fk'] => (int)$arr[$id_fk]]); + unset($arrq['_id']); + $dsp_name = $arrq['nom' . ucfirst($field['table_fk'])]; + // we need default fields here !!! + $out['id' . $field['table_fk']] = (int)$arr[$id_fk]; + $out['nom' . ucfirst($field['table_fk'])] = $dsp_name; + $out['grilleFK'][$field['table_fk']] = $arrq ?: []; + endforeach; + foreach ($GRILLE_COUNT as $key_count => $field): + $APP_TMP = new App($key_count); + $RS_TMP = $APP_TMP->find([$id => $arr[$id]], [$id => 1, "id$key_count" => 1]); + $count_ct = $RS_TMP->count(); + //$link = fonctionsJs::app_liste($key_count, '', ['vars' => [$id => $arr[$id]]]); + /*if ($count_ct == 1) { + $ARR_TMP = $RS_TMP->getNext(); + $link = fonctionsJs::app_fiche($key_count, $ARR_TMP["id$key_count"], ['vars' => [$id => $arr[$id]]]); + }*/ + $attr = " data-count='data-count' data-table='$key_count' data-vars='vars[$id]=$arr[$id]' "; + $count_grille = (empty($count_ct)) ? '' : $count_ct; + //$out['count_' . $key_count] = '' . $count_grille . '' . ((!empty($count_ct)) ? " $key_count" : ''); + $out['count_' . $key_count] = $count_grille; + endforeach; + + if (!empty($key_date)): + $out[$key_date] = ''; + endif; + + if (!empty($MDL)) $out_more['mdl'] = skelMdl::cf_module($MDL, ['table' => $table, 'table_value' => $arr[$id]]);; + + if (droit('DEV') && $table == 'ville') { + if (empty($arr['nomVille']) && !empty($arr['codeVille'])) { + skelMdl::send_cmd('act_notify', ['msg' => '
' . $APP->codeAppscheme . ' ' . $arr['codeVille'] . ' => ' . $arr['nomVille'], 'options' => ['sticky' => 1], 'id' => 'json_debug'], session_id()); + $APP->update(['id' . $APP->codeAppscheme => (int)$arr['id' . $APP->codeAppscheme]], ['nomVille' => ucfirst(strtolower($arr['codeVille']))]); + + } + } + + return array_merge($out, $out_more); // array_merge(['data' => $out, 'md5' => md5(json_encode($out)), 'vars' => $trvars], $out_more); + } diff --git a/web/bin/services/json_scheme legacy.php b/web/bin/services/json_scheme legacy.php index cc9b0f6..fbbdd60 100644 --- a/web/bin/services/json_scheme legacy.php +++ b/web/bin/services/json_scheme legacy.php @@ -1,339 +1,339 @@ -APP = new App(); - $this->APP_SCH = new App('appscheme'); - $this->APP_FIELD = new App('appscheme_field'); - $this->APP_HAS_FIELD = new App('appscheme_has_field'); - $this->APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); - - return parent::__construct($table); - } - - /** - * return mainly : icon, color ... - * - * @param $idappscheme_field - * - * @return array - */ - private function GetField($idappscheme_field) { - $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$idappscheme_field]); - - return ['idppscheme_field' => $idappscheme_field, - 'codeAppscheme_field' => $ARR_FIELD['codeAppscheme_field'], - 'nomAppscheme_field' => $ARR_FIELD['nomAppscheme_field'], - 'codeAppscheme_field_group' => $ARR_FIELD['codeAppscheme_field_group'] ?? '', - 'field_group' => $ARR_FIELD['codeAppscheme_field_group'] ?? '', - 'iconAppscheme_field' => $ARR_FIELD['iconAppscheme_field'] ?? '', - 'codeAppscheme_field_type' => $ARR_FIELD['codeAppscheme_field_type'] ?? '', - 'field_type' => $ARR_FIELD['codeAppscheme_field_type'] ?? '', - 'css' => $this->GetFieldCssRule($ARR_FIELD['codeAppscheme_field_type']), - 'viewFieldType' => 'SCHEME']; - } - - private function GetFieldCssRule($codeAppscheme_field_type = '') { - - $css = ''; - - switch ($codeAppscheme_field_type): - case "date": - $css = 'date_field'; - break; - case "heure": - $css = 'heure_field'; - break; - case "color": - $css = 'color_field'; - break; - default: - if (empty($codeAppscheme_field_type)) { - $css = 'fk '; - } else { - $css = 'css_field_' . $codeAppscheme_field_type; - } - - break; - endswitch; - - return $css; - } - - /** - * fieldModel - * - * @param $idappscheme - * - * @return array - */ - private function RsHasField($idappscheme) { - - $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); - $fieldModel = []; - - foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD): - - $ARR_FIELD = $this->GetField((int)$ARR_HAS_FIELD['idappscheme_field']); - - $ARR_MORE['field_name'] = $ARR_HAS_FIELD['nomAppscheme_has_field']; - $ARR_MORE['field_name_raw'] = $ARR_HAS_FIELD['nomAppscheme_field']; - $ARR_MORE['field_code'] = $ARR_HAS_FIELD['codeAppscheme_has_field']; - $ARR_MORE['field_code_raw'] = $ARR_HAS_FIELD['codeAppscheme_field']; - $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field']; - $ARR_MORE['field_type'] = $ARR_FIELD['field_type']; - $ARR_MORE['field_group'] = $ARR_FIELD['codeAppscheme_field_group']; - $ARR_MORE['field_order'] = $ARR_HAS_FIELD['ordreAppscheme_has_field'] ?? ''; - $ARR_MORE['field_required'] = $ARR_HAS_FIELD['required'] ?? false; - - $fieldModel[$ARR_HAS_FIELD['codeAppscheme_has_field']] = $ARR_MORE;//array_merge($ARR_FIELD, $ARR_MORE, $ARR_HAS_FIELD); - - if ($ARR_FIELD['codeAppscheme_field_group'] == 'codification' || $ARR_FIELD['codeAppscheme_field_group'] == 'identification') { - /*$fieldModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD;*/ - $hasModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD; - }; - endforeach; - - return $fieldModel; - } - - private function RsColumnModel($idappscheme) { - - $ARR_APP = $this->APP_SCH->findOne(['idappscheme' => (int)$idappscheme]); - $table = $ARR_APP['codeAppscheme']; - - $APP = new App($table); - $GRILLE_FK = $APP->get_grille_fk(); - $GRILLE_COUNT = $APP->get_grille_count($table); - - $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); - $columnModel = []; - - foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD): - $ARR_FIELD = $this->GetField((int)$ARR_HAS_FIELD['idappscheme_field']); - - $ARR_MORE['field_code'] = $ARR_HAS_FIELD['codeAppscheme_has_field']; - $ARR_MORE['field_name'] = $ARR_HAS_FIELD['nomAppscheme_has_field']; - $ARR_MORE['field_name_raw'] = $ARR_FIELD['nomAppscheme_field']; - $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field']; - $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field']; - $ARR_MORE['field_type'] = $ARR_FIELD['field_type']; - $ARR_MORE['field_group'] = $ARR_FIELD['field_group']; - $ARR_MORE['field_required'] = $ARR_HAS_FIELD['required'] ?? false; - $ARR_MORE['field_order'] = $ARR_HAS_FIELD['ordreAppscheme_has_field'] ?? ''; - - $columnModel[$ARR_HAS_FIELD['codeAppscheme_has_field']] = $ARR_MORE;//array_merge($ARR_FIELD, $ARR_MORE); - endforeach; - - foreach ($GRILLE_FK as $fk): - $columnModel['grilleFk_' . $fk['table_fk']] = ['field_name_group' => '', - 'viewFieldType' => 'GRILLE_FK', - 'field_name' => 'nom' . ucfirst($fk['table_fk']), - 'field_name_raw' => $fk['table_fk'], - 'title' => $fk['table_fk'], - 'className' => 'fk',/* 'field_icon' => $fk['icon_fk'], - 'icon' => $fk['icon_fk']*/]; - endforeach; - - foreach ($GRILLE_COUNT as $key_count => $fk): - $columnModel['count_' . $key_count] = ['viewFieldType' => 'GRILLE_COUNT', 'field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; - $default_model['count_' . $key_count] = ['viewFieldType' => 'GRILLE_COUNT', 'field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; - endforeach; - - return $columnModel; - } - - private function RsDefaultModel($idappscheme = null) { - $default_model = []; - $RS_HAS_TABLE_FIELD = $this->APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$idappscheme]);//->sort(['ordreAppscheme_has_table_field' => 1]); - - foreach ($RS_HAS_TABLE_FIELD as $ARR_HAS_TABLE_FIELD): // tout les champs declarés dans has_table_field. - $ARR_SCH_FIELD = $this->APP_SCH->findOne(['idappscheme' => (int)$ARR_HAS_TABLE_FIELD['idappscheme_link']]); - $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$ARR_HAS_TABLE_FIELD['idappscheme_field']]); - $DA_TABLE_NANE = $ARR_SCH_FIELD['nomAppscheme']; - $title = ($ARR_HAS_TABLE_FIELD['idappscheme'] == $ARR_HAS_TABLE_FIELD['idappscheme_link']) ? $ARR_FIELD['nomAppscheme_field'] : $ARR_FIELD['nomAppscheme_field'] . ' ' . $DA_TABLE_NANE; - - $ARR_MORE['field_name'] = $ARR_HAS_TABLE_FIELD['nomAppscheme_has_table_field'] ?? ''; - $ARR_MORE['field_name_raw'] = $ARR_HAS_TABLE_FIELD['nomAppscheme_field'] ?? ''; - $ARR_MORE['field_code'] = $ARR_HAS_TABLE_FIELD['codeAppscheme_has_table_field'] ?? $ARR_HAS_TABLE_FIELD['codeAppscheme_has_field'] ?? ''; - $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field'] ?? ''; - $ARR_MORE['field_icon'] = $ARR_HAS_TABLE_FIELD['iconAppscheme_has_table_field'] ?? $ARR_FIELD['iconAppscheme_field'] ?? null; - $ARR_MORE['field_order'] = $ARR_HAS_TABLE_FIELD['ordreAppscheme_has_table_field'] ?? $ARR_FIELD['ordreAppscheme_field']; - /* $ARR_MORE['field_icon'] = $ARR_HAS_TABLE_FIELD['iconAppscheme_field']; - $ARR_MORE['field_color'] = $ARR_HAS_TABLE_FIELD['colorAppscheme_field']; - $ARR_MORE['field_type'] = $ARR_FIELD['field_type'];*/ - $ARR_MORE['field_group'] = $ARR_FIELD['field_group'] ?? $ARR_FIELD['codeAppscheme_field_group'] ?? ''; - $ARR_MORE['field_type'] = $ARR_FIELD['field_type'] ?? $ARR_FIELD['codeAppscheme_field_type'] ?? ''; - $default_model[$ARR_HAS_TABLE_FIELD['codeAppscheme_has_table_field']] = array_merge($this->GetField($ARR_FIELD['codeAppscheme_field']), $ARR_MORE); - - endforeach; - - return $default_model; - } - - private function RsDynamicView($idappscheme = null, $type = 'in_mini_fiche') { - $miniModel = []; - if ($type) { - $RS_HAS_MINI_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme, $type => 1], ['sort' => ['ordreAppscheme_has_table_field' => 1]]); //->sort(['ordreAppscheme_has_table_field' => 1]); - } else { - $RS_HAS_MINI_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme], ['sort' => ['ordreAppscheme_has_table_field' => 1]]);//->sort(['ordreAppscheme_has_table_field' => 1]); - } - - foreach ($RS_HAS_MINI_FIELD as $ARR_HAS_MINI_FIELD): - $ARR_FIELD = $this->GetField((int)$ARR_HAS_MINI_FIELD['idappscheme_field']); - $ARR_MORE['field_code'] = $ARR_HAS_MINI_FIELD['codeAppscheme_has_field'] ?? ''; - $ARR_MORE['field_name'] = $ARR_FIELD['nomAppscheme_field'] ?? ''; - $ARR_MORE['field_name_raw'] = $ARR_FIELD['nomAppscheme_field'] ?? ''; - $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field'] ?? ''; - $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field'] ?? ''; - $ARR_MORE['field_color'] = $ARR_FIELD['colorAppscheme_field'] ?? ''; - $ARR_MORE['field_type'] = $ARR_FIELD['codeAppscheme_field_type'] ?? ''; - $ARR_MORE['field_group'] = $ARR_FIELD['codeAppscheme_field_group'] ?? ''; - $ARR_MORE['field_required'] = $ARR_HAS_MINI_FIELD['required'] ?? ''; - $ARR_MORE['field_order'] = $ARR_HAS_MINI_FIELD['ordreAppscheme_has_field'] ?? $ARR_FIELD['ordreAppscheme_field'] ?? null; - $miniModel[$ARR_HAS_MINI_FIELD['codeAppscheme_has_field']] = $ARR_MORE;//array_merge($ARR_MORE,$ARR_FIELD ); - endforeach; - - return $miniModel; - } - - /** - * @param $table - * - * @return mixed - * @throws \Exception - */ - public function get_schemeParts($table) { - - $this->IDB = new IdaeDataSchemeModel($table); - - return $this->IDB->get_schemeParts(); - } - - /** - * @throws \Exception - * @throws \MongoCursorException - */ - public function legacyParse() { - $INIT = new IdaeDataSchemeInit(); - $PIECE = !isset($_POST['piece']) ? 'scheme' : $_POST['piece']; - - $vars = empty($_GET['vars']) ? [] : function_prod::cleanPostMongo($_POST['vars'], 1); - // $RS_APP = $this->APP_SCH->find($vars)->sort(['codeAppscheme' => 1]); - $RS_APP = $this->APP_SCH->find($vars + ['grouped_scheme' => ['$ne' => 1]]);//->sort(['codeAppscheme' => 1]); - $COLLECT = []; - - $RS_APP = iterator_to_array($RS_APP); - - foreach ($RS_APP as $ARR_APP): - // $INIT->consolidate_app_scheme($ARR_APP['codeAppscheme']); - - //$ARR_APP = MongoDB\BSON\toPHP($ARR_APP); - /*var_dump($ARR_APP ); - die();*/ - $idappscheme = (int)$ARR_APP['idappscheme']; - $table = $ARR_APP['codeAppscheme']; - $Table = ucfirst($table); - $base = $ARR_APP['codeAppscheme_base']; - $Table = ucfirst($ARR_APP['codeAppscheme']); - - $DATA_SCHEME = new IdaeDataScheme($table); - $DATA_SCHEME_MODEL = new IdaeDataSchemeModel($table); - - $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); - - $APP = new App($table); - $APP_TABLE = $APP->app_table_one; - $ENTITY = $APP_TABLE; - $GRILLE_FK = $APP->get_grille_fk(); - $GRILLE_RFK = array_reduce(array_map(function ($scheme) { return [$scheme => $scheme]; }, $APP->get_table_rfk($table)), 'array_merge', []); - $GRILLE_COUNT = $APP->get_grille_count($table); - //$arrFields = $APP->get_basic_fields_nude($table); - - /*$ENTITY['grilleFK'] = $GRILLE_FK; - $ENTITY['grilleRFK'] = $GRILLE_RFK; - $ENTITY['grilleCount'] = $GRILLE_COUNT;*/ - - $fieldModel = $this->RsHasField($idappscheme); - $miniModel = $this->RsDynamicView($idappscheme, 'in_mini_fiche'); - $schemeModel = $this->RsDynamicView($idappscheme); - $default_model = $this->RsDefaultModel($idappscheme); - $columnModel = $this->RsColumnModel($idappscheme); - $schemePartsModel = $this->get_schemeParts($table); - // - $microModelKey = isset($fieldModel["nom$Table"]) ? "nom$Table" : "code$Table"; - $microModel = [$microModelKey => $fieldModel[$microModelKey]]; - - $hasModel = []; - $updateModel = []; - - // start here for all : columnModel => pour table par defaut, sans description, sueleument code et identification + fk - foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD): - $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$ARR_HAS_FIELD['idappscheme_field']]); - if ($ARR_FIELD['codeAppscheme_field_group'] == 'codification' || $ARR_FIELD['codeAppscheme_field_group'] == 'identification') { - - $hasModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD; - }; - endforeach; - - foreach ($GRILLE_COUNT as $key_count => $fk): - // $columnModel[] = ['field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; - $default_model[] = ['field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; - endforeach; - - $APP_MODEL['columnModel'] = $columnModel; - $APP_MODEL['defaultModel'] = $default_model; // utilisateur => table big - $APP_MODEL['hasModel'] = $hasModel; // sans fk - $APP_MODEL['fieldModel'] = $fieldModel; // tout les champs - $APP_MODEL['miniModel'] = $miniModel; // mini - $APP_MODEL['microModel'] = $microModel; // one field no more - // - $COLLECT[$base][$table] = (array)$APP_TABLE; - $COLLECT[$base][$table]['entity'] = $ENTITY; - $COLLECT[$base][$table]['views'] = $APP_MODEL; - $COLLECT[$base][$table]['scheme'] = $DATA_SCHEME->getSchemeData(); - $COLLECT[$base][$table]['fields'] = $DATA_SCHEME->getSchemeFields(); - $COLLECT[$base][$table]['datascheme']['grilleFK'] = $DATA_SCHEME->getGrilleFK(); - $COLLECT[$base][$table]['datascheme']['grilleRFK'] = $DATA_SCHEME->get_grille_rfk(); - - // $COLLECT[$base][$table]['parts'] = $schemePartsModel; // le futur -> nope 22/03/2020 - // $COLLECT[$base][$table]['parts'] = $schemePartsModel; // 2023 - /* echo $schemePartsModel; - die(); */ - /*echo json_encode($APP_TABLE); - die();*/ - endforeach; - - return $COLLECT; - - } - - } - - $JsonSchemeClass = new JsonScheme(); - $out = $JsonSchemeClass->legacyParse(); - - echo json_encode($out); - - /*echo json_encode($out['sitebase_app']['appscheme'],JSON_PRETTY_PRINT); - echo json_last_error() ;*/ +APP = new App(); + $this->APP_SCH = new App('appscheme'); + $this->APP_FIELD = new App('appscheme_field'); + $this->APP_HAS_FIELD = new App('appscheme_has_field'); + $this->APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); + + return parent::__construct($table); + } + + /** + * return mainly : icon, color ... + * + * @param $idappscheme_field + * + * @return array + */ + private function GetField($idappscheme_field) { + $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$idappscheme_field]); + + return ['idppscheme_field' => $idappscheme_field, + 'codeAppscheme_field' => $ARR_FIELD['codeAppscheme_field'], + 'nomAppscheme_field' => $ARR_FIELD['nomAppscheme_field'], + 'codeAppscheme_field_group' => $ARR_FIELD['codeAppscheme_field_group'] ?? '', + 'field_group' => $ARR_FIELD['codeAppscheme_field_group'] ?? '', + 'iconAppscheme_field' => $ARR_FIELD['iconAppscheme_field'] ?? '', + 'codeAppscheme_field_type' => $ARR_FIELD['codeAppscheme_field_type'] ?? '', + 'field_type' => $ARR_FIELD['codeAppscheme_field_type'] ?? '', + 'css' => $this->GetFieldCssRule($ARR_FIELD['codeAppscheme_field_type']), + 'viewFieldType' => 'SCHEME']; + } + + private function GetFieldCssRule($codeAppscheme_field_type = '') { + + $css = ''; + + switch ($codeAppscheme_field_type): + case "date": + $css = 'date_field'; + break; + case "heure": + $css = 'heure_field'; + break; + case "color": + $css = 'color_field'; + break; + default: + if (empty($codeAppscheme_field_type)) { + $css = 'fk '; + } else { + $css = 'css_field_' . $codeAppscheme_field_type; + } + + break; + endswitch; + + return $css; + } + + /** + * fieldModel + * + * @param $idappscheme + * + * @return array + */ + private function RsHasField($idappscheme) { + + $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); + $fieldModel = []; + + foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD): + + $ARR_FIELD = $this->GetField((int)$ARR_HAS_FIELD['idappscheme_field']); + + $ARR_MORE['field_name'] = $ARR_HAS_FIELD['nomAppscheme_has_field']; + $ARR_MORE['field_name_raw'] = $ARR_HAS_FIELD['nomAppscheme_field']; + $ARR_MORE['field_code'] = $ARR_HAS_FIELD['codeAppscheme_has_field']; + $ARR_MORE['field_code_raw'] = $ARR_HAS_FIELD['codeAppscheme_field']; + $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field']; + $ARR_MORE['field_type'] = $ARR_FIELD['field_type']; + $ARR_MORE['field_group'] = $ARR_FIELD['codeAppscheme_field_group']; + $ARR_MORE['field_order'] = $ARR_HAS_FIELD['ordreAppscheme_has_field'] ?? ''; + $ARR_MORE['field_required'] = $ARR_HAS_FIELD['required'] ?? false; + + $fieldModel[$ARR_HAS_FIELD['codeAppscheme_has_field']] = $ARR_MORE;//array_merge($ARR_FIELD, $ARR_MORE, $ARR_HAS_FIELD); + + if ($ARR_FIELD['codeAppscheme_field_group'] == 'codification' || $ARR_FIELD['codeAppscheme_field_group'] == 'identification') { + /*$fieldModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD;*/ + $hasModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD; + }; + endforeach; + + return $fieldModel; + } + + private function RsColumnModel($idappscheme) { + + $ARR_APP = $this->APP_SCH->findOne(['idappscheme' => (int)$idappscheme]); + $table = $ARR_APP['codeAppscheme']; + + $APP = new App($table); + $GRILLE_FK = $APP->get_grille_fk(); + $GRILLE_COUNT = $APP->get_grille_count($table); + + $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); + $columnModel = []; + + foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD): + $ARR_FIELD = $this->GetField((int)$ARR_HAS_FIELD['idappscheme_field']); + + $ARR_MORE['field_code'] = $ARR_HAS_FIELD['codeAppscheme_has_field']; + $ARR_MORE['field_name'] = $ARR_HAS_FIELD['nomAppscheme_has_field']; + $ARR_MORE['field_name_raw'] = $ARR_FIELD['nomAppscheme_field']; + $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field']; + $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field']; + $ARR_MORE['field_type'] = $ARR_FIELD['field_type']; + $ARR_MORE['field_group'] = $ARR_FIELD['field_group']; + $ARR_MORE['field_required'] = $ARR_HAS_FIELD['required'] ?? false; + $ARR_MORE['field_order'] = $ARR_HAS_FIELD['ordreAppscheme_has_field'] ?? ''; + + $columnModel[$ARR_HAS_FIELD['codeAppscheme_has_field']] = $ARR_MORE;//array_merge($ARR_FIELD, $ARR_MORE); + endforeach; + + foreach ($GRILLE_FK as $fk): + $columnModel['grilleFk_' . $fk['table_fk']] = ['field_name_group' => '', + 'viewFieldType' => 'GRILLE_FK', + 'field_name' => 'nom' . ucfirst($fk['table_fk']), + 'field_name_raw' => $fk['table_fk'], + 'title' => $fk['table_fk'], + 'className' => 'fk',/* 'field_icon' => $fk['icon_fk'], + 'icon' => $fk['icon_fk']*/]; + endforeach; + + foreach ($GRILLE_COUNT as $key_count => $fk): + $columnModel['count_' . $key_count] = ['viewFieldType' => 'GRILLE_COUNT', 'field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; + $default_model['count_' . $key_count] = ['viewFieldType' => 'GRILLE_COUNT', 'field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; + endforeach; + + return $columnModel; + } + + private function RsDefaultModel($idappscheme = null) { + $default_model = []; + $RS_HAS_TABLE_FIELD = $this->APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$idappscheme]);//->sort(['ordreAppscheme_has_table_field' => 1]); + + foreach ($RS_HAS_TABLE_FIELD as $ARR_HAS_TABLE_FIELD): // tout les champs declarés dans has_table_field. + $ARR_SCH_FIELD = $this->APP_SCH->findOne(['idappscheme' => (int)$ARR_HAS_TABLE_FIELD['idappscheme_link']]); + $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$ARR_HAS_TABLE_FIELD['idappscheme_field']]); + $DA_TABLE_NANE = $ARR_SCH_FIELD['nomAppscheme']; + $title = ($ARR_HAS_TABLE_FIELD['idappscheme'] == $ARR_HAS_TABLE_FIELD['idappscheme_link']) ? $ARR_FIELD['nomAppscheme_field'] : $ARR_FIELD['nomAppscheme_field'] . ' ' . $DA_TABLE_NANE; + + $ARR_MORE['field_name'] = $ARR_HAS_TABLE_FIELD['nomAppscheme_has_table_field'] ?? ''; + $ARR_MORE['field_name_raw'] = $ARR_HAS_TABLE_FIELD['nomAppscheme_field'] ?? ''; + $ARR_MORE['field_code'] = $ARR_HAS_TABLE_FIELD['codeAppscheme_has_table_field'] ?? $ARR_HAS_TABLE_FIELD['codeAppscheme_has_field'] ?? ''; + $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field'] ?? ''; + $ARR_MORE['field_icon'] = $ARR_HAS_TABLE_FIELD['iconAppscheme_has_table_field'] ?? $ARR_FIELD['iconAppscheme_field'] ?? null; + $ARR_MORE['field_order'] = $ARR_HAS_TABLE_FIELD['ordreAppscheme_has_table_field'] ?? $ARR_FIELD['ordreAppscheme_field']; + /* $ARR_MORE['field_icon'] = $ARR_HAS_TABLE_FIELD['iconAppscheme_field']; + $ARR_MORE['field_color'] = $ARR_HAS_TABLE_FIELD['colorAppscheme_field']; + $ARR_MORE['field_type'] = $ARR_FIELD['field_type'];*/ + $ARR_MORE['field_group'] = $ARR_FIELD['field_group'] ?? $ARR_FIELD['codeAppscheme_field_group'] ?? ''; + $ARR_MORE['field_type'] = $ARR_FIELD['field_type'] ?? $ARR_FIELD['codeAppscheme_field_type'] ?? ''; + $default_model[$ARR_HAS_TABLE_FIELD['codeAppscheme_has_table_field']] = array_merge($this->GetField($ARR_FIELD['codeAppscheme_field']), $ARR_MORE); + + endforeach; + + return $default_model; + } + + private function RsDynamicView($idappscheme = null, $type = 'in_mini_fiche') { + $miniModel = []; + if ($type) { + $RS_HAS_MINI_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme, $type => 1], ['sort' => ['ordreAppscheme_has_table_field' => 1]]); //->sort(['ordreAppscheme_has_table_field' => 1]); + } else { + $RS_HAS_MINI_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme], ['sort' => ['ordreAppscheme_has_table_field' => 1]]);//->sort(['ordreAppscheme_has_table_field' => 1]); + } + + foreach ($RS_HAS_MINI_FIELD as $ARR_HAS_MINI_FIELD): + $ARR_FIELD = $this->GetField((int)$ARR_HAS_MINI_FIELD['idappscheme_field']); + $ARR_MORE['field_code'] = $ARR_HAS_MINI_FIELD['codeAppscheme_has_field'] ?? ''; + $ARR_MORE['field_name'] = $ARR_FIELD['nomAppscheme_field'] ?? ''; + $ARR_MORE['field_name_raw'] = $ARR_FIELD['nomAppscheme_field'] ?? ''; + $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field'] ?? ''; + $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field'] ?? ''; + $ARR_MORE['field_color'] = $ARR_FIELD['colorAppscheme_field'] ?? ''; + $ARR_MORE['field_type'] = $ARR_FIELD['codeAppscheme_field_type'] ?? ''; + $ARR_MORE['field_group'] = $ARR_FIELD['codeAppscheme_field_group'] ?? ''; + $ARR_MORE['field_required'] = $ARR_HAS_MINI_FIELD['required'] ?? ''; + $ARR_MORE['field_order'] = $ARR_HAS_MINI_FIELD['ordreAppscheme_has_field'] ?? $ARR_FIELD['ordreAppscheme_field'] ?? null; + $miniModel[$ARR_HAS_MINI_FIELD['codeAppscheme_has_field']] = $ARR_MORE;//array_merge($ARR_MORE,$ARR_FIELD ); + endforeach; + + return $miniModel; + } + + /** + * @param $table + * + * @return mixed + * @throws \Exception + */ + public function get_schemeParts($table) { + + $this->IDB = new IdaeDataSchemeModel($table); + + return $this->IDB->get_schemeParts(); + } + + /** + * @throws \Exception + * @throws \MongoCursorException + */ + public function legacyParse() { + $INIT = new IdaeDataSchemeInit(); + $PIECE = !isset($_POST['piece']) ? 'scheme' : $_POST['piece']; + + $vars = empty($_GET['vars']) ? [] : function_prod::cleanPostMongo($_POST['vars'], 1); + // $RS_APP = $this->APP_SCH->find($vars)->sort(['codeAppscheme' => 1]); + $RS_APP = $this->APP_SCH->find($vars + ['grouped_scheme' => ['$ne' => 1]]);//->sort(['codeAppscheme' => 1]); + $COLLECT = []; + + $RS_APP = iterator_to_array($RS_APP); + + foreach ($RS_APP as $ARR_APP): + // $INIT->consolidate_app_scheme($ARR_APP['codeAppscheme']); + + //$ARR_APP = MongoDB\BSON\toPHP($ARR_APP); + /*var_dump($ARR_APP ); + die();*/ + $idappscheme = (int)$ARR_APP['idappscheme']; + $table = $ARR_APP['codeAppscheme']; + $Table = ucfirst($table); + $base = $ARR_APP['codeAppscheme_base']; + $Table = ucfirst($ARR_APP['codeAppscheme']); + + $DATA_SCHEME = new IdaeDataScheme($table); + $DATA_SCHEME_MODEL = new IdaeDataSchemeModel($table); + + $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); + + $APP = new App($table); + $APP_TABLE = $APP->app_table_one; + $ENTITY = $APP_TABLE; + $GRILLE_FK = $APP->get_grille_fk(); + $GRILLE_RFK = array_reduce(array_map(function ($scheme) { return [$scheme => $scheme]; }, $APP->get_table_rfk($table)), 'array_merge', []); + $GRILLE_COUNT = $APP->get_grille_count($table); + //$arrFields = $APP->get_basic_fields_nude($table); + + /*$ENTITY['grilleFK'] = $GRILLE_FK; + $ENTITY['grilleRFK'] = $GRILLE_RFK; + $ENTITY['grilleCount'] = $GRILLE_COUNT;*/ + + $fieldModel = $this->RsHasField($idappscheme); + $miniModel = $this->RsDynamicView($idappscheme, 'in_mini_fiche'); + $schemeModel = $this->RsDynamicView($idappscheme); + $default_model = $this->RsDefaultModel($idappscheme); + $columnModel = $this->RsColumnModel($idappscheme); + $schemePartsModel = $this->get_schemeParts($table); + // + $microModelKey = isset($fieldModel["nom$Table"]) ? "nom$Table" : "code$Table"; + $microModel = [$microModelKey => $fieldModel[$microModelKey]]; + + $hasModel = []; + $updateModel = []; + + // start here for all : columnModel => pour table par defaut, sans description, sueleument code et identification + fk + foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD): + $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$ARR_HAS_FIELD['idappscheme_field']]); + if ($ARR_FIELD['codeAppscheme_field_group'] == 'codification' || $ARR_FIELD['codeAppscheme_field_group'] == 'identification') { + + $hasModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD; + }; + endforeach; + + foreach ($GRILLE_COUNT as $key_count => $fk): + // $columnModel[] = ['field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; + $default_model[] = ['field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; + endforeach; + + $APP_MODEL['columnModel'] = $columnModel; + $APP_MODEL['defaultModel'] = $default_model; // utilisateur => table big + $APP_MODEL['hasModel'] = $hasModel; // sans fk + $APP_MODEL['fieldModel'] = $fieldModel; // tout les champs + $APP_MODEL['miniModel'] = $miniModel; // mini + $APP_MODEL['microModel'] = $microModel; // one field no more + // + $COLLECT[$base][$table] = (array)$APP_TABLE; + $COLLECT[$base][$table]['entity'] = $ENTITY; + $COLLECT[$base][$table]['views'] = $APP_MODEL; + $COLLECT[$base][$table]['scheme'] = $DATA_SCHEME->getSchemeData(); + $COLLECT[$base][$table]['fields'] = $DATA_SCHEME->getSchemeFields(); + $COLLECT[$base][$table]['datascheme']['grilleFK'] = $DATA_SCHEME->getGrilleFK(); + $COLLECT[$base][$table]['datascheme']['grilleRFK'] = $DATA_SCHEME->get_grille_rfk(); + + // $COLLECT[$base][$table]['parts'] = $schemePartsModel; // le futur -> nope 22/03/2020 + // $COLLECT[$base][$table]['parts'] = $schemePartsModel; // 2023 + /* echo $schemePartsModel; + die(); */ + /*echo json_encode($APP_TABLE); + die();*/ + endforeach; + + return $COLLECT; + + } + + } + + $JsonSchemeClass = new JsonScheme(); + $out = $JsonSchemeClass->legacyParse(); + + echo json_encode($out); + + /*echo json_encode($out['sitebase_app']['appscheme'],JSON_PRETTY_PRINT); + echo json_last_error() ;*/ diff --git a/web/bin/services/json_scheme.php b/web/bin/services/json_scheme.php index 71907c1..f8a9254 100644 --- a/web/bin/services/json_scheme.php +++ b/web/bin/services/json_scheme.php @@ -1,355 +1,355 @@ -APP = new App(); - $this->APP_SCH = new App('appscheme'); - $this->APP_FIELD = new App('appscheme_field'); - $this->APP_HAS_FIELD = new App('appscheme_has_field'); - $this->APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); - - return parent::__construct($table); - } - - /** - * return mainly : icon, color ... - * - * @param $idappscheme_field - * - * @return array - */ - private function GetField($idappscheme_field) - { - $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$idappscheme_field]); - - return [ - 'idppscheme_field' => $idappscheme_field, - 'codeAppscheme_field' => $ARR_FIELD['codeAppscheme_field'], - 'nomAppscheme_field' => $ARR_FIELD['nomAppscheme_field'], - 'codeAppscheme_field_group' => $ARR_FIELD['codeAppscheme_field_group'] ?? '', - 'field_group' => $ARR_FIELD['codeAppscheme_field_group'] ?? '', - 'iconAppscheme_field' => $ARR_FIELD['iconAppscheme_field'] ?? '', - 'codeAppscheme_field_type' => $ARR_FIELD['codeAppscheme_field_type'] ?? '', - 'field_type' => $ARR_FIELD['codeAppscheme_field_type'] ?? '', - 'css' => $this->GetFieldCssRule($ARR_FIELD['codeAppscheme_field_type']), - 'viewFieldType' => 'SCHEME' - ]; - } - - private function GetFieldCssRule($codeAppscheme_field_type = '') - { - - $css = ''; - - switch ($codeAppscheme_field_type): - case "date": - $css = 'date_field'; - break; - case "heure": - $css = 'heure_field'; - break; - case "color": - $css = 'color_field'; - break; - default: - if (empty($codeAppscheme_field_type)) { - $css = 'fk '; - } else { - $css = 'css_field_' . $codeAppscheme_field_type; - } - - break; - endswitch; - - return $css; - } - - /** - * fieldModel - * - * @param $idappscheme - * - * @return array - */ - private function RsHasField($idappscheme) - { - - $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); - $fieldModel = []; - - foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD) : - - $ARR_FIELD = $this->GetField((int)$ARR_HAS_FIELD['idappscheme_field']); - - $ARR_MORE['field_name'] = $ARR_HAS_FIELD['nomAppscheme_has_field']; - $ARR_MORE['field_name_raw'] = $ARR_HAS_FIELD['nomAppscheme_field']; - $ARR_MORE['field_code'] = $ARR_HAS_FIELD['codeAppscheme_has_field']; - $ARR_MORE['field_code_raw'] = $ARR_HAS_FIELD['codeAppscheme_field']; - $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field']; - $ARR_MORE['field_type'] = $ARR_FIELD['field_type']; - $ARR_MORE['field_group'] = $ARR_FIELD['codeAppscheme_field_group']; - $ARR_MORE['field_order'] = $ARR_HAS_FIELD['ordreAppscheme_has_field'] ?? ''; - $ARR_MORE['field_required'] = $ARR_HAS_FIELD['required'] ?? false; - - $fieldModel[$ARR_HAS_FIELD['codeAppscheme_has_field']] = $ARR_MORE; //array_merge($ARR_FIELD, $ARR_MORE, $ARR_HAS_FIELD); - - if ($ARR_FIELD['codeAppscheme_field_group'] == 'codification' || $ARR_FIELD['codeAppscheme_field_group'] == 'identification') { - /*$fieldModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD;*/ - $hasModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD; - }; - endforeach; - - return $fieldModel; - } - - private function RsColumnModel($idappscheme) - { - - $ARR_APP = $this->APP_SCH->findOne(['idappscheme' => (int)$idappscheme]); - $table = $ARR_APP['codeAppscheme']; - - $APP = new App($table); - $GRILLE_FK = $APP->get_grille_fk(); - $GRILLE_COUNT = $APP->get_grille_count($table); - - $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); - $columnModel = []; - - foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD) : - $ARR_FIELD = $this->GetField((int)$ARR_HAS_FIELD['idappscheme_field']); - - $ARR_MORE['field_code'] = $ARR_HAS_FIELD['codeAppscheme_has_field']; - $ARR_MORE['field_name'] = $ARR_HAS_FIELD['nomAppscheme_has_field']; - $ARR_MORE['field_name_raw'] = $ARR_FIELD['nomAppscheme_field']; - $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field']; - $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field']; - $ARR_MORE['field_type'] = $ARR_FIELD['field_type']; - $ARR_MORE['field_group'] = $ARR_FIELD['field_group']; - $ARR_MORE['field_required'] = $ARR_HAS_FIELD['required'] ?? false; - $ARR_MORE['field_order'] = $ARR_HAS_FIELD['ordreAppscheme_has_field'] ?? ''; - - $columnModel[$ARR_HAS_FIELD['codeAppscheme_has_field']] = $ARR_MORE; //array_merge($ARR_FIELD, $ARR_MORE); - endforeach; - - foreach ($GRILLE_FK as $fk) : - $columnModel['GRILLE_FK.' . $fk['table_fk'].'.nom' . ucfirst($fk['table_fk'])] = [ - 'field_name_group' => '', - 'viewFieldType' => 'GRILLE_FK', - 'field_name' => 'nom' . ucfirst($fk['table_fk']), - 'field_name_raw' => $fk['table_fk'], - 'field_type' => 'text', - 'title' => $fk['table_fk'], - 'className' => 'fk',/* 'field_icon' => $fk['icon_fk'], - 'icon' => $fk['icon_fk']*/ - ]; - endforeach; - - foreach ($GRILLE_COUNT as $key_count => $fk) : - $columnModel['count_' . $key_count] = ['field_type' => 'number','viewFieldType' => 'GRILLE_COUNT', 'field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; - $default_model['count_' . $key_count] = ['field_type' => 'number','viewFieldType' => 'GRILLE_COUNT', 'field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; - endforeach; - - return $columnModel; - } - - private function RsDefaultModel($idappscheme = null) - { - $default_model = []; - $RS_HAS_TABLE_FIELD = $this->APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$idappscheme]); //->sort(['ordreAppscheme_has_table_field' => 1]); - - foreach ($RS_HAS_TABLE_FIELD as $ARR_HAS_TABLE_FIELD) : // tout les champs declarés dans has_table_field. - $ARR_SCH_FIELD = $this->APP_SCH->findOne(['idappscheme' => (int)$ARR_HAS_TABLE_FIELD['idappscheme_link']]); - $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$ARR_HAS_TABLE_FIELD['idappscheme_field']]); - $DA_TABLE_NANE = $ARR_SCH_FIELD['nomAppscheme']; - $title = ($ARR_HAS_TABLE_FIELD['idappscheme'] == $ARR_HAS_TABLE_FIELD['idappscheme_link']) ? $ARR_FIELD['nomAppscheme_field'] : $ARR_FIELD['nomAppscheme_field'] . ' ' . $DA_TABLE_NANE; - - $ARR_MORE['field_name'] = $ARR_HAS_TABLE_FIELD['nomAppscheme_has_table_field'] ?? ''; - $ARR_MORE['field_name_raw'] = $ARR_HAS_TABLE_FIELD['nomAppscheme_field'] ?? ''; - $ARR_MORE['field_code'] = $ARR_HAS_TABLE_FIELD['codeAppscheme_has_table_field'] ?? $ARR_HAS_TABLE_FIELD['codeAppscheme_has_field'] ?? ''; - $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field'] ?? ''; - $ARR_MORE['field_icon'] = $ARR_HAS_TABLE_FIELD['iconAppscheme_has_table_field'] ?? $ARR_FIELD['iconAppscheme_field'] ?? null; - $ARR_MORE['field_order'] = $ARR_HAS_TABLE_FIELD['ordreAppscheme_has_table_field'] ?? $ARR_FIELD['ordreAppscheme_field']; - /* $ARR_MORE['field_icon'] = $ARR_HAS_TABLE_FIELD['iconAppscheme_field']; - $ARR_MORE['field_color'] = $ARR_HAS_TABLE_FIELD['colorAppscheme_field']; - $ARR_MORE['field_type'] = $ARR_FIELD['field_type'];*/ - $ARR_MORE['field_group'] = $ARR_FIELD['field_group'] ?? $ARR_FIELD['codeAppscheme_field_group'] ?? ''; - $ARR_MORE['field_type'] = $ARR_FIELD['field_type'] ?? $ARR_FIELD['codeAppscheme_field_type'] ?? ''; - $default_model[$ARR_HAS_TABLE_FIELD['codeAppscheme_has_table_field']] = array_merge($this->GetField($ARR_FIELD['codeAppscheme_field']), $ARR_MORE); - - endforeach; - - return $default_model; - } - - private function RsDynamicView($idappscheme = null, $type = 'in_mini_fiche') - { - $miniModel = []; - if ($type) { - $RS_HAS_MINI_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme, $type => 1], ['sort' => ['ordreAppscheme_has_table_field' => 1]]); //->sort(['ordreAppscheme_has_table_field' => 1]); - } else { - $RS_HAS_MINI_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme], ['sort' => ['ordreAppscheme_has_table_field' => 1]]); //->sort(['ordreAppscheme_has_table_field' => 1]); - } - - foreach ($RS_HAS_MINI_FIELD as $ARR_HAS_MINI_FIELD) : - $ARR_FIELD = $this->GetField((int)$ARR_HAS_MINI_FIELD['idappscheme_field']); - $ARR_MORE['field_code'] = $ARR_HAS_MINI_FIELD['codeAppscheme_has_field'] ?? ''; - $ARR_MORE['field_name'] = $ARR_FIELD['nomAppscheme_field'] ?? ''; - $ARR_MORE['field_name_raw'] = $ARR_FIELD['nomAppscheme_field'] ?? ''; - $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field'] ?? ''; - $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field'] ?? ''; - $ARR_MORE['field_color'] = $ARR_FIELD['colorAppscheme_field'] ?? ''; - $ARR_MORE['field_type'] = $ARR_FIELD['codeAppscheme_field_type'] ?? ''; - $ARR_MORE['field_group'] = $ARR_FIELD['codeAppscheme_field_group'] ?? ''; - $ARR_MORE['field_required'] = $ARR_HAS_MINI_FIELD['required'] ?? ''; - $ARR_MORE['field_order'] = $ARR_HAS_MINI_FIELD['ordreAppscheme_has_field'] ?? $ARR_FIELD['ordreAppscheme_field'] ?? null; - $miniModel[$ARR_HAS_MINI_FIELD['codeAppscheme_has_field']] = $ARR_MORE; //array_merge($ARR_MORE,$ARR_FIELD ); - endforeach; - - return $miniModel; - } - - /** - * @param $table - * - * @return mixed - * @throws \Exception - */ - public function get_schemeParts($table) - { - - $this->IDB = new IdaeDataSchemeModel($table); - - return $this->IDB->get_schemeParts(); - } - - /** - * @throws \Exception - * @throws \MongoCursorException - */ - public function legacyParse() - { - $INIT = new IdaeDataSchemeInit(); - $PIECE = !isset($_POST['piece']) ? 'scheme' : $_POST['piece']; - - $vars = empty($_GET['vars']) ? [] : function_prod::cleanPostMongo($_POST['vars'], 1); - // $RS_APP = $this->APP_SCH->find($vars)->sort(['codeAppscheme' => 1]); - // $RS_APP = $this->APP_SCH->find($vars + ['grouped_scheme' => ['$ne' => 1]]);//->sort(['codeAppscheme' => 1]); - $RS_APP = $this->APP_SCH->find($vars); // 2023 removed grouped_scheme - $COLLECT = []; - - $RS_APP = iterator_to_array($RS_APP); - - foreach ($RS_APP as $ARR_APP) : - // $INIT->consolidate_app_scheme($ARR_APP['codeAppscheme']); - - //$ARR_APP = MongoDB\BSON\toPHP($ARR_APP); - /*var_dump($ARR_APP ); - die();*/ - $idappscheme = (int)$ARR_APP['idappscheme']; - $table = $ARR_APP['codeAppscheme']; - $Table = ucfirst($table); - $base = $ARR_APP['codeAppscheme_base']; - $Table = ucfirst($ARR_APP['codeAppscheme']); - - $DATA_SCHEME = new IdaeDataScheme($table); - $DATA_SCHEME_MODEL = new IdaeDataSchemeModel($table); - - $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); - - $APP = new App($table); - $APP_TABLE = $APP->app_table_one; - $ENTITY = $APP_TABLE; - $GRILLE_FK = $APP->get_grille_fk(); - $GRILLE_RFK = array_reduce(array_map(function ($scheme) { - return [$scheme => $scheme]; - }, $APP->get_table_rfk($table)), 'array_merge', []); - $GRILLE_COUNT = $APP->get_grille_count($table); - //$arrFields = $APP->get_basic_fields_nude($table); - - /*$ENTITY['grilleFK'] = $GRILLE_FK; - $ENTITY['grilleRFK'] = $GRILLE_RFK; - $ENTITY['grilleCount'] = $GRILLE_COUNT;*/ - - $fieldModel = $this->RsHasField($idappscheme); - $miniModel = $this->RsDynamicView($idappscheme, 'in_mini_fiche'); - $schemeModel = $this->RsDynamicView($idappscheme); - $default_model = $this->RsDefaultModel($idappscheme); - $columnModel = $this->RsColumnModel($idappscheme); - $schemePartsModel = $this->get_schemeParts($table); - // - $microModelKey = isset($fieldModel["nom$Table"]) ? "nom$Table" : "code$Table"; - $microModel = [$microModelKey => $fieldModel[$microModelKey]]; - - $hasModel = []; - $updateModel = []; - - // start here for all : columnModel => pour table par defaut, sans description, sueleument code et identification + fk - foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD) : - $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$ARR_HAS_FIELD['idappscheme_field']]); - if ($ARR_FIELD['codeAppscheme_field_group'] == 'codification' || $ARR_FIELD['codeAppscheme_field_group'] == 'identification') { - - $hasModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD; - }; - endforeach; - - foreach ($GRILLE_COUNT as $key_count => $fk) : - // $columnModel[] = ['field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; - $default_model[] = ['field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; - endforeach; - - $APP_MODEL['columnModel'] = $columnModel; - $APP_MODEL['defaultModel'] = $default_model; // user => table big - $APP_MODEL['hasModel'] = $hasModel; // sans fk - $APP_MODEL['fieldModel'] = $fieldModel; // tout les champs - $APP_MODEL['miniModel'] = $miniModel; // mini - $APP_MODEL['microModel'] = $microModel; // one field no more - // - $COLLECT[$base][$table] = (array)$APP_TABLE; - $COLLECT[$base][$table]['entity'] = $ENTITY; - $COLLECT[$base][$table]['views'] = $APP_MODEL; - $COLLECT[$base][$table]['scheme'] = $DATA_SCHEME->getSchemeData(); - $COLLECT[$base][$table]['fields'] = $DATA_SCHEME->getSchemeFields(); - $COLLECT[$base][$table]['datascheme']['grilleFK'] = $DATA_SCHEME->getGrilleFK(); - $COLLECT[$base][$table]['datascheme']['grilleRFK'] = $DATA_SCHEME->get_grille_rfk(); - - /* $COLLECT['ungrouped'][$table] = (array)$APP_TABLE; - $COLLECT['ungrouped'][$table]['entity'] = $ENTITY; - $COLLECT['ungrouped'][$table]['views'] = $APP_MODEL; - $COLLECT['ungrouped'][$table]['scheme'] = $DATA_SCHEME->getSchemeData(); - $COLLECT['ungrouped'][$table]['fields'] = $DATA_SCHEME->getSchemeFields(); - $COLLECT['ungrouped'][$table]['datascheme']['grilleFK'] = $DATA_SCHEME->getGrilleFK(); - $COLLECT['ungrouped'][$table]['datascheme']['grilleRFK'] = $DATA_SCHEME->get_grille_rfk(); */ - - - endforeach; - - return $COLLECT; - } -} - -$JsonSchemeClass = new JsonScheme(); -$out = $JsonSchemeClass->legacyParse(); - +APP = new App(); + $this->APP_SCH = new App('appscheme'); + $this->APP_FIELD = new App('appscheme_field'); + $this->APP_HAS_FIELD = new App('appscheme_has_field'); + $this->APP_HAS_TABLE_FIELD = new App('appscheme_has_table_field'); + + return parent::__construct($table); + } + + /** + * return mainly : icon, color ... + * + * @param $idappscheme_field + * + * @return array + */ + private function GetField($idappscheme_field) + { + $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$idappscheme_field]); + + return [ + 'idppscheme_field' => $idappscheme_field, + 'codeAppscheme_field' => $ARR_FIELD['codeAppscheme_field'], + 'nomAppscheme_field' => $ARR_FIELD['nomAppscheme_field'], + 'codeAppscheme_field_group' => $ARR_FIELD['codeAppscheme_field_group'] ?? '', + 'field_group' => $ARR_FIELD['codeAppscheme_field_group'] ?? '', + 'iconAppscheme_field' => $ARR_FIELD['iconAppscheme_field'] ?? '', + 'codeAppscheme_field_type' => $ARR_FIELD['codeAppscheme_field_type'] ?? '', + 'field_type' => $ARR_FIELD['codeAppscheme_field_type'] ?? '', + 'css' => $this->GetFieldCssRule($ARR_FIELD['codeAppscheme_field_type']), + 'viewFieldType' => 'SCHEME' + ]; + } + + private function GetFieldCssRule($codeAppscheme_field_type = '') + { + + $css = ''; + + switch ($codeAppscheme_field_type): + case "date": + $css = 'date_field'; + break; + case "heure": + $css = 'heure_field'; + break; + case "color": + $css = 'color_field'; + break; + default: + if (empty($codeAppscheme_field_type)) { + $css = 'fk '; + } else { + $css = 'css_field_' . $codeAppscheme_field_type; + } + + break; + endswitch; + + return $css; + } + + /** + * fieldModel + * + * @param $idappscheme + * + * @return array + */ + private function RsHasField($idappscheme) + { + + $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); + $fieldModel = []; + + foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD) : + + $ARR_FIELD = $this->GetField((int)$ARR_HAS_FIELD['idappscheme_field']); + + $ARR_MORE['field_name'] = $ARR_HAS_FIELD['nomAppscheme_has_field']; + $ARR_MORE['field_name_raw'] = $ARR_HAS_FIELD['nomAppscheme_field']; + $ARR_MORE['field_code'] = $ARR_HAS_FIELD['codeAppscheme_has_field']; + $ARR_MORE['field_code_raw'] = $ARR_HAS_FIELD['codeAppscheme_field']; + $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field']; + $ARR_MORE['field_type'] = $ARR_FIELD['field_type']; + $ARR_MORE['field_group'] = $ARR_FIELD['codeAppscheme_field_group']; + $ARR_MORE['field_order'] = $ARR_HAS_FIELD['ordreAppscheme_has_field'] ?? ''; + $ARR_MORE['field_required'] = $ARR_HAS_FIELD['required'] ?? false; + + $fieldModel[$ARR_HAS_FIELD['codeAppscheme_has_field']] = $ARR_MORE; //array_merge($ARR_FIELD, $ARR_MORE, $ARR_HAS_FIELD); + + if ($ARR_FIELD['codeAppscheme_field_group'] == 'codification' || $ARR_FIELD['codeAppscheme_field_group'] == 'identification') { + /*$fieldModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD;*/ + $hasModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD; + }; + endforeach; + + return $fieldModel; + } + + private function RsColumnModel($idappscheme) + { + + $ARR_APP = $this->APP_SCH->findOne(['idappscheme' => (int)$idappscheme]); + $table = $ARR_APP['codeAppscheme']; + + $APP = new App($table); + $GRILLE_FK = $APP->get_grille_fk(); + $GRILLE_COUNT = $APP->get_grille_count($table); + + $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); + $columnModel = []; + + foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD) : + $ARR_FIELD = $this->GetField((int)$ARR_HAS_FIELD['idappscheme_field']); + + $ARR_MORE['field_code'] = $ARR_HAS_FIELD['codeAppscheme_has_field']; + $ARR_MORE['field_name'] = $ARR_HAS_FIELD['nomAppscheme_has_field']; + $ARR_MORE['field_name_raw'] = $ARR_FIELD['nomAppscheme_field']; + $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field']; + $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field']; + $ARR_MORE['field_type'] = $ARR_FIELD['field_type']; + $ARR_MORE['field_group'] = $ARR_FIELD['field_group']; + $ARR_MORE['field_required'] = $ARR_HAS_FIELD['required'] ?? false; + $ARR_MORE['field_order'] = $ARR_HAS_FIELD['ordreAppscheme_has_field'] ?? ''; + + $columnModel[$ARR_HAS_FIELD['codeAppscheme_has_field']] = $ARR_MORE; //array_merge($ARR_FIELD, $ARR_MORE); + endforeach; + + foreach ($GRILLE_FK as $fk) : + $columnModel['GRILLE_FK.' . $fk['table_fk'].'.nom' . ucfirst($fk['table_fk'])] = [ + 'field_name_group' => '', + 'viewFieldType' => 'GRILLE_FK', + 'field_name' => 'nom' . ucfirst($fk['table_fk']), + 'field_name_raw' => $fk['table_fk'], + 'field_type' => 'text', + 'title' => $fk['table_fk'], + 'className' => 'fk',/* 'field_icon' => $fk['icon_fk'], + 'icon' => $fk['icon_fk']*/ + ]; + endforeach; + + foreach ($GRILLE_COUNT as $key_count => $fk) : + $columnModel['count_' . $key_count] = ['field_type' => 'number','viewFieldType' => 'GRILLE_COUNT', 'field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; + $default_model['count_' . $key_count] = ['field_type' => 'number','viewFieldType' => 'GRILLE_COUNT', 'field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; + endforeach; + + return $columnModel; + } + + private function RsDefaultModel($idappscheme = null) + { + $default_model = []; + $RS_HAS_TABLE_FIELD = $this->APP_HAS_TABLE_FIELD->find(['idappscheme' => (int)$idappscheme]); //->sort(['ordreAppscheme_has_table_field' => 1]); + + foreach ($RS_HAS_TABLE_FIELD as $ARR_HAS_TABLE_FIELD) : // tout les champs declarés dans has_table_field. + $ARR_SCH_FIELD = $this->APP_SCH->findOne(['idappscheme' => (int)$ARR_HAS_TABLE_FIELD['idappscheme_link']]); + $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$ARR_HAS_TABLE_FIELD['idappscheme_field']]); + $DA_TABLE_NANE = $ARR_SCH_FIELD['nomAppscheme']; + $title = ($ARR_HAS_TABLE_FIELD['idappscheme'] == $ARR_HAS_TABLE_FIELD['idappscheme_link']) ? $ARR_FIELD['nomAppscheme_field'] : $ARR_FIELD['nomAppscheme_field'] . ' ' . $DA_TABLE_NANE; + + $ARR_MORE['field_name'] = $ARR_HAS_TABLE_FIELD['nomAppscheme_has_table_field'] ?? ''; + $ARR_MORE['field_name_raw'] = $ARR_HAS_TABLE_FIELD['nomAppscheme_field'] ?? ''; + $ARR_MORE['field_code'] = $ARR_HAS_TABLE_FIELD['codeAppscheme_has_table_field'] ?? $ARR_HAS_TABLE_FIELD['codeAppscheme_has_field'] ?? ''; + $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field'] ?? ''; + $ARR_MORE['field_icon'] = $ARR_HAS_TABLE_FIELD['iconAppscheme_has_table_field'] ?? $ARR_FIELD['iconAppscheme_field'] ?? null; + $ARR_MORE['field_order'] = $ARR_HAS_TABLE_FIELD['ordreAppscheme_has_table_field'] ?? $ARR_FIELD['ordreAppscheme_field']; + /* $ARR_MORE['field_icon'] = $ARR_HAS_TABLE_FIELD['iconAppscheme_field']; + $ARR_MORE['field_color'] = $ARR_HAS_TABLE_FIELD['colorAppscheme_field']; + $ARR_MORE['field_type'] = $ARR_FIELD['field_type'];*/ + $ARR_MORE['field_group'] = $ARR_FIELD['field_group'] ?? $ARR_FIELD['codeAppscheme_field_group'] ?? ''; + $ARR_MORE['field_type'] = $ARR_FIELD['field_type'] ?? $ARR_FIELD['codeAppscheme_field_type'] ?? ''; + $default_model[$ARR_HAS_TABLE_FIELD['codeAppscheme_has_table_field']] = array_merge($this->GetField($ARR_FIELD['codeAppscheme_field']), $ARR_MORE); + + endforeach; + + return $default_model; + } + + private function RsDynamicView($idappscheme = null, $type = 'in_mini_fiche') + { + $miniModel = []; + if ($type) { + $RS_HAS_MINI_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme, $type => 1], ['sort' => ['ordreAppscheme_has_table_field' => 1]]); //->sort(['ordreAppscheme_has_table_field' => 1]); + } else { + $RS_HAS_MINI_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme], ['sort' => ['ordreAppscheme_has_table_field' => 1]]); //->sort(['ordreAppscheme_has_table_field' => 1]); + } + + foreach ($RS_HAS_MINI_FIELD as $ARR_HAS_MINI_FIELD) : + $ARR_FIELD = $this->GetField((int)$ARR_HAS_MINI_FIELD['idappscheme_field']); + $ARR_MORE['field_code'] = $ARR_HAS_MINI_FIELD['codeAppscheme_has_field'] ?? ''; + $ARR_MORE['field_name'] = $ARR_FIELD['nomAppscheme_field'] ?? ''; + $ARR_MORE['field_name_raw'] = $ARR_FIELD['nomAppscheme_field'] ?? ''; + $ARR_MORE['field_code_raw'] = $ARR_FIELD['codeAppscheme_field'] ?? ''; + $ARR_MORE['field_icon'] = $ARR_FIELD['iconAppscheme_field'] ?? ''; + $ARR_MORE['field_color'] = $ARR_FIELD['colorAppscheme_field'] ?? ''; + $ARR_MORE['field_type'] = $ARR_FIELD['codeAppscheme_field_type'] ?? ''; + $ARR_MORE['field_group'] = $ARR_FIELD['codeAppscheme_field_group'] ?? ''; + $ARR_MORE['field_required'] = $ARR_HAS_MINI_FIELD['required'] ?? ''; + $ARR_MORE['field_order'] = $ARR_HAS_MINI_FIELD['ordreAppscheme_has_field'] ?? $ARR_FIELD['ordreAppscheme_field'] ?? null; + $miniModel[$ARR_HAS_MINI_FIELD['codeAppscheme_has_field']] = $ARR_MORE; //array_merge($ARR_MORE,$ARR_FIELD ); + endforeach; + + return $miniModel; + } + + /** + * @param $table + * + * @return mixed + * @throws \Exception + */ + public function get_schemeParts($table) + { + + $this->IDB = new IdaeDataSchemeModel($table); + + return $this->IDB->get_schemeParts(); + } + + /** + * @throws \Exception + * @throws \MongoCursorException + */ + public function legacyParse() + { + $INIT = new IdaeDataSchemeInit(); + $PIECE = !isset($_POST['piece']) ? 'scheme' : $_POST['piece']; + + $vars = empty($_GET['vars']) ? [] : function_prod::cleanPostMongo($_POST['vars'], 1); + // $RS_APP = $this->APP_SCH->find($vars)->sort(['codeAppscheme' => 1]); + // $RS_APP = $this->APP_SCH->find($vars + ['grouped_scheme' => ['$ne' => 1]]);//->sort(['codeAppscheme' => 1]); + $RS_APP = $this->APP_SCH->find($vars); // 2023 removed grouped_scheme + $COLLECT = []; + + $RS_APP = iterator_to_array($RS_APP); + + foreach ($RS_APP as $ARR_APP) : + // $INIT->consolidate_app_scheme($ARR_APP['codeAppscheme']); + + //$ARR_APP = MongoDB\BSON\toPHP($ARR_APP); + /*var_dump($ARR_APP ); + die();*/ + $idappscheme = (int)$ARR_APP['idappscheme']; + $table = $ARR_APP['codeAppscheme']; + $Table = ucfirst($table); + $base = $ARR_APP['codeAppscheme_base']; + $Table = ucfirst($ARR_APP['codeAppscheme']); + + $DATA_SCHEME = new IdaeDataScheme($table); + $DATA_SCHEME_MODEL = new IdaeDataSchemeModel($table); + + $RS_HAS_FIELD = $this->APP_HAS_FIELD->find(['idappscheme' => (int)$idappscheme]); + + $APP = new App($table); + $APP_TABLE = $APP->app_table_one; + $ENTITY = $APP_TABLE; + $GRILLE_FK = $APP->get_grille_fk(); + $GRILLE_RFK = array_reduce(array_map(function ($scheme) { + return [$scheme => $scheme]; + }, $APP->get_table_rfk($table)), 'array_merge', []); + $GRILLE_COUNT = $APP->get_grille_count($table); + //$arrFields = $APP->get_basic_fields_nude($table); + + /*$ENTITY['grilleFK'] = $GRILLE_FK; + $ENTITY['grilleRFK'] = $GRILLE_RFK; + $ENTITY['grilleCount'] = $GRILLE_COUNT;*/ + + $fieldModel = $this->RsHasField($idappscheme); + $miniModel = $this->RsDynamicView($idappscheme, 'in_mini_fiche'); + $schemeModel = $this->RsDynamicView($idappscheme); + $default_model = $this->RsDefaultModel($idappscheme); + $columnModel = $this->RsColumnModel($idappscheme); + $schemePartsModel = $this->get_schemeParts($table); + // + $microModelKey = isset($fieldModel["nom$Table"]) ? "nom$Table" : "code$Table"; + $microModel = [$microModelKey => $fieldModel[$microModelKey]]; + + $hasModel = []; + $updateModel = []; + + // start here for all : columnModel => pour table par defaut, sans description, sueleument code et identification + fk + foreach ($RS_HAS_FIELD as $ARR_HAS_FIELD) : + $ARR_FIELD = $this->APP_FIELD->findOne(['idappscheme_field' => (int)$ARR_HAS_FIELD['idappscheme_field']]); + if ($ARR_FIELD['codeAppscheme_field_group'] == 'codification' || $ARR_FIELD['codeAppscheme_field_group'] == 'identification') { + + $hasModel[$ARR_FIELD['codeAppscheme_field']] = $ARR_FIELD; + }; + endforeach; + + foreach ($GRILLE_COUNT as $key_count => $fk) : + // $columnModel[] = ['field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; + $default_model[] = ['field_name_group' => '', 'field_name' => 'count_' . $key_count, 'field_name_raw' => 'count_' . $key_count, 'title' => 'nb ' . $key_count, 'className' => 'nb_field', 'icon' => '']; + endforeach; + + $APP_MODEL['columnModel'] = $columnModel; + $APP_MODEL['defaultModel'] = $default_model; // user => table big + $APP_MODEL['hasModel'] = $hasModel; // sans fk + $APP_MODEL['fieldModel'] = $fieldModel; // tout les champs + $APP_MODEL['miniModel'] = $miniModel; // mini + $APP_MODEL['microModel'] = $microModel; // one field no more + // + $COLLECT[$base][$table] = (array)$APP_TABLE; + $COLLECT[$base][$table]['entity'] = $ENTITY; + $COLLECT[$base][$table]['views'] = $APP_MODEL; + $COLLECT[$base][$table]['scheme'] = $DATA_SCHEME->getSchemeData(); + $COLLECT[$base][$table]['fields'] = $DATA_SCHEME->getSchemeFields(); + $COLLECT[$base][$table]['datascheme']['grilleFK'] = $DATA_SCHEME->getGrilleFK(); + $COLLECT[$base][$table]['datascheme']['grilleRFK'] = $DATA_SCHEME->get_grille_rfk(); + + /* $COLLECT['ungrouped'][$table] = (array)$APP_TABLE; + $COLLECT['ungrouped'][$table]['entity'] = $ENTITY; + $COLLECT['ungrouped'][$table]['views'] = $APP_MODEL; + $COLLECT['ungrouped'][$table]['scheme'] = $DATA_SCHEME->getSchemeData(); + $COLLECT['ungrouped'][$table]['fields'] = $DATA_SCHEME->getSchemeFields(); + $COLLECT['ungrouped'][$table]['datascheme']['grilleFK'] = $DATA_SCHEME->getGrilleFK(); + $COLLECT['ungrouped'][$table]['datascheme']['grilleRFK'] = $DATA_SCHEME->get_grille_rfk(); */ + + + endforeach; + + return $COLLECT; + } +} + +$JsonSchemeClass = new JsonScheme(); +$out = $JsonSchemeClass->legacyParse(); + echo json_encode($out); \ No newline at end of file diff --git a/web/bin/services/json_scheme_field.php b/web/bin/services/json_scheme_field.php index 89dc44e..84bf48e 100644 --- a/web/bin/services/json_scheme_field.php +++ b/web/bin/services/json_scheme_field.php @@ -1,25 +1,25 @@ -find($vars); - $COLLECT = []; - - foreach ($RS_ARR_FIELD as $ARR_FIELD): - unset($ARR_FIELD['_id']); - - $code = $ARR_FIELD['codeAppscheme_field']; - $APP_TABLE[$code] = $ARR_FIELD; - // - $COLLECT[$code] = $ARR_FIELD; - endforeach; - - echo trim(json_encode($COLLECT)); +find($vars); + $COLLECT = []; + + foreach ($RS_ARR_FIELD as $ARR_FIELD): + unset($ARR_FIELD['_id']); + + $code = $ARR_FIELD['codeAppscheme_field']; + $APP_TABLE[$code] = $ARR_FIELD; + // + $COLLECT[$code] = $ARR_FIELD; + endforeach; + + echo trim(json_encode($COLLECT)); diff --git a/web/bin/services/json_ssid.php b/web/bin/services/json_ssid.php index ef90ea2..a872189 100644 --- a/web/bin/services/json_ssid.php +++ b/web/bin/services/json_ssid.php @@ -1,20 +1,20 @@ - '']; - - if (empty($_COOKIE['PHPSESSID'])) { - echo trim(json_encode($COLLECT)); - echo trim(json_encode($_SESSION)); - exit; - } - - $COLLECT['session'] = $_SESSION; - $COLLECT['PHPSESSID'] = $_COOKIE['PHPSESSID']; - $COLLECT['type_session'] = $_SESSION['type_session']; - $COLLECT[$COLLECT['type_session']] = $_SESSION[$_SESSION['type_session']]; - $COLLECT['id' . $COLLECT['type_session']] = $_SESSION['id' . $_SESSION['type_session']]; - + '']; + + if (empty($_COOKIE['PHPSESSID'])) { + echo trim(json_encode($COLLECT)); + echo trim(json_encode($_SESSION)); + exit; + } + + $COLLECT['session'] = $_SESSION; + $COLLECT['PHPSESSID'] = $_COOKIE['PHPSESSID']; + $COLLECT['type_session'] = $_SESSION['type_session']; + $COLLECT[$COLLECT['type_session']] = $_SESSION[$_SESSION['type_session']]; + $COLLECT['id' . $COLLECT['type_session']] = $_SESSION['id' . $_SESSION['type_session']]; + echo trim(json_encode($COLLECT), JSON_FORCE_OBJECT); \ No newline at end of file diff --git a/web/bin/services/json_token.php b/web/bin/services/json_token.php index bc0e044..adad23c 100644 --- a/web/bin/services/json_token.php +++ b/web/bin/services/json_token.php @@ -1,12 +1,12 @@ - - - - - - - - {$meta_tile} {$site_page} - - - - - - - - {if $site_page == 'admin_shop' || $site_page == 'admin_delivery' } - - {/if} - - - -
- -
-
- - {if $site_page != 'admin_shop' && $site_page != 'admin_delivery' && $site_page != 'login_multi'} -
- {$menu_bar|noescape} -
- {/if} - - {$route|noescape} - - {$html_footer|noescape} - - {include fragments/notifications.html} - - {include fragments/map_overlay.html} -
- - - - - - - - - - - - - {if $site_page != 'admin_delivery' && $site_page != 'admin_shop'} - - - {/if} - - - - - - - - - - - {if $site_page == 'admin_shop' } - - - {/if} - {if $site_page == 'admin_delivery'} - - - {/if} - - - - - {if $site_page == 'admin_shop' || $site_page == 'admin_delivery' } - - - - - - - - {/if} - + + + + + + + + {$meta_tile} {$site_page} + + + + + + + + {if $site_page == 'admin_shop' || $site_page == 'admin_delivery' } + + {/if} + + + +
+ +
+
+ + {if $site_page != 'admin_shop' && $site_page != 'admin_delivery' && $site_page != 'login_multi'} +
+ {$menu_bar|noescape} +
+ {/if} + + {$route|noescape} + + {$html_footer|noescape} + + {include fragments/notifications.html} + + {include fragments/map_overlay.html} +
+ + + + + + + + + + + + + {if $site_page != 'admin_delivery' && $site_page != 'admin_shop'} + + + {/if} + + + + + + + + + + + {if $site_page == 'admin_shop' } + + + {/if} + {if $site_page == 'admin_delivery'} + + + {/if} + + + + + {if $site_page == 'admin_shop' || $site_page == 'admin_delivery' } + + + + + + + + {/if} + \ No newline at end of file diff --git a/web/bin/templates/fragments/cart_big.html b/web/bin/templates/fragments/cart_big.html index 11e669f..0401e9a 100644 --- a/web/bin/templates/fragments/cart_big.html +++ b/web/bin/templates/fragments/cart_big.html @@ -1,76 +1,76 @@ -
-
-
- {if $_SESSION['client']} - Client Tac-Tac {$_SESSION['client_identity']} - {else} - J'ai un compte - {/if} -
-
-
-
- -
-
-
-
-
-
-
- Temps d' attente' : {$var_cart['cart_total_time']} min. -
-
-
-
- Volume : {$var_cart['cart_total_volume']} / 100 -
-
-
-
-
- {php $dsp_empty = (sizeof($var_cart['cart_lines'])==0)? '':'none'} - {php $dsp_sum_zone = (sizeof($var_cart['cart_lines'])==0)? 'none':''} - -
-
-
- total {$var_cart['cart_total']} ttc € -
-
- dont course {$var_cart['cart_sous_total']} ttc € -
-
-
-
-
- - -
- Votre panier est vide -
-
- - {foreach $var_cart['cart_lines'] as $cart_line_key => $cart_line} - {include cart_big_line.html, cart_line => $cart_line, cart_line_key => $cart_line_key} - {/foreach} -
- -
- {include cart_big_item.html, cart_line => $cart_line, cart_line_key => $cart_line_key} -
-
-
-
- - +
+
+
+ {if $_SESSION['client']} + Client Tac-Tac {$_SESSION['client_identity']} + {else} + J'ai un compte + {/if} +
+
+
+
+ +
+
+
+
+
+
+
+ Temps d' attente' : {$var_cart['cart_total_time']} min. +
+
+
+
+ Volume : {$var_cart['cart_total_volume']} / 100 +
+
+
+
+
+ {php $dsp_empty = (sizeof($var_cart['cart_lines'])==0)? '':'none'} + {php $dsp_sum_zone = (sizeof($var_cart['cart_lines'])==0)? 'none':''} + +
+
+
+ total {$var_cart['cart_total']} ttc € +
+
+ dont course {$var_cart['cart_sous_total']} ttc € +
+
+
+
+
+ + +
+ Votre panier est vide +
+
+ + {foreach $var_cart['cart_lines'] as $cart_line_key => $cart_line} + {include cart_big_line.html, cart_line => $cart_line, cart_line_key => $cart_line_key} + {/foreach} +
+ +
+ {include cart_big_item.html, cart_line => $cart_line, cart_line_key => $cart_line_key} +
+
+
+
+ +
\ No newline at end of file diff --git a/web/bin/templates/fragments/cart_big_item.html b/web/bin/templates/fragments/cart_big_item.html index 6755fbf..00a08a2 100644 --- a/web/bin/templates/fragments/cart_big_item.html +++ b/web/bin/templates/fragments/cart_big_item.html @@ -1,56 +1,56 @@ -
- -
- - - - - {php $cart_line_total = $cart_line['qte'] * $cart_line['id']['prix_siteProduit'] } - - - - -
- - -
-
- -
-
{$cart_line['id']['nomProduit']}
- -
-
-
-
-
{$cart_line['qte']}
-
-
{$cart_line['id']['prix_siteProduit']}
-
-
-
{$cart_line_total} € -
-
-
-
- -
-
- -
-
- -
- -
-
- -
-
+
+ +
+ + + + + {php $cart_line_total = $cart_line['qte'] * $cart_line['id']['prix_siteProduit'] } + + + + +
+ + +
+
+ +
+
{$cart_line['id']['nomProduit']}
+ +
+
+
+
+
{$cart_line['qte']}
+
+
{$cart_line['id']['prix_siteProduit']}
+
+
+
{$cart_line_total} € +
+
+
+
+ +
+
+ +
+
+ +
+ +
+
+ +
+
\ No newline at end of file diff --git a/web/bin/templates/fragments/cart_big_line.html b/web/bin/templates/fragments/cart_big_line.html index fa2e2a9..bd48b9c 100644 --- a/web/bin/templates/fragments/cart_big_line.html +++ b/web/bin/templates/fragments/cart_big_line.html @@ -1,37 +1,37 @@ - - - {php $cart_line_total = $cart_line['qte'] * $cart_line['id']['prix_siteProduit'] } - - - - -
-
- -
-
-
{$cart_line['id']['nomProduit']}
-
{$cart_line['description']}
- -
- -
- - -
-
-
{$cart_line['qte']}
-
-
{$cart_line['id']['prix_siteProduit']}
-
-
-
{$cart_line_total} € -
-
- -
- + + + {php $cart_line_total = $cart_line['qte'] * $cart_line['id']['prix_siteProduit'] } + + + + +
+
+ +
+
+
{$cart_line['id']['nomProduit']}
+
{$cart_line['description']}
+ +
+ +
+ + +
+
+
{$cart_line['qte']}
+
+
{$cart_line['id']['prix_siteProduit']}
+
+
+
{$cart_line_total} € +
+
+ +
+ \ No newline at end of file diff --git a/web/bin/templates/fragments/cart_small.html b/web/bin/templates/fragments/cart_small.html index d5b6e82..0702eb1 100644 --- a/web/bin/templates/fragments/cart_small.html +++ b/web/bin/templates/fragments/cart_small.html @@ -1,89 +1,89 @@ -
-
- {php $dsp_empty = (sizeof($var_cart['cart_lines'])==0)? '':'none'} - {php $dsp_sum_zone = (sizeof($var_cart['cart_lines'])==0)? 'none':''} - -
-
- - -
- Votre panier est vide -
-
-
-
- {php $cart_line_total = $cart_line['qte'] * $cart_line['id']['prix_siteProduit'] } -
-
-
-
-
- -
-
-
-
-
-
{$cart_line['id']['nomProduit']}
-
{$cart_line_total}  € 
-
-
-
-
-
-
-
-
total
-
- ttc € {$var_cart['cart_total']}
-
-
-
Livraison
-
- ttc € {$var_cart['cart_sous_total']}
-
-
-
-
- -
-
-
-
-
Temps d' attente : {$var_cart['cart_total_time']} min. -
-
Volume : {$var_cart['cart_total_volume']} / 100 -
-
{$var_cart['cart_adresse']['formatted_address']}
-
-
- -