@ozguraltan/strapi-content-input 1.0.10 → 1.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +387 -230
  2. package/dist/admin/AnalyticsHubPage-DNREITPq.js +637 -0
  3. package/dist/admin/AnalyticsHubPage-Dj4roAe0.mjs +637 -0
  4. package/dist/admin/{ContentInputField-figtXsYp.js → ContentInputField-2hk9xG8p.js} +5881 -4757
  5. package/dist/admin/{ContentInputField-B917gT8j.mjs → ContentInputField-Ko-r12jl.mjs} +5744 -4619
  6. package/dist/admin/SurveyWidgetEditor-B1S83aBE.mjs +7956 -0
  7. package/dist/admin/SurveyWidgetEditor-B3F4DE5r.js +7957 -0
  8. package/dist/admin/{en-D7v9nv9J.mjs → en-DnLdDKyq.mjs} +2 -1
  9. package/dist/admin/{en-DF-a59T_.js → en-bneQpRJa.js} +2 -1
  10. package/dist/admin/{index-WlNKw5Qo.js → index-B4FpXxnK.js} +43 -4
  11. package/dist/admin/{index-DV8S3QWG.mjs → index-gn-4eO6g.mjs} +43 -4
  12. package/dist/admin/index.js +1 -1
  13. package/dist/admin/index.mjs +1 -1
  14. package/dist/admin/src/components/analytics/SurveyAnalyticsView.d.ts +6 -0
  15. package/dist/admin/src/components/widgets/ContentFormWidgetEditor.d.ts +81 -0
  16. package/dist/admin/src/components/widgets/EntityCardWidgetEditor.d.ts +46 -0
  17. package/dist/admin/src/components/widgets/SurveyWidgetEditor.d.ts +91 -0
  18. package/dist/admin/src/core/useStrapiLocales.d.ts +13 -0
  19. package/dist/admin/src/pages/AnalyticsHubPage.d.ts +3 -0
  20. package/dist/admin/{tr-ByHzf64V.mjs → tr-00QqO0E7.mjs} +2 -1
  21. package/dist/admin/{tr-SNvSmKZQ.js → tr-O0nhB9er.js} +2 -1
  22. package/dist/server/index.js +4148 -46
  23. package/dist/server/index.mjs +4148 -46
  24. package/dist/server/src/bootstrap.d.ts +1 -1
  25. package/dist/server/src/content-types/ci-form/schema.json.d.ts +77 -0
  26. package/dist/server/src/content-types/ci-form-submission/schema.json.d.ts +54 -0
  27. package/dist/server/src/content-types/ci-survey/schema.json.d.ts +111 -0
  28. package/dist/server/src/content-types/ci-survey-response/schema.json.d.ts +81 -0
  29. package/dist/server/src/content-types/index.d.ts +315 -0
  30. package/dist/server/src/controllers/ci-form.d.ts +17 -0
  31. package/dist/server/src/controllers/ci-survey.d.ts +18 -0
  32. package/dist/server/src/controllers/index.d.ts +31 -0
  33. package/dist/server/src/index.d.ts +731 -1
  34. package/dist/server/src/services/ci-form.d.ts +250 -0
  35. package/dist/server/src/services/ci-survey.d.ts +296 -0
  36. package/dist/server/src/services/index.d.ts +384 -0
  37. package/dist/server/src/utils/formValidator.d.ts +19 -0
  38. package/dist/server/src/utils/mailer.d.ts +41 -0
  39. package/dist/server/src/utils/surveyEngine.d.ts +252 -0
  40. package/dist/server/src/utils/surveySeedData.d.ts +4 -0
  41. package/package.json +1 -1
@@ -14,7 +14,13 @@ const register = ({ strapi }) => {
14
14
  }
15
15
  });
16
16
  };
17
- const bootstrap = ({ strapi }) => {
17
+ const bootstrap = async ({ strapi }) => {
18
+ try {
19
+ await strapi.plugin("content-input").service("ci-form").ensureSeeded();
20
+ await strapi.plugin("content-input").service("ci-survey").ensureSeeded(false);
21
+ } catch (err) {
22
+ strapi.log.warn(`[content-input] Bootstrap seed skipped: ${err?.message || err}`);
23
+ }
18
24
  };
19
25
  const destroy = ({ strapi }) => {
20
26
  };
@@ -25,13 +31,69 @@ const config = {
25
31
  validator() {
26
32
  }
27
33
  };
34
+ const kind$5 = "collectionType";
35
+ const collectionName$5 = "ci_templates";
36
+ const info$5 = { "singularName": "ci-template", "pluralName": "ci-templates", "displayName": "ContentInput Template", "description": "Saved visual editor row/section templates" };
37
+ const options$5 = { "draftAndPublish": false };
38
+ const pluginOptions$5 = { "content-manager": { "visible": false }, "content-type-builder": { "visible": false } };
39
+ const attributes$5 = { "name": { "type": "string", "required": true }, "category": { "type": "string", "default": "custom" }, "structure": { "type": "json", "required": true }, "thumbnail": { "type": "string", "default": "" } };
40
+ const templateSchema = {
41
+ kind: kind$5,
42
+ collectionName: collectionName$5,
43
+ info: info$5,
44
+ options: options$5,
45
+ pluginOptions: pluginOptions$5,
46
+ attributes: attributes$5
47
+ };
48
+ const kind$4 = "collectionType";
49
+ const collectionName$4 = "ci_menus";
50
+ const info$4 = { "singularName": "ci-menu", "pluralName": "ci-menus", "displayName": "ContentInput Menu", "description": "Reusable nested menus (horizontal & vertical) for ContentInput" };
51
+ const options$4 = { "draftAndPublish": false };
52
+ const pluginOptions$4 = { "content-manager": { "visible": false }, "content-type-builder": { "visible": false } };
53
+ const attributes$4 = { "name": { "type": "string", "required": true }, "slug": { "type": "string", "required": true }, "mode": { "type": "string", "default": "horizontal" }, "items": { "type": "json", "required": true }, "options": { "type": "json" } };
54
+ const menuSchema = {
55
+ kind: kind$4,
56
+ collectionName: collectionName$4,
57
+ info: info$4,
58
+ options: options$4,
59
+ pluginOptions: pluginOptions$4,
60
+ attributes: attributes$4
61
+ };
62
+ const kind$3 = "collectionType";
63
+ const collectionName$3 = "ci_forms";
64
+ const info$3 = { "singularName": "ci-form", "pluralName": "ci-forms", "displayName": "ContentInput Dynamic Form", "description": "Reusable cms-core style dynamic forms with responsive grid layout, validation rules, reCAPTCHA and mail delivery settings" };
65
+ const options$3 = { "draftAndPublish": false };
66
+ const pluginOptions$3 = { "content-manager": { "visible": true }, "content-type-builder": { "visible": false } };
67
+ const attributes$3 = { "title": { "type": "string", "required": true }, "slug": { "type": "string", "required": true }, "to": { "type": "string" }, "subject": { "type": "string" }, "buttonLabel": { "type": "json" }, "successMessage": { "type": "json" }, "redirect": { "type": "string" }, "hideLabels": { "type": "boolean", "default": false }, "useRecaptcha": { "type": "boolean", "default": true }, "recaptchaSiteKey": { "type": "string" }, "recaptchaSecretKey": { "type": "string", "private": true }, "mailConfig": { "type": "json", "private": true }, "fields": { "type": "json", "required": true }, "form": { "type": "json", "required": true } };
68
+ const formSchema = {
69
+ kind: kind$3,
70
+ collectionName: collectionName$3,
71
+ info: info$3,
72
+ options: options$3,
73
+ pluginOptions: pluginOptions$3,
74
+ attributes: attributes$3
75
+ };
76
+ const kind$2 = "collectionType";
77
+ const collectionName$2 = "ci_form_submissions";
78
+ const info$2 = { "singularName": "ci-form-submission", "pluralName": "ci-form-submissions", "displayName": "ContentInput Form Submission", "description": "Submitted entries from ContentInput dynamic forms" };
79
+ const options$2 = { "draftAndPublish": false };
80
+ const pluginOptions$2 = { "content-manager": { "visible": true }, "content-type-builder": { "visible": false } };
81
+ const attributes$2 = { "formId": { "type": "string", "required": true }, "formSlug": { "type": "string" }, "formTitle": { "type": "string" }, "data": { "type": "json", "required": true }, "ip": { "type": "string" }, "userAgent": { "type": "string" }, "mailSent": { "type": "boolean", "default": false }, "mailInfo": { "type": "json" } };
82
+ const formSubmissionSchema = {
83
+ kind: kind$2,
84
+ collectionName: collectionName$2,
85
+ info: info$2,
86
+ options: options$2,
87
+ pluginOptions: pluginOptions$2,
88
+ attributes: attributes$2
89
+ };
28
90
  const kind$1 = "collectionType";
29
- const collectionName$1 = "ci_templates";
30
- const info$1 = { "singularName": "ci-template", "pluralName": "ci-templates", "displayName": "ContentInput Template", "description": "Saved visual editor row/section templates" };
91
+ const collectionName$1 = "ci_surveys";
92
+ const info$1 = { "singularName": "ci-survey", "pluralName": "ci-surveys", "displayName": "ContentInput Survey", "description": "Enterprise surveys, multi-step questionnaires, and live polls with i18n, conditional logic, and analytics" };
31
93
  const options$1 = { "draftAndPublish": false };
32
- const pluginOptions$1 = { "content-manager": { "visible": false }, "content-type-builder": { "visible": false } };
33
- const attributes$1 = { "name": { "type": "string", "required": true }, "category": { "type": "string", "default": "custom" }, "structure": { "type": "json", "required": true }, "thumbnail": { "type": "string", "default": "" } };
34
- const templateSchema = {
94
+ const pluginOptions$1 = { "content-manager": { "visible": true }, "content-type-builder": { "visible": false } };
95
+ const attributes$1 = { "title": { "type": "string", "required": true }, "titleI18n": { "type": "json" }, "slug": { "type": "string", "required": true }, "description": { "type": "json" }, "status": { "type": "enumeration", "enum": ["draft", "published", "closed"], "default": "published" }, "displayMode": { "type": "enumeration", "enum": ["quick_poll", "single_page", "multi_step"], "default": "single_page" }, "startsAt": { "type": "datetime" }, "endsAt": { "type": "datetime" }, "quotaLimit": { "type": "integer" }, "submissionPolicy": { "type": "enumeration", "enum": ["unlimited", "one_per_voter", "one_per_token"], "default": "one_per_voter" }, "anonymizeIp": { "type": "boolean", "default": true }, "showPublicResults": { "type": "enumeration", "enum": ["never", "after_vote", "always"], "default": "never" }, "allowBackNavigation": { "type": "boolean", "default": true }, "showProgressBar": { "type": "boolean", "default": true }, "useRecaptcha": { "type": "boolean", "default": false }, "recaptchaSiteKey": { "type": "string" }, "recaptchaSecretKey": { "type": "string", "private": true }, "mailConfig": { "type": "json", "private": true }, "steps": { "type": "json" }, "questions": { "type": "json", "required": true }, "settings": { "type": "json" }, "version": { "type": "integer", "default": 1 } };
96
+ const surveySchema = {
35
97
  kind: kind$1,
36
98
  collectionName: collectionName$1,
37
99
  info: info$1,
@@ -40,12 +102,12 @@ const templateSchema = {
40
102
  attributes: attributes$1
41
103
  };
42
104
  const kind = "collectionType";
43
- const collectionName = "ci_menus";
44
- const info = { "singularName": "ci-menu", "pluralName": "ci-menus", "displayName": "ContentInput Menu", "description": "Reusable nested menus (horizontal & vertical) for ContentInput" };
105
+ const collectionName = "ci_survey_responses";
106
+ const info = { "singularName": "ci-survey-response", "pluralName": "ci-survey-responses", "displayName": "ContentInput Survey Response", "description": "Recorded participant responses and telemetry for ContentInput surveys and polls" };
45
107
  const options = { "draftAndPublish": false };
46
- const pluginOptions = { "content-manager": { "visible": false }, "content-type-builder": { "visible": false } };
47
- const attributes = { "name": { "type": "string", "required": true }, "slug": { "type": "string", "required": true }, "mode": { "type": "string", "default": "horizontal" }, "items": { "type": "json", "required": true }, "options": { "type": "json" } };
48
- const menuSchema = {
108
+ const pluginOptions = { "content-manager": { "visible": true }, "content-type-builder": { "visible": false } };
109
+ const attributes = { "surveyId": { "type": "string", "required": true }, "surveySlug": { "type": "string", "required": true }, "surveyTitle": { "type": "string" }, "surveyVersion": { "type": "integer", "default": 1 }, "answers": { "type": "json", "required": true }, "otherTexts": { "type": "json" }, "score": { "type": "float" }, "npsValue": { "type": "integer" }, "npsCategory": { "type": "string" }, "locale": { "type": "string", "default": "tr" }, "durationSeconds": { "type": "integer", "default": 0 }, "voterHash": { "type": "string" }, "respondentToken": { "type": "string" }, "ip": { "type": "string" }, "userAgent": { "type": "string" }, "submittedAt": { "type": "datetime" } };
110
+ const surveyResponseSchema = {
49
111
  kind,
50
112
  collectionName,
51
113
  info,
@@ -59,6 +121,18 @@ const contentTypes = {
59
121
  },
60
122
  "ci-menu": {
61
123
  schema: menuSchema
124
+ },
125
+ "ci-form": {
126
+ schema: formSchema
127
+ },
128
+ "ci-form-submission": {
129
+ schema: formSubmissionSchema
130
+ },
131
+ "ci-survey": {
132
+ schema: surveySchema
133
+ },
134
+ "ci-survey-response": {
135
+ schema: surveyResponseSchema
62
136
  }
63
137
  };
64
138
  const ciTemplateController = ({ strapi }) => ({
@@ -586,15 +660,307 @@ const ciImageController = ({ strapi }) => ({
586
660
  }
587
661
  }
588
662
  });
663
+ const ciFormController = ({ strapi }) => ({
664
+ async locales(ctx) {
665
+ try {
666
+ const locales = await strapi.plugin("content-input").service("ci-form").listStrapiLocales();
667
+ ctx.body = { data: locales };
668
+ } catch (err) {
669
+ ctx.throw(500, err);
670
+ }
671
+ },
672
+ async indexAdmin(ctx) {
673
+ try {
674
+ const list = await strapi.plugin("content-input").service("ci-form").findAllAdmin();
675
+ ctx.body = list;
676
+ } catch (err) {
677
+ ctx.throw(500, err);
678
+ }
679
+ },
680
+ async findOneAdmin(ctx) {
681
+ try {
682
+ const { id } = ctx.params;
683
+ const found = await strapi.plugin("content-input").service("ci-form").findOneAdmin(id);
684
+ if (!found) {
685
+ return ctx.notFound("Form not found");
686
+ }
687
+ ctx.body = found;
688
+ } catch (err) {
689
+ ctx.throw(500, err);
690
+ }
691
+ },
692
+ async indexPublic(ctx) {
693
+ try {
694
+ const list = await strapi.plugin("content-input").service("ci-form").findAllPublic();
695
+ ctx.body = list;
696
+ } catch (err) {
697
+ ctx.throw(500, err);
698
+ }
699
+ },
700
+ async findOnePublic(ctx) {
701
+ try {
702
+ const { id } = ctx.params;
703
+ const found = await strapi.plugin("content-input").service("ci-form").findOnePublic(id);
704
+ if (!found) {
705
+ return ctx.notFound("Form not found");
706
+ }
707
+ ctx.body = found;
708
+ } catch (err) {
709
+ ctx.throw(500, err);
710
+ }
711
+ },
712
+ async save(ctx) {
713
+ try {
714
+ const body = ctx.request.body || {};
715
+ if (!body.title) {
716
+ return ctx.badRequest("Form title is required");
717
+ }
718
+ const saved = await strapi.plugin("content-input").service("ci-form").save(body);
719
+ ctx.status = 200;
720
+ ctx.body = saved;
721
+ } catch (err) {
722
+ ctx.throw(500, err);
723
+ }
724
+ },
725
+ async delete(ctx) {
726
+ try {
727
+ const { id } = ctx.params;
728
+ const result = await strapi.plugin("content-input").service("ci-form").remove(id);
729
+ ctx.body = result;
730
+ } catch (err) {
731
+ ctx.throw(500, err);
732
+ }
733
+ },
734
+ async submissions(ctx) {
735
+ try {
736
+ const { id } = ctx.params || {};
737
+ const list = await strapi.plugin("content-input").service("ci-form").listSubmissions(id);
738
+ ctx.body = list;
739
+ } catch (err) {
740
+ ctx.throw(500, err);
741
+ }
742
+ },
743
+ async recaptchaKey(ctx) {
744
+ try {
745
+ const config2 = strapi.plugin("content-input").service("ci-form").getPublicRecaptchaConfig();
746
+ ctx.body = config2;
747
+ } catch (err) {
748
+ ctx.throw(500, err);
749
+ }
750
+ },
751
+ async submit(ctx) {
752
+ try {
753
+ const { id } = ctx.params;
754
+ const rawBody = ctx.request.body || {};
755
+ const payload = rawBody && typeof rawBody.data === "object" && !Array.isArray(rawBody.data) && Object.keys(rawBody).length === 1 ? rawBody.data : rawBody;
756
+ const acceptLang = String(ctx.request.headers?.["accept-language"] || "").split(",")[0].split(";")[0].trim();
757
+ const queryLocale = String(ctx.query?.locale || "").trim();
758
+ const inferredLocale = (queryLocale || acceptLang || "tr").toLowerCase();
759
+ const ip = String(ctx.request.headers?.["x-forwarded-for"] || "").split(",")[0].trim() || ctx.request.ip || "";
760
+ const userAgent = String(ctx.request.headers?.["user-agent"] || "");
761
+ const result = await strapi.plugin("content-input").service("ci-form").submitForm(id, payload, {
762
+ ip,
763
+ userAgent,
764
+ locale: inferredLocale
765
+ });
766
+ ctx.status = result.status || (result.ok ? 200 : 400);
767
+ ctx.body = result;
768
+ } catch (err) {
769
+ ctx.throw(500, err);
770
+ }
771
+ },
772
+ async entityCard(ctx) {
773
+ try {
774
+ const { uid, documentId, id, slug } = ctx.query || {};
775
+ if (!uid) {
776
+ return ctx.badRequest('Query parameter "uid" is required');
777
+ }
778
+ const resolved = await strapi.plugin("content-input").service("ci-form").resolveEntityCard({
779
+ uid: String(uid),
780
+ documentId: documentId ? String(documentId) : void 0,
781
+ id: id !== void 0 ? String(id) : void 0,
782
+ slug: slug ? String(slug) : void 0
783
+ });
784
+ if (!resolved) {
785
+ return ctx.notFound("Entity not found");
786
+ }
787
+ ctx.body = { data: resolved };
788
+ } catch (err) {
789
+ ctx.throw(500, err);
790
+ }
791
+ }
792
+ });
793
+ const ciSurveyController = ({ strapi }) => ({
794
+ async indexAdmin(ctx) {
795
+ try {
796
+ const list = await strapi.plugin("content-input").service("ci-survey").findAllAdmin();
797
+ ctx.body = list;
798
+ } catch (err) {
799
+ ctx.throw(500, err);
800
+ }
801
+ },
802
+ async findOneAdmin(ctx) {
803
+ try {
804
+ const { id } = ctx.params;
805
+ const found = await strapi.plugin("content-input").service("ci-survey").findOneAdmin(id);
806
+ if (!found) {
807
+ return ctx.notFound("Survey not found");
808
+ }
809
+ ctx.body = found;
810
+ } catch (err) {
811
+ ctx.throw(500, err);
812
+ }
813
+ },
814
+ async indexPublic(ctx) {
815
+ try {
816
+ const list = await strapi.plugin("content-input").service("ci-survey").findAllPublic();
817
+ ctx.body = list;
818
+ } catch (err) {
819
+ ctx.throw(500, err);
820
+ }
821
+ },
822
+ async findOnePublic(ctx) {
823
+ try {
824
+ const { id } = ctx.params;
825
+ const ip = String(ctx.request.headers?.["x-forwarded-for"] || "").split(",")[0].trim() || ctx.request.ip || "";
826
+ const userAgent = String(ctx.request.headers?.["user-agent"] || "");
827
+ const voterToken = String(ctx.query?.voterToken || ctx.query?.token || "").trim();
828
+ const found = await strapi.plugin("content-input").service("ci-survey").findOnePublic(id, { ip, userAgent, voterToken });
829
+ if (!found) {
830
+ return ctx.notFound("Survey not found");
831
+ }
832
+ ctx.body = found;
833
+ } catch (err) {
834
+ ctx.throw(500, err);
835
+ }
836
+ },
837
+ async save(ctx) {
838
+ try {
839
+ const body = ctx.request.body || {};
840
+ if (!body.title) {
841
+ return ctx.badRequest("Survey title is required");
842
+ }
843
+ const saved = await strapi.plugin("content-input").service("ci-survey").save(body);
844
+ ctx.status = 200;
845
+ ctx.body = saved;
846
+ } catch (err) {
847
+ ctx.throw(500, err);
848
+ }
849
+ },
850
+ async delete(ctx) {
851
+ try {
852
+ const { id } = ctx.params;
853
+ const result = await strapi.plugin("content-input").service("ci-survey").remove(id);
854
+ ctx.body = result;
855
+ } catch (err) {
856
+ ctx.throw(500, err);
857
+ }
858
+ },
859
+ async submit(ctx) {
860
+ try {
861
+ const { id } = ctx.params;
862
+ const rawBody = ctx.request.body || {};
863
+ const payload = rawBody && typeof rawBody.data === "object" && !Array.isArray(rawBody.data) && Object.keys(rawBody).length === 1 ? rawBody.data : rawBody;
864
+ const acceptLang = String(ctx.request.headers?.["accept-language"] || "").split(",")[0].split(";")[0].trim();
865
+ const queryLocale = String(ctx.query?.locale || "").trim();
866
+ const inferredLocale = (queryLocale || acceptLang || "tr").toLowerCase();
867
+ const ip = String(ctx.request.headers?.["x-forwarded-for"] || "").split(",")[0].trim() || ctx.request.ip || "";
868
+ const userAgent = String(ctx.request.headers?.["user-agent"] || "");
869
+ const result = await strapi.plugin("content-input").service("ci-survey").submitSurvey(id, payload, {
870
+ ip,
871
+ userAgent,
872
+ locale: inferredLocale
873
+ });
874
+ ctx.status = result.status || (result.ok ? 200 : 400);
875
+ ctx.body = result;
876
+ } catch (err) {
877
+ ctx.throw(500, err);
878
+ }
879
+ },
880
+ async publicResults(ctx) {
881
+ try {
882
+ const { id } = ctx.params;
883
+ const result = await strapi.plugin("content-input").service("ci-survey").getPublicResults(id);
884
+ ctx.status = result.status || 200;
885
+ ctx.body = result;
886
+ } catch (err) {
887
+ ctx.throw(500, err);
888
+ }
889
+ },
890
+ async analytics(ctx) {
891
+ try {
892
+ const { id } = ctx.params;
893
+ const { from, to, locale } = ctx.query || {};
894
+ const result = await strapi.plugin("content-input").service("ci-survey").getAnalytics(id, {
895
+ from: from ? String(from) : void 0,
896
+ to: to ? String(to) : void 0,
897
+ locale: locale ? String(locale) : void 0
898
+ });
899
+ if (!result) {
900
+ return ctx.notFound("Survey not found");
901
+ }
902
+ ctx.body = result;
903
+ } catch (err) {
904
+ ctx.throw(500, err);
905
+ }
906
+ },
907
+ async responses(ctx) {
908
+ try {
909
+ const { id } = ctx.params;
910
+ const limit = Math.min(500, Math.max(10, Number(ctx.query?.limit || 150) || 150));
911
+ const rows = await strapi.plugin("content-input").service("ci-survey").listResponses(id, limit);
912
+ ctx.body = rows;
913
+ } catch (err) {
914
+ ctx.throw(500, err);
915
+ }
916
+ },
917
+ async exportResponses(ctx) {
918
+ try {
919
+ const { id } = ctx.params;
920
+ const format = String(ctx.query?.format || "csv").toLowerCase() === "json" ? "json" : "csv";
921
+ const locale = String(ctx.query?.locale || "tr").trim();
922
+ const from = ctx.query?.from ? String(ctx.query.from) : void 0;
923
+ const to = ctx.query?.to ? String(ctx.query.to) : void 0;
924
+ const exported = await strapi.plugin("content-input").service("ci-survey").exportResponses(id, { format, locale, from, to });
925
+ if (!exported) {
926
+ return ctx.notFound("Survey not found");
927
+ }
928
+ ctx.set("Content-Type", exported.contentType);
929
+ ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
930
+ ctx.status = 200;
931
+ ctx.body = exported.body;
932
+ } catch (err) {
933
+ ctx.throw(500, err);
934
+ }
935
+ },
936
+ async reseedDemo(ctx) {
937
+ try {
938
+ const res = await strapi.plugin("content-input").service("ci-survey").reseedSampleData();
939
+ ctx.body = res;
940
+ } catch (err) {
941
+ ctx.throw(500, err);
942
+ }
943
+ }
944
+ });
589
945
  const controllers = {
590
946
  "ci-template": ciTemplateController,
591
947
  "ci-menu": ciMenuController,
592
- "ci-image": ciImageController
948
+ "ci-image": ciImageController,
949
+ "ci-form": ciFormController,
950
+ "ci-survey": ciSurveyController
593
951
  };
594
952
  const routes = {
595
953
  admin: {
596
954
  type: "admin",
597
955
  routes: [
956
+ {
957
+ method: "GET",
958
+ path: "/locales",
959
+ handler: "ci-form.locales",
960
+ config: {
961
+ policies: []
962
+ }
963
+ },
598
964
  {
599
965
  method: "GET",
600
966
  path: "/templates",
@@ -661,75 +1027,285 @@ const routes = {
661
1027
  },
662
1028
  {
663
1029
  method: "GET",
664
- path: "/media",
665
- handler: "ci-menu.mediaList",
1030
+ path: "/entity-card",
1031
+ handler: "ci-form.entityCard",
666
1032
  config: {
667
1033
  policies: []
668
1034
  }
669
1035
  },
670
1036
  {
671
- method: "POST",
672
- path: "/media/crop",
673
- handler: "ci-image.cropMedia",
1037
+ method: "GET",
1038
+ path: "/forms",
1039
+ handler: "ci-form.indexAdmin",
674
1040
  config: {
675
1041
  policies: []
676
1042
  }
677
1043
  },
678
1044
  {
679
- method: "PUT",
680
- path: "/media/:id",
681
- handler: "ci-image.updateMediaInfo",
1045
+ method: "GET",
1046
+ path: "/forms/submissions",
1047
+ handler: "ci-form.submissions",
1048
+ config: {
1049
+ policies: []
1050
+ }
1051
+ },
1052
+ {
1053
+ method: "GET",
1054
+ path: "/forms/:id",
1055
+ handler: "ci-form.findOneAdmin",
1056
+ config: {
1057
+ policies: []
1058
+ }
1059
+ },
1060
+ {
1061
+ method: "POST",
1062
+ path: "/forms",
1063
+ handler: "ci-form.save",
682
1064
  config: {
683
1065
  policies: []
684
1066
  }
685
1067
  },
686
1068
  {
687
1069
  method: "DELETE",
688
- path: "/media/:id",
689
- handler: "ci-image.deleteMedia",
1070
+ path: "/forms/:id",
1071
+ handler: "ci-form.delete",
1072
+ config: {
1073
+ policies: []
1074
+ }
1075
+ },
1076
+ {
1077
+ method: "GET",
1078
+ path: "/forms/:id/submissions",
1079
+ handler: "ci-form.submissions",
1080
+ config: {
1081
+ policies: []
1082
+ }
1083
+ },
1084
+ {
1085
+ method: "GET",
1086
+ path: "/surveys",
1087
+ handler: "ci-survey.indexAdmin",
690
1088
  config: {
691
1089
  policies: []
692
1090
  }
693
1091
  },
694
1092
  {
695
1093
  method: "POST",
696
- path: "/media/folder",
697
- handler: "ci-image.createFolder",
1094
+ path: "/surveys/reseed-demo",
1095
+ handler: "ci-survey.reseedDemo",
1096
+ config: {
1097
+ policies: []
1098
+ }
1099
+ },
1100
+ {
1101
+ method: "POST",
1102
+ path: "/surveys",
1103
+ handler: "ci-survey.save",
698
1104
  config: {
699
1105
  policies: []
700
1106
  }
701
1107
  },
702
1108
  {
703
1109
  method: "GET",
704
- path: "/image",
705
- handler: "ci-image.processImage",
1110
+ path: "/surveys/:id",
1111
+ handler: "ci-survey.findOneAdmin",
706
1112
  config: {
707
- auth: false,
708
1113
  policies: []
709
1114
  }
710
- }
711
- ]
712
- },
713
- "content-api": {
714
- type: "content-api",
715
- routes: [
1115
+ },
1116
+ {
1117
+ method: "DELETE",
1118
+ path: "/surveys/:id",
1119
+ handler: "ci-survey.delete",
1120
+ config: {
1121
+ policies: []
1122
+ }
1123
+ },
716
1124
  {
717
1125
  method: "GET",
718
- path: "/image",
719
- handler: "ci-image.processImage",
1126
+ path: "/surveys/:id/analytics",
1127
+ handler: "ci-survey.analytics",
720
1128
  config: {
721
- auth: false,
722
1129
  policies: []
723
1130
  }
724
- }
725
- ]
726
- }
727
- };
728
- const UID = "plugin::content-input.ci-template";
729
- const ciTemplateService = ({ strapi }) => ({
730
- async findAll() {
731
- const entries = await strapi.db.query(UID).findMany({
732
- orderBy: { createdAt: "desc" }
1131
+ },
1132
+ {
1133
+ method: "GET",
1134
+ path: "/surveys/:id/responses",
1135
+ handler: "ci-survey.responses",
1136
+ config: {
1137
+ policies: []
1138
+ }
1139
+ },
1140
+ {
1141
+ method: "GET",
1142
+ path: "/surveys/:id/export",
1143
+ handler: "ci-survey.exportResponses",
1144
+ config: {
1145
+ policies: []
1146
+ }
1147
+ },
1148
+ {
1149
+ method: "GET",
1150
+ path: "/media",
1151
+ handler: "ci-menu.mediaList",
1152
+ config: {
1153
+ policies: []
1154
+ }
1155
+ },
1156
+ {
1157
+ method: "POST",
1158
+ path: "/media/crop",
1159
+ handler: "ci-image.cropMedia",
1160
+ config: {
1161
+ policies: []
1162
+ }
1163
+ },
1164
+ {
1165
+ method: "PUT",
1166
+ path: "/media/:id",
1167
+ handler: "ci-image.updateMediaInfo",
1168
+ config: {
1169
+ policies: []
1170
+ }
1171
+ },
1172
+ {
1173
+ method: "DELETE",
1174
+ path: "/media/:id",
1175
+ handler: "ci-image.deleteMedia",
1176
+ config: {
1177
+ policies: []
1178
+ }
1179
+ },
1180
+ {
1181
+ method: "POST",
1182
+ path: "/media/folder",
1183
+ handler: "ci-image.createFolder",
1184
+ config: {
1185
+ policies: []
1186
+ }
1187
+ },
1188
+ {
1189
+ method: "GET",
1190
+ path: "/image",
1191
+ handler: "ci-image.processImage",
1192
+ config: {
1193
+ auth: false,
1194
+ policies: []
1195
+ }
1196
+ }
1197
+ ]
1198
+ },
1199
+ "content-api": {
1200
+ type: "content-api",
1201
+ routes: [
1202
+ {
1203
+ method: "GET",
1204
+ path: "/locales",
1205
+ handler: "ci-form.locales",
1206
+ config: {
1207
+ auth: false,
1208
+ policies: []
1209
+ }
1210
+ },
1211
+ {
1212
+ method: "GET",
1213
+ path: "/image",
1214
+ handler: "ci-image.processImage",
1215
+ config: {
1216
+ auth: false,
1217
+ policies: []
1218
+ }
1219
+ },
1220
+ {
1221
+ method: "GET",
1222
+ path: "/forms",
1223
+ handler: "ci-form.indexPublic",
1224
+ config: {
1225
+ auth: false,
1226
+ policies: []
1227
+ }
1228
+ },
1229
+ {
1230
+ method: "GET",
1231
+ path: "/forms/:id",
1232
+ handler: "ci-form.findOnePublic",
1233
+ config: {
1234
+ auth: false,
1235
+ policies: []
1236
+ }
1237
+ },
1238
+ {
1239
+ method: "POST",
1240
+ path: "/forms/:id/submit",
1241
+ handler: "ci-form.submit",
1242
+ config: {
1243
+ auth: false,
1244
+ policies: []
1245
+ }
1246
+ },
1247
+ {
1248
+ method: "GET",
1249
+ path: "/surveys",
1250
+ handler: "ci-survey.indexPublic",
1251
+ config: {
1252
+ auth: false,
1253
+ policies: []
1254
+ }
1255
+ },
1256
+ {
1257
+ method: "GET",
1258
+ path: "/surveys/:id",
1259
+ handler: "ci-survey.findOnePublic",
1260
+ config: {
1261
+ auth: false,
1262
+ policies: []
1263
+ }
1264
+ },
1265
+ {
1266
+ method: "POST",
1267
+ path: "/surveys/:id/submit",
1268
+ handler: "ci-survey.submit",
1269
+ config: {
1270
+ auth: false,
1271
+ policies: []
1272
+ }
1273
+ },
1274
+ {
1275
+ method: "GET",
1276
+ path: "/surveys/:id/results",
1277
+ handler: "ci-survey.publicResults",
1278
+ config: {
1279
+ auth: false,
1280
+ policies: []
1281
+ }
1282
+ },
1283
+ {
1284
+ method: "GET",
1285
+ path: "/recaptcha-key",
1286
+ handler: "ci-form.recaptchaKey",
1287
+ config: {
1288
+ auth: false,
1289
+ policies: []
1290
+ }
1291
+ },
1292
+ {
1293
+ method: "GET",
1294
+ path: "/entity-card",
1295
+ handler: "ci-form.entityCard",
1296
+ config: {
1297
+ auth: false,
1298
+ policies: []
1299
+ }
1300
+ }
1301
+ ]
1302
+ }
1303
+ };
1304
+ const UID = "plugin::content-input.ci-template";
1305
+ const ciTemplateService = ({ strapi }) => ({
1306
+ async findAll() {
1307
+ const entries = await strapi.db.query(UID).findMany({
1308
+ orderBy: { createdAt: "desc" }
733
1309
  });
734
1310
  return entries.map((item) => ({
735
1311
  ...item,
@@ -1161,9 +1737,3535 @@ const ciMenuService = ({ strapi }) => ({
1161
1737
  };
1162
1738
  }
1163
1739
  });
1740
+ const KNOWN_RULE_PREFIXES = [
1741
+ "required",
1742
+ "filled",
1743
+ "email",
1744
+ "numeric",
1745
+ "integer",
1746
+ "min:",
1747
+ "max:",
1748
+ "min_value:",
1749
+ "max_value:",
1750
+ "between:",
1751
+ "phone",
1752
+ "url",
1753
+ "alpha_num",
1754
+ "alpha",
1755
+ "in:",
1756
+ "regex:",
1757
+ "accepted",
1758
+ "confirmed"
1759
+ ];
1760
+ function splitValidationRules(validationStr) {
1761
+ if (!validationStr || typeof validationStr !== "string") return [];
1762
+ const rawParts = validationStr.split("|").map((s) => s.trim()).filter(Boolean);
1763
+ const merged = [];
1764
+ for (const part of rawParts) {
1765
+ const prev = merged[merged.length - 1];
1766
+ if (prev && prev.startsWith("regex:") && !KNOWN_RULE_PREFIXES.some(
1767
+ (prefix) => prefix.endsWith(":") ? part.startsWith(prefix) : part === prefix || part.startsWith(`${prefix}:`)
1768
+ )) {
1769
+ merged[merged.length - 1] = `${prev}|${part}`;
1770
+ } else {
1771
+ merged.push(part);
1772
+ }
1773
+ }
1774
+ return merged;
1775
+ }
1776
+ function resolveLocalizedText(val, locale = "tr", fallback = "") {
1777
+ if (!val) return fallback;
1778
+ if (typeof val === "string") return val;
1779
+ if (typeof val === "object") {
1780
+ const code = String(locale || "tr").trim();
1781
+ const shortCode = code.split(/[-_]/)[0];
1782
+ return val[code] || val[shortCode] || val.tr || val.en || Object.values(val).find((v) => typeof v === "string" && v.trim() !== "") || fallback;
1783
+ }
1784
+ return fallback;
1785
+ }
1786
+ function isEmptyFieldValue(value) {
1787
+ if (value === null || value === void 0) return true;
1788
+ if (typeof value === "string") return value.trim().length === 0;
1789
+ if (Array.isArray(value)) return value.length === 0;
1790
+ if (typeof value === "boolean") return false;
1791
+ if (typeof value === "object") return Object.keys(value).length === 0;
1792
+ return false;
1793
+ }
1794
+ function msg(locale, trText, enText) {
1795
+ return String(locale || "").toLowerCase().startsWith("tr") ? trText : enText;
1796
+ }
1797
+ function validateSingleField(value, field, allData = {}, locale = "tr") {
1798
+ const errors = [];
1799
+ const rawValidation = typeof field.validation === "object" && field.validation !== null ? resolveLocalizedText(field.validation, locale, "") : String(field.validation || "");
1800
+ const rules = splitValidationRules(rawValidation);
1801
+ if (rules.length === 0) return errors;
1802
+ const label = resolveLocalizedText(
1803
+ field.alias,
1804
+ locale,
1805
+ field.name || (locale === "tr" ? "Bu alan" : "This field")
1806
+ );
1807
+ const empty = isEmptyFieldValue(value);
1808
+ for (const rule of rules) {
1809
+ if (rule === "required" || rule === "filled") {
1810
+ if (field.field_type === "switchBox") {
1811
+ if (value !== true && value !== "true" && value !== 1 && value !== "1") {
1812
+ errors.push(
1813
+ msg(locale, `${label} alanı zorunludur.`, `${label} is required.`)
1814
+ );
1815
+ }
1816
+ } else if (empty) {
1817
+ errors.push(
1818
+ msg(locale, `${label} alanı zorunludur.`, `${label} is required.`)
1819
+ );
1820
+ }
1821
+ continue;
1822
+ }
1823
+ if (rule === "accepted") {
1824
+ const accepted = value === true || value === "true" || value === 1 || value === "1" || value === "on" || value === "yes";
1825
+ if (!accepted) {
1826
+ errors.push(
1827
+ msg(
1828
+ locale,
1829
+ `${label} onaylanmalıdır.`,
1830
+ `${label} must be accepted.`
1831
+ )
1832
+ );
1833
+ }
1834
+ continue;
1835
+ }
1836
+ if (empty) continue;
1837
+ const strVal = Array.isArray(value) ? value.join(",") : String(value).trim();
1838
+ if (rule === "email") {
1839
+ const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1840
+ if (!emailRe.test(strVal)) {
1841
+ errors.push(
1842
+ msg(
1843
+ locale,
1844
+ `Lütfen geçerli bir e-posta adresi giriniz.`,
1845
+ `Please enter a valid email address.`
1846
+ )
1847
+ );
1848
+ }
1849
+ } else if (rule === "numeric") {
1850
+ if (Number.isNaN(Number(strVal))) {
1851
+ errors.push(
1852
+ msg(
1853
+ locale,
1854
+ `${label} sayısal bir değer olmalıdır.`,
1855
+ `${label} must be a numeric value.`
1856
+ )
1857
+ );
1858
+ }
1859
+ } else if (rule === "integer") {
1860
+ if (!/^-?\d+$/.test(strVal)) {
1861
+ errors.push(
1862
+ msg(
1863
+ locale,
1864
+ `${label} tam sayı olmalıdır.`,
1865
+ `${label} must be an integer.`
1866
+ )
1867
+ );
1868
+ }
1869
+ } else if (rule.startsWith("min:")) {
1870
+ const min = Number(rule.slice(4));
1871
+ if (!Number.isNaN(min)) {
1872
+ const len = Array.isArray(value) ? value.length : strVal.length;
1873
+ if (len < min) {
1874
+ errors.push(
1875
+ Array.isArray(value) ? msg(
1876
+ locale,
1877
+ `${label} için en az ${min} seçim yapılmalıdır.`,
1878
+ `Please select at least ${min} option(s) for ${label}.`
1879
+ ) : msg(
1880
+ locale,
1881
+ `${label} en az ${min} karakter olmalıdır.`,
1882
+ `${label} must be at least ${min} characters.`
1883
+ )
1884
+ );
1885
+ }
1886
+ }
1887
+ } else if (rule.startsWith("max:")) {
1888
+ const max = Number(rule.slice(4));
1889
+ if (!Number.isNaN(max)) {
1890
+ const len = Array.isArray(value) ? value.length : strVal.length;
1891
+ if (len > max) {
1892
+ errors.push(
1893
+ Array.isArray(value) ? msg(
1894
+ locale,
1895
+ `${label} için en fazla ${max} seçim yapılabilir.`,
1896
+ `You can select at most ${max} option(s) for ${label}.`
1897
+ ) : msg(
1898
+ locale,
1899
+ `${label} en fazla ${max} karakter olmalıdır.`,
1900
+ `${label} may not be greater than ${max} characters.`
1901
+ )
1902
+ );
1903
+ }
1904
+ }
1905
+ } else if (rule.startsWith("min_value:")) {
1906
+ const minVal = Number(rule.slice(10));
1907
+ const num = Number(strVal);
1908
+ if (!Number.isNaN(minVal) && (Number.isNaN(num) || num < minVal)) {
1909
+ errors.push(
1910
+ msg(
1911
+ locale,
1912
+ `${label} en az ${minVal} olmalıdır.`,
1913
+ `${label} must be at least ${minVal}.`
1914
+ )
1915
+ );
1916
+ }
1917
+ } else if (rule.startsWith("max_value:")) {
1918
+ const maxVal = Number(rule.slice(10));
1919
+ const num = Number(strVal);
1920
+ if (!Number.isNaN(maxVal) && (Number.isNaN(num) || num > maxVal)) {
1921
+ errors.push(
1922
+ msg(
1923
+ locale,
1924
+ `${label} en fazla ${maxVal} olabilir.`,
1925
+ `${label} must be at most ${maxVal}.`
1926
+ )
1927
+ );
1928
+ }
1929
+ } else if (rule.startsWith("between:")) {
1930
+ const [minRaw, maxRaw] = rule.slice(8).split(",");
1931
+ const minB = Number(minRaw);
1932
+ const maxB = Number(maxRaw);
1933
+ if (!Number.isNaN(minB) && !Number.isNaN(maxB)) {
1934
+ if (field.field_type === "numeric" || rules.includes("numeric")) {
1935
+ const num = Number(strVal);
1936
+ if (Number.isNaN(num) || num < minB || num > maxB) {
1937
+ errors.push(
1938
+ msg(
1939
+ locale,
1940
+ `${label} ${minB} ile ${maxB} arasında olmalıdır.`,
1941
+ `${label} must be between ${minB} and ${maxB}.`
1942
+ )
1943
+ );
1944
+ }
1945
+ } else if (strVal.length < minB || strVal.length > maxB) {
1946
+ errors.push(
1947
+ msg(
1948
+ locale,
1949
+ `${label} ${minB} ile ${maxB} karakter arasında olmalıdır.`,
1950
+ `${label} must be between ${minB} and ${maxB} characters.`
1951
+ )
1952
+ );
1953
+ }
1954
+ }
1955
+ } else if (rule === "phone") {
1956
+ const digits = strVal.replace(/[^\d]/g, "");
1957
+ const phoneRe = /^[+]?[0-9\s\-().]{7,22}$/;
1958
+ if (!phoneRe.test(strVal) || digits.length < 7 || digits.length > 15) {
1959
+ errors.push(
1960
+ msg(
1961
+ locale,
1962
+ `Lütfen geçerli bir telefon numarası giriniz.`,
1963
+ `Please enter a valid phone number.`
1964
+ )
1965
+ );
1966
+ }
1967
+ } else if (rule === "url") {
1968
+ try {
1969
+ const parsed = new URL(strVal);
1970
+ if (!["http:", "https:"].includes(parsed.protocol)) {
1971
+ throw new Error("protocol");
1972
+ }
1973
+ } catch {
1974
+ errors.push(
1975
+ msg(
1976
+ locale,
1977
+ `Lütfen geçerli bir URL (http/https) giriniz.`,
1978
+ `Please enter a valid URL (http/https).`
1979
+ )
1980
+ );
1981
+ }
1982
+ } else if (rule === "alpha") {
1983
+ if (!/^[\p{L}\s]+$/u.test(strVal)) {
1984
+ errors.push(
1985
+ msg(
1986
+ locale,
1987
+ `${label} yalnızca harflerden oluşmalıdır.`,
1988
+ `${label} may only contain alphabetic characters.`
1989
+ )
1990
+ );
1991
+ }
1992
+ } else if (rule === "alpha_num") {
1993
+ if (!/^[\p{L}\p{N}\s]+$/u.test(strVal)) {
1994
+ errors.push(
1995
+ msg(
1996
+ locale,
1997
+ `${label} yalnızca harf ve rakamlardan oluşmalıdır.`,
1998
+ `${label} may only contain letters and numbers.`
1999
+ )
2000
+ );
2001
+ }
2002
+ } else if (rule.startsWith("in:")) {
2003
+ const allowed = rule.slice(3).split(",").map((s) => s.trim()).filter(Boolean);
2004
+ const valuesToCheck = Array.isArray(value) ? value.map(String) : [strVal];
2005
+ if (valuesToCheck.some((v) => !allowed.includes(v))) {
2006
+ errors.push(
2007
+ msg(
2008
+ locale,
2009
+ `${label} için geçersiz bir seçenek belirlendi.`,
2010
+ `Selected value for ${label} is invalid.`
2011
+ )
2012
+ );
2013
+ }
2014
+ } else if (rule.startsWith("regex:")) {
2015
+ const pattern = rule.slice(6);
2016
+ try {
2017
+ const re = new RegExp(pattern);
2018
+ if (!re.test(strVal)) {
2019
+ errors.push(
2020
+ msg(
2021
+ locale,
2022
+ `${label} formatı geçersiz.`,
2023
+ `${label} format is invalid.`
2024
+ )
2025
+ );
2026
+ }
2027
+ } catch {
2028
+ }
2029
+ } else if (rule.startsWith("confirmed")) {
2030
+ const targetField = rule.includes(":") ? rule.split(":")[1] : `${field.name}_confirmation`;
2031
+ if (allData[targetField] !== value) {
2032
+ errors.push(
2033
+ msg(
2034
+ locale,
2035
+ `${label} doğrulama alanıyla eşleşmiyor.`,
2036
+ `${label} confirmation does not match.`
2037
+ )
2038
+ );
2039
+ }
2040
+ }
2041
+ }
2042
+ return errors;
2043
+ }
2044
+ function validateFormSubmission(fieldsMap, payload, locale = "tr") {
2045
+ const errors = {};
2046
+ const data = payload || {};
2047
+ for (const [key, fieldDef] of Object.entries(fieldsMap || {})) {
2048
+ const normalizedField = {
2049
+ ...fieldDef,
2050
+ name: fieldDef?.name || key
2051
+ };
2052
+ const fieldErrors = validateSingleField(data[key], normalizedField, data, locale);
2053
+ if (fieldErrors.length > 0) {
2054
+ errors[key] = fieldErrors;
2055
+ }
2056
+ }
2057
+ return {
2058
+ valid: Object.keys(errors).length === 0,
2059
+ errors
2060
+ };
2061
+ }
2062
+ async function verifyRecaptchaToken(token, secretKey, remoteIp) {
2063
+ if (!token || typeof token !== "string" || !token.trim()) {
2064
+ return false;
2065
+ }
2066
+ if (!secretKey || !secretKey.trim()) {
2067
+ return true;
2068
+ }
2069
+ try {
2070
+ const body = new URLSearchParams();
2071
+ body.set("secret", secretKey.trim());
2072
+ body.set("response", token.trim());
2073
+ if (remoteIp) {
2074
+ body.set("remoteip", remoteIp);
2075
+ }
2076
+ const res = await fetch("https://www.google.com/recaptcha/api/siteverify", {
2077
+ method: "POST",
2078
+ headers: {
2079
+ "Content-Type": "application/x-www-form-urlencoded"
2080
+ },
2081
+ body: body.toString()
2082
+ });
2083
+ if (!res.ok) return false;
2084
+ const json = await res.json();
2085
+ return Boolean(json && json.success);
2086
+ } catch {
2087
+ return false;
2088
+ }
2089
+ }
2090
+ function getNodemailer() {
2091
+ const req = typeof require !== "undefined" ? require : createRequire(path.join(process.cwd(), "package.json"));
2092
+ return req("nodemailer");
2093
+ }
2094
+ function escapeHtml(input) {
2095
+ const str = input === null || input === void 0 ? "" : String(input);
2096
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2097
+ }
2098
+ function formatFieldValue(val) {
2099
+ if (val === null || val === void 0 || val === "") return "-";
2100
+ if (Array.isArray(val)) return val.join(", ");
2101
+ if (typeof val === "boolean") return val ? "Evet / Yes" : "Hayır / No";
2102
+ if (typeof val === "object") return JSON.stringify(val);
2103
+ return String(val);
2104
+ }
2105
+ function renderContentFormMailHtml(params) {
2106
+ const { form, data, meta } = params;
2107
+ const locale = meta?.locale || "tr";
2108
+ const fields = form.fields || {};
2109
+ const entries = Object.keys(fields).length > 0 ? Object.entries(fields).map(([key, def]) => ({
2110
+ key,
2111
+ label: resolveLocalizedText(def?.alias, locale, key),
2112
+ value: formatFieldValue(data[key])
2113
+ })) : Object.entries(data || {}).map(([key, val]) => ({
2114
+ key,
2115
+ label: key,
2116
+ value: formatFieldValue(val)
2117
+ }));
2118
+ const rowsHtml = entries.map(
2119
+ (item) => `
2120
+ <tr>
2121
+ <td style="padding:10px 14px;border-bottom:1px solid #e2e8f0;font-weight:600;color:#334155;width:34%;background:#f8fafc;">
2122
+ ${escapeHtml(item.label)}
2123
+ </td>
2124
+ <td style="padding:10px 14px;border-bottom:1px solid #e2e8f0;color:#0f172a;white-space:pre-wrap;">
2125
+ ${escapeHtml(item.value)}
2126
+ </td>
2127
+ </tr>`
2128
+ ).join("");
2129
+ const html = `<!doctype html>
2130
+ <html lang="${locale}">
2131
+ <head>
2132
+ <meta charset="UTF-8" />
2133
+ <title>${escapeHtml(form.title)}</title>
2134
+ </head>
2135
+ <body style="margin:0;padding:24px;background:#f1f5f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;">
2136
+ <div style="max-width:640px;margin:0 auto;background:#ffffff;border-radius:10px;overflow:hidden;border:1px solid #cbd5e1;">
2137
+ <div style="background:#1e3a8a;color:#ffffff;padding:18px 24px;">
2138
+ <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.08em;opacity:0.85;">Strapi ContentInput Form</div>
2139
+ <h2 style="margin:4px 0 0;font-size:18px;">${escapeHtml(form.title)}</h2>
2140
+ </div>
2141
+ <div style="padding:20px 24px;">
2142
+ <p style="margin:0 0 16px;color:#475569;font-size:14px;">
2143
+ ${locale === "tr" ? "Web siteniz üzerinden yeni bir dinamik form başvurusu alındı:" : "A new dynamic form submission was received from your website:"}
2144
+ </p>
2145
+ <table style="width:100%;border-collapse:collapse;border:1px solid #e2e8f0;font-size:14px;">
2146
+ <tbody>${rowsHtml}</tbody>
2147
+ </table>
2148
+ <div style="margin-top:16px;font-size:11px;color:#94a3b8;">
2149
+ ${meta?.ip ? `IP: ${escapeHtml(meta.ip)} • ` : ""}${escapeHtml((/* @__PURE__ */ new Date()).toISOString())}
2150
+ </div>
2151
+ </div>
2152
+ </div>
2153
+ </body>
2154
+ </html>`;
2155
+ const text = [
2156
+ `[${form.title}]`,
2157
+ ...entries.map((item) => `${item.label}: ${item.value}`)
2158
+ ].join("\n");
2159
+ return { html, text };
2160
+ }
2161
+ function parseFromAddress(rawFrom, rawName) {
2162
+ const fallbackEmail = process.env.MAIL_FROM_ADDRESS || process.env.MAILGUN_USERNAME || "no-reply@example.com";
2163
+ const fallbackName = process.env.MAIL_FROM_NAME || "Strapi ContentInput";
2164
+ if (!rawFrom || !rawFrom.trim()) {
2165
+ const name2 = rawName?.trim() || fallbackName;
2166
+ return {
2167
+ email: fallbackEmail,
2168
+ name: name2,
2169
+ formatted: `"${name2}" <${fallbackEmail}>`
2170
+ };
2171
+ }
2172
+ const trimmed = rawFrom.trim();
2173
+ const angleMatch = trimmed.match(/^(?:"?([^"<]*)"?\s*)?<([^>]+)>$/);
2174
+ if (angleMatch) {
2175
+ const name2 = (rawName || angleMatch[1] || fallbackName).trim();
2176
+ const email = angleMatch[2].trim();
2177
+ return { email, name: name2, formatted: `"${name2}" <${email}>` };
2178
+ }
2179
+ const name = (rawName || fallbackName).trim();
2180
+ return { email: trimmed, name, formatted: `"${name}" <${trimmed}>` };
2181
+ }
2182
+ async function sendDynamicFormMail(params) {
2183
+ const { form, strapi } = params;
2184
+ const cfg = form.mailConfig || {};
2185
+ const rawRecipients = form.to || process.env.MAIL_TO || "";
2186
+ const recipients = rawRecipients.split(/[,;]+/).map((s) => s.trim()).filter(Boolean);
2187
+ if (recipients.length === 0) {
2188
+ return {
2189
+ sent: false,
2190
+ driver: "none",
2191
+ detail: "No recipient email configured (form.to or MAIL_TO is empty)"
2192
+ };
2193
+ }
2194
+ const explicitDriver = cfg.driver && cfg.driver !== "env" ? cfg.driver : process.env.MAIL_DRIVER || "auto";
2195
+ const mailtrapToken = (cfg.driver === "mailtrap" && cfg.apiKey ? cfg.apiKey : "") || process.env.MAILTRAP_API_TOKEN || process.env.MAILTRAP_TOKEN || "";
2196
+ const mailtrapInboxId = cfg.inboxId || process.env.MAILTRAP_INBOX_ID || "";
2197
+ const mailgunKey = (cfg.driver === "mailgun" && cfg.apiKey ? cfg.apiKey : "") || process.env.MAILGUN_SECRET || process.env.MAILGUN_API_KEY || "";
2198
+ const mailgunDomain = cfg.domain || process.env.MAILGUN_DOMAIN || "";
2199
+ const mailgunHost = cfg.apiHost || process.env.MAILGUN_HOST || "api.mailgun.net";
2200
+ const smtpHost = cfg.host || process.env.MAIL_HOST || "";
2201
+ const smtpPort = Number(cfg.port || process.env.MAIL_PORT || 2525);
2202
+ const smtpUser = cfg.username || process.env.MAIL_USERNAME || "";
2203
+ const smtpPass = cfg.password || process.env.MAIL_PASSWORD || "";
2204
+ const smtpEncryption = cfg.encryption || process.env.MAIL_ENCRYPTION || "";
2205
+ const fromInfo = parseFromAddress(
2206
+ cfg.from || process.env.MAIL_FROM,
2207
+ cfg.fromName || process.env.MAIL_FROM_NAME
2208
+ );
2209
+ const subject = form.subject?.trim() || `${form.title} — Yeni Form Başvurusu`;
2210
+ const { html, text } = renderContentFormMailHtml(params);
2211
+ let resolvedDriver = explicitDriver;
2212
+ if (resolvedDriver === "auto") {
2213
+ if (mailtrapToken) resolvedDriver = "mailtrap";
2214
+ else if (mailgunKey && mailgunDomain) resolvedDriver = "mailgun";
2215
+ else if (smtpHost && smtpUser && smtpPass) resolvedDriver = "smtp";
2216
+ else resolvedDriver = "strapi";
2217
+ }
2218
+ try {
2219
+ if (resolvedDriver === "mailtrap") {
2220
+ if (mailtrapToken) {
2221
+ const endpoint = mailtrapInboxId ? `https://sandbox.api.mailtrap.io/api/send/${encodeURIComponent(mailtrapInboxId)}` : "https://send.api.mailtrap.io/api/send";
2222
+ const res = await fetch(endpoint, {
2223
+ method: "POST",
2224
+ headers: {
2225
+ Authorization: `Bearer ${mailtrapToken.trim()}`,
2226
+ "Content-Type": "application/json"
2227
+ },
2228
+ body: JSON.stringify({
2229
+ from: { email: fromInfo.email, name: fromInfo.name },
2230
+ to: recipients.map((email) => ({ email })),
2231
+ subject,
2232
+ text,
2233
+ html
2234
+ })
2235
+ });
2236
+ const resBody = await res.text();
2237
+ if (!res.ok) {
2238
+ throw new Error(`Mailtrap API HTTP ${res.status}: ${resBody}`);
2239
+ }
2240
+ return {
2241
+ sent: true,
2242
+ driver: mailtrapInboxId ? "mailtrap-sandbox-api" : "mailtrap-sending-api",
2243
+ detail: resBody
2244
+ };
2245
+ }
2246
+ const hostToUse = smtpHost || "sandbox.smtp.mailtrap.io";
2247
+ if (smtpUser && smtpPass) {
2248
+ const nodemailer = getNodemailer();
2249
+ const transporter = nodemailer.createTransport({
2250
+ host: hostToUse,
2251
+ port: smtpPort || 2525,
2252
+ secure: smtpEncryption === "ssl" || smtpPort === 465,
2253
+ auth: {
2254
+ user: smtpUser,
2255
+ pass: smtpPass
2256
+ }
2257
+ });
2258
+ const info2 = await transporter.sendMail({
2259
+ from: fromInfo.formatted,
2260
+ to: recipients.join(", "),
2261
+ subject,
2262
+ text,
2263
+ html
2264
+ });
2265
+ return {
2266
+ sent: true,
2267
+ driver: "mailtrap-smtp",
2268
+ detail: info2?.messageId || "ok"
2269
+ };
2270
+ }
2271
+ return {
2272
+ sent: false,
2273
+ driver: "mailtrap",
2274
+ error: "Mailtrap selected but neither MAILTRAP_API_TOKEN nor MAIL_USERNAME/MAIL_PASSWORD was provided."
2275
+ };
2276
+ }
2277
+ if (resolvedDriver === "mailgun") {
2278
+ if (mailgunKey && mailgunDomain) {
2279
+ const authHeader = Buffer.from(`api:${mailgunKey.trim()}`).toString("base64");
2280
+ const formData = new URLSearchParams();
2281
+ formData.set("from", fromInfo.formatted);
2282
+ for (const r of recipients) formData.append("to", r);
2283
+ formData.set("subject", subject);
2284
+ formData.set("text", text);
2285
+ formData.set("html", html);
2286
+ const cleanHost = mailgunHost.replace(/^https?:\/\//, "").replace(/\/+$/, "");
2287
+ const res = await fetch(
2288
+ `https://${cleanHost}/v3/${encodeURIComponent(mailgunDomain)}/messages`,
2289
+ {
2290
+ method: "POST",
2291
+ headers: {
2292
+ Authorization: `Basic ${authHeader}`,
2293
+ "Content-Type": "application/x-www-form-urlencoded"
2294
+ },
2295
+ body: formData.toString()
2296
+ }
2297
+ );
2298
+ const resBody = await res.text();
2299
+ if (!res.ok) {
2300
+ throw new Error(`Mailgun API HTTP ${res.status}: ${resBody}`);
2301
+ }
2302
+ return {
2303
+ sent: true,
2304
+ driver: "mailgun-api",
2305
+ detail: resBody
2306
+ };
2307
+ }
2308
+ return {
2309
+ sent: false,
2310
+ driver: "mailgun",
2311
+ error: "Mailgun selected but MAILGUN_SECRET or MAILGUN_DOMAIN is missing."
2312
+ };
2313
+ }
2314
+ if (resolvedDriver === "smtp") {
2315
+ if (!smtpHost) {
2316
+ return {
2317
+ sent: false,
2318
+ driver: "smtp",
2319
+ error: "SMTP selected but MAIL_HOST is missing."
2320
+ };
2321
+ }
2322
+ const nodemailer = getNodemailer();
2323
+ const transporter = nodemailer.createTransport({
2324
+ host: smtpHost,
2325
+ port: smtpPort || 587,
2326
+ secure: smtpEncryption === "ssl" || smtpPort === 465,
2327
+ auth: smtpUser ? { user: smtpUser, pass: smtpPass } : void 0
2328
+ });
2329
+ const info2 = await transporter.sendMail({
2330
+ from: fromInfo.formatted,
2331
+ to: recipients.join(", "),
2332
+ subject,
2333
+ text,
2334
+ html
2335
+ });
2336
+ return {
2337
+ sent: true,
2338
+ driver: "smtp",
2339
+ detail: info2?.messageId || "ok"
2340
+ };
2341
+ }
2342
+ if (strapi?.plugin?.("email")?.service?.("email")) {
2343
+ await strapi.plugin("email").service("email").send({
2344
+ to: recipients,
2345
+ from: fromInfo.formatted,
2346
+ subject,
2347
+ text,
2348
+ html
2349
+ });
2350
+ return {
2351
+ sent: true,
2352
+ driver: "strapi-email"
2353
+ };
2354
+ }
2355
+ return {
2356
+ sent: false,
2357
+ driver: "none",
2358
+ detail: "No active mail driver configured"
2359
+ };
2360
+ } catch (err) {
2361
+ return {
2362
+ sent: false,
2363
+ driver: resolvedDriver,
2364
+ error: err?.message || String(err)
2365
+ };
2366
+ }
2367
+ }
2368
+ const DEFAULT_SEED_SURVEYS = [
2369
+ {
2370
+ title: "Kurumsal Ürün & Geliştirici Deneyimi Anketi (3 Adımlı)",
2371
+ titleI18n: {
2372
+ tr: "Kurumsal Ürün & Geliştirici Deneyimi Anketi",
2373
+ en: "Enterprise Product & Developer Experience Survey"
2374
+ },
2375
+ slug: "showcase_dx_survey",
2376
+ description: {
2377
+ tr: "ContentInput görsel sayfa oluşturucu, Nuxt Vuetify/Element Plus bileşenleri ve yeni özellik yol haritamız hakkındaki görüşlerinizi 1 dakikada paylaşın.",
2378
+ en: "Share your feedback on the ContentInput visual builder, Nuxt Vuetify/Element Plus renderers, and our upcoming roadmap in 1 minute."
2379
+ },
2380
+ status: "published",
2381
+ displayMode: "multi_step",
2382
+ quotaLimit: 500,
2383
+ submissionPolicy: "one_per_voter",
2384
+ anonymizeIp: true,
2385
+ showPublicResults: "after_vote",
2386
+ allowBackNavigation: true,
2387
+ showProgressBar: true,
2388
+ useRecaptcha: false,
2389
+ version: 1,
2390
+ steps: [
2391
+ {
2392
+ id: "step_satisfaction",
2393
+ title: {
2394
+ tr: "1. Genel Memnuniyet & NPS",
2395
+ en: "1. Overall Satisfaction & NPS"
2396
+ },
2397
+ description: {
2398
+ tr: "Genel deneyiminizi değerlendirin; düşük puanlarda iyileştirme sorusu otomatik açılır.",
2399
+ en: "Rate your overall experience; conditional follow-up appears automatically for low scores."
2400
+ }
2401
+ },
2402
+ {
2403
+ id: "step_evaluation",
2404
+ title: {
2405
+ tr: "2. Kullanım Profili, Matris & Sıralama",
2406
+ en: "2. Usage Profile, Matrix & Ranking"
2407
+ },
2408
+ description: {
2409
+ tr: "Kullandığınız modülleri, alt kriterleri ve gelecek önceliklerinizi belirleyin.",
2410
+ en: "Select the modules you use, evaluate core criteria, and rank roadmap items."
2411
+ }
2412
+ },
2413
+ {
2414
+ id: "step_visual_finish",
2415
+ title: {
2416
+ tr: "3. Görsel Tercih & Tamamlama",
2417
+ en: "3. Visual Preference & Submit"
2418
+ },
2419
+ description: {
2420
+ tr: "Kart tasarım tercihinizi seçip anketi tamamlayın.",
2421
+ en: "Choose your preferred card layout and complete the survey."
2422
+ }
2423
+ }
2424
+ ],
2425
+ questions: [
2426
+ {
2427
+ key: "intro_banner",
2428
+ stepId: "step_satisfaction",
2429
+ type: "statement",
2430
+ title: {
2431
+ tr: "Katılımınız ürün yol haritamızı doğrudan şekillendiriyor.",
2432
+ en: "Your feedback directly shapes our product roadmap."
2433
+ },
2434
+ description: {
2435
+ tr: "Not: NPS sorusunda 0–6 arası puan verirseniz koşullu (Skip Logic) açık uçlu iyileştirme sorusu otomatik olarak görünür.",
2436
+ en: "Tip: Selecting 0–6 on the NPS question dynamically reveals a conditional follow-up question."
2437
+ }
2438
+ },
2439
+ {
2440
+ key: "nps_recommend",
2441
+ stepId: "step_satisfaction",
2442
+ type: "nps",
2443
+ required: true,
2444
+ title: {
2445
+ tr: "ContentInput ekosistemini bir meslektaşınıza veya ekibinize önerme olasılığınız nedir?",
2446
+ en: "How likely are you to recommend the ContentInput ecosystem to a colleague or team?"
2447
+ },
2448
+ lowLabel: {
2449
+ tr: "0 — Hiç Olası Değil",
2450
+ en: "0 — Not at all likely"
2451
+ },
2452
+ highLabel: {
2453
+ tr: "10 — Kesinlikle Öneririm",
2454
+ en: "10 — Extremely likely"
2455
+ }
2456
+ },
2457
+ {
2458
+ key: "detractor_feedback",
2459
+ stepId: "step_satisfaction",
2460
+ type: "long_text",
2461
+ required: true,
2462
+ validation: "min:5|max:600",
2463
+ title: {
2464
+ tr: "Deneyiminizi 9 veya 10 puana taşımak için öncelikle neyi iyileştirmeliyiz?",
2465
+ en: "What is the primary improvement we could make to earn a 9 or 10 from you?"
2466
+ },
2467
+ placeholder: {
2468
+ tr: "Yaşadığınız zorluğu veya beklentinizi kısaca yazınız...",
2469
+ en: "Briefly describe the pain point or missing capability..."
2470
+ },
2471
+ conditions: {
2472
+ match: "all",
2473
+ rules: [
2474
+ {
2475
+ questionKey: "nps_recommend",
2476
+ operator: "lte",
2477
+ value: 6
2478
+ }
2479
+ ]
2480
+ }
2481
+ },
2482
+ {
2483
+ key: "overall_stars",
2484
+ stepId: "step_satisfaction",
2485
+ type: "star_rating",
2486
+ required: true,
2487
+ maxStars: 5,
2488
+ title: {
2489
+ tr: "Görsel Editör ve Sürükle-Bırak arayüzünün kullanım kolaylığına kaç yıldız verirsiniz?",
2490
+ en: "How many stars would you give the Visual Editor & Drag-and-Drop usability?"
2491
+ }
2492
+ },
2493
+ {
2494
+ key: "primary_role",
2495
+ stepId: "step_evaluation",
2496
+ type: "single_choice",
2497
+ required: true,
2498
+ allowOther: true,
2499
+ otherLabel: { tr: "Diğer Rol", en: "Other Role" },
2500
+ title: {
2501
+ tr: "Ekibinizdeki birincil rolünüz nedir?",
2502
+ en: "What is your primary role in your team?"
2503
+ },
2504
+ options: [
2505
+ {
2506
+ id: "fullstack_dev",
2507
+ labels: { tr: "Full-Stack / Backend Geliştirici", en: "Full-Stack / Backend Developer" }
2508
+ },
2509
+ {
2510
+ id: "frontend_nuxt",
2511
+ labels: { tr: "Frontend / Nuxt & Vue Geliştirici", en: "Frontend / Nuxt & Vue Developer" }
2512
+ },
2513
+ {
2514
+ id: "content_editor",
2515
+ labels: { tr: "İçerik Editörü & Dijital Pazarlama", en: "Content Editor & Digital Marketing" }
2516
+ },
2517
+ {
2518
+ id: "product_lead",
2519
+ labels: { tr: "Ürün Yöneticisi / Teknik Lider", en: "Product Manager / Tech Lead" }
2520
+ }
2521
+ ]
2522
+ },
2523
+ {
2524
+ key: "used_widgets",
2525
+ stepId: "step_evaluation",
2526
+ type: "multiple_choice",
2527
+ required: true,
2528
+ minSelections: 1,
2529
+ maxSelections: 4,
2530
+ title: {
2531
+ tr: "Projelerinizde en sık kullandığınız bileşenler hangileridir? (En fazla 4 seçim)",
2532
+ en: "Which built-in widgets do you use most frequently? (Up to 4)"
2533
+ },
2534
+ options: [
2535
+ {
2536
+ id: "swiper_gallery",
2537
+ labels: { tr: "Swiper.js Galeri & Lightbox", en: "Swiper.js Gallery & Lightbox" }
2538
+ },
2539
+ {
2540
+ id: "dynamic_form",
2541
+ labels: { tr: "Dinamik Form Oluşturucu (contentForm)", en: "Dynamic Form Studio (contentForm)" }
2542
+ },
2543
+ {
2544
+ id: "entity_card",
2545
+ labels: { tr: "Bağlı İçerik Kartı (entityCard)", en: "Linked Entity Card (entityCard)" }
2546
+ },
2547
+ {
2548
+ id: "tabs_accordion",
2549
+ labels: { tr: "İç İçe Sekme & Akordiyon", en: "Nested Tabs & Accordion" }
2550
+ },
2551
+ {
2552
+ id: "hierarchical_menu",
2553
+ labels: { tr: "Hiyerarşik Menü Ağacı", en: "Hierarchical Menu Builder" }
2554
+ },
2555
+ {
2556
+ id: "rich_html",
2557
+ labels: { tr: "Zengin Metin / HTML Editörü", en: "Rich HTML Editor" }
2558
+ }
2559
+ ]
2560
+ },
2561
+ {
2562
+ key: "team_size",
2563
+ stepId: "step_evaluation",
2564
+ type: "dropdown",
2565
+ required: true,
2566
+ title: {
2567
+ tr: "Organizasyonunuzun büyüklüğü",
2568
+ en: "Organization size"
2569
+ },
2570
+ options: [
2571
+ { id: "size_1_5", labels: { tr: "1–5 Kişi (Butik / Freelance)", en: "1–5 People (Studio / Freelance)" } },
2572
+ { id: "size_6_25", labels: { tr: "6–25 Kişi (Ajans / Startup)", en: "6–25 People (Agency / Startup)" } },
2573
+ { id: "size_26_100", labels: { tr: "26–100 Kişi (Orta Ölçekli)", en: "26–100 People (Mid-Market)" } },
2574
+ { id: "size_100_plus", labels: { tr: "100+ Kişi (Kurumsal / Enterprise)", en: "100+ People (Enterprise)" } }
2575
+ ]
2576
+ },
2577
+ {
2578
+ key: "criteria_matrix",
2579
+ stepId: "step_evaluation",
2580
+ type: "matrix_single",
2581
+ required: true,
2582
+ title: {
2583
+ tr: "Aşağıdaki teknik ve operasyonel kriterleri nasıl değerlendirirsiniz?",
2584
+ en: "How would you rate the following technical and operational aspects?"
2585
+ },
2586
+ matrixRows: [
2587
+ { id: "perf", labels: { tr: "Editör ve SSR Performansı", en: "Editor & SSR Performance" } },
2588
+ { id: "dnd", labels: { tr: "Sürükle-Bırak & Grid Esnekliği", en: "Drag-and-Drop & Grid Flexibility" } },
2589
+ { id: "nuxt_ui", labels: { tr: "Vuetify / Element Plus Uyumu", en: "Vuetify / Element Plus Parity" } },
2590
+ { id: "docs", labels: { tr: "Dokümantasyon & CLI Eject", en: "Documentation & CLI Eject" } }
2591
+ ],
2592
+ matrixColumns: [
2593
+ { id: "poor", labels: { tr: "Geliştirilmeli", en: "Needs Work" } },
2594
+ { id: "fair", labels: { tr: "Orta", en: "Fair" } },
2595
+ { id: "good", labels: { tr: "İyi", en: "Good" } },
2596
+ { id: "excellent", labels: { tr: "Mükemmel", en: "Excellent" } }
2597
+ ]
2598
+ },
2599
+ {
2600
+ key: "roadmap_ranking",
2601
+ stepId: "step_evaluation",
2602
+ type: "ranking",
2603
+ required: true,
2604
+ title: {
2605
+ tr: "Gelecek sürüm başlıklarını sizin için en önemliden (1.) başlayarak sürükleyip sıralayın",
2606
+ en: "Drag to rank upcoming roadmap initiatives from most important (#1) to least"
2607
+ },
2608
+ options: [
2609
+ {
2610
+ id: "ai_block_copilot",
2611
+ labels: { tr: "AI Destekli Sayfa & Metin Üretici", en: "AI Page & Copy Copilot" }
2612
+ },
2613
+ {
2614
+ id: "ab_experiment",
2615
+ labels: { tr: "Yerleşik A/B Varyant Testi", en: "Built-in A/B Variant Testing" }
2616
+ },
2617
+ {
2618
+ id: "realtime_presence",
2619
+ labels: { tr: "Çoklu Editör Canlı İmleç (Collaboration)", en: "Multi-Editor Live Presence" }
2620
+ },
2621
+ {
2622
+ id: "sector_templates",
2623
+ labels: { tr: "Hazır Sektörel Sayfa Şablon Paketi", en: "Ready-Made Industry Page Templates" }
2624
+ }
2625
+ ]
2626
+ },
2627
+ {
2628
+ key: "card_style_pref",
2629
+ stepId: "step_visual_finish",
2630
+ type: "image_choice",
2631
+ required: true,
2632
+ title: {
2633
+ tr: "Kurumsal vitrin sayfalarında hangi kart görünümünü daha çok tercih ediyorsunuz?",
2634
+ en: "Which visual card presentation do you prefer most on corporate landing pages?"
2635
+ },
2636
+ options: [
2637
+ {
2638
+ id: "style_vertical_clean",
2639
+ labels: { tr: "Klasik Dikey Kart (Elevated)", en: "Classic Vertical Card (Elevated)" },
2640
+ image: { url: "/uploads/dummy-slide-1-blue.png", name: "Vertical Card" }
2641
+ },
2642
+ {
2643
+ id: "style_horizontal_split",
2644
+ labels: { tr: "Yatay Bölünmüş Kart (Horizontal)", en: "Horizontal Split Card" },
2645
+ image: { url: "/uploads/dummy-slide-2-teal.png", name: "Horizontal Card" }
2646
+ },
2647
+ {
2648
+ id: "style_hero_overlay",
2649
+ labels: { tr: "Tam Görsel Kaplama (Overlay)", en: "Full Image Overlay Card" },
2650
+ image: { url: "/uploads/dummy-slide-4-emerald.png", name: "Overlay Card" }
2651
+ }
2652
+ ]
2653
+ },
2654
+ {
2655
+ key: "docs_clarity",
2656
+ stepId: "step_visual_finish",
2657
+ type: "likert_scale",
2658
+ required: true,
2659
+ scaleMin: 1,
2660
+ scaleMax: 5,
2661
+ lowLabel: { tr: "1 — Katılmıyorum", en: "1 — Strongly Disagree" },
2662
+ highLabel: { tr: "5 — Kesinlikle Katılıyorum", en: "5 — Strongly Agree" },
2663
+ title: {
2664
+ tr: "CLI şablon çıkarma (eject) ve slot özelleştirme dokümanları ekibimiz için yeterince nettir.",
2665
+ en: "The CLI template eject and slot customization guides are clear enough for our team."
2666
+ }
2667
+ },
2668
+ {
2669
+ key: "feature_wish",
2670
+ stepId: "step_visual_finish",
2671
+ type: "short_text",
2672
+ required: false,
2673
+ validation: "max:240",
2674
+ title: {
2675
+ tr: "Eklemek istediğiniz başka bir öneri veya yorum var mı? (İsteğe bağlı)",
2676
+ en: "Any additional feature request or comment? (Optional)"
2677
+ },
2678
+ placeholder: {
2679
+ tr: "Kısa notunuz...",
2680
+ en: "Your short note..."
2681
+ }
2682
+ },
2683
+ {
2684
+ key: "privacy_consent",
2685
+ stepId: "step_visual_finish",
2686
+ type: "consent",
2687
+ required: true,
2688
+ title: {
2689
+ tr: "Yanıtlarımın ürün analitiği kapsamında anonim olarak işlenmesini kabul ediyorum.",
2690
+ en: "I agree to the anonymous processing of my responses for product analytics."
2691
+ }
2692
+ }
2693
+ ],
2694
+ settings: {
2695
+ submitLabel: { tr: "Anketi Tamamla", en: "Submit Survey" },
2696
+ nextLabel: { tr: "Devam Et →", en: "Next Step →" },
2697
+ prevLabel: { tr: "← Geri", en: "← Back" },
2698
+ thankYouTitle: {
2699
+ tr: "Değerli Katkınız İçin Teşekkürler!",
2700
+ en: "Thank You for Your Valuable Feedback!"
2701
+ },
2702
+ thankYouMessage: {
2703
+ tr: "Yanıtlarınız başarıyla kaydedildi. Aşağıda tüm katılımcıların güncel özet dağılımını inceleyebilirsiniz.",
2704
+ en: "Your response has been recorded. Below is the live aggregated summary across all participants."
2705
+ }
2706
+ }
2707
+ },
2708
+ {
2709
+ title: "Hızlı Oylama: Sıradaki Büyük Özellik Ne Olsun?",
2710
+ titleI18n: {
2711
+ tr: "Hızlı Oylama: Sıradaki Büyük Özellik Ne Olsun?",
2712
+ en: "Quick Poll: What Should We Ship Next?"
2713
+ },
2714
+ slug: "showcase_roadmap_poll",
2715
+ description: {
2716
+ tr: "Tek tıkla oy verin ve topluluğun anlık oy dağılımını hemen görün!",
2717
+ en: "Cast your vote in one click and instantly see live community results!"
2718
+ },
2719
+ status: "published",
2720
+ displayMode: "quick_poll",
2721
+ quotaLimit: 1e3,
2722
+ submissionPolicy: "one_per_voter",
2723
+ anonymizeIp: true,
2724
+ showPublicResults: "after_vote",
2725
+ allowBackNavigation: false,
2726
+ showProgressBar: false,
2727
+ useRecaptcha: false,
2728
+ version: 1,
2729
+ steps: [],
2730
+ questions: [
2731
+ {
2732
+ key: "next_big_feature",
2733
+ type: "single_choice",
2734
+ required: true,
2735
+ allowOther: true,
2736
+ otherLabel: { tr: "Diğer (Belirtin)", en: "Other (Specify)" },
2737
+ title: {
2738
+ tr: "ContentInput v2 yol haritasında hangi modülü ilk sırada görmek istersiniz?",
2739
+ en: "Which module would you most like to see first on the ContentInput v2 roadmap?"
2740
+ },
2741
+ options: [
2742
+ {
2743
+ id: "ai_content_assistant",
2744
+ labels: {
2745
+ tr: "Yapay Zeka İçerik & SEO Asistanı",
2746
+ en: "AI Content & SEO Assistant"
2747
+ }
2748
+ },
2749
+ {
2750
+ id: "realtime_multiplayer",
2751
+ labels: {
2752
+ tr: "Gerçek Zamanlı Çoklu Editör (Multiplayer)",
2753
+ en: "Real-Time Multiplayer Editing"
2754
+ }
2755
+ },
2756
+ {
2757
+ id: "ab_testing_engine",
2758
+ labels: {
2759
+ tr: "Blok Bazlı A/B Test & Dönüşüm İzleme",
2760
+ en: "Block-Level A/B Testing & Conversion Tracking"
2761
+ }
2762
+ },
2763
+ {
2764
+ id: "figma_import",
2765
+ labels: {
2766
+ tr: "Figma Tasarımından Otomatik Grid Aktarımı",
2767
+ en: "Figma-to-ContentInput Grid Importer"
2768
+ }
2769
+ }
2770
+ ]
2771
+ }
2772
+ ],
2773
+ settings: {
2774
+ submitLabel: { tr: "Oy Ver & Sonuçları Gör", en: "Vote & See Results" },
2775
+ thankYouTitle: { tr: "Oyunuz Kaydedildi!", en: "Vote Recorded!" },
2776
+ thankYouMessage: {
2777
+ tr: "Topluluk oylamasının güncel sonuçları aşağıdadır:",
2778
+ en: "Here are the live community poll results:"
2779
+ }
2780
+ }
2781
+ },
2782
+ {
2783
+ title: "Görsel Vitrin & Okunabilirlik Tercihi (Açık Sonuçlu)",
2784
+ titleI18n: {
2785
+ tr: "Görsel Vitrin & Okunabilirlik Tercihi (Açık Sonuçlu)",
2786
+ en: "Visual Showcase & Readability Poll (Live Results)"
2787
+ },
2788
+ slug: "showcase_visual_theme_poll",
2789
+ description: {
2790
+ tr: 'Bu ankette "Her Zaman Sonuçları Göster" modu aktiftir; oy vermeden önce de dağılım incelenebilir.',
2791
+ en: 'This survey uses "Always Show Public Results" mode so visitors can inspect live stats anytime.'
2792
+ },
2793
+ status: "published",
2794
+ displayMode: "single_page",
2795
+ submissionPolicy: "unlimited",
2796
+ anonymizeIp: true,
2797
+ showPublicResults: "always",
2798
+ allowBackNavigation: false,
2799
+ showProgressBar: false,
2800
+ useRecaptcha: false,
2801
+ version: 1,
2802
+ steps: [],
2803
+ questions: [
2804
+ {
2805
+ key: "hero_palette_choice",
2806
+ type: "image_choice",
2807
+ required: true,
2808
+ title: {
2809
+ tr: "Kurumsal açılış sayfalarında hangi renk atmosferini daha etkileyici buluyorsunuz?",
2810
+ en: "Which hero color palette feels most compelling for enterprise landing pages?"
2811
+ },
2812
+ options: [
2813
+ {
2814
+ id: "palette_violet",
2815
+ labels: { tr: "Modern İndigo & Mor", en: "Modern Indigo & Violet" },
2816
+ image: { url: "/uploads/dummy-hero-wide-violet.png", name: "Violet Hero" }
2817
+ },
2818
+ {
2819
+ id: "palette_sky",
2820
+ labels: { tr: "Ferah Gökyüzü Mavisi", en: "Clean Sky Blue" },
2821
+ image: { url: "/uploads/dummy-hero-wide-sky.png", name: "Sky Blue Hero" }
2822
+ },
2823
+ {
2824
+ id: "palette_amber",
2825
+ labels: { tr: "Sıcak Kehribar Vurgu", en: "Warm Amber Accent" },
2826
+ image: { url: "/uploads/dummy-single-amber.png", name: "Amber Hero" }
2827
+ }
2828
+ ]
2829
+ },
2830
+ {
2831
+ key: "contrast_satisfaction",
2832
+ type: "likert_scale",
2833
+ required: true,
2834
+ scaleMin: 1,
2835
+ scaleMax: 5,
2836
+ lowLabel: { tr: "1 — Düşük", en: "1 — Low" },
2837
+ highLabel: { tr: "5 — Çok Yüksek", en: "5 — Very High" },
2838
+ title: {
2839
+ tr: "Tipografi ve kart kontrast okunabilirliğini nasıl değerlendiriyorsunuz?",
2840
+ en: "How do you rate typography and card contrast readability?"
2841
+ }
2842
+ }
2843
+ ],
2844
+ settings: {
2845
+ submitLabel: { tr: "Tercihimi Gönder", en: "Submit Preference" },
2846
+ thankYouTitle: { tr: "Teşekkür Ederiz!", en: "Thank You!" },
2847
+ thankYouMessage: {
2848
+ tr: "Tercihiniz canlı istatistiklere eklendi.",
2849
+ en: "Your preference has been added to the live stats."
2850
+ }
2851
+ }
2852
+ }
2853
+ ];
2854
+ function createMulberry32(seed) {
2855
+ let a = seed >>> 0;
2856
+ return function nextRandom() {
2857
+ a |= 0;
2858
+ a = a + 1831565813 | 0;
2859
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
2860
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
2861
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
2862
+ };
2863
+ }
2864
+ function pickWeighted(rng, items) {
2865
+ const total = items.reduce((acc, it) => acc + it.weight, 0);
2866
+ let r = rng() * total;
2867
+ for (const it of items) {
2868
+ r -= it.weight;
2869
+ if (r <= 0) return it.value;
2870
+ }
2871
+ return items[items.length - 1].value;
2872
+ }
2873
+ const DETRACTOR_COMMENTS_TR = [
2874
+ "Hazır sektörel sayfa şablonlarının sayısı artırılırsa başlangıç süresi çok kısalır.",
2875
+ "Görsel editörde karanlık mod (dark mode) desteği gece çalışırken çok faydalı olurdu.",
2876
+ "Tablo ve fiyatlandırma karşılaştırma bileşeni de yerleşik olarak gelmeli.",
2877
+ "Büyük galerilerde toplu alt-metin (alt text) düzenleme ekranı eklenebilir.",
2878
+ "Mobilde önizleme yaparken özel kırılım genişliği girebilmek isterdim.",
2879
+ "Çok dilli formlarda otomatik çeviri önerisi (AI translate) harika olurdu.",
2880
+ " Medya seçicide klasör bazlı filtreleme biraz daha hızlandırılabilir.",
2881
+ "JSON şema dışa/içe aktarma ekranında şablon önizleme küçük resimleri olmalı.",
2882
+ "Form gönderimlerinde Slack ve Webhook entegrasyonu da yerleşik sunulabilir.",
2883
+ "Editör içinde klavye kısayolları listesini gösteren küçük bir yardım penceresi iyi olur."
2884
+ ];
2885
+ const DETRACTOR_COMMENTS_EN = [
2886
+ "Adding more pre-built industry landing page templates would speed up onboarding significantly.",
2887
+ "Dark mode inside the full-screen Visual Editor would be much easier on the eyes.",
2888
+ "A built-in comparison table / pricing matrix widget would save us custom HTML work.",
2889
+ "Bulk alt-text editing for 20+ gallery images at once would be super helpful.",
2890
+ "Outgoing webhook & Slack notifications alongside Mailtrap/Mailgun would be awesome.",
2891
+ "Version diffing between previous ContentInput saves would help large editorial teams.",
2892
+ "Keyboard shortcut cheat-sheet modal inside the visual builder would improve discoverability.",
2893
+ "SVG icon picker with custom brand icon upload support would be great."
2894
+ ];
2895
+ const POSITIVE_WISHES_TR = [
2896
+ "Vuetify ve Element Plus paketlerinin aynı JSON verisiyle birebir çalışması muazzam hız kazandırdı.",
2897
+ "Swiper.js ve sharp kırpma entegrasyonu tam ihtiyacımız olan yapıydı, elinize sağlık.",
2898
+ "CLI eject komutu sayesinde kendi kurumsal tasarım sistemimize 10 dakikada uyarladık.",
2899
+ "Dinamik form validasyonlarının hem Nuxt hem Strapi tarafında aynı kuralla çalışması çok güven verici.",
2900
+ "Sürükle-bırak form stüdyosu içerik ekibimizin geliştiriciye bağımlılığını sıfırladı.",
2901
+ "Entity Card miras alma mantığı blog ve ürün vitrinlerinde çok pratik çalışıyor.",
2902
+ "İç içe sekme ve akordiyon içinde tekrar grid kurabilmek büyük esneklik sağlıyor.",
2903
+ "PDF ve Excel raporlama seçeneklerinin genişlemesini heyecanla bekliyoruz."
2904
+ ];
2905
+ const POSITIVE_WISHES_EN = [
2906
+ "Having Vuetify and Element Plus render the exact same Strapi JSONB tree saved weeks of frontend work.",
2907
+ "The CLI template eject workflow is super clean and developer-friendly.",
2908
+ "Shared vee-validate rules across Nuxt client and Strapi server prevented validation drift completely.",
2909
+ "EntityCard automatic fallback from linked Strapi entries is a huge time saver for editors.",
2910
+ "Drag-and-drop inside the Form Studio feels intuitive and fast.",
2911
+ "Looking forward to the AI page copilot in upcoming releases!"
2912
+ ];
2913
+ const OTHER_ROLE_SAMPLES_TR = ["SEO Uzmanı", "Dijital Ajans Kurucusu", "UI/UX Tasarımcı", "Çözüm Mimarı"];
2914
+ const OTHER_ROLE_SAMPLES_EN = ["SEO Specialist", "Agency Founder", "UI/UX Designer", "Solutions Architect"];
2915
+ const OTHER_POLL_SAMPLES_TR = [
2916
+ "Strapi v5 GraphQL şema yardımcıları",
2917
+ "Otomatik WebP/AVIF toplu dönüştürücü",
2918
+ "Gelişmiş veri tablosu (DataTable) bileşeni"
2919
+ ];
2920
+ const OTHER_POLL_SAMPLES_EN = [
2921
+ "Advanced responsive pricing table widget",
2922
+ "Outgoing Zapier / Make webhook connector",
2923
+ "Automatic Lighthouse accessibility checker"
2924
+ ];
2925
+ function generateSeedSurveyResponses(surveyMapBySlug) {
2926
+ const rng = createMulberry32(20261114);
2927
+ const now = Date.now();
2928
+ const dayMs = 24 * 60 * 60 * 1e3;
2929
+ const rows = [];
2930
+ const dxSurvey = surveyMapBySlug["showcase_dx_survey"];
2931
+ if (dxSurvey) {
2932
+ const dxId = String(dxSurvey.documentId || dxSurvey.id);
2933
+ for (let i = 0; i < 185; i += 1) {
2934
+ const locale = rng() < 0.64 ? "tr" : "en";
2935
+ const dayBucket = pickWeighted(rng, [
2936
+ { value: Math.floor(rng() * 5), weight: 28 },
2937
+ // last 5 days brisk
2938
+ { value: 5 + Math.floor(rng() * 10), weight: 36 },
2939
+ // days 5..14
2940
+ { value: 15 + Math.floor(rng() * 8), weight: 22 },
2941
+ // days 15..22
2942
+ { value: 23 + Math.floor(rng() * 7), weight: 14 }
2943
+ // days 23..29
2944
+ ]);
2945
+ const submittedAt = new Date(
2946
+ now - dayBucket * dayMs - Math.floor(rng() * 18 * 3600 * 1e3) - Math.floor(rng() * 3600 * 1e3)
2947
+ ).toISOString();
2948
+ const persona = pickWeighted(rng, [
2949
+ { value: "promoter", weight: 58 },
2950
+ { value: "passive", weight: 25 },
2951
+ { value: "detractor", weight: 17 }
2952
+ ]);
2953
+ const nps = persona === "promoter" ? rng() < 0.62 ? 10 : 9 : persona === "passive" ? rng() < 0.58 ? 8 : 7 : pickWeighted(rng, [
2954
+ { value: 6, weight: 38 },
2955
+ { value: 5, weight: 30 },
2956
+ { value: 4, weight: 18 },
2957
+ { value: 3, weight: 10 },
2958
+ { value: 2, weight: 4 }
2959
+ ]);
2960
+ const stars = persona === "promoter" ? rng() < 0.72 ? 5 : 4 : persona === "passive" ? rng() < 0.65 ? 4 : 3 : pickWeighted(rng, [
2961
+ { value: 3, weight: 45 },
2962
+ { value: 2, weight: 40 },
2963
+ { value: 1, weight: 15 }
2964
+ ]);
2965
+ const role = pickWeighted(rng, [
2966
+ { value: "frontend_nuxt", weight: 36 },
2967
+ { value: "fullstack_dev", weight: 31 },
2968
+ { value: "content_editor", weight: 19 },
2969
+ { value: "product_lead", weight: 10 },
2970
+ { value: "__other__", weight: 4 }
2971
+ ]);
2972
+ const otherTexts = {};
2973
+ if (role === "__other__") {
2974
+ const pool = locale === "tr" ? OTHER_ROLE_SAMPLES_TR : OTHER_ROLE_SAMPLES_EN;
2975
+ otherTexts.primary_role = pool[i % pool.length];
2976
+ }
2977
+ const widgetWeights = [
2978
+ { id: "swiper_gallery", p: 0.76 },
2979
+ { id: "dynamic_form", p: 0.68 },
2980
+ { id: "entity_card", p: 0.54 },
2981
+ { id: "rich_html", p: 0.62 },
2982
+ { id: "tabs_accordion", p: 0.46 },
2983
+ { id: "hierarchical_menu", p: 0.39 }
2984
+ ];
2985
+ const chosenWidgets = widgetWeights.filter((w) => rng() < w.p).map((w) => w.id).slice(0, 4);
2986
+ if (chosenWidgets.length === 0) chosenWidgets.push("swiper_gallery", "dynamic_form");
2987
+ const teamSize = pickWeighted(rng, [
2988
+ { value: "size_1_5", weight: 18 },
2989
+ { value: "size_6_25", weight: 37 },
2990
+ { value: "size_26_100", weight: 29 },
2991
+ { value: "size_100_plus", weight: 16 }
2992
+ ]);
2993
+ const pickMatrixCol = (highBias) => {
2994
+ if (persona === "promoter") {
2995
+ return rng() < highBias ? "excellent" : "good";
2996
+ }
2997
+ if (persona === "passive") {
2998
+ return pickWeighted(rng, [
2999
+ { value: "excellent", weight: 22 },
3000
+ { value: "good", weight: 55 },
3001
+ { value: "fair", weight: 20 },
3002
+ { value: "poor", weight: 3 }
3003
+ ]);
3004
+ }
3005
+ return pickWeighted(rng, [
3006
+ { value: "good", weight: 25 },
3007
+ { value: "fair", weight: 50 },
3008
+ { value: "poor", weight: 25 }
3009
+ ]);
3010
+ };
3011
+ const criteriaMatrix = {
3012
+ perf: pickMatrixCol(0.74),
3013
+ dnd: pickMatrixCol(0.69),
3014
+ nuxt_ui: pickMatrixCol(0.78),
3015
+ docs: pickMatrixCol(0.62)
3016
+ };
3017
+ const rankPool = [
3018
+ { id: "ai_block_copilot", score: 4.2 + rng() * 2.5 },
3019
+ { id: "sector_templates", score: 3.6 + rng() * 2.5 },
3020
+ { id: "ab_experiment", score: 3.1 + rng() * 2.5 },
3021
+ { id: "realtime_presence", score: 2.7 + rng() * 2.5 }
3022
+ ].sort((a, b) => b.score - a.score).map((x) => x.id);
3023
+ const cardStyle = pickWeighted(rng, [
3024
+ { value: "style_vertical_clean", weight: 44 },
3025
+ { value: "style_hero_overlay", weight: 33 },
3026
+ { value: "style_horizontal_split", weight: 23 }
3027
+ ]);
3028
+ const docsClarity = persona === "promoter" ? rng() < 0.68 ? 5 : 4 : persona === "passive" ? rng() < 0.6 ? 4 : 3 : rng() < 0.55 ? 3 : 2;
3029
+ const answers = {
3030
+ nps_recommend: nps,
3031
+ overall_stars: stars,
3032
+ primary_role: role,
3033
+ used_widgets: chosenWidgets,
3034
+ team_size: teamSize,
3035
+ criteria_matrix: criteriaMatrix,
3036
+ roadmap_ranking: rankPool,
3037
+ card_style_pref: cardStyle,
3038
+ docs_clarity: docsClarity,
3039
+ privacy_consent: true
3040
+ };
3041
+ if (nps <= 6) {
3042
+ const pool = locale === "tr" ? DETRACTOR_COMMENTS_TR : DETRACTOR_COMMENTS_EN;
3043
+ answers.detractor_feedback = pool[i % pool.length];
3044
+ }
3045
+ if (rng() < 0.28) {
3046
+ const pool = locale === "tr" ? POSITIVE_WISHES_TR : POSITIVE_WISHES_EN;
3047
+ answers.feature_wish = pool[i % pool.length];
3048
+ }
3049
+ const durationSeconds = 36 + Math.floor(rng() * 68);
3050
+ rows.push({
3051
+ surveyId: dxId,
3052
+ surveySlug: "showcase_dx_survey",
3053
+ surveyTitle: dxSurvey.title,
3054
+ surveyVersion: 1,
3055
+ answers,
3056
+ otherTexts,
3057
+ score: stars,
3058
+ npsValue: nps,
3059
+ npsCategory: persona,
3060
+ locale,
3061
+ durationSeconds,
3062
+ voterHash: `seed_dx_${i + 1}`,
3063
+ ip: null,
3064
+ userAgent: "Mozilla/5.0 (Seeded Analytics Dataset)",
3065
+ submittedAt
3066
+ });
3067
+ }
3068
+ }
3069
+ const pollSurvey = surveyMapBySlug["showcase_roadmap_poll"];
3070
+ if (pollSurvey) {
3071
+ const pollId = String(pollSurvey.documentId || pollSurvey.id);
3072
+ for (let i = 0; i < 245; i += 1) {
3073
+ const locale = rng() < 0.66 ? "tr" : "en";
3074
+ const dayOffset = Math.floor(Math.pow(rng(), 1.25) * 18);
3075
+ const submittedAt = new Date(
3076
+ now - dayOffset * dayMs - Math.floor(rng() * 20 * 3600 * 1e3)
3077
+ ).toISOString();
3078
+ const choice = pickWeighted(rng, [
3079
+ { value: "ai_content_assistant", weight: 37 },
3080
+ { value: "realtime_multiplayer", weight: 26 },
3081
+ { value: "ab_testing_engine", weight: 20 },
3082
+ { value: "figma_import", weight: 12 },
3083
+ { value: "__other__", weight: 5 }
3084
+ ]);
3085
+ const otherTexts = {};
3086
+ if (choice === "__other__") {
3087
+ const pool = locale === "tr" ? OTHER_POLL_SAMPLES_TR : OTHER_POLL_SAMPLES_EN;
3088
+ otherTexts.next_big_feature = pool[i % pool.length];
3089
+ }
3090
+ rows.push({
3091
+ surveyId: pollId,
3092
+ surveySlug: "showcase_roadmap_poll",
3093
+ surveyTitle: pollSurvey.title,
3094
+ surveyVersion: 1,
3095
+ answers: { next_big_feature: choice },
3096
+ otherTexts,
3097
+ score: null,
3098
+ npsValue: null,
3099
+ npsCategory: null,
3100
+ locale,
3101
+ durationSeconds: 6 + Math.floor(rng() * 14),
3102
+ voterHash: `seed_poll_${i + 1}`,
3103
+ ip: null,
3104
+ userAgent: "Mozilla/5.0 (Seeded Analytics Dataset)",
3105
+ submittedAt
3106
+ });
3107
+ }
3108
+ }
3109
+ const themeSurvey = surveyMapBySlug["showcase_visual_theme_poll"];
3110
+ if (themeSurvey) {
3111
+ const themeId = String(themeSurvey.documentId || themeSurvey.id);
3112
+ for (let i = 0; i < 95; i += 1) {
3113
+ const locale = rng() < 0.6 ? "tr" : "en";
3114
+ const dayOffset = Math.floor(rng() * 14);
3115
+ const submittedAt = new Date(
3116
+ now - dayOffset * dayMs - Math.floor(rng() * 18 * 3600 * 1e3)
3117
+ ).toISOString();
3118
+ const palette = pickWeighted(rng, [
3119
+ { value: "palette_violet", weight: 46 },
3120
+ { value: "palette_sky", weight: 35 },
3121
+ { value: "palette_amber", weight: 19 }
3122
+ ]);
3123
+ const contrast = pickWeighted(rng, [
3124
+ { value: 5, weight: 52 },
3125
+ { value: 4, weight: 34 },
3126
+ { value: 3, weight: 11 },
3127
+ { value: 2, weight: 3 }
3128
+ ]);
3129
+ rows.push({
3130
+ surveyId: themeId,
3131
+ surveySlug: "showcase_visual_theme_poll",
3132
+ surveyTitle: themeSurvey.title,
3133
+ surveyVersion: 1,
3134
+ answers: {
3135
+ hero_palette_choice: palette,
3136
+ contrast_satisfaction: contrast
3137
+ },
3138
+ otherTexts: {},
3139
+ score: contrast,
3140
+ npsValue: null,
3141
+ npsCategory: null,
3142
+ locale,
3143
+ durationSeconds: 11 + Math.floor(rng() * 18),
3144
+ voterHash: `seed_theme_${i + 1}`,
3145
+ ip: null,
3146
+ userAgent: "Mozilla/5.0 (Seeded Analytics Dataset)",
3147
+ submittedAt
3148
+ });
3149
+ }
3150
+ }
3151
+ return rows;
3152
+ }
3153
+ function generateSampleFormSubmissions(formEntry) {
3154
+ if (!formEntry) return [];
3155
+ const formId = String(formEntry.documentId || formEntry.id);
3156
+ const samplePeople = [
3157
+ {
3158
+ name: "Selin Kaya",
3159
+ email: "selin.kaya@teknolojiajans.com.tr",
3160
+ phone: "+90 532 410 22 11",
3161
+ dept: "Strapi & Nuxt Mimari Danışmanlık",
3162
+ prio: "Yüksek Öncelik",
3163
+ services: ["Strapi ContentInput Builder", "Nuxt Vuetify Renderer"],
3164
+ msg: "Kurumsal portal projemizde 40+ içerik editörü için ContentInput ve çok dilli anket yapısını konumlandırmak istiyoruz."
3165
+ },
3166
+ {
3167
+ name: "Mert Demir",
3168
+ email: "mert.demir@fintechcloud.io",
3169
+ phone: "+90 544 812 90 34",
3170
+ dept: "Satış & Kurumsal Çözümler",
3171
+ prio: "Kritik / Acil",
3172
+ services: ["Strapi ContentInput Builder", "Nuxt Element Plus Renderer", "Özel Entegrasyon"],
3173
+ msg: "Element Plus tabanlı yönetim önyüzümüzde dinamik form ve Entity Card özelleştirmeleri için teknik toplantı talep ediyoruz."
3174
+ },
3175
+ {
3176
+ name: "Elif Yılmaz",
3177
+ email: "elif.yilmaz@medyagrup.com",
3178
+ phone: "+90 533 209 45 67",
3179
+ dept: "Teknik Destek & SLA",
3180
+ prio: "Standart",
3181
+ services: ["Strapi ContentInput Builder"],
3182
+ msg: "Yüksek trafikli haber sitemizde CDN üzerinden sharp görsel boyutlandırma önbellek ayarları hakkında bilgi almak istiyoruz."
3183
+ },
3184
+ {
3185
+ name: "James Carter",
3186
+ email: "j.carter@nordicdigital.eu",
3187
+ phone: "+44 7700 900412",
3188
+ dept: "Sales & Enterprise Solutions",
3189
+ prio: "High Priority",
3190
+ services: ["Strapi ContentInput Builder", "Nuxt Vuetify Renderer"],
3191
+ msg: "We are migrating 12 regional storefronts to Strapi v5 + Nuxt 3 and love the CLI template eject workflow."
3192
+ },
3193
+ {
3194
+ name: "Burak Aydın",
3195
+ email: "burak@eticaretstüdyo.com",
3196
+ phone: "+90 535 678 12 90",
3197
+ dept: "Strapi & Nuxt Mimari Danışmanlık",
3198
+ prio: "Yüksek Öncelik",
3199
+ services: ["Nuxt Vuetify Renderer", "Özel Entegrasyon"],
3200
+ msg: "Kampanya sayfalarında hem hızlı oylama (quick poll) hem de Mailtrap/Mailgun bildirimli başvuru formlarını birlikte kullanacağız."
3201
+ },
3202
+ {
3203
+ name: "Zeynep Arslan",
3204
+ email: "zeynep.arslan@holdingkurumsal.com.tr",
3205
+ phone: "+90 212 345 67 89",
3206
+ dept: "İnsan Kaynakları",
3207
+ prio: "Standart",
3208
+ services: ["Strapi ContentInput Builder"],
3209
+ msg: "Çalışan memnuniyeti ve etkinlik geri bildirim anketlerini Strapi panelinden CSV olarak dışa aktarma özelliğini test ettik, harika çalışıyor."
3210
+ },
3211
+ {
3212
+ name: "Clara Müller",
3213
+ email: "clara.mueller@berlincommerce.de",
3214
+ phone: "+49 1512 3456789",
3215
+ dept: "Strapi & Nuxt Architecture Consulting",
3216
+ prio: "Standard",
3217
+ services: ["Strapi ContentInput Builder", "Nuxt Element Plus Renderer"],
3218
+ msg: "Multi-locale support with Strapi i18n (DE / EN / TR) works seamlessly across our product pages."
3219
+ },
3220
+ {
3221
+ name: "Caner Özkan",
3222
+ email: "caner.ozkan@saasplatform.net",
3223
+ phone: "+90 505 991 34 56",
3224
+ dept: "Teknik Destek & SLA",
3225
+ prio: "Standart",
3226
+ services: ["Nuxt Element Plus Renderer"],
3227
+ msg: "SSR hydration ve Swiper mousewheel geçişleri çok akıcı, ekibinize teşekkür ederiz."
3228
+ }
3229
+ ];
3230
+ const now = Date.now();
3231
+ const list = [];
3232
+ for (let i = 0; i < 20; i += 1) {
3233
+ const p = samplePeople[i % samplePeople.length];
3234
+ const createdDate = new Date(now - i * 19 * 3600 * 1e3).toISOString();
3235
+ list.push({
3236
+ formId,
3237
+ formSlug: formEntry.slug,
3238
+ formTitle: formEntry.title,
3239
+ data: {
3240
+ full_name: i >= samplePeople.length ? `${p.name} (#${i + 1})` : p.name,
3241
+ email: p.email,
3242
+ phone: p.phone,
3243
+ department: p.dept,
3244
+ priority: p.prio,
3245
+ services: p.services,
3246
+ message: p.msg,
3247
+ kvkk_consent: true
3248
+ },
3249
+ ip: "127.0.0.1",
3250
+ userAgent: "Mozilla/5.0 (Sample Submission Seed)",
3251
+ mailSent: i % 3 === 0,
3252
+ mailInfo: {
3253
+ driver: i % 3 === 0 ? "mailtrap-seed" : "none",
3254
+ seededAt: createdDate
3255
+ }
3256
+ });
3257
+ }
3258
+ return list;
3259
+ }
3260
+ const FORM_UID = "plugin::content-input.ci-form";
3261
+ const SUBMISSION_UID = "plugin::content-input.ci-form-submission";
3262
+ function slugifyIdentifier$1(text) {
3263
+ const map = {
3264
+ ç: "c",
3265
+ Ç: "c",
3266
+ ğ: "g",
3267
+ Ğ: "g",
3268
+ ı: "i",
3269
+ İ: "i",
3270
+ ö: "o",
3271
+ Ö: "o",
3272
+ ş: "s",
3273
+ Ş: "s",
3274
+ ü: "u",
3275
+ Ü: "u"
3276
+ };
3277
+ return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
3278
+ }
3279
+ function stripHtmlTags(html) {
3280
+ return String(html || "").replace(/<style[\s\S]*?<\/style>/gi, " ").replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<[^>]+>/g, " ").replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'").replace(/\s+/g, " ").trim();
3281
+ }
3282
+ const DEFAULT_SEED_FORMS = [
3283
+ {
3284
+ title: "Enterprise Inquiry & Support Form",
3285
+ slug: "showcase_contact_form",
3286
+ to: "info@example.com",
3287
+ subject: "Kurumsal İletişim & Destek Başvurusu",
3288
+ buttonLabel: {
3289
+ tr: "Başvuruyu Gönder",
3290
+ en: "Submit Inquiry"
3291
+ },
3292
+ successMessage: {
3293
+ tr: "Başvurunuz başarıyla kaydedildi. Ekibimiz en kısa sürede sizinle iletişime geçecektir.",
3294
+ en: "Your inquiry has been submitted successfully. Our team will get back to you shortly."
3295
+ },
3296
+ redirect: "",
3297
+ hideLabels: false,
3298
+ useRecaptcha: true,
3299
+ recaptchaSiteKey: "",
3300
+ recaptchaSecretKey: "",
3301
+ mailConfig: {
3302
+ driver: "env"
3303
+ },
3304
+ fields: {
3305
+ full_name: {
3306
+ name: "full_name",
3307
+ field_type: "input",
3308
+ alias: { tr: "Adınız Soyadınız", en: "Full Name" },
3309
+ placeholder: { tr: "Örn: Özgür Altan", en: "e.g. Jane Doe" },
3310
+ validation: "required|min:3|max:100",
3311
+ options: {}
3312
+ },
3313
+ email: {
3314
+ name: "email",
3315
+ field_type: "emailInput",
3316
+ alias: { tr: "Kurumsal E-Posta", en: "Work Email" },
3317
+ placeholder: { tr: "ad.soyad@sirket.com", en: "name@company.com" },
3318
+ validation: "required|email",
3319
+ options: {}
3320
+ },
3321
+ phone: {
3322
+ name: "phone",
3323
+ field_type: "telInput",
3324
+ alias: { tr: "Telefon Numarası", en: "Phone Number" },
3325
+ placeholder: { tr: "+90 555 123 45 67", en: "+1 555 123 4567" },
3326
+ hint: {
3327
+ tr: "İsteğe bağlı; girildiğinde telefon formatı doğrulanır.",
3328
+ en: "Optional; validated when entered."
3329
+ },
3330
+ validation: "phone",
3331
+ options: {}
3332
+ },
3333
+ department: {
3334
+ name: "department",
3335
+ field_type: "selectGroup",
3336
+ alias: { tr: "İlgili Departman", en: "Department" },
3337
+ placeholder: { tr: "Departman seçiniz...", en: "Select department..." },
3338
+ validation: "required",
3339
+ options: {
3340
+ optionList: {
3341
+ tr: [
3342
+ "Satış & Kurumsal Çözümler",
3343
+ "Teknik Destek & SLA",
3344
+ "Strapi & Nuxt Mimari Danışmanlık",
3345
+ "İnsan Kaynakları"
3346
+ ],
3347
+ en: [
3348
+ "Sales & Enterprise Solutions",
3349
+ "Technical Support & SLA",
3350
+ "Strapi & Nuxt Architecture Consulting",
3351
+ "Human Resources"
3352
+ ]
3353
+ }
3354
+ }
3355
+ },
3356
+ priority: {
3357
+ name: "priority",
3358
+ field_type: "radioGroup",
3359
+ alias: { tr: "Öncelik Seviyesi", en: "Priority Level" },
3360
+ validation: "required",
3361
+ options: {
3362
+ inline: true,
3363
+ optionList: {
3364
+ tr: ["Standart", "Yüksek Öncelik", "Kritik / Acil"],
3365
+ en: ["Standard", "High Priority", "Critical / Urgent"]
3366
+ }
3367
+ }
3368
+ },
3369
+ services: {
3370
+ name: "services",
3371
+ field_type: "checkboxGroup",
3372
+ alias: { tr: "İlgilendiğiniz Modüller", en: "Modules of Interest" },
3373
+ validation: "min:1",
3374
+ options: {
3375
+ optionList: {
3376
+ tr: [
3377
+ "Strapi ContentInput Builder",
3378
+ "Nuxt Vuetify Renderer",
3379
+ "Nuxt Element Plus Renderer",
3380
+ "Özel Entegrasyon"
3381
+ ],
3382
+ en: [
3383
+ "Strapi ContentInput Builder",
3384
+ "Nuxt Vuetify Renderer",
3385
+ "Nuxt Element Plus Renderer",
3386
+ "Custom Integration"
3387
+ ]
3388
+ }
3389
+ }
3390
+ },
3391
+ message: {
3392
+ name: "message",
3393
+ field_type: "textArea",
3394
+ alias: { tr: "Proje Detayları & Mesajınız", en: "Project Details & Message" },
3395
+ placeholder: {
3396
+ tr: "Projeniz ve beklentileriniz hakkında bilgi paylaşınız (en az 10 karakter)...",
3397
+ en: "Tell us about your project and requirements (at least 10 characters)..."
3398
+ },
3399
+ validation: "required|min:10|max:1000",
3400
+ options: { rows: 4 }
3401
+ },
3402
+ kvkk_consent: {
3403
+ name: "kvkk_consent",
3404
+ field_type: "switchBox",
3405
+ alias: {
3406
+ tr: "KVKK Aydınlatma Metnini okudum ve kişisel verilerimin işlenmesini kabul ediyorum.",
3407
+ en: "I have read and accept the Privacy Policy & GDPR data processing notice."
3408
+ },
3409
+ validation: "accepted",
3410
+ options: {}
3411
+ }
3412
+ },
3413
+ form: [
3414
+ {
3415
+ _uId: "frow_1",
3416
+ blocks: [
3417
+ { _uId: "fblk_1a", cols: [12, 6, 6, 6, 6], fields: ["full_name"] },
3418
+ { _uId: "fblk_1b", cols: [12, 6, 6, 6, 6], fields: ["email"] }
3419
+ ]
3420
+ },
3421
+ {
3422
+ _uId: "frow_2",
3423
+ blocks: [
3424
+ { _uId: "fblk_2a", cols: [12, 6, 6, 6, 6], fields: ["phone"] },
3425
+ { _uId: "fblk_2b", cols: [12, 6, 6, 6, 6], fields: ["department"] }
3426
+ ]
3427
+ },
3428
+ {
3429
+ _uId: "frow_3",
3430
+ blocks: [
3431
+ { _uId: "fblk_3a", cols: [12, 6, 6, 6, 6], fields: ["priority"] },
3432
+ { _uId: "fblk_3b", cols: [12, 6, 6, 6, 6], fields: ["services"] }
3433
+ ]
3434
+ },
3435
+ {
3436
+ _uId: "frow_4",
3437
+ blocks: [
3438
+ {
3439
+ _uId: "fblk_4a",
3440
+ cols: [12, 12, 12, 12, 12],
3441
+ fields: ["message", "kvkk_consent"]
3442
+ }
3443
+ ]
3444
+ }
3445
+ ]
3446
+ }
3447
+ ];
3448
+ function getEnvRecaptchaPublicKey$1() {
3449
+ return (process.env.MIX_RECAPTCHA_PUBLIC_KEY || process.env.RECAPTCHA_PUBLIC_KEY || process.env.NUXT_PUBLIC_RECAPTCHA_SITE_KEY || "").trim();
3450
+ }
3451
+ function getEnvRecaptchaPrivateKey$1() {
3452
+ return (process.env.RECAPTCHA_PRIVATE_KEY || process.env.RECAPTCHA_SECRET_KEY || "").trim();
3453
+ }
3454
+ function getEnvStatusSummary$1() {
3455
+ return {
3456
+ hasEnvRecaptchaPublicKey: Boolean(getEnvRecaptchaPublicKey$1()),
3457
+ hasEnvRecaptchaPrivateKey: Boolean(getEnvRecaptchaPrivateKey$1()),
3458
+ envMailDriver: process.env.MAIL_DRIVER || "auto",
3459
+ hasMailtrapToken: Boolean(process.env.MAILTRAP_API_TOKEN || process.env.MAILTRAP_TOKEN),
3460
+ hasMailgunSecret: Boolean(process.env.MAILGUN_SECRET || process.env.MAILGUN_API_KEY),
3461
+ hasSmtpHost: Boolean(process.env.MAIL_HOST)
3462
+ };
3463
+ }
3464
+ function sanitizeFormForPublic(entry) {
3465
+ if (!entry) return null;
3466
+ const { recaptchaSecretKey, mailConfig, ...safeRest } = entry;
3467
+ const publicKey = entry.useRecaptcha !== false ? String(entry.recaptchaSiteKey || getEnvRecaptchaPublicKey$1() || "").trim() : "";
3468
+ return {
3469
+ ...safeRest,
3470
+ _id: entry.documentId || String(entry.id),
3471
+ recaptchaPublicKey: publicKey,
3472
+ recaptchaEnabled: Boolean(entry.useRecaptcha !== false && publicKey)
3473
+ };
3474
+ }
3475
+ function formatFormForAdmin(entry) {
3476
+ if (!entry) return null;
3477
+ return {
3478
+ ...entry,
3479
+ _id: entry.documentId || String(entry.id),
3480
+ envStatus: getEnvStatusSummary$1()
3481
+ };
3482
+ }
3483
+ function extractSnippetAndImageFromContentInput(content) {
3484
+ let snippet = "";
3485
+ let image = null;
3486
+ const visitRows = (rows) => {
3487
+ if (!Array.isArray(rows)) return;
3488
+ for (const row of rows) {
3489
+ const blocks = Array.isArray(row?.blocks) ? row.blocks : [];
3490
+ for (const block of blocks) {
3491
+ const widgets = Array.isArray(block?.widgets) ? block.widgets : [];
3492
+ for (const widget of widgets) {
3493
+ const wId = widget?.id;
3494
+ const wData = widget?.data || {};
3495
+ if (!image) {
3496
+ if (wId === "singleImage") {
3497
+ if (wData?.image?.url) image = wData.image;
3498
+ else if (wData?.file?.url) image = wData.file;
3499
+ } else if (wId === "gallery") {
3500
+ if (Array.isArray(wData) && wData[0]?.url) {
3501
+ image = wData[0];
3502
+ } else if (Array.isArray(wData?.images) && wData.images[0]?.url) {
3503
+ image = wData.images[0];
3504
+ }
3505
+ } else if (wId === "banner" && wData?.image?.url) {
3506
+ image = wData.image;
3507
+ }
3508
+ }
3509
+ if (!snippet) {
3510
+ const rawHtml = wId === "HtmlEditor" ? typeof wData === "string" ? wData : wData?.content : "";
3511
+ if (typeof rawHtml === "string" && rawHtml.trim()) {
3512
+ const plain = stripHtmlTags(rawHtml);
3513
+ if (plain.length > 15) {
3514
+ snippet = plain.length > 180 ? `${plain.slice(0, 177)}...` : plain;
3515
+ }
3516
+ }
3517
+ }
3518
+ if (wId === "tab" && Array.isArray(wData?.tabs)) {
3519
+ for (const tab of wData.tabs) {
3520
+ if (Array.isArray(tab?.content)) visitRows(tab.content);
3521
+ }
3522
+ }
3523
+ }
3524
+ }
3525
+ }
3526
+ };
3527
+ if (Array.isArray(content)) {
3528
+ visitRows(content);
3529
+ }
3530
+ return { snippet, image };
3531
+ }
3532
+ const ciFormService = ({ strapi }) => ({
3533
+ async listStrapiLocales() {
3534
+ try {
3535
+ let rawLocales = [];
3536
+ let defaultCode = "";
3537
+ const i18nPlugin = strapi.plugin?.("i18n");
3538
+ if (i18nPlugin) {
3539
+ try {
3540
+ const localesService = i18nPlugin.service?.("locales");
3541
+ if (localesService?.find) {
3542
+ rawLocales = await localesService.find() || [];
3543
+ }
3544
+ if (localesService?.getDefaultLocale) {
3545
+ defaultCode = String(await localesService.getDefaultLocale() || "");
3546
+ }
3547
+ } catch {
3548
+ }
3549
+ }
3550
+ if (!Array.isArray(rawLocales) || rawLocales.length === 0) {
3551
+ try {
3552
+ rawLocales = await strapi.db.query("plugin::i18n.locale").findMany({
3553
+ orderBy: { id: "asc" }
3554
+ }) || [];
3555
+ } catch {
3556
+ rawLocales = [];
3557
+ }
3558
+ }
3559
+ if (Array.isArray(rawLocales) && rawLocales.length > 0) {
3560
+ const mapped = rawLocales.filter((loc) => loc && typeof loc.code === "string" && loc.code.trim()).map((loc) => {
3561
+ const code = String(loc.code).trim();
3562
+ const isDefault = Boolean(
3563
+ loc.isDefault || defaultCode && code === defaultCode
3564
+ );
3565
+ return {
3566
+ code,
3567
+ name: String(loc.name || code.toUpperCase()),
3568
+ isDefault
3569
+ };
3570
+ });
3571
+ if (mapped.length > 0) {
3572
+ if (!mapped.some((m) => m.isDefault)) {
3573
+ mapped[0].isDefault = true;
3574
+ }
3575
+ mapped.sort((a, b) => Number(b.isDefault) - Number(a.isDefault));
3576
+ return mapped;
3577
+ }
3578
+ }
3579
+ } catch {
3580
+ }
3581
+ return [
3582
+ { code: "tr", name: "Türkçe (tr)", isDefault: true },
3583
+ { code: "en", name: "English (en)", isDefault: false }
3584
+ ];
3585
+ },
3586
+ async ensureSampleSubmissions(force = false) {
3587
+ try {
3588
+ const subCount = await strapi.db.query(SUBMISSION_UID).count();
3589
+ if (subCount > 0 && !force) return;
3590
+ const showcaseForm = await strapi.db.query(FORM_UID).findOne({
3591
+ where: { slug: "showcase_contact_form" }
3592
+ });
3593
+ if (!showcaseForm) return;
3594
+ if (force) {
3595
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
3596
+ where: { formSlug: "showcase_contact_form" }
3597
+ });
3598
+ }
3599
+ const samples = generateSampleFormSubmissions(showcaseForm);
3600
+ for (const item of samples) {
3601
+ await strapi.db.query(SUBMISSION_UID).create({ data: item });
3602
+ }
3603
+ } catch {
3604
+ }
3605
+ },
3606
+ async ensureSeeded() {
3607
+ let count = 0;
3608
+ try {
3609
+ count = await strapi.db.query(FORM_UID).count();
3610
+ } catch {
3611
+ return;
3612
+ }
3613
+ if (count === 0) {
3614
+ for (const seed of DEFAULT_SEED_FORMS) {
3615
+ await strapi.db.query(FORM_UID).create({ data: seed });
3616
+ }
3617
+ }
3618
+ await this.ensureSampleSubmissions(false);
3619
+ },
3620
+ async findRawByIdOrSlug(idOrSlug) {
3621
+ await this.ensureSeeded();
3622
+ const raw = String(idOrSlug || "").trim();
3623
+ if (!raw) return null;
3624
+ let found = null;
3625
+ const numericId = Number(raw);
3626
+ if (!Number.isNaN(numericId) && String(numericId) === raw) {
3627
+ found = await strapi.db.query(FORM_UID).findOne({ where: { id: numericId } });
3628
+ }
3629
+ if (!found) {
3630
+ found = await strapi.db.query(FORM_UID).findOne({ where: { documentId: raw } });
3631
+ }
3632
+ if (!found) {
3633
+ found = await strapi.db.query(FORM_UID).findOne({ where: { slug: raw } });
3634
+ }
3635
+ return found;
3636
+ },
3637
+ async findAllAdmin() {
3638
+ await this.ensureSeeded();
3639
+ const entries = await strapi.db.query(FORM_UID).findMany({
3640
+ orderBy: { createdAt: "desc" }
3641
+ });
3642
+ return (entries || []).map(formatFormForAdmin);
3643
+ },
3644
+ async findAllPublic() {
3645
+ await this.ensureSeeded();
3646
+ const entries = await strapi.db.query(FORM_UID).findMany({
3647
+ orderBy: { createdAt: "desc" }
3648
+ });
3649
+ return (entries || []).map(sanitizeFormForPublic);
3650
+ },
3651
+ async findOneAdmin(idOrSlug) {
3652
+ const found = await this.findRawByIdOrSlug(idOrSlug);
3653
+ return formatFormForAdmin(found);
3654
+ },
3655
+ async findOnePublic(idOrSlug) {
3656
+ const found = await this.findRawByIdOrSlug(idOrSlug);
3657
+ return sanitizeFormForPublic(found);
3658
+ },
3659
+ async save(payload) {
3660
+ const cleanTitle = String(payload.title || "Yeni Dinamik Form").trim();
3661
+ const cleanSlug = String(
3662
+ payload.slug || slugifyIdentifier$1(cleanTitle) || `form_${Date.now()}`
3663
+ ).trim();
3664
+ let existing = null;
3665
+ if (payload.id) {
3666
+ const rawId = String(payload.id).trim();
3667
+ const numId = Number(rawId);
3668
+ if (!Number.isNaN(numId) && String(numId) === rawId) {
3669
+ existing = await strapi.db.query(FORM_UID).findOne({ where: { id: numId } });
3670
+ } else {
3671
+ existing = await strapi.db.query(FORM_UID).findOne({ where: { documentId: rawId } });
3672
+ }
3673
+ }
3674
+ if (!existing && cleanSlug) {
3675
+ existing = await strapi.db.query(FORM_UID).findOne({ where: { slug: cleanSlug } });
3676
+ }
3677
+ const recordData = {
3678
+ title: cleanTitle,
3679
+ slug: cleanSlug,
3680
+ to: payload.to ?? existing?.to ?? "",
3681
+ subject: payload.subject ?? existing?.subject ?? cleanTitle,
3682
+ buttonLabel: payload.buttonLabel ?? existing?.buttonLabel ?? {
3683
+ tr: "Gönder",
3684
+ en: "Submit"
3685
+ },
3686
+ successMessage: payload.successMessage ?? existing?.successMessage ?? {
3687
+ tr: "Mesajınız başarıyla iletildi.",
3688
+ en: "Your message has been sent successfully."
3689
+ },
3690
+ redirect: payload.redirect ?? existing?.redirect ?? "",
3691
+ hideLabels: Boolean(payload.hideLabels ?? existing?.hideLabels ?? false),
3692
+ useRecaptcha: payload.useRecaptcha !== void 0 ? Boolean(payload.useRecaptcha) : existing?.useRecaptcha !== void 0 ? Boolean(existing.useRecaptcha) : true,
3693
+ recaptchaSiteKey: payload.recaptchaSiteKey !== void 0 ? String(payload.recaptchaSiteKey) : existing?.recaptchaSiteKey || "",
3694
+ recaptchaSecretKey: payload.recaptchaSecretKey !== void 0 ? String(payload.recaptchaSecretKey) : existing?.recaptchaSecretKey || "",
3695
+ mailConfig: payload.mailConfig ?? existing?.mailConfig ?? { driver: "env" },
3696
+ fields: payload.fields && typeof payload.fields === "object" ? payload.fields : existing?.fields || {},
3697
+ form: Array.isArray(payload.form) ? payload.form : existing?.form || []
3698
+ };
3699
+ if (existing) {
3700
+ const updated = await strapi.db.query(FORM_UID).update({
3701
+ where: { id: existing.id },
3702
+ data: recordData
3703
+ });
3704
+ return formatFormForAdmin(updated);
3705
+ }
3706
+ const created = await strapi.db.query(FORM_UID).create({
3707
+ data: recordData
3708
+ });
3709
+ return formatFormForAdmin(created);
3710
+ },
3711
+ async remove(idOrDocId) {
3712
+ const raw = String(idOrDocId || "").trim();
3713
+ const numericId = Number(raw);
3714
+ if (!Number.isNaN(numericId) && String(numericId) === raw) {
3715
+ await strapi.db.query(FORM_UID).delete({ where: { id: numericId } });
3716
+ } else {
3717
+ const byDoc = await strapi.db.query(FORM_UID).findOne({ where: { documentId: raw } });
3718
+ if (byDoc) {
3719
+ await strapi.db.query(FORM_UID).delete({ where: { id: byDoc.id } });
3720
+ } else {
3721
+ await strapi.db.query(FORM_UID).delete({ where: { slug: raw } });
3722
+ }
3723
+ }
3724
+ return { success: true };
3725
+ },
3726
+ async listSubmissions(formIdOrSlug) {
3727
+ const where = {};
3728
+ if (formIdOrSlug) {
3729
+ const form = await this.findRawByIdOrSlug(formIdOrSlug);
3730
+ if (form) {
3731
+ where.$or = [
3732
+ { formId: String(form.documentId || form.id) },
3733
+ { formId: String(form.id) },
3734
+ { formSlug: form.slug }
3735
+ ];
3736
+ } else {
3737
+ where.$or = [{ formId: formIdOrSlug }, { formSlug: formIdOrSlug }];
3738
+ }
3739
+ }
3740
+ const rows = await strapi.db.query(SUBMISSION_UID).findMany({
3741
+ where: Object.keys(where).length > 0 ? where : void 0,
3742
+ orderBy: { createdAt: "desc" },
3743
+ limit: 200
3744
+ });
3745
+ return rows || [];
3746
+ },
3747
+ getPublicRecaptchaConfig() {
3748
+ const publicKey = getEnvRecaptchaPublicKey$1();
3749
+ return {
3750
+ publicKey,
3751
+ enabled: Boolean(publicKey)
3752
+ };
3753
+ },
3754
+ async submitForm(idOrSlug, rawBody, meta = {}) {
3755
+ const form = await this.findRawByIdOrSlug(idOrSlug);
3756
+ if (!form) {
3757
+ return {
3758
+ ok: false,
3759
+ status: 404,
3760
+ message: "Form not found"
3761
+ };
3762
+ }
3763
+ const body = rawBody && typeof rawBody === "object" ? rawBody : {};
3764
+ const rawLocale = String(body._locale || meta.locale || "tr").trim().toLowerCase();
3765
+ const locale = rawLocale ? rawLocale.split(/[,;]/)[0].trim() : "tr";
3766
+ const fieldsMap = form.fields && typeof form.fields === "object" ? form.fields : {};
3767
+ const { errors } = validateFormSubmission(fieldsMap, body, locale);
3768
+ const activeSecretKey = String(
3769
+ form.recaptchaSecretKey || getEnvRecaptchaPrivateKey$1() || ""
3770
+ ).trim();
3771
+ const activePublicKey = String(
3772
+ form.recaptchaSiteKey || getEnvRecaptchaPublicKey$1() || ""
3773
+ ).trim();
3774
+ if (form.useRecaptcha !== false && activeSecretKey && activePublicKey) {
3775
+ const recaptchaToken = body["g-recaptcha-response"];
3776
+ const recaptchaValid = await verifyRecaptchaToken(
3777
+ recaptchaToken,
3778
+ activeSecretKey,
3779
+ meta.ip
3780
+ );
3781
+ if (!recaptchaValid) {
3782
+ errors["g-recaptcha-response"] = [
3783
+ locale === "tr" ? "Lütfen robot olmadığınızı doğrulayınız (reCAPTCHA)." : "Please complete the reCAPTCHA verification."
3784
+ ];
3785
+ }
3786
+ }
3787
+ if (Object.keys(errors).length > 0) {
3788
+ return {
3789
+ ok: false,
3790
+ status: 422,
3791
+ errors
3792
+ };
3793
+ }
3794
+ const cleanData = {};
3795
+ const definedKeys = Object.keys(fieldsMap);
3796
+ if (definedKeys.length > 0) {
3797
+ for (const k of definedKeys) {
3798
+ cleanData[k] = body[k] !== void 0 ? body[k] : null;
3799
+ }
3800
+ } else {
3801
+ for (const [k, v] of Object.entries(body)) {
3802
+ if (k === "g-recaptcha-response" || k === "_locale") continue;
3803
+ cleanData[k] = v;
3804
+ }
3805
+ }
3806
+ const mailResult = await sendDynamicFormMail({
3807
+ strapi,
3808
+ form: {
3809
+ title: form.title,
3810
+ to: form.to,
3811
+ subject: form.subject,
3812
+ fields: fieldsMap,
3813
+ mailConfig: form.mailConfig
3814
+ },
3815
+ data: cleanData,
3816
+ meta: {
3817
+ ip: meta.ip,
3818
+ userAgent: meta.userAgent,
3819
+ locale
3820
+ }
3821
+ });
3822
+ const createdSubmission = await strapi.db.query(SUBMISSION_UID).create({
3823
+ data: {
3824
+ formId: String(form.documentId || form.id),
3825
+ formSlug: form.slug,
3826
+ formTitle: form.title,
3827
+ data: cleanData,
3828
+ ip: meta.ip || "",
3829
+ userAgent: meta.userAgent || "",
3830
+ mailSent: Boolean(mailResult.sent),
3831
+ mailInfo: mailResult
3832
+ }
3833
+ });
3834
+ const successMsg = resolveLocalizedText(
3835
+ form.successMessage,
3836
+ locale,
3837
+ locale === "tr" ? "Mesajınız başarıyla gönderildi." : "Your message has been submitted successfully."
3838
+ );
3839
+ return {
3840
+ ok: true,
3841
+ status: 200,
3842
+ submissionId: createdSubmission?.documentId || String(createdSubmission?.id || ""),
3843
+ message: successMsg,
3844
+ redirect: form.redirect || "",
3845
+ mailSent: Boolean(mailResult.sent),
3846
+ mailDriver: mailResult.driver
3847
+ };
3848
+ },
3849
+ async resolveEntityCard(params) {
3850
+ const uid = String(params.uid || "").trim();
3851
+ if (!uid || !uid.startsWith("api::")) {
3852
+ return null;
3853
+ }
3854
+ const ct = (strapi.contentTypes || {})[uid];
3855
+ if (!ct) {
3856
+ return null;
3857
+ }
3858
+ const attrs = ct.attributes || {};
3859
+ const populate = {};
3860
+ const mediaFields = [];
3861
+ const ciFields = [];
3862
+ for (const [attrName, attrDef] of Object.entries(attrs)) {
3863
+ if (attrDef?.type === "media") {
3864
+ populate[attrName] = true;
3865
+ mediaFields.push(attrName);
3866
+ }
3867
+ if (attrDef?.customField === "plugin::content-input.content-input" || attrDef?.type === "json") {
3868
+ ciFields.push(attrName);
3869
+ }
3870
+ }
3871
+ let rows = [];
3872
+ try {
3873
+ const where = {};
3874
+ if (params.documentId) {
3875
+ where.documentId = String(params.documentId);
3876
+ } else if (params.id !== void 0 && params.id !== "") {
3877
+ const numId = Number(params.id);
3878
+ if (!Number.isNaN(numId)) where.id = numId;
3879
+ } else if (params.slug) {
3880
+ where.slug = String(params.slug);
3881
+ }
3882
+ rows = await strapi.db.query(uid).findMany({
3883
+ where: Object.keys(where).length > 0 ? where : void 0,
3884
+ populate: Object.keys(populate).length > 0 ? populate : void 0,
3885
+ limit: 10,
3886
+ orderBy: { id: "desc" }
3887
+ });
3888
+ } catch {
3889
+ rows = [];
3890
+ }
3891
+ if (!rows || rows.length === 0) {
3892
+ return null;
3893
+ }
3894
+ const entry = rows.find((r) => Boolean(r.publishedAt)) || rows[0];
3895
+ const titleCandidates = ["title", "name", "heading", "label", "subject", "baslik", "ad"];
3896
+ const subtitleCandidates = ["subtitle", "kicker", "categoryName", "role", "department", "tag"];
3897
+ const descCandidates = [
3898
+ "description",
3899
+ "excerpt",
3900
+ "summary",
3901
+ "seoDescription",
3902
+ "shortDescription",
3903
+ "lead",
3904
+ "bio",
3905
+ "ozet",
3906
+ "aciklama"
3907
+ ];
3908
+ const imagePriority = [
3909
+ "image",
3910
+ "cover",
3911
+ "thumbnail",
3912
+ "featuredImage",
3913
+ "photo",
3914
+ "banner",
3915
+ "media",
3916
+ "avatar",
3917
+ ...mediaFields
3918
+ ];
3919
+ const pickFirstString = (candidates) => {
3920
+ for (const key of candidates) {
3921
+ const val = entry[key];
3922
+ if (typeof val === "string" && val.trim()) {
3923
+ return stripHtmlTags(val);
3924
+ }
3925
+ }
3926
+ return "";
3927
+ };
3928
+ let title = pickFirstString(titleCandidates);
3929
+ if (!title) {
3930
+ const fallbackStrKey = Object.keys(attrs).find(
3931
+ (k) => ["string", "text"].includes(attrs[k]?.type)
3932
+ );
3933
+ if (fallbackStrKey && typeof entry[fallbackStrKey] === "string") {
3934
+ title = entry[fallbackStrKey];
3935
+ } else {
3936
+ title = `#${entry.documentId || entry.id}`;
3937
+ }
3938
+ }
3939
+ const collectionLabel = ct.info?.displayName || ct.info?.singularName || uid;
3940
+ const subtitle = pickFirstString(subtitleCandidates);
3941
+ let description = pickFirstString(descCandidates);
3942
+ let imageObj = null;
3943
+ for (const imgKey of imagePriority) {
3944
+ const rawMedia = entry[imgKey];
3945
+ if (!rawMedia) continue;
3946
+ const firstMedia = Array.isArray(rawMedia) ? rawMedia[0] : rawMedia;
3947
+ if (firstMedia && typeof firstMedia === "object" && firstMedia.url) {
3948
+ imageObj = {
3949
+ id: firstMedia.id,
3950
+ documentId: firstMedia.documentId,
3951
+ url: firstMedia.url,
3952
+ name: firstMedia.name || title,
3953
+ alternativeText: firstMedia.alternativeText || title,
3954
+ width: firstMedia.width,
3955
+ height: firstMedia.height,
3956
+ formats: firstMedia.formats
3957
+ };
3958
+ break;
3959
+ }
3960
+ }
3961
+ if (!description || !imageObj) {
3962
+ for (const ciField of ciFields) {
3963
+ if (Array.isArray(entry[ciField])) {
3964
+ const extracted = extractSnippetAndImageFromContentInput(entry[ciField]);
3965
+ if (!description && extracted.snippet) {
3966
+ description = extracted.snippet;
3967
+ }
3968
+ if (!imageObj && extracted.image) {
3969
+ imageObj = extracted.image;
3970
+ }
3971
+ }
3972
+ }
3973
+ }
3974
+ const pluralName = ct.info?.pluralName || "items";
3975
+ const slugField = ["slug", "path", "url", "permalink"].find(
3976
+ (k) => typeof entry[k] === "string" && entry[k].trim()
3977
+ );
3978
+ const rawSlug = slugField ? String(entry[slugField]).trim() : String(entry.documentId || entry.id);
3979
+ let url = "/";
3980
+ if (rawSlug === "home" || rawSlug === "anasayfa" || rawSlug === "/") {
3981
+ url = "/";
3982
+ } else if (rawSlug.startsWith("/")) {
3983
+ url = rawSlug;
3984
+ } else {
3985
+ const prefix = pluralName === "pages" ? "" : `/${pluralName}`;
3986
+ url = `${prefix}/${rawSlug}`.replace(/\/+/g, "/");
3987
+ }
3988
+ return {
3989
+ id: entry.id,
3990
+ documentId: String(entry.documentId || entry.id),
3991
+ uid,
3992
+ collectionName: pluralName,
3993
+ collectionLabel,
3994
+ title,
3995
+ subtitle,
3996
+ description,
3997
+ image: imageObj,
3998
+ url,
3999
+ slug: rawSlug,
4000
+ publishedAt: entry.publishedAt || entry.updatedAt || entry.createdAt || null
4001
+ };
4002
+ }
4003
+ });
4004
+ function evalSingleRule(rule, answers) {
4005
+ const targetVal = answers ? answers[rule.questionKey] : void 0;
4006
+ const op = rule.operator;
4007
+ if (op === "is_answered") {
4008
+ return !isEmptyFieldValue(targetVal);
4009
+ }
4010
+ if (op === "is_empty") {
4011
+ return isEmptyFieldValue(targetVal);
4012
+ }
4013
+ const cmp = rule.value;
4014
+ if (op === "equals") {
4015
+ if (Array.isArray(targetVal)) return targetVal.map(String).includes(String(cmp));
4016
+ return String(targetVal ?? "") === String(cmp ?? "");
4017
+ }
4018
+ if (op === "not_equals") {
4019
+ if (Array.isArray(targetVal)) return !targetVal.map(String).includes(String(cmp));
4020
+ return String(targetVal ?? "") !== String(cmp ?? "");
4021
+ }
4022
+ if (op === "includes") {
4023
+ if (Array.isArray(targetVal)) return targetVal.map(String).includes(String(cmp));
4024
+ return String(targetVal ?? "").includes(String(cmp ?? ""));
4025
+ }
4026
+ if (op === "not_includes") {
4027
+ if (Array.isArray(targetVal)) return !targetVal.map(String).includes(String(cmp));
4028
+ return !String(targetVal ?? "").includes(String(cmp ?? ""));
4029
+ }
4030
+ const numTarget = Number(targetVal);
4031
+ const numCmp = Number(cmp);
4032
+ if (isEmptyFieldValue(targetVal) || Number.isNaN(numTarget) || Number.isNaN(numCmp)) {
4033
+ return false;
4034
+ }
4035
+ if (op === "gt") return numTarget > numCmp;
4036
+ if (op === "gte") return numTarget >= numCmp;
4037
+ if (op === "lt") return numTarget < numCmp;
4038
+ if (op === "lte") return numTarget <= numCmp;
4039
+ return true;
4040
+ }
4041
+ function evaluateSurveyConditions(conditions, answers) {
4042
+ if (!conditions || !Array.isArray(conditions.rules) || conditions.rules.length === 0) {
4043
+ return true;
4044
+ }
4045
+ if (conditions.match === "any") {
4046
+ return conditions.rules.some((r) => evalSingleRule(r, answers));
4047
+ }
4048
+ return conditions.rules.every((r) => evalSingleRule(r, answers));
4049
+ }
4050
+ function isQuestionVisible(question, survey, answers) {
4051
+ if (survey.displayMode === "multi_step" && question.stepId && Array.isArray(survey.steps)) {
4052
+ const parentStep = survey.steps.find((s) => s.id === question.stepId);
4053
+ if (parentStep && !evaluateSurveyConditions(parentStep.conditions, answers)) {
4054
+ return false;
4055
+ }
4056
+ }
4057
+ return evaluateSurveyConditions(question.conditions, answers);
4058
+ }
4059
+ function lMsg(locale, tr, en) {
4060
+ return String(locale || "").toLowerCase().startsWith("tr") ? tr : en;
4061
+ }
4062
+ function validateSurveySubmission(survey, answers, otherTexts = {}, locale = "tr") {
4063
+ const errors = {};
4064
+ const questions = Array.isArray(survey.questions) ? survey.questions : [];
4065
+ for (const q of questions) {
4066
+ if (!q || !q.key || q.type === "statement") continue;
4067
+ if (!isQuestionVisible(q, survey, answers)) continue;
4068
+ const val = answers ? answers[q.key] : void 0;
4069
+ const qLabel = resolveLocalizedText(q.title, locale, q.key);
4070
+ const qErrors = [];
4071
+ const empty = isEmptyFieldValue(val);
4072
+ if (q.type === "consent") {
4073
+ if (q.required !== false && val !== true && val !== "true" && val !== 1) {
4074
+ qErrors.push(lMsg(locale, `${qLabel} onaylanmalıdır.`, `${qLabel} must be accepted.`));
4075
+ }
4076
+ } else if (q.type === "matrix_single") {
4077
+ const mRows = Array.isArray(q.matrixRows) ? q.matrixRows : [];
4078
+ if (q.required) {
4079
+ const objVal = val && typeof val === "object" && !Array.isArray(val) ? val : {};
4080
+ const missingRow = mRows.some((r) => isEmptyFieldValue(objVal[r.id]));
4081
+ if (missingRow) {
4082
+ qErrors.push(
4083
+ lMsg(
4084
+ locale,
4085
+ `Lütfen "${qLabel}" tablosundaki tüm satırları yanıtlayınız.`,
4086
+ `Please answer all rows in "${qLabel}".`
4087
+ )
4088
+ );
4089
+ }
4090
+ }
4091
+ } else if (q.type === "multiple_choice" || q.type === "image_choice" && (q.maxSelections ?? 1) > 1) {
4092
+ const arr = Array.isArray(val) ? val : [];
4093
+ if (q.required && arr.length === 0) {
4094
+ qErrors.push(lMsg(locale, `Lütfen en az bir seçenek işaretleyiniz.`, `Please select at least one option.`));
4095
+ } else if (arr.length > 0) {
4096
+ if (q.minSelections && arr.length < q.minSelections) {
4097
+ qErrors.push(
4098
+ lMsg(
4099
+ locale,
4100
+ `En az ${q.minSelections} seçenek işaretlemelisiniz.`,
4101
+ `Please select at least ${q.minSelections} options.`
4102
+ )
4103
+ );
4104
+ }
4105
+ if (q.maxSelections && arr.length > q.maxSelections) {
4106
+ qErrors.push(
4107
+ lMsg(
4108
+ locale,
4109
+ `En fazla ${q.maxSelections} seçenek işaretleyebilirsiniz.`,
4110
+ `You may select at most ${q.maxSelections} options.`
4111
+ )
4112
+ );
4113
+ }
4114
+ }
4115
+ if (q.allowOther && arr.includes("__other__") && !String(otherTexts?.[q.key] || "").trim()) {
4116
+ qErrors.push(
4117
+ lMsg(locale, `Lütfen "Diğer" seçeneği için açıklama giriniz.`, `Please specify your "Other" choice.`)
4118
+ );
4119
+ }
4120
+ } else if (q.type === "single_choice" || q.type === "dropdown" || q.type === "image_choice") {
4121
+ if (q.required && empty) {
4122
+ qErrors.push(lMsg(locale, `Lütfen bir seçim yapınız.`, `Please choose an option.`));
4123
+ }
4124
+ if (q.allowOther && val === "__other__" && !String(otherTexts?.[q.key] || "").trim()) {
4125
+ qErrors.push(
4126
+ lMsg(locale, `Lütfen "Diğer" seçeneği için açıklama giriniz.`, `Please specify your "Other" choice.`)
4127
+ );
4128
+ }
4129
+ } else if (q.type === "nps") {
4130
+ if (q.required && empty) {
4131
+ qErrors.push(lMsg(locale, `Lütfen 0 ile 10 arasında bir puan seçiniz.`, `Please choose a score from 0 to 10.`));
4132
+ } else if (!empty) {
4133
+ const n = Number(val);
4134
+ if (Number.isNaN(n) || n < 0 || n > 10) {
4135
+ qErrors.push(lMsg(locale, `Puan 0 ile 10 arasında olmalıdır.`, `Score must be between 0 and 10.`));
4136
+ }
4137
+ }
4138
+ } else if (q.type === "star_rating") {
4139
+ const maxS = q.maxStars || 5;
4140
+ if (q.required && empty) {
4141
+ qErrors.push(lMsg(locale, `Lütfen derecelendirme yapınız.`, `Please provide a rating.`));
4142
+ } else if (!empty) {
4143
+ const n = Number(val);
4144
+ if (Number.isNaN(n) || n < 1 || n > maxS) {
4145
+ qErrors.push(lMsg(locale, `Derece 1 ile ${maxS} arasında olmalıdır.`, `Rating must be between 1 and ${maxS}.`));
4146
+ }
4147
+ }
4148
+ } else if (q.type === "likert_scale") {
4149
+ const sMin = q.scaleMin ?? 1;
4150
+ const sMax = q.scaleMax ?? 5;
4151
+ if (q.required && empty) {
4152
+ qErrors.push(lMsg(locale, `Lütfen ölçekten bir değer seçiniz.`, `Please select a value on the scale.`));
4153
+ } else if (!empty) {
4154
+ const n = Number(val);
4155
+ if (Number.isNaN(n) || n < sMin || n > sMax) {
4156
+ qErrors.push(
4157
+ lMsg(locale, `Değer ${sMin} ile ${sMax} arasında olmalıdır.`, `Value must be between ${sMin} and ${sMax}.`)
4158
+ );
4159
+ }
4160
+ }
4161
+ } else if (q.type === "ranking") {
4162
+ if (q.required && (!Array.isArray(val) || val.length === 0)) {
4163
+ qErrors.push(lMsg(locale, `Lütfen sıralamayı onaylayınız.`, `Please confirm the ranking.`));
4164
+ }
4165
+ } else if (q.type === "short_text" || q.type === "long_text") {
4166
+ const ruleParts = [];
4167
+ if (q.required) ruleParts.push("required");
4168
+ if (q.validation) ruleParts.push(q.validation);
4169
+ const combinedRules = Array.from(new Set(ruleParts.join("|").split("|").filter(Boolean))).join("|");
4170
+ if (combinedRules) {
4171
+ const vErrs = validateSingleField(
4172
+ val,
4173
+ {
4174
+ name: q.key,
4175
+ field_type: q.type === "long_text" ? "textArea" : "input",
4176
+ alias: q.title,
4177
+ validation: combinedRules
4178
+ },
4179
+ answers,
4180
+ locale
4181
+ );
4182
+ qErrors.push(...vErrs);
4183
+ }
4184
+ }
4185
+ if (qErrors.length > 0) {
4186
+ errors[q.key] = qErrors;
4187
+ }
4188
+ }
4189
+ return {
4190
+ valid: Object.keys(errors).length === 0,
4191
+ errors
4192
+ };
4193
+ }
4194
+ function computeVoterHash(surveySlug, ip, userAgent, voterToken) {
4195
+ const salt = process.env.APP_KEYS || process.env.API_TOKEN_SALT || "ci-survey-default-salt";
4196
+ const rawIdentity = voterToken ? `${surveySlug}::token::${voterToken}` : `${surveySlug}::ipua::${ip || "unknown"}::${(userAgent || "").slice(0, 120)}`;
4197
+ return crypto.createHmac("sha256", salt).update(rawIdentity).digest("hex");
4198
+ }
4199
+ function computeResponseMetrics(survey, answers) {
4200
+ let totalScore = 0;
4201
+ let hasScoredItem = false;
4202
+ let npsValue = null;
4203
+ let npsCategory = null;
4204
+ for (const q of survey.questions || []) {
4205
+ const val = answers?.[q.key];
4206
+ if (isEmptyFieldValue(val)) continue;
4207
+ if (q.type === "nps" && npsValue === null) {
4208
+ const n = Number(val);
4209
+ if (!Number.isNaN(n)) {
4210
+ npsValue = n;
4211
+ npsCategory = n >= 9 ? "promoter" : n >= 7 ? "passive" : "detractor";
4212
+ }
4213
+ }
4214
+ if (Array.isArray(q.options) && q.options.length > 0) {
4215
+ if (Array.isArray(val)) {
4216
+ for (const chosen of val) {
4217
+ const opt = q.options.find((o) => o.id === chosen);
4218
+ if (opt && typeof opt.score === "number") {
4219
+ totalScore += opt.score;
4220
+ hasScoredItem = true;
4221
+ }
4222
+ }
4223
+ } else {
4224
+ const opt = q.options.find((o) => o.id === val);
4225
+ if (opt && typeof opt.score === "number") {
4226
+ totalScore += opt.score;
4227
+ hasScoredItem = true;
4228
+ }
4229
+ }
4230
+ }
4231
+ }
4232
+ return {
4233
+ score: hasScoredItem ? totalScore : null,
4234
+ npsValue,
4235
+ npsCategory
4236
+ };
4237
+ }
4238
+ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
4239
+ const fromTime = filter.from ? new Date(filter.from).getTime() : null;
4240
+ const toTime = filter.to ? (/* @__PURE__ */ new Date(`${filter.to}T23:59:59.999Z`)).getTime() : null;
4241
+ const filterLocale = filter.locale && filter.locale !== "all" ? filter.locale : null;
4242
+ const responses = (rawResponses || []).filter((r) => {
4243
+ const tsRaw = r.submittedAt || r.createdAt;
4244
+ const ts = tsRaw ? new Date(tsRaw).getTime() : 0;
4245
+ if (fromTime && !Number.isNaN(fromTime) && ts < fromTime) return false;
4246
+ if (toTime && !Number.isNaN(toTime) && ts > toTime) return false;
4247
+ if (filterLocale && r.locale !== filterLocale) return false;
4248
+ return true;
4249
+ });
4250
+ const totalResponses = responses.length;
4251
+ const durations = responses.map((r) => Number(r.durationSeconds || 0)).filter((d) => d > 0).sort((a, b) => a - b);
4252
+ const avgDurationSeconds = durations.length > 0 ? Math.round(durations.reduce((acc, d) => acc + d, 0) / durations.length) : 0;
4253
+ const medianDurationSeconds = durations.length > 0 ? durations[Math.floor(durations.length / 2)] : 0;
4254
+ const localeCounts = {};
4255
+ const dailyCounts = {};
4256
+ let lastSubmittedAt = null;
4257
+ for (const r of responses) {
4258
+ const loc = String(r.locale || "tr");
4259
+ localeCounts[loc] = (localeCounts[loc] || 0) + 1;
4260
+ const tsRaw = r.submittedAt || r.createdAt;
4261
+ if (tsRaw) {
4262
+ const iso = new Date(tsRaw).toISOString();
4263
+ const dayKey = iso.slice(0, 10);
4264
+ dailyCounts[dayKey] = (dailyCounts[dayKey] || 0) + 1;
4265
+ if (!lastSubmittedAt || iso > lastSubmittedAt) {
4266
+ lastSubmittedAt = iso;
4267
+ }
4268
+ }
4269
+ }
4270
+ const localeBreakdown = Object.entries(localeCounts).map(([locale, count]) => ({
4271
+ locale,
4272
+ count,
4273
+ percentage: totalResponses > 0 ? Math.round(count / totalResponses * 1e3) / 10 : 0
4274
+ })).sort((a, b) => b.count - a.count);
4275
+ const dailyTrend = Object.entries(dailyCounts).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
4276
+ let promoters = 0;
4277
+ let passives = 0;
4278
+ let detractors = 0;
4279
+ for (const r of responses) {
4280
+ if (typeof r.npsValue === "number") {
4281
+ if (r.npsValue >= 9) promoters += 1;
4282
+ else if (r.npsValue >= 7) passives += 1;
4283
+ else detractors += 1;
4284
+ }
4285
+ }
4286
+ const totalNpsResponses = promoters + passives + detractors;
4287
+ const promotersPct = totalNpsResponses > 0 ? Math.round(promoters / totalNpsResponses * 1e3) / 10 : 0;
4288
+ const passivesPct = totalNpsResponses > 0 ? Math.round(passives / totalNpsResponses * 1e3) / 10 : 0;
4289
+ const detractorsPct = totalNpsResponses > 0 ? Math.round(detractors / totalNpsResponses * 1e3) / 10 : 0;
4290
+ const npsScore = totalNpsResponses > 0 ? Math.round((promoters - detractors) / totalNpsResponses * 100) : 0;
4291
+ const questionStats = (survey.questions || []).filter((q) => q && q.type !== "statement").map((q) => {
4292
+ let answeredCount = 0;
4293
+ const baseInfo = {
4294
+ key: q.key,
4295
+ type: q.type,
4296
+ title: q.title,
4297
+ required: Boolean(q.required),
4298
+ hasConditions: Boolean(q.conditions?.rules?.length)
4299
+ };
4300
+ if (q.type === "single_choice" || q.type === "multiple_choice" || q.type === "dropdown" || q.type === "image_choice") {
4301
+ const opts = Array.isArray(q.options) ? q.options : [];
4302
+ const countsMap = {};
4303
+ opts.forEach((o) => {
4304
+ countsMap[o.id] = 0;
4305
+ });
4306
+ let otherCount = 0;
4307
+ const otherSamples = [];
4308
+ for (const r of responses) {
4309
+ const v = r.answers?.[q.key];
4310
+ if (isEmptyFieldValue(v)) continue;
4311
+ answeredCount += 1;
4312
+ const selectedArr = Array.isArray(v) ? v.map(String) : [String(v)];
4313
+ for (const item of selectedArr) {
4314
+ if (item === "__other__") {
4315
+ otherCount += 1;
4316
+ const txt = String(r.otherTexts?.[q.key] || "").trim();
4317
+ if (txt && otherSamples.length < 30) {
4318
+ otherSamples.push({
4319
+ text: txt,
4320
+ locale: r.locale || "tr",
4321
+ submittedAt: r.submittedAt || r.createdAt || ""
4322
+ });
4323
+ }
4324
+ } else {
4325
+ countsMap[item] = (countsMap[item] || 0) + 1;
4326
+ }
4327
+ }
4328
+ }
4329
+ const optionsBreakdown = opts.map((o) => {
4330
+ const count = countsMap[o.id] || 0;
4331
+ return {
4332
+ id: o.id,
4333
+ labels: o.labels,
4334
+ image: o.image || null,
4335
+ count,
4336
+ percentage: answeredCount > 0 ? Math.round(count / answeredCount * 1e3) / 10 : 0
4337
+ };
4338
+ });
4339
+ if (q.allowOther || otherCount > 0) {
4340
+ optionsBreakdown.push({
4341
+ id: "__other__",
4342
+ labels: typeof q.otherLabel === "object" && q.otherLabel ? q.otherLabel : { tr: "Diğer", en: "Other" },
4343
+ image: null,
4344
+ count: otherCount,
4345
+ percentage: answeredCount > 0 ? Math.round(otherCount / answeredCount * 1e3) / 10 : 0
4346
+ });
4347
+ }
4348
+ return {
4349
+ ...baseInfo,
4350
+ answeredCount,
4351
+ optionsBreakdown,
4352
+ otherSamples
4353
+ };
4354
+ }
4355
+ if (q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") {
4356
+ const minVal = q.type === "nps" ? 0 : q.type === "likert_scale" ? q.scaleMin ?? 1 : 1;
4357
+ const maxVal = q.type === "nps" ? 10 : q.type === "likert_scale" ? q.scaleMax ?? 5 : q.maxStars ?? 5;
4358
+ const distMap = {};
4359
+ for (let i = minVal; i <= maxVal; i += 1) distMap[i] = 0;
4360
+ let sum = 0;
4361
+ let qPromoters = 0;
4362
+ let qPassives = 0;
4363
+ let qDetractors = 0;
4364
+ for (const r of responses) {
4365
+ const rawV = r.answers?.[q.key];
4366
+ if (isEmptyFieldValue(rawV)) continue;
4367
+ const n = Number(rawV);
4368
+ if (Number.isNaN(n)) continue;
4369
+ answeredCount += 1;
4370
+ sum += n;
4371
+ distMap[n] = (distMap[n] || 0) + 1;
4372
+ if (q.type === "nps") {
4373
+ if (n >= 9) qPromoters += 1;
4374
+ else if (n >= 7) qPassives += 1;
4375
+ else qDetractors += 1;
4376
+ }
4377
+ }
4378
+ const distribution = Object.keys(distMap).map(Number).sort((a, b) => a - b).map((value) => ({
4379
+ value,
4380
+ count: distMap[value] || 0,
4381
+ percentage: answeredCount > 0 ? Math.round((distMap[value] || 0) / answeredCount * 1e3) / 10 : 0
4382
+ }));
4383
+ return {
4384
+ ...baseInfo,
4385
+ answeredCount,
4386
+ min: minVal,
4387
+ max: maxVal,
4388
+ lowLabel: q.lowLabel,
4389
+ highLabel: q.highLabel,
4390
+ average: answeredCount > 0 ? Math.round(sum / answeredCount * 100) / 100 : 0,
4391
+ distribution,
4392
+ npsBreakdown: q.type === "nps" ? {
4393
+ score: answeredCount > 0 ? Math.round((qPromoters - qDetractors) / answeredCount * 100) : 0,
4394
+ promoters: qPromoters,
4395
+ passives: qPassives,
4396
+ detractors: qDetractors,
4397
+ promotersPct: answeredCount > 0 ? Math.round(qPromoters / answeredCount * 1e3) / 10 : 0,
4398
+ passivesPct: answeredCount > 0 ? Math.round(qPassives / answeredCount * 1e3) / 10 : 0,
4399
+ detractorsPct: answeredCount > 0 ? Math.round(qDetractors / answeredCount * 1e3) / 10 : 0
4400
+ } : void 0
4401
+ };
4402
+ }
4403
+ if (q.type === "matrix_single") {
4404
+ const mRows = Array.isArray(q.matrixRows) ? q.matrixRows : [];
4405
+ const mCols = Array.isArray(q.matrixColumns) ? q.matrixColumns : [];
4406
+ const matrixData = {};
4407
+ const rowTotals = {};
4408
+ for (const rItem of mRows) {
4409
+ matrixData[rItem.id] = {};
4410
+ rowTotals[rItem.id] = 0;
4411
+ for (const cItem of mCols) {
4412
+ matrixData[rItem.id][cItem.id] = 0;
4413
+ }
4414
+ }
4415
+ for (const r of responses) {
4416
+ const valObj = r.answers?.[q.key];
4417
+ if (!valObj || typeof valObj !== "object" || Array.isArray(valObj)) continue;
4418
+ let anyRow = false;
4419
+ for (const rItem of mRows) {
4420
+ const chosenCol = valObj[rItem.id];
4421
+ if (!isEmptyFieldValue(chosenCol)) {
4422
+ anyRow = true;
4423
+ rowTotals[rItem.id] = (rowTotals[rItem.id] || 0) + 1;
4424
+ if (matrixData[rItem.id]) {
4425
+ matrixData[rItem.id][chosenCol] = (matrixData[rItem.id][chosenCol] || 0) + 1;
4426
+ }
4427
+ }
4428
+ }
4429
+ if (anyRow) answeredCount += 1;
4430
+ }
4431
+ const rowsBreakdown = mRows.map((rItem) => {
4432
+ const rTot = rowTotals[rItem.id] || 0;
4433
+ return {
4434
+ rowId: rItem.id,
4435
+ labels: rItem.labels,
4436
+ total: rTot,
4437
+ columns: mCols.map((cItem) => {
4438
+ const cnt = matrixData[rItem.id]?.[cItem.id] || 0;
4439
+ return {
4440
+ colId: cItem.id,
4441
+ labels: cItem.labels,
4442
+ count: cnt,
4443
+ percentage: rTot > 0 ? Math.round(cnt / rTot * 1e3) / 10 : 0
4444
+ };
4445
+ })
4446
+ };
4447
+ });
4448
+ return {
4449
+ ...baseInfo,
4450
+ answeredCount,
4451
+ rowsBreakdown
4452
+ };
4453
+ }
4454
+ if (q.type === "ranking") {
4455
+ const opts = Array.isArray(q.options) ? q.options : [];
4456
+ const nOpts = opts.length;
4457
+ const rankSumMap = {};
4458
+ const bordaSumMap = {};
4459
+ const firstPlaceMap = {};
4460
+ const itemCountMap = {};
4461
+ opts.forEach((o) => {
4462
+ rankSumMap[o.id] = 0;
4463
+ bordaSumMap[o.id] = 0;
4464
+ firstPlaceMap[o.id] = 0;
4465
+ itemCountMap[o.id] = 0;
4466
+ });
4467
+ for (const r of responses) {
4468
+ const arr = r.answers?.[q.key];
4469
+ if (!Array.isArray(arr) || arr.length === 0) continue;
4470
+ answeredCount += 1;
4471
+ arr.forEach((optId, idx) => {
4472
+ if (rankSumMap[optId] !== void 0) {
4473
+ rankSumMap[optId] += idx + 1;
4474
+ bordaSumMap[optId] += Math.max(1, nOpts - idx);
4475
+ itemCountMap[optId] += 1;
4476
+ if (idx === 0) firstPlaceMap[optId] += 1;
4477
+ }
4478
+ });
4479
+ }
4480
+ const maxPossibleBorda = answeredCount * nOpts;
4481
+ const rankingBreakdown = opts.map((o) => {
4482
+ const cnt = itemCountMap[o.id] || 0;
4483
+ const avgRank = cnt > 0 ? Math.round(rankSumMap[o.id] / cnt * 100) / 100 : nOpts;
4484
+ const bordaPoints = bordaSumMap[o.id] || 0;
4485
+ const firstPlaces = firstPlaceMap[o.id] || 0;
4486
+ return {
4487
+ id: o.id,
4488
+ labels: o.labels,
4489
+ averageRank: avgRank,
4490
+ bordaPoints,
4491
+ scorePercentage: maxPossibleBorda > 0 ? Math.round(bordaPoints / maxPossibleBorda * 1e3) / 10 : 0,
4492
+ firstPlaceCount: firstPlaces,
4493
+ firstPlacePercentage: answeredCount > 0 ? Math.round(firstPlaces / answeredCount * 1e3) / 10 : 0
4494
+ };
4495
+ }).sort((a, b) => a.averageRank - b.averageRank);
4496
+ return {
4497
+ ...baseInfo,
4498
+ answeredCount,
4499
+ rankingBreakdown
4500
+ };
4501
+ }
4502
+ if (q.type === "consent") {
4503
+ let acceptedCount = 0;
4504
+ for (const r of responses) {
4505
+ const v = r.answers?.[q.key];
4506
+ if (v === true || v === "true" || v === 1) {
4507
+ answeredCount += 1;
4508
+ acceptedCount += 1;
4509
+ }
4510
+ }
4511
+ return {
4512
+ ...baseInfo,
4513
+ answeredCount,
4514
+ acceptedCount,
4515
+ acceptedPercentage: totalResponses > 0 ? Math.round(acceptedCount / totalResponses * 1e3) / 10 : 0
4516
+ };
4517
+ }
4518
+ const textResponses = [];
4519
+ for (const r of responses) {
4520
+ const v = r.answers?.[q.key];
4521
+ if (typeof v === "string" && v.trim()) {
4522
+ answeredCount += 1;
4523
+ if (textResponses.length < 100) {
4524
+ textResponses.push({
4525
+ id: r.id || r.documentId,
4526
+ text: v.trim(),
4527
+ locale: r.locale || "tr",
4528
+ submittedAt: r.submittedAt || r.createdAt || "",
4529
+ npsValue: r.npsValue ?? null
4530
+ });
4531
+ }
4532
+ }
4533
+ }
4534
+ return {
4535
+ ...baseInfo,
4536
+ answeredCount,
4537
+ textResponses
4538
+ };
4539
+ });
4540
+ return {
4541
+ summary: {
4542
+ totalResponses,
4543
+ unfilteredTotalResponses: (rawResponses || []).length,
4544
+ quotaLimit: survey.quotaLimit || null,
4545
+ quotaPercentage: survey.quotaLimit && survey.quotaLimit > 0 ? Math.min(100, Math.round((rawResponses || []).length / survey.quotaLimit * 1e3) / 10) : null,
4546
+ avgDurationSeconds,
4547
+ medianDurationSeconds,
4548
+ lastSubmittedAt,
4549
+ localeBreakdown,
4550
+ dailyTrend,
4551
+ nps: {
4552
+ hasNps: totalNpsResponses > 0,
4553
+ score: npsScore,
4554
+ promoters,
4555
+ passives,
4556
+ detractors,
4557
+ promotersPct,
4558
+ passivesPct,
4559
+ detractorsPct,
4560
+ totalNpsResponses
4561
+ }
4562
+ },
4563
+ questionStats
4564
+ };
4565
+ }
4566
+ function computePublicSurveyResults(survey, rawResponses) {
4567
+ const full = computeSurveyAnalytics(survey, rawResponses);
4568
+ return {
4569
+ totalResponses: full.summary.totalResponses,
4570
+ questions: full.questionStats.filter((qs) => qs.type !== "short_text" && qs.type !== "long_text" && qs.type !== "consent").map((qs) => ({
4571
+ key: qs.key,
4572
+ type: qs.type,
4573
+ title: qs.title,
4574
+ answeredCount: qs.answeredCount,
4575
+ optionsBreakdown: qs.optionsBreakdown,
4576
+ average: qs.average,
4577
+ distribution: qs.distribution,
4578
+ npsBreakdown: qs.npsBreakdown,
4579
+ rankingBreakdown: qs.rankingBreakdown
4580
+ }))
4581
+ };
4582
+ }
4583
+ function escapeCsvCell(val) {
4584
+ const str = val === null || val === void 0 ? "" : String(val);
4585
+ if (/[",\r\n]/.test(str)) {
4586
+ return `"${str.replace(/"/g, '""')}"`;
4587
+ }
4588
+ return str;
4589
+ }
4590
+ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "tr") {
4591
+ const activeQuestions = (survey.questions || []).filter((q) => q && q.type !== "statement");
4592
+ const headers = [
4593
+ "Response ID",
4594
+ "Submitted At",
4595
+ "Locale",
4596
+ "Duration (s)",
4597
+ "NPS Value",
4598
+ "NPS Category"
4599
+ ];
4600
+ for (const q of activeQuestions) {
4601
+ const qTitle = resolveLocalizedText(q.title, locale, q.key);
4602
+ if (q.type === "matrix_single" && Array.isArray(q.matrixRows)) {
4603
+ for (const mRow of q.matrixRows) {
4604
+ const rTitle = resolveLocalizedText(mRow.labels, locale, mRow.id);
4605
+ headers.push(`${qTitle} [${rTitle}]`);
4606
+ }
4607
+ } else {
4608
+ headers.push(`${qTitle} (${q.key})`);
4609
+ if (q.allowOther) {
4610
+ headers.push(`${qTitle} [Other Text]`);
4611
+ }
4612
+ }
4613
+ }
4614
+ const lines = [headers.map(escapeCsvCell).join(",")];
4615
+ for (const r of rawResponses || []) {
4616
+ const rowCells = [
4617
+ String(r.id || r.documentId || ""),
4618
+ String(r.submittedAt || r.createdAt || ""),
4619
+ String(r.locale || ""),
4620
+ String(r.durationSeconds ?? ""),
4621
+ r.npsValue !== null && r.npsValue !== void 0 ? String(r.npsValue) : "",
4622
+ String(r.npsCategory || "")
4623
+ ];
4624
+ for (const q of activeQuestions) {
4625
+ const ans = r.answers?.[q.key];
4626
+ if (q.type === "matrix_single" && Array.isArray(q.matrixRows)) {
4627
+ const mCols = Array.isArray(q.matrixColumns) ? q.matrixColumns : [];
4628
+ for (const mRow of q.matrixRows) {
4629
+ const chosenColId = ans && typeof ans === "object" ? ans[mRow.id] : "";
4630
+ const foundCol = mCols.find((c) => c.id === chosenColId);
4631
+ rowCells.push(
4632
+ foundCol ? resolveLocalizedText(foundCol.labels, locale, chosenColId) : String(chosenColId || "")
4633
+ );
4634
+ }
4635
+ } else if (Array.isArray(q.options) && q.options.length > 0) {
4636
+ if (Array.isArray(ans)) {
4637
+ const mapped = ans.map((optId) => {
4638
+ if (optId === "__other__") return locale === "tr" ? "Diğer" : "Other";
4639
+ const found = q.options.find((o) => o.id === optId);
4640
+ return found ? resolveLocalizedText(found.labels, locale, optId) : optId;
4641
+ });
4642
+ rowCells.push(mapped.join(q.type === "ranking" ? " > " : "; "));
4643
+ } else if (ans !== void 0 && ans !== null && ans !== "") {
4644
+ const strAns = String(ans);
4645
+ if (strAns === "__other__") {
4646
+ rowCells.push(locale === "tr" ? "Diğer" : "Other");
4647
+ } else {
4648
+ const found = q.options.find((o) => o.id === strAns);
4649
+ rowCells.push(found ? resolveLocalizedText(found.labels, locale, strAns) : strAns);
4650
+ }
4651
+ } else {
4652
+ rowCells.push("");
4653
+ }
4654
+ if (q.allowOther) {
4655
+ rowCells.push(String(r.otherTexts?.[q.key] || ""));
4656
+ }
4657
+ } else {
4658
+ rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
4659
+ if (q.allowOther) {
4660
+ rowCells.push(String(r.otherTexts?.[q.key] || ""));
4661
+ }
4662
+ }
4663
+ }
4664
+ lines.push(rowCells.map(escapeCsvCell).join(","));
4665
+ }
4666
+ return `\uFEFF${lines.join("\r\n")}`;
4667
+ }
4668
+ const SURVEY_UID = "plugin::content-input.ci-survey";
4669
+ const SURVEY_RESPONSE_UID = "plugin::content-input.ci-survey-response";
4670
+ let activeSeedPromise = null;
4671
+ function slugifyIdentifier(text) {
4672
+ const map = {
4673
+ ç: "c",
4674
+ Ç: "c",
4675
+ ğ: "g",
4676
+ Ğ: "g",
4677
+ ı: "i",
4678
+ İ: "i",
4679
+ ö: "o",
4680
+ Ö: "o",
4681
+ ş: "s",
4682
+ Ş: "s",
4683
+ ü: "u",
4684
+ Ü: "u"
4685
+ };
4686
+ return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
4687
+ }
4688
+ function getEnvRecaptchaPublicKey() {
4689
+ return (process.env.MIX_RECAPTCHA_PUBLIC_KEY || process.env.RECAPTCHA_PUBLIC_KEY || process.env.NUXT_PUBLIC_RECAPTCHA_SITE_KEY || "").trim();
4690
+ }
4691
+ function getEnvRecaptchaPrivateKey() {
4692
+ return (process.env.RECAPTCHA_PRIVATE_KEY || process.env.RECAPTCHA_SECRET_KEY || "").trim();
4693
+ }
4694
+ function getEnvStatusSummary() {
4695
+ return {
4696
+ hasEnvRecaptchaPublicKey: Boolean(getEnvRecaptchaPublicKey()),
4697
+ hasEnvRecaptchaPrivateKey: Boolean(getEnvRecaptchaPrivateKey()),
4698
+ envMailDriver: process.env.MAIL_DRIVER || "auto",
4699
+ hasMailtrapToken: Boolean(process.env.MAILTRAP_API_TOKEN || process.env.MAILTRAP_TOKEN),
4700
+ hasMailgunSecret: Boolean(process.env.MAILGUN_SECRET || process.env.MAILGUN_API_KEY),
4701
+ hasSmtpHost: Boolean(process.env.MAIL_HOST)
4702
+ };
4703
+ }
4704
+ function evaluateLifecycleState(survey, responseCount) {
4705
+ if (!survey) return { isOpen: false, closedReason: "closed" };
4706
+ if (survey.status === "draft") return { isOpen: false, closedReason: "draft" };
4707
+ if (survey.status === "closed") return { isOpen: false, closedReason: "closed" };
4708
+ const now = Date.now();
4709
+ if (survey.startsAt) {
4710
+ const startTs = new Date(survey.startsAt).getTime();
4711
+ if (!Number.isNaN(startTs) && now < startTs) {
4712
+ return { isOpen: false, closedReason: "not_started" };
4713
+ }
4714
+ }
4715
+ if (survey.endsAt) {
4716
+ const endTs = new Date(survey.endsAt).getTime();
4717
+ if (!Number.isNaN(endTs) && now > endTs) {
4718
+ return { isOpen: false, closedReason: "expired" };
4719
+ }
4720
+ }
4721
+ if (survey.quotaLimit && Number(survey.quotaLimit) > 0 && responseCount >= Number(survey.quotaLimit)) {
4722
+ return { isOpen: false, closedReason: "quota_reached" };
4723
+ }
4724
+ return { isOpen: true, closedReason: null };
4725
+ }
4726
+ function formatSurveyForAdmin(entry, extra = {}) {
4727
+ if (!entry) return null;
4728
+ return {
4729
+ ...entry,
4730
+ _id: entry.documentId || String(entry.id),
4731
+ envStatus: getEnvStatusSummary(),
4732
+ ...extra
4733
+ };
4734
+ }
4735
+ function sanitizeSurveyForPublic(entry, extra = {}) {
4736
+ if (!entry) return null;
4737
+ const { recaptchaSecretKey, mailConfig, ...safeRest } = entry;
4738
+ const publicKey = entry.useRecaptcha === true ? String(entry.recaptchaSiteKey || getEnvRecaptchaPublicKey() || "").trim() : "";
4739
+ const responseCount = extra.responseCount ?? 0;
4740
+ const lifecycle = evaluateLifecycleState(entry, responseCount);
4741
+ return {
4742
+ ...safeRest,
4743
+ _id: entry.documentId || String(entry.id),
4744
+ recaptchaPublicKey: publicKey,
4745
+ recaptchaEnabled: Boolean(entry.useRecaptcha === true && publicKey),
4746
+ responseCount,
4747
+ isOpen: lifecycle.isOpen,
4748
+ closedReason: lifecycle.closedReason,
4749
+ alreadyVoted: Boolean(extra.alreadyVoted),
4750
+ publicResults: extra.publicResults || null
4751
+ };
4752
+ }
4753
+ const ciSurveyService = ({ strapi }) => ({
4754
+ async ensureSeeded(forceReseedResponses = false) {
4755
+ if (activeSeedPromise && !forceReseedResponses) {
4756
+ return activeSeedPromise;
4757
+ }
4758
+ const runSeed = async () => {
4759
+ let existingSurveys = [];
4760
+ try {
4761
+ existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
4762
+ } catch {
4763
+ return;
4764
+ }
4765
+ const bySlug = {};
4766
+ for (const s of existingSurveys) {
4767
+ if (s?.slug) bySlug[s.slug] = s;
4768
+ }
4769
+ for (const seed of DEFAULT_SEED_SURVEYS) {
4770
+ if (!bySlug[seed.slug]) {
4771
+ const created = await strapi.db.query(SURVEY_UID).create({
4772
+ data: seed
4773
+ });
4774
+ bySlug[seed.slug] = created;
4775
+ }
4776
+ }
4777
+ const totalResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
4778
+ if (totalResponses === 0 || forceReseedResponses) {
4779
+ if (forceReseedResponses) {
4780
+ const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
4781
+ for (const slug of demoSlugs) {
4782
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
4783
+ where: { surveySlug: slug }
4784
+ });
4785
+ }
4786
+ }
4787
+ const rows = generateSeedSurveyResponses(bySlug);
4788
+ const batchSize = 25;
4789
+ for (let i = 0; i < rows.length; i += batchSize) {
4790
+ const chunk = rows.slice(i, i + batchSize);
4791
+ await Promise.all(
4792
+ chunk.map(
4793
+ (row) => strapi.db.query(SURVEY_RESPONSE_UID).create({
4794
+ data: row
4795
+ })
4796
+ )
4797
+ );
4798
+ }
4799
+ }
4800
+ };
4801
+ activeSeedPromise = runSeed().finally(() => {
4802
+ activeSeedPromise = null;
4803
+ });
4804
+ return activeSeedPromise;
4805
+ },
4806
+ async reseedSampleData() {
4807
+ await this.ensureSeeded(true);
4808
+ try {
4809
+ await strapi.plugin("content-input").service("ci-form").ensureSampleSubmissions(true);
4810
+ } catch {
4811
+ }
4812
+ const totalSurveyResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
4813
+ return {
4814
+ ok: true,
4815
+ totalSurveyResponses
4816
+ };
4817
+ },
4818
+ async findRawByIdOrSlug(idOrSlug) {
4819
+ await this.ensureSeeded(false);
4820
+ const raw = String(idOrSlug || "").trim();
4821
+ if (!raw) return null;
4822
+ let found = null;
4823
+ const numericId = Number(raw);
4824
+ if (!Number.isNaN(numericId) && String(numericId) === raw) {
4825
+ found = await strapi.db.query(SURVEY_UID).findOne({ where: { id: numericId } });
4826
+ }
4827
+ if (!found) {
4828
+ found = await strapi.db.query(SURVEY_UID).findOne({ where: { documentId: raw } });
4829
+ }
4830
+ if (!found) {
4831
+ found = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: raw } });
4832
+ }
4833
+ return found;
4834
+ },
4835
+ async getResponsesForSurvey(survey) {
4836
+ if (!survey) return [];
4837
+ const docOrId = String(survey.documentId || survey.id);
4838
+ const rows = await strapi.db.query(SURVEY_RESPONSE_UID).findMany({
4839
+ where: {
4840
+ $or: [
4841
+ { surveySlug: survey.slug },
4842
+ { surveyId: docOrId },
4843
+ { surveyId: String(survey.id) }
4844
+ ]
4845
+ },
4846
+ orderBy: { id: "desc" }
4847
+ });
4848
+ return (rows || []).sort((a, b) => {
4849
+ const ta = new Date(a.submittedAt || a.createdAt || 0).getTime();
4850
+ const tb = new Date(b.submittedAt || b.createdAt || 0).getTime();
4851
+ return tb - ta;
4852
+ });
4853
+ },
4854
+ async findAllAdmin() {
4855
+ await this.ensureSeeded(false);
4856
+ const entries = await strapi.db.query(SURVEY_UID).findMany({
4857
+ orderBy: { id: "asc" }
4858
+ }) || [];
4859
+ const allResponses = await strapi.db.query(SURVEY_RESPONSE_UID).findMany({
4860
+ select: ["id", "surveyId", "surveySlug", "npsValue", "submittedAt", "createdAt"]
4861
+ }) || [];
4862
+ return entries.map((entry) => {
4863
+ const docId = String(entry.documentId || entry.id);
4864
+ const matching = allResponses.filter(
4865
+ (r) => r.surveySlug === entry.slug || r.surveyId === docId || r.surveyId === String(entry.id)
4866
+ );
4867
+ let prom = 0;
4868
+ let det = 0;
4869
+ let npsCount = 0;
4870
+ let latestAt = null;
4871
+ for (const r of matching) {
4872
+ if (typeof r.npsValue === "number") {
4873
+ npsCount += 1;
4874
+ if (r.npsValue >= 9) prom += 1;
4875
+ else if (r.npsValue <= 6) det += 1;
4876
+ }
4877
+ const ts = r.submittedAt || r.createdAt;
4878
+ if (ts && (!latestAt || ts > latestAt)) latestAt = ts;
4879
+ }
4880
+ const npsScore = npsCount > 0 ? Math.round((prom - det) / npsCount * 100) : null;
4881
+ return formatSurveyForAdmin(entry, {
4882
+ responseCount: matching.length,
4883
+ npsScore,
4884
+ lastSubmittedAt: latestAt
4885
+ });
4886
+ });
4887
+ },
4888
+ async findOneAdmin(idOrSlug) {
4889
+ const found = await this.findRawByIdOrSlug(idOrSlug);
4890
+ if (!found) return null;
4891
+ const responses = await this.getResponsesForSurvey(found);
4892
+ return formatSurveyForAdmin(found, {
4893
+ responseCount: responses.length
4894
+ });
4895
+ },
4896
+ async findAllPublic() {
4897
+ await this.ensureSeeded(false);
4898
+ const entries = await strapi.db.query(SURVEY_UID).findMany({
4899
+ where: { status: "published" },
4900
+ orderBy: { id: "asc" }
4901
+ }) || [];
4902
+ return entries.map((entry) => sanitizeSurveyForPublic(entry));
4903
+ },
4904
+ async findOnePublic(idOrSlug, meta = {}) {
4905
+ const found = await this.findRawByIdOrSlug(idOrSlug);
4906
+ if (!found) return null;
4907
+ const responses = await this.getResponsesForSurvey(found);
4908
+ let alreadyVoted = false;
4909
+ if (found.submissionPolicy === "one_per_voter") {
4910
+ const vHash = computeVoterHash(
4911
+ found.slug,
4912
+ meta.ip || "",
4913
+ meta.userAgent || "",
4914
+ meta.voterToken
4915
+ );
4916
+ const ipHashOnly = meta.voterToken ? computeVoterHash(found.slug, meta.ip || "", meta.userAgent || "") : vHash;
4917
+ alreadyVoted = responses.some(
4918
+ (r) => r.voterHash && (r.voterHash === vHash || r.voterHash === ipHashOnly)
4919
+ );
4920
+ } else if (found.submissionPolicy === "one_per_token" && meta.voterToken) {
4921
+ alreadyVoted = responses.some((r) => r.respondentToken === meta.voterToken);
4922
+ }
4923
+ const shouldIncludeResults = found.showPublicResults === "always" || found.showPublicResults === "after_vote" && alreadyVoted;
4924
+ const publicResults = shouldIncludeResults ? computePublicSurveyResults(found, responses) : null;
4925
+ return sanitizeSurveyForPublic(found, {
4926
+ responseCount: responses.length,
4927
+ alreadyVoted,
4928
+ publicResults
4929
+ });
4930
+ },
4931
+ async save(payload) {
4932
+ const cleanTitle = String(payload.title || "Yeni Anket").trim();
4933
+ const cleanSlug = String(
4934
+ payload.slug || slugifyIdentifier(cleanTitle) || `survey_${Date.now()}`
4935
+ ).trim();
4936
+ let existing = null;
4937
+ if (payload.id) {
4938
+ const rawId = String(payload.id).trim();
4939
+ const numId = Number(rawId);
4940
+ if (!Number.isNaN(numId) && String(numId) === rawId) {
4941
+ existing = await strapi.db.query(SURVEY_UID).findOne({ where: { id: numId } });
4942
+ } else {
4943
+ existing = await strapi.db.query(SURVEY_UID).findOne({ where: { documentId: rawId } });
4944
+ }
4945
+ }
4946
+ if (!existing && cleanSlug) {
4947
+ existing = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: cleanSlug } });
4948
+ }
4949
+ const recordData = {
4950
+ title: cleanTitle,
4951
+ titleI18n: payload.titleI18n ?? existing?.titleI18n ?? { tr: cleanTitle, en: cleanTitle },
4952
+ slug: cleanSlug,
4953
+ description: payload.description ?? existing?.description ?? { tr: "", en: "" },
4954
+ status: payload.status ?? existing?.status ?? "published",
4955
+ displayMode: payload.displayMode ?? existing?.displayMode ?? "single_page",
4956
+ startsAt: payload.startsAt !== void 0 ? payload.startsAt || null : existing?.startsAt || null,
4957
+ endsAt: payload.endsAt !== void 0 ? payload.endsAt || null : existing?.endsAt || null,
4958
+ quotaLimit: payload.quotaLimit !== void 0 ? payload.quotaLimit ? Number(payload.quotaLimit) : null : existing?.quotaLimit ?? null,
4959
+ submissionPolicy: payload.submissionPolicy ?? existing?.submissionPolicy ?? "one_per_voter",
4960
+ anonymizeIp: payload.anonymizeIp !== void 0 ? Boolean(payload.anonymizeIp) : existing?.anonymizeIp ?? true,
4961
+ showPublicResults: payload.showPublicResults ?? existing?.showPublicResults ?? "after_vote",
4962
+ allowBackNavigation: payload.allowBackNavigation !== void 0 ? Boolean(payload.allowBackNavigation) : existing?.allowBackNavigation ?? true,
4963
+ showProgressBar: payload.showProgressBar !== void 0 ? Boolean(payload.showProgressBar) : existing?.showProgressBar ?? true,
4964
+ useRecaptcha: payload.useRecaptcha !== void 0 ? Boolean(payload.useRecaptcha) : existing?.useRecaptcha ?? false,
4965
+ recaptchaSiteKey: payload.recaptchaSiteKey !== void 0 ? String(payload.recaptchaSiteKey) : existing?.recaptchaSiteKey || "",
4966
+ recaptchaSecretKey: payload.recaptchaSecretKey !== void 0 ? String(payload.recaptchaSecretKey) : existing?.recaptchaSecretKey || "",
4967
+ mailConfig: payload.mailConfig ?? existing?.mailConfig ?? { driver: "env" },
4968
+ steps: Array.isArray(payload.steps) ? payload.steps : existing?.steps || [],
4969
+ questions: Array.isArray(payload.questions) ? payload.questions : existing?.questions || [],
4970
+ settings: payload.settings ?? existing?.settings ?? {},
4971
+ version: existing ? Number(existing.version || 1) + 1 : 1
4972
+ };
4973
+ if (existing) {
4974
+ const updated = await strapi.db.query(SURVEY_UID).update({
4975
+ where: { id: existing.id },
4976
+ data: recordData
4977
+ });
4978
+ const responses = await this.getResponsesForSurvey(updated);
4979
+ return formatSurveyForAdmin(updated, { responseCount: responses.length });
4980
+ }
4981
+ const created = await strapi.db.query(SURVEY_UID).create({
4982
+ data: recordData
4983
+ });
4984
+ return formatSurveyForAdmin(created, { responseCount: 0 });
4985
+ },
4986
+ async remove(idOrSlug) {
4987
+ const found = await this.findRawByIdOrSlug(idOrSlug);
4988
+ if (found) {
4989
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
4990
+ where: { surveySlug: found.slug }
4991
+ });
4992
+ await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
4993
+ }
4994
+ return { success: true };
4995
+ },
4996
+ async submitSurvey(idOrSlug, rawBody, meta = {}) {
4997
+ const survey = await this.findRawByIdOrSlug(idOrSlug);
4998
+ if (!survey) {
4999
+ return {
5000
+ ok: false,
5001
+ status: 404,
5002
+ message: "Survey not found"
5003
+ };
5004
+ }
5005
+ const body = rawBody && typeof rawBody === "object" ? rawBody : {};
5006
+ const rawLocale = String(body._locale || meta.locale || "tr").trim().toLowerCase();
5007
+ const locale = rawLocale ? rawLocale.split(/[,;]/)[0].trim() : "tr";
5008
+ const isTr = locale.startsWith("tr");
5009
+ if (body._hp && String(body._hp).trim() !== "") {
5010
+ return {
5011
+ ok: false,
5012
+ status: 400,
5013
+ message: isTr ? "Geçersiz istek." : "Invalid request."
5014
+ };
5015
+ }
5016
+ const existingResponses = await this.getResponsesForSurvey(survey);
5017
+ const lifecycle = evaluateLifecycleState(survey, existingResponses.length);
5018
+ if (!lifecycle.isOpen) {
5019
+ const defaultClosedMsg = lifecycle.closedReason === "quota_reached" ? isTr ? "Bu anket maksimum katılımcı kotasına ulaşmıştır." : "This survey has reached its response quota." : isTr ? "Bu anket şu anda yanıtlara kapalıdır." : "This survey is currently closed.";
5020
+ return {
5021
+ ok: false,
5022
+ status: 403,
5023
+ closedReason: lifecycle.closedReason,
5024
+ message: resolveLocalizedText(
5025
+ survey.settings?.closedMessage,
5026
+ locale,
5027
+ defaultClosedMsg
5028
+ )
5029
+ };
5030
+ }
5031
+ const voterToken = String(body.voterToken || body.respondentToken || "").trim();
5032
+ const voterHash = computeVoterHash(
5033
+ survey.slug,
5034
+ meta.ip || "",
5035
+ meta.userAgent || "",
5036
+ voterToken || void 0
5037
+ );
5038
+ const ipUaHash = computeVoterHash(survey.slug, meta.ip || "", meta.userAgent || "");
5039
+ if (survey.submissionPolicy === "one_per_voter") {
5040
+ const duplicate = existingResponses.some(
5041
+ (r) => r.voterHash && (r.voterHash === voterHash || r.voterHash === ipUaHash)
5042
+ );
5043
+ if (duplicate) {
5044
+ const dupMsg = resolveLocalizedText(
5045
+ survey.settings?.alreadyVotedMessage,
5046
+ locale,
5047
+ isTr ? "Bu ankete daha önce katıldınız. İlginiz için teşekkür ederiz." : "You have already participated in this survey. Thank you!"
5048
+ );
5049
+ return {
5050
+ ok: false,
5051
+ status: 409,
5052
+ alreadyVoted: true,
5053
+ message: dupMsg,
5054
+ publicResults: survey.showPublicResults !== "never" ? computePublicSurveyResults(survey, existingResponses) : null
5055
+ };
5056
+ }
5057
+ } else if (survey.submissionPolicy === "one_per_token") {
5058
+ if (!voterToken) {
5059
+ return {
5060
+ ok: false,
5061
+ status: 403,
5062
+ message: isTr ? "Bu anket yalnızca davet bağlantısı ile yanıtlanabilir." : "A valid respondent token is required for this survey."
5063
+ };
5064
+ }
5065
+ const duplicateToken = existingResponses.some(
5066
+ (r) => r.respondentToken === voterToken
5067
+ );
5068
+ if (duplicateToken) {
5069
+ return {
5070
+ ok: false,
5071
+ status: 409,
5072
+ alreadyVoted: true,
5073
+ message: resolveLocalizedText(
5074
+ survey.settings?.alreadyVotedMessage,
5075
+ locale,
5076
+ isTr ? "Bu davet bağlantısı ile daha önce oy kullanılmış." : "This invitation token has already been used."
5077
+ )
5078
+ };
5079
+ }
5080
+ }
5081
+ const answers = body.answers && typeof body.answers === "object" && !Array.isArray(body.answers) ? body.answers : {};
5082
+ const otherTexts = body.otherTexts && typeof body.otherTexts === "object" && !Array.isArray(body.otherTexts) ? body.otherTexts : {};
5083
+ const { errors } = validateSurveySubmission(
5084
+ survey,
5085
+ answers,
5086
+ otherTexts,
5087
+ locale
5088
+ );
5089
+ const activeSecretKey = String(
5090
+ survey.recaptchaSecretKey || getEnvRecaptchaPrivateKey() || ""
5091
+ ).trim();
5092
+ const activePublicKey = String(
5093
+ survey.recaptchaSiteKey || getEnvRecaptchaPublicKey() || ""
5094
+ ).trim();
5095
+ if (survey.useRecaptcha === true && activeSecretKey && activePublicKey) {
5096
+ const recaptchaToken = body["g-recaptcha-response"];
5097
+ const recaptchaValid = await verifyRecaptchaToken(
5098
+ recaptchaToken,
5099
+ activeSecretKey,
5100
+ meta.ip
5101
+ );
5102
+ if (!recaptchaValid) {
5103
+ errors["g-recaptcha-response"] = [
5104
+ isTr ? "Lütfen robot olmadığınızı doğrulayınız (reCAPTCHA)." : "Please complete the reCAPTCHA verification."
5105
+ ];
5106
+ }
5107
+ }
5108
+ if (Object.keys(errors).length > 0) {
5109
+ return {
5110
+ ok: false,
5111
+ status: 422,
5112
+ errors
5113
+ };
5114
+ }
5115
+ const metrics = computeResponseMetrics(survey, answers);
5116
+ const durationSeconds = Math.max(0, Math.min(86400, Number(body.durationSeconds || 0) || 0));
5117
+ const submittedAt = (/* @__PURE__ */ new Date()).toISOString();
5118
+ const createdResponse = await strapi.db.query(SURVEY_RESPONSE_UID).create({
5119
+ data: {
5120
+ surveyId: String(survey.documentId || survey.id),
5121
+ surveySlug: survey.slug,
5122
+ surveyTitle: survey.title,
5123
+ surveyVersion: Number(survey.version || 1),
5124
+ answers,
5125
+ otherTexts,
5126
+ score: metrics.score,
5127
+ npsValue: metrics.npsValue,
5128
+ npsCategory: metrics.npsCategory,
5129
+ locale,
5130
+ durationSeconds,
5131
+ voterHash: survey.submissionPolicy === "unlimited" ? null : voterHash,
5132
+ respondentToken: voterToken || null,
5133
+ ip: survey.anonymizeIp !== false ? null : meta.ip || "",
5134
+ userAgent: meta.userAgent || "",
5135
+ submittedAt
5136
+ }
5137
+ });
5138
+ const notifyEmails = String(survey.settings?.notifyEmails || "").trim();
5139
+ if (notifyEmails) {
5140
+ try {
5141
+ await sendDynamicFormMail({
5142
+ strapi,
5143
+ form: {
5144
+ title: survey.title,
5145
+ to: notifyEmails,
5146
+ subject: `[Anket Yanıtı] ${survey.title}`,
5147
+ mailConfig: survey.mailConfig
5148
+ },
5149
+ data: {
5150
+ ...answers,
5151
+ ...metrics.npsValue !== null ? { _nps: metrics.npsValue } : {}
5152
+ },
5153
+ meta: {
5154
+ ip: survey.anonymizeIp !== false ? "anonymized" : meta.ip,
5155
+ userAgent: meta.userAgent,
5156
+ locale
5157
+ }
5158
+ });
5159
+ } catch {
5160
+ }
5161
+ }
5162
+ const updatedResponses = [createdResponse, ...existingResponses];
5163
+ const publicResults = survey.showPublicResults === "after_vote" || survey.showPublicResults === "always" ? computePublicSurveyResults(survey, updatedResponses) : null;
5164
+ const thankYouTitle = resolveLocalizedText(
5165
+ survey.settings?.thankYouTitle,
5166
+ locale,
5167
+ isTr ? "Katılımınız İçin Teşekkürler!" : "Thank You for Participating!"
5168
+ );
5169
+ const thankYouMessage = resolveLocalizedText(
5170
+ survey.settings?.thankYouMessage,
5171
+ locale,
5172
+ isTr ? "Yanıtlarınız başarıyla kaydedildi." : "Your responses have been recorded successfully."
5173
+ );
5174
+ return {
5175
+ ok: true,
5176
+ status: 200,
5177
+ responseId: createdResponse?.documentId || String(createdResponse?.id || ""),
5178
+ thankYouTitle,
5179
+ message: thankYouMessage,
5180
+ redirectUrl: survey.settings?.redirectUrl || "",
5181
+ publicResults
5182
+ };
5183
+ },
5184
+ async getPublicResults(idOrSlug) {
5185
+ const survey = await this.findRawByIdOrSlug(idOrSlug);
5186
+ if (!survey) {
5187
+ return { ok: false, status: 404, message: "Survey not found" };
5188
+ }
5189
+ if (survey.showPublicResults === "never") {
5190
+ return { ok: false, status: 403, message: "Public results are disabled for this survey" };
5191
+ }
5192
+ const responses = await this.getResponsesForSurvey(survey);
5193
+ return {
5194
+ ok: true,
5195
+ status: 200,
5196
+ data: computePublicSurveyResults(survey, responses)
5197
+ };
5198
+ },
5199
+ async getAnalytics(idOrSlug, filter = {}) {
5200
+ const survey = await this.findRawByIdOrSlug(idOrSlug);
5201
+ if (!survey) return null;
5202
+ const responses = await this.getResponsesForSurvey(survey);
5203
+ const analytics = computeSurveyAnalytics(
5204
+ survey,
5205
+ responses,
5206
+ filter
5207
+ );
5208
+ return {
5209
+ survey: formatSurveyForAdmin(survey, { responseCount: responses.length }),
5210
+ ...analytics
5211
+ };
5212
+ },
5213
+ async listResponses(idOrSlug, limit = 150) {
5214
+ const survey = await this.findRawByIdOrSlug(idOrSlug);
5215
+ if (!survey) return [];
5216
+ const responses = await this.getResponsesForSurvey(survey);
5217
+ return responses.slice(0, limit);
5218
+ },
5219
+ async exportResponses(idOrSlug, options2 = {}) {
5220
+ const survey = await this.findRawByIdOrSlug(idOrSlug);
5221
+ if (!survey) return null;
5222
+ let responses = await this.getResponsesForSurvey(survey);
5223
+ if (options2.from || options2.to) {
5224
+ const fromTs = options2.from ? new Date(options2.from).getTime() : null;
5225
+ const toTs = options2.to ? (/* @__PURE__ */ new Date(`${options2.to}T23:59:59.999Z`)).getTime() : null;
5226
+ responses = responses.filter((r) => {
5227
+ const ts = new Date(r.submittedAt || r.createdAt || 0).getTime();
5228
+ if (fromTs && !Number.isNaN(fromTs) && ts < fromTs) return false;
5229
+ if (toTs && !Number.isNaN(toTs) && ts > toTs) return false;
5230
+ return true;
5231
+ });
5232
+ }
5233
+ if (options2.format === "json") {
5234
+ return {
5235
+ filename: `${survey.slug}-responses.json`,
5236
+ contentType: "application/json; charset=utf-8",
5237
+ body: JSON.stringify(
5238
+ {
5239
+ survey: {
5240
+ slug: survey.slug,
5241
+ title: survey.title,
5242
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
5243
+ totalResponses: responses.length
5244
+ },
5245
+ responses
5246
+ },
5247
+ null,
5248
+ 2
5249
+ )
5250
+ };
5251
+ }
5252
+ const csv = exportSurveyResponsesToCsv(
5253
+ survey,
5254
+ responses,
5255
+ options2.locale || "tr"
5256
+ );
5257
+ return {
5258
+ filename: `${survey.slug}-responses.csv`,
5259
+ contentType: "text/csv; charset=utf-8",
5260
+ body: csv
5261
+ };
5262
+ }
5263
+ });
1164
5264
  const services = {
1165
5265
  "ci-template": ciTemplateService,
1166
- "ci-menu": ciMenuService
5266
+ "ci-menu": ciMenuService,
5267
+ "ci-form": ciFormService,
5268
+ "ci-survey": ciSurveyService
1167
5269
  };
1168
5270
  const index = {
1169
5271
  register,