diff --git a/app/Http/Controllers/FormController.php b/app/Http/Controllers/FormController.php index dfa672ad..85c9b599 100644 --- a/app/Http/Controllers/FormController.php +++ b/app/Http/Controllers/FormController.php @@ -9056,7 +9056,11 @@ class FormController extends Controller return redirect('/form/show'); } //echo '
'; print_r($formdata); exit;
-        $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', ['form_id' => $form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition ]);
+        $historyParams = ['form_id' => $form_id, 'user_id' => $formdata->user_id, 'partition' => $formdata->partition];
+        if ($request->input('export', false)) {
+            $historyParams['designer_flag'] = 'show_in_export';
+        }
+        $history = LambdaRequest::postrequest('form', 'formentity/getformhistory', $historyParams);
         //echo '
'; print_r($history); print_r($formdata); exit;
         //Log::debug(print_r($history, true));
         $canDeleteSubmission = $this->sessionFlag($formdata, 'delete_submission');
@@ -9082,62 +9086,94 @@ class FormController extends Controller
             $exceldata = [];
             $exceldata[] = [$formdata->title];
             $exceldata[] = [''];
-            $headers = ['Submission Date', 'Submitted By'];
-            foreach ($userAttrs as $attr) {
-                $headers[] = $userAttrLabels[$attr] ?? ucwords(str_replace('_', ' ', (string) $attr));
-            }
-            $headers[] = 'Approval Status';
-            foreach($history->data->questions as $question) {
-                if (isset($question->type) && $question->type == 'hidden') {
-                    continue;
-                }
-                if (isset($question->type) && $question->type == 'multitextbox' && !empty($question->options)) {
-                    foreach ($question->options as $k => $v) {
-                        $optLabel = is_object($v) ? ($v->display ?? $v->label ?? $k) : $v;
-                        $headers[] = $optLabel.' ('.$question->label.')';
+            $dataDesignerExport = $this->hasDataDesignerExport($history->data->form ?? null);
+            $headers = [];
+            if ($dataDesignerExport) {
+                foreach ($history->data->questions as $code => $question) {
+                    if (isset($question->type) && $question->type == 'hidden') {
+                        continue;
+                    }
+                    $headers[] = $question->label ?? (is_object($question) && isset($question->code) ? $question->code : $code);
+                }
+            } else {
+                $headers = ['Submission Date', 'Submitted By'];
+                foreach ($userAttrs as $attr) {
+                    $headers[] = $userAttrLabels[$attr] ?? ucwords(str_replace('_', ' ', (string) $attr));
+                }
+                $headers[] = 'Approval Status';
+                foreach($history->data->questions as $question) {
+                    if (isset($question->type) && $question->type == 'hidden') {
+                        continue;
+                    }
+                    if (isset($question->type) && $question->type == 'multitextbox' && !empty($question->options)) {
+                        foreach ($question->options as $k => $v) {
+                            $optLabel = is_object($v) ? ($v->display ?? $v->label ?? $k) : $v;
+                            $headers[] = $optLabel.' ('.$question->label.')';
+                        }
+                    } else {
+                        $headers[] = $question->label;
                     }
-                } else {
-                    $headers[] = $question->label;
                 }
             }
             $exceldata[] = $headers;
             foreach($history->data->submissions as $submission) {
                 $row = [];
-                $row[] = $submission->createdAt;
-                $row[] = isset($submission->user_info->name) ? $submission->user_info->name : '';
-                foreach ($userAttrs as $attr) {
-                    $row[] = $this->userAttributeValue($submission->user_info ?? null, $attr);
-                }
-                $row[] = isset($submission->workflow_status) ? $submission->workflow_status : '';
-                foreach($history->data->questions as $q => $v) {
-                    if (isset($v->type) && $v->type == 'hidden') {
-                        continue;
-                    }
-                    if (isset($v->type) && $v->type == 'multitextbox' && !empty($v->options)) {
-                        foreach ($v->options as $optKey => $optMeta) {
-                            $fieldKey = is_object($optMeta) ? ($optMeta->value ?? $optKey) : $optKey;
-                            if (isset($submission->formdata->{$fieldKey})) {
-                                $raw = $submission->formdata->{$fieldKey};
-                                $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
-                            } elseif (isset($submission->formdata->{$q}) && (is_object($submission->formdata->{$q}) || is_array($submission->formdata->{$q}))) {
-                                $box = (array) $submission->formdata->{$q};
-                                $raw = $box[$fieldKey] ?? '-';
-                                $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
-                            } else {
-                                $row[] = '-';
-                            }
+                if ($dataDesignerExport) {
+                    foreach ($history->data->questions as $code => $question) {
+                        if (isset($question->type) && $question->type == 'hidden') {
+                            continue;
                         }
-                    } else {
-                        if (!isset($submission->formdata->{$q})) {
+                        $col = is_object($question) && isset($question->code) ? $question->code : $code;
+                        if (!isset($submission->formdata->{$col})) {
                             $row[] = '-';
-                        } elseif (is_array($submission->formdata->{$q})) {
-                            $row[] = implode(', ', $submission->formdata->{$q});
-                        } elseif (is_object($submission->formdata->{$q})) {
-                            $row[] = collect((array) $submission->formdata->{$q})->map(function ($val, $key) {
+                        } elseif (is_array($submission->formdata->{$col})) {
+                            $row[] = implode(', ', $submission->formdata->{$col});
+                        } elseif (is_object($submission->formdata->{$col})) {
+                            $row[] = collect((array) $submission->formdata->{$col})->map(function ($val, $key) {
                                 return $key.': '.$val;
                             })->implode(', ');
                         } else {
-                            $row[] = $submission->formdata->{$q};
+                            $row[] = $submission->formdata->{$col};
+                        }
+                    }
+                } else {
+                    $row[] = $submission->createdAt;
+                    $row[] = isset($submission->user_info->name) ? $submission->user_info->name : '';
+                    foreach ($userAttrs as $attr) {
+                        $row[] = $this->userAttributeValue($submission->user_info ?? null, $attr);
+                    }
+                    $row[] = isset($submission->workflow_status) ? $submission->workflow_status : '';
+                    foreach($history->data->questions as $q => $v) {
+                        if (isset($v->type) && $v->type == 'hidden') {
+                            continue;
+                        }
+                        $col = is_object($v) && isset($v->code) ? $v->code : $q;
+                        if (isset($v->type) && $v->type == 'multitextbox' && !empty($v->options)) {
+                            foreach ($v->options as $optKey => $optMeta) {
+                                $fieldKey = is_object($optMeta) ? ($optMeta->value ?? $optKey) : $optKey;
+                                if (isset($submission->formdata->{$fieldKey})) {
+                                    $raw = $submission->formdata->{$fieldKey};
+                                    $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
+                                } elseif (isset($submission->formdata->{$col}) && (is_object($submission->formdata->{$col}) || is_array($submission->formdata->{$col}))) {
+                                    $box = (array) $submission->formdata->{$col};
+                                    $raw = $box[$fieldKey] ?? '-';
+                                    $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
+                                } else {
+                                    $row[] = '-';
+                                }
+                            }
+                        } else {
+                            if (!isset($submission->formdata->{$col})) {
+                                $row[] = '-';
+                            } elseif (is_array($submission->formdata->{$col})) {
+                                $row[] = implode(', ', $submission->formdata->{$col});
+                            } elseif (is_object($submission->formdata->{$col})) {
+                                $row[] = collect((array) $submission->formdata->{$col})->map(function ($val, $key) {
+                                    return $key.': '.$val;
+                                })->implode(', ');
+                            } else {
+                                $row[] = $submission->formdata->{$col};
+                            }
                         }
                     }
                 }
@@ -11291,7 +11327,8 @@ class FormController extends Controller
                 'user_id' => $formdata->user_id,
                 'partition' => $formdata->partition,
                 'team_report' => 1,
-                'json_file' => 1
+                'json_file' => 1,
+                'designer_flag' => 'show_in_export',
             ];
             if (isset($formdata->all_data_access) && $formdata->all_data_access == true) {
                 $serviceParams['alldata'] = 1;
@@ -11310,87 +11347,122 @@ class FormController extends Controller
         $exceldata[] = [$formdata->title];
      
         $exceldata[] = [''];
-        $headers = ['Submission Date', 'Submitted By', 'Employee Code', 'Approval Status'];
-        $userAttrs = $this->userAttributeCodes($history->data->form ?? null);
-        $userAttrLabels = $this->resolveUserAttributeLabels($userAttrs);
-        foreach ($userAttrs as $attr) {
-            $headers[] = $userAttrLabels[$attr] ?? ucwords(str_replace('_', ' ', (string) $attr));
-        }
-        $exportShowPositions = $history->data->form->show_positions ?? $history->data->form->show_position ?? 'no';
-        $exportPositionColumns = $this->getAvailablePositionColumns($history->data->submissions ?? [], $exportShowPositions);
-        $positionLabels = [
-            'territory' => 'Territory',
-            'area' => 'Area',
-            'region' => 'Region',
-            'zone' => 'Zone',
-        ];
-        foreach ($exportPositionColumns as $positionField) {
-            $headers[] = $positionLabels[$positionField] ?? ucfirst($positionField);
-        }
-        if(isset($history->data) && isset($history->data->form) && isset($history->data->form->show_manager_details) && $history->data->form->show_manager_details === 'yes'){
-            $headers = array_merge( $headers, ['L1 Manager', 'L1 Employee Code', 'L2 Manager', 'L2 Employee Code'] );
-        }
-        foreach($history->data->questions as $question) {
-            if (isset($question->type) && $question->type == 'hidden') {
-                continue;
-            }
-            if (isset($question->type) && $question->type == 'multitextbox' && !empty($question->options)) {
-                foreach ($question->options as $k => $v) {
-                    $optLabel = is_object($v) ? ($v->display ?? $v->label ?? $k) : $v;
-                    $headers[] = $optLabel.' ('.$question->label.')';
+        $dataDesignerExport = $this->hasDataDesignerExport($history->data->form ?? null);
+        $headers = [];
+        $userAttrs = [];
+        $userAttrLabels = [];
+        $exportPositionColumns = [];
+        if ($dataDesignerExport) {
+            foreach ($history->data->questions as $code => $question) {
+                if (isset($question->type) && $question->type == 'hidden') {
+                    continue;
+                }
+                $headers[] = $question->label ?? (is_object($question) && isset($question->code) ? $question->code : $code);
+            }
+        } else {
+            $headers = ['Submission Date', 'Submitted By', 'Employee Code', 'Approval Status'];
+            $userAttrs = $this->userAttributeCodes($history->data->form ?? null);
+            $userAttrLabels = $this->resolveUserAttributeLabels($userAttrs);
+            foreach ($userAttrs as $attr) {
+                $headers[] = $userAttrLabels[$attr] ?? ucwords(str_replace('_', ' ', (string) $attr));
+            }
+            $exportShowPositions = $history->data->form->show_positions ?? $history->data->form->show_position ?? 'no';
+            $exportPositionColumns = $this->getAvailablePositionColumns($history->data->submissions ?? [], $exportShowPositions);
+            $positionLabels = [
+                'territory' => 'Territory',
+                'area' => 'Area',
+                'region' => 'Region',
+                'zone' => 'Zone',
+            ];
+            foreach ($exportPositionColumns as $positionField) {
+                $headers[] = $positionLabels[$positionField] ?? ucfirst($positionField);
+            }
+            if(isset($history->data) && isset($history->data->form) && isset($history->data->form->show_manager_details) && $history->data->form->show_manager_details === 'yes'){
+                $headers = array_merge( $headers, ['L1 Manager', 'L1 Employee Code', 'L2 Manager', 'L2 Employee Code'] );
+            }
+            foreach($history->data->questions as $question) {
+                if (isset($question->type) && $question->type == 'hidden') {
+                    continue;
+                }
+                if (isset($question->type) && $question->type == 'multitextbox' && !empty($question->options)) {
+                    foreach ($question->options as $k => $v) {
+                        $optLabel = is_object($v) ? ($v->display ?? $v->label ?? $k) : $v;
+                        $headers[] = $optLabel.' ('.$question->label.')';
+                    }
+                } else {
+                    $headers[] = $question->label;
                 }
-            } else {
-                $headers[] = $question->label;
             }
         }
         $exceldata[] = $headers;
         foreach($history->data->submissions as $submission) {
             $row = [];
-            $row[] = $submission->createdAt;
-            $row[] = isset($submission->user_info->name) ? $submission->user_info->name : '';
-            $row[] = isset($submission->user_info->employee_code) ? $submission->user_info->employee_code : '';
-            $row[] = isset($submission->workflow_status) ? $submission->workflow_status : '';
-            foreach ($userAttrs as $attr) {
-                $row[] = $this->userAttributeValue($submission->user_info ?? null, $attr);
-            }
-            foreach ($exportPositionColumns as $positionField) {
-                $row[] = isset($submission->{$positionField}) ? $submission->{$positionField} : '';
-            }
-            if(isset($history->data) && isset($history->data->form) && isset($history->data->form->show_manager_details) && $history->data->form->show_manager_details === 'yes'){
-                $row[] = isset($submission->manager1_name) ? $submission->manager1_name : '';
-                $row[] = isset($submission->manager1_code) ? $submission->manager1_code : '';
-                $row[] = isset($submission->manager2_name) ? $submission->manager2_name : '';
-                $row[] = isset($submission->manager2_code) ? $submission->manager2_code : '';
-            }
-            foreach($history->data->questions as $q => $v) {
-                if (isset($v->type) && $v->type == 'hidden') {
-                    continue;
-                }
-                if (isset($v->type) && $v->type == 'multitextbox' && !empty($v->options)) {
-                    foreach ($v->options as $optKey => $optMeta) {
-                        $fieldKey = is_object($optMeta) ? ($optMeta->value ?? $optKey) : $optKey;
-                        if (isset($submission->formdata->{$fieldKey})) {
-                            $raw = $submission->formdata->{$fieldKey};
-                            $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
-                        } elseif (isset($submission->formdata->{$q}) && (is_object($submission->formdata->{$q}) || is_array($submission->formdata->{$q}))) {
-                            $box = (array) $submission->formdata->{$q};
-                            $raw = $box[$fieldKey] ?? '-';
-                            $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
-                        } else {
-                            $row[] = '-';
-                        }
+            if ($dataDesignerExport) {
+                foreach ($history->data->questions as $code => $question) {
+                    if (isset($question->type) && $question->type == 'hidden') {
+                        continue;
                     }
-                } else {
-                    if (!isset($submission->formdata->{$q})) {
+                    $col = is_object($question) && isset($question->code) ? $question->code : $code;
+                    if (!isset($submission->formdata->{$col})) {
                         $row[] = '-';
-                    } elseif (is_array($submission->formdata->{$q})) {
-                        $row[] = implode(', ', $submission->formdata->{$q});
-                    } elseif (is_object($submission->formdata->{$q})) {
-                        $row[] = collect((array) $submission->formdata->{$q})->map(function ($val, $key) {
+                    } elseif (is_array($submission->formdata->{$col})) {
+                        $row[] = implode(', ', $submission->formdata->{$col});
+                    } elseif (is_object($submission->formdata->{$col})) {
+                        $row[] = collect((array) $submission->formdata->{$col})->map(function ($val, $key) {
                             return $key.': '.$val;
                         })->implode(', ');
                     } else {
-                        $row[] = $submission->formdata->{$q};
+                        $row[] = $submission->formdata->{$col};
+                    }
+                }
+            } else {
+                $row[] = $submission->createdAt;
+                $row[] = isset($submission->user_info->name) ? $submission->user_info->name : '';
+                $row[] = isset($submission->user_info->employee_code) ? $submission->user_info->employee_code : '';
+                $row[] = isset($submission->workflow_status) ? $submission->workflow_status : '';
+                foreach ($userAttrs as $attr) {
+                    $row[] = $this->userAttributeValue($submission->user_info ?? null, $attr);
+                }
+                foreach ($exportPositionColumns as $positionField) {
+                    $row[] = isset($submission->{$positionField}) ? $submission->{$positionField} : '';
+                }
+                if(isset($history->data) && isset($history->data->form) && isset($history->data->form->show_manager_details) && $history->data->form->show_manager_details === 'yes'){
+                    $row[] = isset($submission->manager1_name) ? $submission->manager1_name : '';
+                    $row[] = isset($submission->manager1_code) ? $submission->manager1_code : '';
+                    $row[] = isset($submission->manager2_name) ? $submission->manager2_name : '';
+                    $row[] = isset($submission->manager2_code) ? $submission->manager2_code : '';
+                }
+                foreach($history->data->questions as $q => $v) {
+                    if (isset($v->type) && $v->type == 'hidden') {
+                        continue;
+                    }
+                    $col = is_object($v) && isset($v->code) ? $v->code : $q;
+                    if (isset($v->type) && $v->type == 'multitextbox' && !empty($v->options)) {
+                        foreach ($v->options as $optKey => $optMeta) {
+                            $fieldKey = is_object($optMeta) ? ($optMeta->value ?? $optKey) : $optKey;
+                            if (isset($submission->formdata->{$fieldKey})) {
+                                $raw = $submission->formdata->{$fieldKey};
+                                $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
+                            } elseif (isset($submission->formdata->{$col}) && (is_object($submission->formdata->{$col}) || is_array($submission->formdata->{$col}))) {
+                                $box = (array) $submission->formdata->{$col};
+                                $raw = $box[$fieldKey] ?? '-';
+                                $row[] = is_array($raw) ? implode(', ', $raw) : (is_object($raw) ? json_encode($raw) : $raw);
+                            } else {
+                                $row[] = '-';
+                            }
+                        }
+                    } else {
+                        if (!isset($submission->formdata->{$col})) {
+                            $row[] = '-';
+                        } elseif (is_array($submission->formdata->{$col})) {
+                            $row[] = implode(', ', $submission->formdata->{$col});
+                        } elseif (is_object($submission->formdata->{$col})) {
+                            $row[] = collect((array) $submission->formdata->{$col})->map(function ($val, $key) {
+                                return $key.': '.$val;
+                            })->implode(', ');
+                        } else {
+                            $row[] = $submission->formdata->{$col};
+                        }
                     }
                 }
             }
@@ -11506,6 +11578,29 @@ class FormController extends Controller
         return response()->json($docs);
     }
 
+    /**
+     * Hierarchies below a given user (for RBM → ABM → TM doctor loading).
+     */
+    public function hierarchyBelow(Request $request)
+    {
+        $partition = (string) $request->input('partition', '');
+        $userId = (string) $request->input('user_id', '');
+        if ($partition === '' || $userId === '') {
+            return response()->json(['hierarchies' => []], 422);
+        }
+        $response = LambdaRequest::getrequest('ums', 'hierarchy/hierarchy_below_me', [
+            'partition' => $partition,
+            'user_id' => $userId,
+        ]);
+        $hierarchies = [];
+        if (isset($response->data->hierarchies) && is_array($response->data->hierarchies)) {
+            $hierarchies = $response->data->hierarchies;
+        } elseif (isset($response->data) && is_array($response->data)) {
+            $hierarchies = $response->data;
+        }
+        return response()->json(['hierarchies' => $hierarchies]);
+    }
+
     public function surveyhandle($finfo, Request $request) {
         $request->session()->put('finfo', $finfo);
         $finfo = LambdaRequest::postrequest('form', 'survey/getforminfo', ['finfo' => $finfo]);
@@ -13375,6 +13470,117 @@ class FormController extends Controller
         return $text;
     }
 
+    /**
+     * Resolve left edge + max draw width from personalization position.
+     * Supports max_width, width, or x range "left-right" (used for center boxes).
+     *
+     * @return array{0:int,1:int}|null [left, maxWidth]
+     */
+    protected function resolvePersonalizationTextBounds(object $pos): ?array
+    {
+        $x = $pos->x ?? 0;
+        $left = null;
+        $maxWidth = 0;
+
+        if (is_string($x) && strpos($x, '-') !== false) {
+            $parts = explode('-', $x, 2);
+            if (count($parts) === 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
+                $x1 = (int) $parts[0];
+                $x2 = (int) $parts[1];
+                $left = min($x1, $x2);
+                $maxWidth = abs($x2 - $x1);
+            }
+        } else {
+            $left = (int) $x;
+        }
+
+        if (isset($pos->max_width) && (float) $pos->max_width > 0) {
+            $maxWidth = (int) $pos->max_width;
+        } elseif (isset($pos->width) && (float) $pos->width > 0) {
+            $maxWidth = (int) $pos->width;
+        }
+
+        if ($maxWidth <= 0 || $left === null) {
+            return null;
+        }
+
+        return [$left, $maxWidth];
+    }
+
+    protected function measurePersonalizationTextWidth(float $size, float $angle, string $font, string $text): float
+    {
+        $box = imagettfbbox($size, $angle, $font, $text);
+        if ($box === false) {
+            return 0.0;
+        }
+
+        return (float) abs($box[2] - $box[0]);
+    }
+
+    protected function fitPersonalizationFontSize(
+        float $size,
+        float $angle,
+        string $font,
+        string $text,
+        int $maxWidth,
+        float $minSize = 5.0
+    ): float {
+        if ($maxWidth <= 0 || $text === '') {
+            return $size;
+        }
+
+        $currentSize = $size;
+        $textWidth = $this->measurePersonalizationTextWidth($currentSize, $angle, $font, $text);
+        while ($textWidth > $maxWidth && $currentSize > $minSize) {
+            $currentSize = max($minSize, $currentSize - 0.5);
+            $textWidth = $this->measurePersonalizationTextWidth($currentSize, $angle, $font, $text);
+        }
+
+        return $currentSize;
+    }
+
+    /**
+     * Wrap text so each line fits maxWidth at the given font size.
+     *
+     * @return string[]
+     */
+    protected function wrapPersonalizationTextToWidth(
+        string $text,
+        float $size,
+        string $font,
+        int $maxWidth,
+        int $fallbackChars = 40
+    ): array {
+        $text = trim(preg_replace('/\s+/u', ' ', $text) ?? $text);
+        if ($text === '') {
+            return [];
+        }
+        if ($maxWidth <= 0) {
+            return explode("\n", wordwrap($text, max(1, $fallbackChars), "\n", true));
+        }
+
+        $words = preg_split('/\s+/u', $text) ?: [$text];
+        $lines = [];
+        $current = '';
+        foreach ($words as $word) {
+            $candidate = $current === '' ? $word : $current.' '.$word;
+            if ($this->measurePersonalizationTextWidth($size, 0.0, $font, $candidate) <= $maxWidth) {
+                $current = $candidate;
+                continue;
+            }
+            if ($current !== '') {
+                $lines[] = $current;
+            }
+            // Single word longer than width: shrink handled by caller; keep as own line
+            $current = $word;
+        }
+        if ($current !== '') {
+            $lines[] = $current;
+        }
+
+        return $lines;
+    }
+
     protected function drawPersonalizationMultilineOnImage($outputImage, object $pos, string $text): void
     {
         $fontFile = $pos->font ?? '';
@@ -13393,13 +13599,42 @@ class FormController extends Controller
 
         $text = $this->formatPersonalizationText($pos, $text);
         $lineChars = (int) ($pos->linechars ?? 40);
-        $lineHeight = (int) ($pos->linehieght ?? $pos->lineheight ?? 20);
-        $lines = wordwrap($text, $lineChars, "\n", true);
-        $xPosition = (int) $pos->x;
-        $yPosition = (int) $pos->y;
+        $baseLineHeight = (int) ($pos->linehieght ?? $pos->lineheight ?? 20);
+        $size = (float) ($pos->size ?? 12);
+        $bounds = $this->resolvePersonalizationTextBounds($pos);
+        $xPosition = $bounds ? $bounds[0] : (int) $pos->x;
+        $maxWidth = $bounds ? $bounds[1] : 0;
 
-        foreach (explode("\n", $lines) as $line) {
-            imagettftext($outputImage, (float) $pos->size, 0, $xPosition, $yPosition, $textColor, $font, $line);
+        if ($maxWidth > 0) {
+            // Shrink until the longest wrapped line fits (and optionally max line count)
+            $maxLines = isset($pos->max_lines) ? max(1, (int) $pos->max_lines) : 6;
+            do {
+                $lines = $this->wrapPersonalizationTextToWidth($text, $size, $font, $maxWidth, $lineChars);
+                $longest = 0.0;
+                foreach ($lines as $line) {
+                    $longest = max($longest, $this->measurePersonalizationTextWidth($size, 0.0, $font, $line));
+                }
+                $fits = $longest <= $maxWidth && count($lines) <= $maxLines;
+                if ($fits || $size <= 5) {
+                    break;
+                }
+                $size = max(5.0, $size - 0.5);
+            } while (true);
+            $lineHeight = max(8, (int) round($baseLineHeight * ($size / max(1.0, (float) ($pos->size ?? $size)))));
+        } else {
+            $lines = explode("\n", wordwrap($text, max(1, $lineChars), "\n", true));
+            $lineHeight = $baseLineHeight;
+        }
+
+        $yPosition = (int) $pos->y;
+        $alignCenter = isset($pos->align) && $pos->align === 'center' && $maxWidth > 0;
+        foreach ($lines as $line) {
+            $drawX = $xPosition;
+            if ($alignCenter) {
+                $lineWidth = $this->measurePersonalizationTextWidth($size, 0.0, $font, $line);
+                $drawX = (int) round($xPosition + (($maxWidth - $lineWidth) / 2));
+            }
+            imagettftext($outputImage, $size, 0, $drawX, $yPosition, $textColor, $font, $line);
             $yPosition += $lineHeight;
         }
     }
@@ -13423,29 +13658,27 @@ class FormController extends Controller
         $text = $this->formatPersonalizationText($pos, $text);
 
         $angle = isset($pos->angle) ? (float) $pos->angle : 0.0;
-        $size = (float) $pos->size;
-        if (isset($pos->max_width) && $pos->max_width > 0) {
-            $currentSize = $size;
-            $box = imagettfbbox($currentSize, $angle, $font, $text);
-            $textWidth = abs($box[4] - $box[0]);
-            while ($textWidth > $pos->max_width && $currentSize > 5) {
-                $currentSize--;
-                $box = imagettfbbox($currentSize, $angle, $font, $text);
-                $textWidth = abs($box[4] - $box[0]);
-            }
-            $size = $currentSize;
+        $size = (float) ($pos->size ?? 12);
+        $bounds = $this->resolvePersonalizationTextBounds($pos);
+        $maxWidth = $bounds ? $bounds[1] : 0;
+        if ($maxWidth > 0) {
+            $size = $this->fitPersonalizationFontSize($size, $angle, $font, $text, $maxWidth);
         }
 
-        $x = $pos->x;
-        if (isset($pos->align) && $pos->align === 'center') {
-            $box = imagettfbbox($size, 0, $font, $text);
+        $x = is_numeric($pos->x) ? (float) $pos->x : 0.0;
+        if (isset($pos->align) && $pos->align === 'center' && $bounds) {
+            $textWidth = $this->measurePersonalizationTextWidth($size, 0.0, $font, $text);
+            $x = $bounds[0] + (($bounds[1] - $textWidth) / 2);
+        } elseif (isset($pos->align) && $pos->align === 'center') {
+            // Legacy: x range without resolved bounds
             $xRange = explode('-', (string) $pos->x);
             if (count($xRange) === 2) {
-                $x = $xRange[0] + (($xRange[1] - $xRange[0]) - $box[2]) / 2;
+                $textWidth = $this->measurePersonalizationTextWidth($size, 0.0, $font, $text);
+                $x = ((float) $xRange[0]) + ((((float) $xRange[1]) - ((float) $xRange[0])) - $textWidth) / 2;
             }
         }
 
-        imagettftext($outputImage, $size, $angle, (int) $x, (int) $pos->y, $textColor, $font, $text);
+        imagettftext($outputImage, $size, $angle, (int) round($x), (int) $pos->y, $textColor, $font, $text);
     }
 
     protected function resolvePersonalizationPdfScript(): string
@@ -13524,6 +13757,20 @@ class FormController extends Controller
      * Opt-in only: empty designer or export-only fields keep the legacy list.
      */
     protected function hasDataDesignerView($form): bool
+    {
+        return $this->hasDataDesignerFlag($form, 'show_in_view');
+    }
+
+    /**
+     * True when the form Data Designer has at least one show_in_export field.
+     * Opt-in only: empty designer keeps the legacy export columns.
+     */
+    protected function hasDataDesignerExport($form): bool
+    {
+        return $this->hasDataDesignerFlag($form, 'show_in_export');
+    }
+
+    protected function hasDataDesignerFlag($form, string $flag): bool
     {
         if (!$form) {
             return false;
@@ -13547,9 +13794,9 @@ class FormController extends Controller
         }
         foreach ($fields as $field) {
             if (is_object($field)) {
-                $show = $field->show_in_view ?? false;
+                $show = $field->{$flag} ?? false;
             } elseif (is_array($field)) {
-                $show = $field['show_in_view'] ?? false;
+                $show = $field[$flag] ?? false;
             } else {
                 continue;
             }
diff --git a/app/Http/Controllers/ZenovaReportController.php b/app/Http/Controllers/ZenovaReportController.php
index 54ebbf3f..3bdaa6f5 100644
--- a/app/Http/Controllers/ZenovaReportController.php
+++ b/app/Http/Controllers/ZenovaReportController.php
@@ -76,8 +76,8 @@ class ZenovaReportController extends Controller
     private function months(): array
     {
         $now = now()->startOfMonth();
-        $startYear = $now->month >= 4 ? $now->year : $now->year - 1;
-        $cursor = now()->setDate($startYear, 4, 1)->startOfMonth();
+        $startYear = $now->month >= 10 ? $now->year : $now->year - 1;
+        $cursor = now()->setDate($startYear, 10, 1)->startOfMonth();
         $months = [];
         while ($cursor->lte($now)) {
             $months[$cursor->format('Y-m')] = $cursor->format('F Y');
@@ -293,13 +293,21 @@ class ZenovaReportController extends Controller
             $demoColumns[] = $this->column($key, 'Demography & Details', $key, $type);
         }
 
-        $dayMetrics = ['GLIPIQ Total Rx', 'ABSI Camp Count', 'Patients Screened Count', 'Sitazit Total RX'];
+        $dayMetrics = [
+            'Glipiq Total Invoice Count',
+            'Obesity Strength Invoice Count',
+            'ABSI Camp Count',
+            'Patients Screened Count',
+            'Sitazit Total RX',
+        ];
         $periodMetrics = [
-            'GLIPIQ Total Rx',
+            'Glipiq Total Invoice Count',
+            'Obesity Strength Invoice Count',
             'GLIPIQ New Conversion',
             'ABSI Camp Count',
             'Patients Screened Count',
             'GLIPIQ Total POB Units',
+            'Obesity Strength POB Units',
             'Sitazit Total RX',
             'Sitazit New Conversions',
             'Sitazit Total POB Units',
diff --git a/resources/views/form/rapport-team3/personalization-1708679320-f4b89729-03d0-4c8d-b5bb-43209c0b7240.blade.php b/resources/views/form/rapport-team3/personalization-1708679320-f4b89729-03d0-4c8d-b5bb-43209c0b7240.blade.php
index 3dd40348..20d84d1a 100644
--- a/resources/views/form/rapport-team3/personalization-1708679320-f4b89729-03d0-4c8d-b5bb-43209c0b7240.blade.php
+++ b/resources/views/form/rapport-team3/personalization-1708679320-f4b89729-03d0-4c8d-b5bb-43209c0b7240.blade.php
@@ -58,7 +58,14 @@
                                         
                                         
@foreach($questions as $question) -
+ @php + $qLabel = strtolower(trim((string) ($question->question ?? ''))); + $qCode = strtolower(trim((string) ($question->code ?? ''))); + $isTopic2 = str_contains($qLabel, 'topic 2') || in_array($qCode, ['topic_2', 'topic2', 'topic-2'], true); + // Honor Form Question required (default yes for legacy); Topic 2 always optional. + $isRequired = !$isTopic2 && (($question->required ?? 'yes') === 'yes'); + @endphp +
@switch($question->type) @case('hidden') @@ -198,8 +205,10 @@ for(let que of personalize.questions) { let $w = $('#wrapper-'+que) $w.show() - $w.find('.req-star').show() - $w.find('input:not([type="hidden"]):not([type="checkbox"]), textarea, select').attr('required', 'required') + if ($w.attr('data-required') === 'yes') { + $w.find('.req-star').show() + $w.find('input:not([type="hidden"]):not([type="checkbox"]), textarea, select').attr('required', 'required') + } } $('#report-form :input').removeAttr('readonly') $('#wrapper-template_id img').attr('src', personalize.icon) diff --git a/resources/views/form/rapport-team4/1791539482-b06c2f9a-fe45-4b16-843a-224f07ed0d7b.blade.php b/resources/views/form/rapport-team4/1791539482-b06c2f9a-fe45-4b16-843a-224f07ed0d7b.blade.php index 33b6f065..b0824642 100644 --- a/resources/views/form/rapport-team4/1791539482-b06c2f9a-fe45-4b16-843a-224f07ed0d7b.blade.php +++ b/resources/views/form/rapport-team4/1791539482-b06c2f9a-fe45-4b16-843a-224f07ed0d7b.blade.php @@ -159,13 +159,14 @@ @endif - @if(isset($form->manager_can_submit) && $form->manager_can_submit == true) + @php $managerEntryMode = $form->manager_entry_mode ?? 'abm'; @endphp + @if(isset($form->manager_can_submit) && $form->manager_can_submit == true && $managerEntryMode === 'rbm')
- + @@ -501,97 +502,72 @@ } $('[data-toggle="select2"]').select2(); - var hierarcies = []; - var contacts = []; + var managerEntryMode = @json($form->manager_entry_mode ?? 'abm'); + var managerUserHierarchies = [ + @if(isset($form->manager_can_submit) && $form->manager_can_submit == true) + @foreach(($form->users ?? []) as $option) + '{{ $option->hierarchy_id }}', + @endforeach + @endif + ].filter(Boolean); - @if(isset($form->manager_can_submit) && $form->manager_can_submit == true) - @foreach($form->users as $option) - hierarcies.push('{{$option->hierarchy_id}}'); - @endforeach - $("#pageloader").fadeIn(); - Promise.all( - hierarcies.map(hierarchy => { - return $.ajax({ - type: "GET", - url: '/form/getdoctorlist?partition={{$form->partition}}&hierarchy=' + hierarchy, - processData: false, - contentType: false - }).then(data => { - console.log(data); - contacts = contacts.concat(data); - }).catch(function(err) { - console.log(err); - }); - }) - ).then(function() { - // All contacts loaded for each hierarchy - // Example usage: console.log(contacts); - // Filter out contacts where value == 'sample' - contacts = contacts.filter(function(itm) { return itm.value !== 'sample'; }); - console.log(contacts); - - // Loop through contacts and append options to select elements whose id starts with 'field-contact_id' - // We assume contact_id fields may be suffixed, e.g. field-contact_id_1, field-contact_id, etc. - function applySelect2ToDoctorDropdowns() { - $("[id^='field-contact_id']").each(function () { - var select = $(this); - if (select.data("select2")) return; - select.select2({ - width: "100%", - placeholder: "-- Select --", - allowClear: true - }); - }); - } - - function enforceUniqueDoctorSelections() { - var selectedValues = []; - - // Collect selected values (ignore empty) - $("[id^='field-contact_id']").each(function () { - var v = $(this).val(); - if (v) selectedValues.push(String(v)); - }); - - // Reset all option disabled states, then disable duplicates across selects - $("[id^='field-contact_id']").each(function () { - var currentSelect = $(this); - var currentVal = currentSelect.val() ? String(currentSelect.val()) : ""; - - currentSelect.find("option").prop("disabled", false); - - selectedValues.forEach(function (v) { - if (v && v !== currentVal) { - currentSelect - .find("option[value=\"" + v.replace(/"/g, '\\"') + "\"]") - .prop("disabled", true); - } - }); - - if (currentSelect.data("select2")) { - currentSelect.trigger("change.select2"); - } - }); - } - - $("[id^='field-contact_id']").each(function() { + function applySelect2ToDoctorDropdowns() { + $("[id^='field-contact_id']").each(function () { var select = $(this); + if (select.data("select2")) return; + select.select2({ + width: "100%", + placeholder: "-- Select --", + allowClear: true + }); + }); + } - - var existingVal = select.attr('data-initial-value') || select.val(); + function enforceUniqueDoctorSelections() { + var selectedValues = []; + $("[id^='field-contact_id']").each(function () { + var v = $(this).val(); + if (v) selectedValues.push(String(v)); + }); + $("[id^='field-contact_id']").each(function () { + var currentSelect = $(this); + var currentVal = currentSelect.val() ? String(currentSelect.val()) : ""; + currentSelect.find("option").prop("disabled", false); + selectedValues.forEach(function (v) { + if (v && v !== currentVal) { + currentSelect + .find("option[value=\"" + v.replace(/"/g, '\\"') + "\"]") + .prop("disabled", true); + } + }); + if (currentSelect.data("select2")) { + currentSelect.trigger("change.select2"); + } + }); + } - + function clearDoctorDropdowns() { + $("[id^='field-contact_id']").each(function () { + var select = $(this); select.empty(); - - // Default option select.append($("").attr("value", '').text('-- Select --')); + if (select.data("select2")) { + select.trigger("change.select2"); + } + }); + } - - contacts.forEach(function(itm) { + function fillDoctorDropdowns(contacts) { + contacts = (contacts || []).filter(function (itm) { return itm.value !== 'sample'; }); + $("[id^='field-contact_id']").each(function () { + var select = $(this); + var existingVal = select.attr('data-initial-value') || select.val(); + select.empty(); + select.append($("").attr("value", '').text('-- Select --')); + contacts.forEach(function (itm) { var option = $("") .attr("value", itm.value) .text(itm.display); - if (itm.contact && itm.contact.legacy_code) { option.attr("msl_code", itm.contact.legacy_code); } @@ -600,26 +576,17 @@ } select.append(option); }); - - if (existingVal) { select.val(String(existingVal)); } - - select.off('change').on('change select2:select select2:clear', function () { handleDoctorChange($(this)); enforceUniqueDoctorSelections(); }); }); - - applySelect2ToDoctorDropdowns(); - - $("[id^='field-msl_code'], [id^='field-speciality']").prop('readonly', true); - - $("[id^='field-contact_id']").each(function() { + $("[id^='field-contact_id']").each(function () { var select = $(this); var existingVal = select.attr('data-initial-value'); if (existingVal) { @@ -629,15 +596,44 @@ if ($('#field-replace_submission_id').length && $('#field-month').val()) { applyMonth(String($('#field-month').val())); } + } + function loadDoctorsForHierarchies(hierarchyIds) { + hierarchyIds = (hierarchyIds || []).filter(Boolean); + if (!hierarchyIds.length) { + clearDoctorDropdowns(); + $("#pageloader").fadeOut(); + return Promise.resolve([]); + } + $("#pageloader").fadeIn(); + var contacts = []; + return Promise.all( + hierarchyIds.map(function (hierarchy) { + return $.ajax({ + type: "GET", + url: '/form/getdoctorlist?partition={{$form->partition}}&hierarchy=' + hierarchy, + processData: false, + contentType: false + }).then(function (data) { + contacts = contacts.concat(data || []); + }).catch(function (err) { + console.log(err); + }); + }) + ).then(function () { + fillDoctorDropdowns(contacts); + $("#pageloader").fadeOut(); + return contacts; + }).catch(function () { + $("#pageloader").fadeOut(); + }); + } - $("[id^='field-city_']").on('input keyup paste', function() { - + function bindCityPinHandlers() { + $("[id^='field-city_']").on('input keyup paste', function () { this.value = this.value.replace(/[^a-zA-Z\s]/g, ''); }); - - - $("[id^='field-city_']").on('keypress', function(e) { + $("[id^='field-city_']").on('keypress', function (e) { var regex = new RegExp("^[a-zA-Z\\s]+$"); var str = String.fromCharCode(!e.charCode ? e.which : e.charCode); if (!regex.test(str)) { @@ -645,50 +641,60 @@ return false; } }); - - $("[id^='field-pin_code_']").on('input keyup paste', function() { + $("[id^='field-pin_code_']").on('input keyup paste', function () { var val = this.value; - - val = val.replace(/\D/g, ''); - - val = val.replace(/^0+/, ''); - - if (val.length > 6) { val = val.substring(0, 6); } - this.value = val; }); - - - $("[id^='field-pin_code_']").on('keypress', function(e) { + $("[id^='field-pin_code_']").on('keypress', function (e) { var char = String.fromCharCode(e.which || e.keyCode); - - if (!/^\d$/.test(char)) { e.preventDefault(); return false; } - - if (this.value.length === 0 && char === '0') { e.preventDefault(); return false; } }); + } - - - $("#pageloader").fadeOut(); - - + @if(isset($form->manager_can_submit) && $form->manager_can_submit == true) + bindCityPinHandlers(); + if (managerEntryMode === 'rbm') { + $('#field-user_id').on('change', function () { + var abmUserId = $(this).val() || ''; + var abmHierarchy = $('option:selected', this).attr('hierarchy') || ''; + $('#field-hierarchy_id').val(abmHierarchy); + if (!abmUserId) { + clearDoctorDropdowns(); + return; + } + $("#pageloader").fadeIn(); + $.ajax({ + type: "GET", + url: '/form/hierarchybelow?partition={{$form->partition}}&user_id=' + encodeURIComponent(abmUserId), + success: function (data) { + var hierarchies = (data && data.hierarchies) ? data.hierarchies : []; + var tmIds = hierarchies + .filter(function (h) { return h && h.type === 'Territory' && h.id; }) + .map(function (h) { return h.id; }); + loadDoctorsForHierarchies(tmIds); + }, + error: function (err) { + console.log(err); + clearDoctorDropdowns(); + $("#pageloader").fadeOut(); + } }); - - - + }); + } else { + loadDoctorsForHierarchies(managerUserHierarchies); + } @endif $("[id^='field-contact_id_']").on('change', function () { diff --git a/routes/edit/web.php b/routes/edit/web.php index da7fe716..fcaa291c 100644 --- a/routes/edit/web.php +++ b/routes/edit/web.php @@ -242,6 +242,7 @@ Route::post('/form/ajaxdoctortagging', [FormController::class, 'ajaxdoctortaggin Route::get('/form/pulmocarecoachingtool', [FormController::class, 'pulmocarecoachingtool']); Route::get('/form/getdoctorlist', [FormController::class, 'getdoctorlist']); +Route::get('/form/hierarchybelow', [FormController::class, 'hierarchyBelow']); Route::get('/form/preview', [FormController::class, 'preview']); Route::get('/form/history', [FormController::class, 'history']); Route::get('/form/show', [FormController::class, 'show']); diff --git a/routes/web.php b/routes/web.php index 0ab994d7..197bdc2d 100755 --- a/routes/web.php +++ b/routes/web.php @@ -313,6 +313,7 @@ Route::post('/form/ajaxdoctortagging', [FormController::class, 'ajaxdoctortaggin Route::get('/form/pulmocarecoachingtool', [FormController::class, 'pulmocarecoachingtool']); Route::get('/form/getdoctorlist', [FormController::class, 'getdoctorlist']); +Route::get('/form/hierarchybelow', [FormController::class, 'hierarchyBelow']); Route::get('/form/preview', [FormController::class, 'preview']); Route::get('/form/history', [FormController::class, 'history']); Route::get('/form/show', [FormController::class, 'show']);