@ozguraltan/strapi-content-input 1.0.25 → 1.0.27

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 (25) hide show
  1. package/README.md +10 -2
  2. package/dist/admin/{AnalyticsHubPage-BO6Lg1qh.mjs → AnalyticsHubPage-1d4lx37k.mjs} +30 -52
  3. package/dist/admin/{AnalyticsHubPage-0fb7chuv.js → AnalyticsHubPage-BzKx8DTv.js} +30 -70
  4. package/dist/admin/{ContentInputField-C-fh5qGC.mjs → ContentInputField-DQvPlNcD.mjs} +427 -11
  5. package/dist/admin/{ContentInputField-CnVzTBNf.js → ContentInputField-DgS2wZNb.js} +427 -29
  6. package/dist/admin/{SurveyWidgetEditor-DdZBpfbS.mjs → SurveyWidgetEditor-BZHyY2eb.mjs} +2893 -107
  7. package/dist/admin/{SurveyWidgetEditor-DNDtKbmo.js → SurveyWidgetEditor-k7kA6LQT.js} +2893 -107
  8. package/dist/admin/{index--fSIDKkt.js → index-BvofXe07.js} +2 -2
  9. package/dist/admin/{index-BdrFmPg5.mjs → index-CStmbvTw.mjs} +2 -2
  10. package/dist/admin/index.js +1 -1
  11. package/dist/admin/index.mjs +1 -1
  12. package/dist/admin/src/components/analytics/ExcelReportStudioModal.d.ts +17 -0
  13. package/dist/admin/src/components/widgets/SurveyWidgetEditor.d.ts +2 -0
  14. package/dist/admin/src/core/xlsxBrowserReader.d.ts +11 -0
  15. package/dist/server/index.js +3081 -1524
  16. package/dist/server/index.mjs +3081 -1506
  17. package/dist/server/src/controllers/ci-form.d.ts +1 -0
  18. package/dist/server/src/controllers/index.d.ts +1 -0
  19. package/dist/server/src/index.d.ts +31 -1
  20. package/dist/server/src/services/ci-form.d.ts +6 -1
  21. package/dist/server/src/services/ci-survey.d.ts +25 -1
  22. package/dist/server/src/services/index.d.ts +30 -1
  23. package/dist/server/src/utils/surveyEngine.d.ts +22 -1
  24. package/dist/server/src/utils/xlsxReportBuilder.d.ts +38 -0
  25. package/package.json +2 -3
@@ -3,7 +3,6 @@ import fs from "fs";
3
3
  import { createRequire } from "module";
4
4
  import os from "os";
5
5
  import path from "path";
6
- import * as XLSXNs from "xlsx";
7
6
  const register = ({ strapi }) => {
8
7
  strapi.customFields.register({
9
8
  name: "content-input",
@@ -1733,6 +1732,32 @@ const ciFormController = ({ strapi }) => ({
1733
1732
  ctx.throw(500, err);
1734
1733
  }
1735
1734
  },
1735
+ async exportSubmissions(ctx) {
1736
+ try {
1737
+ const formSlug = String(
1738
+ ctx.query?.formSlug || ctx.params?.id || "all"
1739
+ ).trim();
1740
+ const locale = String(ctx.query?.locale || "en").trim();
1741
+ const encoding = String(ctx.query?.encoding || "").toLowerCase();
1742
+ const exported = await strapi.plugin("content-input").service("ci-form").exportSubmissionsXlsx(formSlug, locale);
1743
+ if (encoding === "base64") {
1744
+ ctx.status = 200;
1745
+ ctx.body = {
1746
+ filename: exported.filename,
1747
+ contentType: exported.contentType,
1748
+ base64: exported.body.toString("base64")
1749
+ };
1750
+ return;
1751
+ }
1752
+ ctx.body = exported.body;
1753
+ ctx.type = exported.contentType;
1754
+ ctx.set("Content-Type", exported.contentType);
1755
+ ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
1756
+ ctx.status = 200;
1757
+ } catch (err) {
1758
+ ctx.throw(500, err);
1759
+ }
1760
+ },
1736
1761
  async recaptchaKey(ctx) {
1737
1762
  try {
1738
1763
  const config2 = strapi.plugin("content-input").service("ci-form").getPublicRecaptchaConfig();
@@ -1909,13 +1934,28 @@ const ciSurveyController = ({ strapi }) => ({
1909
1934
  async exportResponses(ctx) {
1910
1935
  try {
1911
1936
  const { id } = ctx.params;
1912
- const rawFmt = String(ctx.query?.format || "xlsx").toLowerCase();
1937
+ const rawBody = ctx.request?.body || {};
1938
+ const bodyPayload = rawBody && typeof rawBody.data === "object" && !Array.isArray(rawBody.data) && Object.keys(rawBody).length === 1 ? rawBody.data : rawBody;
1939
+ const rawFmt = String(
1940
+ ctx.query?.format || bodyPayload?.format || "xlsx"
1941
+ ).toLowerCase();
1913
1942
  const format = rawFmt === "json" ? "json" : rawFmt === "csv" ? "csv" : "xlsx";
1914
- const locale = String(ctx.query?.locale || "en").trim();
1915
- const from = ctx.query?.from ? String(ctx.query.from) : void 0;
1916
- const to = ctx.query?.to ? String(ctx.query.to) : void 0;
1917
- const encoding = String(ctx.query?.encoding || "").toLowerCase();
1918
- const exported = await strapi.plugin("content-input").service("ci-survey").exportResponses(id, { format, locale, from, to });
1943
+ const locale = String(ctx.query?.locale || bodyPayload?.locale || "en").trim();
1944
+ const from = ctx.query?.from ? String(ctx.query.from) : bodyPayload?.from ? String(bodyPayload.from) : void 0;
1945
+ const to = ctx.query?.to ? String(ctx.query.to) : bodyPayload?.to ? String(bodyPayload.to) : void 0;
1946
+ const encoding = String(
1947
+ ctx.query?.encoding || bodyPayload?.encoding || ""
1948
+ ).toLowerCase();
1949
+ const xlsxOptions = format === "xlsx" && bodyPayload && typeof bodyPayload === "object" ? {
1950
+ reportTitle: typeof bodyPayload.reportTitle === "string" ? bodyPayload.reportTitle : void 0,
1951
+ executiveNote: typeof bodyPayload.executiveNote === "string" ? bodyPayload.executiveNote : void 0,
1952
+ themeColor: typeof bodyPayload.themeColor === "string" ? bodyPayload.themeColor : void 0,
1953
+ includeTrendChart: typeof bodyPayload.includeTrendChart === "boolean" ? bodyPayload.includeTrendChart : void 0,
1954
+ includeDataBars: typeof bodyPayload.includeDataBars === "boolean" ? bodyPayload.includeDataBars : void 0,
1955
+ includeRawSheet: typeof bodyPayload.includeRawSheet === "boolean" ? bodyPayload.includeRawSheet : void 0,
1956
+ questionOverrides: bodyPayload.questionOverrides && typeof bodyPayload.questionOverrides === "object" && !Array.isArray(bodyPayload.questionOverrides) ? bodyPayload.questionOverrides : void 0
1957
+ } : void 0;
1958
+ const exported = await strapi.plugin("content-input").service("ci-survey").exportResponses(id, { format, locale, from, to, xlsxOptions });
1919
1959
  if (!exported) {
1920
1960
  return ctx.notFound("Survey not found");
1921
1961
  }
@@ -2283,6 +2323,14 @@ const routes = {
2283
2323
  policies: []
2284
2324
  }
2285
2325
  },
2326
+ {
2327
+ method: "GET",
2328
+ path: "/forms/submissions/export",
2329
+ handler: "ci-form.exportSubmissions",
2330
+ config: {
2331
+ policies: []
2332
+ }
2333
+ },
2286
2334
  {
2287
2335
  method: "GET",
2288
2336
  path: "/forms/:id",
@@ -2427,6 +2475,14 @@ const routes = {
2427
2475
  policies: []
2428
2476
  }
2429
2477
  },
2478
+ {
2479
+ method: "POST",
2480
+ path: "/surveys/:id/export",
2481
+ handler: "ci-survey.exportResponses",
2482
+ config: {
2483
+ policies: []
2484
+ }
2485
+ },
2430
2486
  {
2431
2487
  method: "GET",
2432
2488
  path: "/media",
@@ -4702,1637 +4758,3136 @@ async function setDemoSeedCleared(strapi, cleared) {
4702
4758
  formsInitialized: true
4703
4759
  });
4704
4760
  }
4705
- const FORM_UID = "plugin::content-input.ci-form";
4706
- const SUBMISSION_UID = "plugin::content-input.ci-form-submission";
4707
- function slugifyIdentifier$1(text) {
4708
- const map = {
4709
- ç: "c",
4710
- Ç: "c",
4711
- ğ: "g",
4712
- Ğ: "g",
4713
- ı: "i",
4714
- İ: "i",
4715
- ö: "o",
4716
- Ö: "o",
4717
- ş: "s",
4718
- Ş: "s",
4719
- ü: "u",
4720
- Ü: "u"
4721
- };
4722
- return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-{2,}/g, "-").replace(/_{2,}/g, "_").replace(/^[-_]+|[-_]+$/g, "");
4761
+ const NO_OPINION_VALUE = "__na__";
4762
+ function resolveNoOpinionLabels(raw) {
4763
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
4764
+ return {
4765
+ tr: raw.tr || "Fikrim yok",
4766
+ en: raw.en || "No idea",
4767
+ ...raw
4768
+ };
4769
+ }
4770
+ if (typeof raw === "string" && raw.trim()) {
4771
+ return { tr: raw.trim(), en: raw.trim() };
4772
+ }
4773
+ return { tr: "Fikrim yok", en: "No idea" };
4723
4774
  }
4724
- function stripHtmlTags(html) {
4725
- 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();
4775
+ function evalSingleRule(rule, answers) {
4776
+ const targetVal = answers ? answers[rule.questionKey] : void 0;
4777
+ const op = rule.operator;
4778
+ if (op === "is_answered") {
4779
+ return !isEmptyFieldValue(targetVal);
4780
+ }
4781
+ if (op === "is_empty") {
4782
+ return isEmptyFieldValue(targetVal);
4783
+ }
4784
+ const cmp = rule.value;
4785
+ if (op === "equals") {
4786
+ if (Array.isArray(targetVal)) return targetVal.map(String).includes(String(cmp));
4787
+ return String(targetVal ?? "") === String(cmp ?? "");
4788
+ }
4789
+ if (op === "not_equals") {
4790
+ if (Array.isArray(targetVal)) return !targetVal.map(String).includes(String(cmp));
4791
+ return String(targetVal ?? "") !== String(cmp ?? "");
4792
+ }
4793
+ if (op === "includes") {
4794
+ if (Array.isArray(targetVal)) return targetVal.map(String).includes(String(cmp));
4795
+ return String(targetVal ?? "").includes(String(cmp ?? ""));
4796
+ }
4797
+ if (op === "not_includes") {
4798
+ if (Array.isArray(targetVal)) return !targetVal.map(String).includes(String(cmp));
4799
+ return !String(targetVal ?? "").includes(String(cmp ?? ""));
4800
+ }
4801
+ const numTarget = Number(targetVal);
4802
+ const numCmp = Number(cmp);
4803
+ if (isEmptyFieldValue(targetVal) || Number.isNaN(numTarget) || Number.isNaN(numCmp)) {
4804
+ return false;
4805
+ }
4806
+ if (op === "gt") return numTarget > numCmp;
4807
+ if (op === "gte") return numTarget >= numCmp;
4808
+ if (op === "lt") return numTarget < numCmp;
4809
+ if (op === "lte") return numTarget <= numCmp;
4810
+ return true;
4726
4811
  }
4727
- const DEFAULT_SEED_FORMS = [
4728
- {
4729
- title: "Enterprise Inquiry & Support Form",
4730
- slug: "showcase_contact_form",
4731
- to: "info@example.com",
4732
- subject: "Enterprise Inquiry & Support Submission",
4733
- buttonLabel: {
4734
- tr: "Başvuruyu Gönder",
4735
- en: "Submit Inquiry"
4736
- },
4737
- successMessage: {
4738
- tr: "Başvurunuz başarıyla kaydedildi. Ekibimiz en kısa sürede sizinle iletişime geçecektir.",
4739
- en: "Your inquiry has been submitted successfully. Our team will get back to you shortly."
4740
- },
4741
- redirect: "",
4742
- hideLabels: false,
4743
- useRecaptcha: true,
4744
- recaptchaSiteKey: "",
4745
- recaptchaSecretKey: "",
4746
- mailConfig: {
4747
- driver: "env"
4748
- },
4749
- fields: {
4750
- full_name: {
4751
- name: "full_name",
4752
- field_type: "input",
4753
- alias: { tr: "Adınız Soyadınız", en: "Full Name" },
4754
- placeholder: { tr: "Örn: Özgür Altan", en: "e.g. Jane Doe" },
4755
- validation: "required|min:3|max:100",
4756
- options: {}
4757
- },
4758
- email: {
4759
- name: "email",
4760
- field_type: "emailInput",
4761
- alias: { tr: "Kurumsal E-Posta", en: "Work Email" },
4762
- placeholder: { tr: "ad.soyad@sirket.com", en: "name@company.com" },
4763
- validation: "required|email",
4764
- options: {}
4765
- },
4766
- phone: {
4767
- name: "phone",
4768
- field_type: "telInput",
4769
- alias: { tr: "Telefon Numarası", en: "Phone Number" },
4770
- placeholder: { tr: "+90 555 123 45 67", en: "+1 555 123 4567" },
4771
- hint: {
4772
- tr: "İsteğe bağlı; girildiğinde telefon formatı doğrulanır.",
4773
- en: "Optional; validated when entered."
4774
- },
4775
- validation: "phone",
4776
- options: {}
4777
- },
4778
- department: {
4779
- name: "department",
4780
- field_type: "selectGroup",
4781
- alias: { tr: "İlgili Departman", en: "Department" },
4782
- placeholder: { tr: "Departman seçiniz...", en: "Select department..." },
4783
- validation: "required",
4784
- options: {
4785
- optionList: {
4786
- tr: [
4787
- "Satış & Kurumsal Çözümler",
4788
- "Teknik Destek & SLA",
4789
- "Strapi & Nuxt Mimari Danışmanlık",
4790
- "İnsan Kaynakları"
4791
- ],
4792
- en: [
4793
- "Sales & Enterprise Solutions",
4794
- "Technical Support & SLA",
4795
- "Strapi & Nuxt Architecture Consulting",
4796
- "Human Resources"
4797
- ]
4798
- }
4812
+ function evaluateSurveyConditions(conditions, answers) {
4813
+ if (!conditions || !Array.isArray(conditions.rules) || conditions.rules.length === 0) {
4814
+ return true;
4815
+ }
4816
+ if (conditions.match === "any") {
4817
+ return conditions.rules.some((r) => evalSingleRule(r, answers));
4818
+ }
4819
+ return conditions.rules.every((r) => evalSingleRule(r, answers));
4820
+ }
4821
+ function isQuestionVisible(question, survey, answers) {
4822
+ if (survey.displayMode === "multi_step" && question.stepId && Array.isArray(survey.steps)) {
4823
+ const parentStep = survey.steps.find((s) => s.id === question.stepId);
4824
+ if (parentStep && !evaluateSurveyConditions(parentStep.conditions, answers)) {
4825
+ return false;
4826
+ }
4827
+ }
4828
+ return evaluateSurveyConditions(question.conditions, answers);
4829
+ }
4830
+ function lMsg(locale, tr, en) {
4831
+ return String(locale || "").toLowerCase().startsWith("tr") ? tr : en;
4832
+ }
4833
+ function validateSurveySubmission(survey, answers, otherTexts = {}, locale = "en") {
4834
+ const errors = {};
4835
+ const questions = Array.isArray(survey.questions) ? survey.questions : [];
4836
+ for (const q of questions) {
4837
+ if (!q || !q.key || q.type === "statement") continue;
4838
+ if (!isQuestionVisible(q, survey, answers)) continue;
4839
+ const val = answers ? answers[q.key] : void 0;
4840
+ const qLabel = resolveLocalizedText(q.title, locale, q.key);
4841
+ const qErrors = [];
4842
+ const empty = isEmptyFieldValue(val);
4843
+ if (q.type === "consent") {
4844
+ if (q.required !== false && val !== true && val !== "true" && val !== 1) {
4845
+ qErrors.push(lMsg(locale, `${qLabel} onaylanmalıdır.`, `${qLabel} must be accepted.`));
4846
+ }
4847
+ } else if (q.type === "matrix_single") {
4848
+ const mRows = Array.isArray(q.matrixRows) ? q.matrixRows : [];
4849
+ if (q.required) {
4850
+ const objVal = val && typeof val === "object" && !Array.isArray(val) ? val : {};
4851
+ const missingRow = mRows.some((r) => isEmptyFieldValue(objVal[r.id]));
4852
+ if (missingRow) {
4853
+ qErrors.push(
4854
+ lMsg(
4855
+ locale,
4856
+ `Lütfen "${qLabel}" tablosundaki tüm satırları yanıtlayınız.`,
4857
+ `Please answer all rows in "${qLabel}".`
4858
+ )
4859
+ );
4799
4860
  }
4800
- },
4801
- priority: {
4802
- name: "priority",
4803
- field_type: "radioGroup",
4804
- alias: { tr: "Öncelik Seviyesi", en: "Priority Level" },
4805
- validation: "required",
4806
- options: {
4807
- inline: true,
4808
- optionList: {
4809
- tr: ["Standart", "Yüksek Öncelik", "Kritik / Acil"],
4810
- en: ["Standard", "High Priority", "Critical / Urgent"]
4811
- }
4861
+ }
4862
+ } else if (q.type === "multiple_choice" || q.type === "image_choice" && (q.maxSelections ?? 1) > 1) {
4863
+ const arr = Array.isArray(val) ? val : [];
4864
+ const isExclusiveNoOpinion = q.allowNoOpinion && arr.includes(NO_OPINION_VALUE);
4865
+ if (q.required && arr.length === 0) {
4866
+ qErrors.push(lMsg(locale, `Lütfen en az bir seçenek işaretleyiniz.`, `Please select at least one option.`));
4867
+ } else if (arr.length > 0 && !isExclusiveNoOpinion) {
4868
+ if (q.minSelections && arr.length < q.minSelections) {
4869
+ qErrors.push(
4870
+ lMsg(
4871
+ locale,
4872
+ `En az ${q.minSelections} seçenek işaretlemelisiniz.`,
4873
+ `Please select at least ${q.minSelections} options.`
4874
+ )
4875
+ );
4812
4876
  }
4813
- },
4814
- services: {
4815
- name: "services",
4816
- field_type: "checkboxGroup",
4817
- alias: { tr: "İlgilendiğiniz Modüller", en: "Modules of Interest" },
4818
- validation: "min:1",
4819
- options: {
4820
- optionList: {
4821
- tr: [
4822
- "Strapi ContentInput Builder",
4823
- "Nuxt Vuetify Renderer",
4824
- "Nuxt Element Plus Renderer",
4825
- "Özel Entegrasyon"
4826
- ],
4827
- en: [
4828
- "Strapi ContentInput Builder",
4829
- "Nuxt Vuetify Renderer",
4830
- "Nuxt Element Plus Renderer",
4831
- "Custom Integration"
4832
- ]
4833
- }
4877
+ if (q.maxSelections && arr.length > q.maxSelections) {
4878
+ qErrors.push(
4879
+ lMsg(
4880
+ locale,
4881
+ `En fazla ${q.maxSelections} seçenek işaretleyebilirsiniz.`,
4882
+ `You may select at most ${q.maxSelections} options.`
4883
+ )
4884
+ );
4834
4885
  }
4835
- },
4836
- message: {
4837
- name: "message",
4838
- field_type: "textArea",
4839
- alias: { tr: "Proje Detayları & Mesajınız", en: "Project Details & Message" },
4840
- placeholder: {
4841
- tr: "Projeniz ve beklentileriniz hakkında bilgi paylaşınız (en az 10 karakter)...",
4842
- en: "Tell us about your project and requirements (at least 10 characters)..."
4843
- },
4844
- validation: "required|min:10|max:1000",
4845
- options: { rows: 4 }
4846
- },
4847
- kvkk_consent: {
4848
- name: "kvkk_consent",
4849
- field_type: "switchBox",
4850
- alias: {
4851
- tr: "KVKK Aydınlatma Metnini okudum ve kişisel verilerimin işlenmesini kabul ediyorum.",
4852
- en: "I have read and accept the Privacy Policy & GDPR data processing notice."
4853
- },
4854
- validation: "accepted",
4855
- options: {}
4856
4886
  }
4857
- },
4858
- form: [
4859
- {
4860
- _uId: "frow_1",
4861
- blocks: [
4862
- { _uId: "fblk_1a", cols: [12, 6, 6, 6, 6], fields: ["full_name"] },
4863
- { _uId: "fblk_1b", cols: [12, 6, 6, 6, 6], fields: ["email"] }
4864
- ]
4865
- },
4866
- {
4867
- _uId: "frow_2",
4868
- blocks: [
4869
- { _uId: "fblk_2a", cols: [12, 6, 6, 6, 6], fields: ["phone"] },
4870
- { _uId: "fblk_2b", cols: [12, 6, 6, 6, 6], fields: ["department"] }
4871
- ]
4872
- },
4873
- {
4874
- _uId: "frow_3",
4875
- blocks: [
4876
- { _uId: "fblk_3a", cols: [12, 6, 6, 6, 6], fields: ["priority"] },
4877
- { _uId: "fblk_3b", cols: [12, 6, 6, 6, 6], fields: ["services"] }
4878
- ]
4879
- },
4880
- {
4881
- _uId: "frow_4",
4882
- blocks: [
4887
+ if (!isExclusiveNoOpinion && q.allowOther && arr.includes("__other__") && !String(otherTexts?.[q.key] || "").trim()) {
4888
+ qErrors.push(
4889
+ lMsg(locale, `Lütfen "Diğer" seçeneği için açıklama giriniz.`, `Please specify your "Other" choice.`)
4890
+ );
4891
+ }
4892
+ } else if (q.type === "single_choice" || q.type === "dropdown" || q.type === "image_choice") {
4893
+ if (q.required && empty) {
4894
+ qErrors.push(lMsg(locale, `Lütfen bir seçim yapınız.`, `Please choose an option.`));
4895
+ }
4896
+ if (q.allowOther && val === "__other__" && !String(otherTexts?.[q.key] || "").trim()) {
4897
+ qErrors.push(
4898
+ lMsg(locale, `Lütfen "Diğer" seçeneği için açıklama giriniz.`, `Please specify your "Other" choice.`)
4899
+ );
4900
+ }
4901
+ } else if (q.type === "nps") {
4902
+ const isNoOp = Boolean(q.allowNoOpinion && val === NO_OPINION_VALUE);
4903
+ if (q.required && empty) {
4904
+ qErrors.push(lMsg(locale, `Lütfen 0 ile 10 arasında bir puan seçiniz.`, `Please choose a score from 0 to 10.`));
4905
+ } else if (!empty && !isNoOp) {
4906
+ const n = Number(val);
4907
+ if (Number.isNaN(n) || n < 0 || n > 10) {
4908
+ qErrors.push(lMsg(locale, `Puan 0 ile 10 arasında olmalıdır.`, `Score must be between 0 and 10.`));
4909
+ }
4910
+ }
4911
+ } else if (q.type === "star_rating") {
4912
+ const maxS = q.maxStars || 5;
4913
+ const isNoOp = Boolean(q.allowNoOpinion && val === NO_OPINION_VALUE);
4914
+ if (q.required && empty) {
4915
+ qErrors.push(lMsg(locale, `Lütfen derecelendirme yapınız.`, `Please provide a rating.`));
4916
+ } else if (!empty && !isNoOp) {
4917
+ const n = Number(val);
4918
+ if (Number.isNaN(n) || n < 1 || n > maxS) {
4919
+ qErrors.push(lMsg(locale, `Derece 1 ile ${maxS} arasında olmalıdır.`, `Rating must be between 1 and ${maxS}.`));
4920
+ }
4921
+ }
4922
+ } else if (q.type === "likert_scale") {
4923
+ const sMin = q.scaleMin ?? 1;
4924
+ const sMax = q.scaleMax ?? 5;
4925
+ const isNoOp = Boolean(q.allowNoOpinion && val === NO_OPINION_VALUE);
4926
+ if (q.required && empty) {
4927
+ qErrors.push(lMsg(locale, `Lütfen ölçekten bir değer seçiniz.`, `Please select a value on the scale.`));
4928
+ } else if (!empty && !isNoOp) {
4929
+ const n = Number(val);
4930
+ if (Number.isNaN(n) || n < sMin || n > sMax) {
4931
+ qErrors.push(
4932
+ lMsg(locale, `Değer ${sMin} ile ${sMax} arasında olmalıdır.`, `Value must be between ${sMin} and ${sMax}.`)
4933
+ );
4934
+ }
4935
+ }
4936
+ } else if (q.type === "ranking") {
4937
+ const isNoOp = Boolean(
4938
+ q.allowNoOpinion && (val === NO_OPINION_VALUE || Array.isArray(val) && val[0] === NO_OPINION_VALUE)
4939
+ );
4940
+ if (q.required && !isNoOp && (!Array.isArray(val) || val.length === 0)) {
4941
+ qErrors.push(lMsg(locale, `Lütfen sıralamayı onaylayınız.`, `Please confirm the ranking.`));
4942
+ }
4943
+ } else if (q.type === "short_text" || q.type === "long_text") {
4944
+ const ruleParts = [];
4945
+ if (q.required) ruleParts.push("required");
4946
+ if (q.validation) ruleParts.push(q.validation);
4947
+ const combinedRules = Array.from(new Set(ruleParts.join("|").split("|").filter(Boolean))).join("|");
4948
+ if (combinedRules) {
4949
+ const vErrs = validateSingleField(
4950
+ val,
4883
4951
  {
4884
- _uId: "fblk_4a",
4885
- cols: [12, 12, 12, 12, 12],
4886
- fields: ["message", "kvkk_consent"]
4887
- }
4888
- ]
4952
+ name: q.key,
4953
+ field_type: q.type === "long_text" ? "textArea" : "input",
4954
+ alias: q.title,
4955
+ validation: combinedRules
4956
+ },
4957
+ answers,
4958
+ locale
4959
+ );
4960
+ qErrors.push(...vErrs);
4889
4961
  }
4890
- ]
4962
+ }
4963
+ if (qErrors.length > 0) {
4964
+ errors[q.key] = qErrors;
4965
+ }
4891
4966
  }
4892
- ];
4893
- function getEnvRecaptchaPublicKey$1() {
4894
- return (process.env.MIX_RECAPTCHA_PUBLIC_KEY || process.env.RECAPTCHA_PUBLIC_KEY || process.env.NUXT_PUBLIC_RECAPTCHA_SITE_KEY || "").trim();
4895
- }
4896
- function getEnvRecaptchaPrivateKey$1() {
4897
- return (process.env.RECAPTCHA_PRIVATE_KEY || process.env.RECAPTCHA_SECRET_KEY || "").trim();
4898
- }
4899
- function getEnvStatusSummary$1() {
4900
- return {
4901
- hasEnvRecaptchaPublicKey: Boolean(getEnvRecaptchaPublicKey$1()),
4902
- hasEnvRecaptchaPrivateKey: Boolean(getEnvRecaptchaPrivateKey$1()),
4903
- envMailDriver: process.env.MAIL_DRIVER || "auto",
4904
- hasMailtrapToken: Boolean(process.env.MAILTRAP_API_TOKEN || process.env.MAILTRAP_TOKEN),
4905
- hasMailgunSecret: Boolean(process.env.MAILGUN_SECRET || process.env.MAILGUN_API_KEY),
4906
- hasSmtpHost: Boolean(process.env.MAIL_HOST)
4907
- };
4908
- }
4909
- function sanitizeFormForPublic(entry) {
4910
- if (!entry) return null;
4911
- const { recaptchaSecretKey, mailConfig, ...safeRest } = entry;
4912
- const publicKey = entry.useRecaptcha !== false ? String(entry.recaptchaSiteKey || getEnvRecaptchaPublicKey$1() || "").trim() : "";
4913
4967
  return {
4914
- ...safeRest,
4915
- _id: entry.documentId || String(entry.id),
4916
- recaptchaPublicKey: publicKey,
4917
- recaptchaEnabled: Boolean(entry.useRecaptcha !== false && publicKey)
4968
+ valid: Object.keys(errors).length === 0,
4969
+ errors
4918
4970
  };
4919
4971
  }
4920
- function formatFormForAdmin(entry) {
4921
- if (!entry) return null;
4922
- return {
4923
- ...entry,
4924
- _id: entry.documentId || String(entry.id),
4925
- envStatus: getEnvStatusSummary$1()
4926
- };
4972
+ function computeVoterHash(surveySlug, ip, userAgent, voterToken) {
4973
+ const salt = process.env.APP_KEYS || process.env.API_TOKEN_SALT || "ci-survey-default-salt";
4974
+ const rawIdentity = voterToken ? `${surveySlug}::token::${voterToken}` : `${surveySlug}::ipua::${ip || "unknown"}::${(userAgent || "").slice(0, 120)}`;
4975
+ return crypto.createHmac("sha256", salt).update(rawIdentity).digest("hex");
4927
4976
  }
4928
- function extractSnippetAndImageFromContentInput(content) {
4929
- let snippet = "";
4930
- let image = null;
4931
- const visitRows = (rows) => {
4932
- if (!Array.isArray(rows)) return;
4933
- for (const row of rows) {
4934
- const blocks = Array.isArray(row?.blocks) ? row.blocks : [];
4935
- for (const block of blocks) {
4936
- const widgets = Array.isArray(block?.widgets) ? block.widgets : [];
4937
- for (const widget of widgets) {
4938
- const wId = widget?.id;
4939
- const wData = widget?.data || {};
4940
- if (!image) {
4941
- if (wId === "singleImage") {
4942
- if (wData?.image?.url) image = wData.image;
4943
- else if (wData?.file?.url) image = wData.file;
4944
- } else if (wId === "gallery") {
4945
- if (Array.isArray(wData) && wData[0]?.url) {
4946
- image = wData[0];
4947
- } else if (Array.isArray(wData?.images) && wData.images[0]?.url) {
4948
- image = wData.images[0];
4949
- }
4950
- } else if (wId === "banner" && wData?.image?.url) {
4951
- image = wData.image;
4952
- }
4953
- }
4954
- if (!snippet) {
4955
- const rawHtml = wId === "HtmlEditor" ? typeof wData === "string" ? wData : wData?.content : "";
4956
- if (typeof rawHtml === "string" && rawHtml.trim()) {
4957
- const plain = stripHtmlTags(rawHtml);
4958
- if (plain.length > 15) {
4959
- snippet = plain.length > 180 ? `${plain.slice(0, 177)}...` : plain;
4960
- }
4961
- }
4962
- }
4963
- if (wId === "tab" && Array.isArray(wData?.tabs)) {
4964
- for (const tab of wData.tabs) {
4965
- if (Array.isArray(tab?.content)) visitRows(tab.content);
4966
- }
4977
+ function computeResponseMetrics(survey, answers) {
4978
+ let totalScore = 0;
4979
+ let hasScoredItem = false;
4980
+ let npsValue = null;
4981
+ let npsCategory = null;
4982
+ for (const q of survey.questions || []) {
4983
+ const val = answers?.[q.key];
4984
+ if (isEmptyFieldValue(val)) continue;
4985
+ if (q.type === "nps" && npsValue === null) {
4986
+ const n = Number(val);
4987
+ if (!Number.isNaN(n)) {
4988
+ npsValue = n;
4989
+ npsCategory = n >= 9 ? "promoter" : n >= 7 ? "passive" : "detractor";
4990
+ }
4991
+ }
4992
+ if (Array.isArray(q.options) && q.options.length > 0) {
4993
+ if (Array.isArray(val)) {
4994
+ for (const chosen of val) {
4995
+ const opt = q.options.find((o) => o.id === chosen);
4996
+ if (opt && typeof opt.score === "number") {
4997
+ totalScore += opt.score;
4998
+ hasScoredItem = true;
4967
4999
  }
4968
5000
  }
5001
+ } else {
5002
+ const opt = q.options.find((o) => o.id === val);
5003
+ if (opt && typeof opt.score === "number") {
5004
+ totalScore += opt.score;
5005
+ hasScoredItem = true;
5006
+ }
4969
5007
  }
4970
5008
  }
4971
- };
4972
- if (Array.isArray(content)) {
4973
- visitRows(content);
4974
5009
  }
4975
- return { snippet, image };
5010
+ return {
5011
+ score: hasScoredItem ? totalScore : null,
5012
+ npsValue,
5013
+ npsCategory
5014
+ };
4976
5015
  }
4977
- const ciFormService = ({ strapi }) => ({
4978
- async listStrapiLocales() {
4979
- try {
4980
- let rawLocales = [];
4981
- let defaultCode = "";
4982
- const i18nPlugin = strapi.plugin?.("i18n");
4983
- if (i18nPlugin) {
4984
- try {
4985
- const localesService = i18nPlugin.service?.("locales");
4986
- if (localesService?.find) {
4987
- rawLocales = await localesService.find() || [];
4988
- }
4989
- if (localesService?.getDefaultLocale) {
4990
- defaultCode = String(await localesService.getDefaultLocale() || "");
4991
- }
4992
- } catch {
4993
- }
4994
- }
4995
- if (!Array.isArray(rawLocales) || rawLocales.length === 0) {
4996
- try {
4997
- rawLocales = await strapi.db.query("plugin::i18n.locale").findMany({
4998
- orderBy: { id: "asc" }
4999
- }) || [];
5000
- } catch {
5001
- rawLocales = [];
5002
- }
5003
- }
5004
- if (Array.isArray(rawLocales) && rawLocales.length > 0) {
5005
- const mapped = rawLocales.filter((loc) => loc && typeof loc.code === "string" && loc.code.trim()).map((loc) => {
5006
- const code = String(loc.code).trim();
5007
- const isDefault = Boolean(
5008
- loc.isDefault || defaultCode && code === defaultCode
5009
- );
5010
- return {
5011
- code,
5012
- name: String(loc.name || code.toUpperCase()),
5013
- isDefault
5014
- };
5015
- });
5016
- if (mapped.length > 0) {
5017
- if (!mapped.some((m) => m.isDefault)) {
5018
- mapped[0].isDefault = true;
5019
- }
5020
- mapped.sort((a, b) => Number(b.isDefault) - Number(a.isDefault));
5021
- return mapped;
5022
- }
5016
+ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
5017
+ const fromTime = filter.from ? new Date(filter.from).getTime() : null;
5018
+ const toTime = filter.to ? (/* @__PURE__ */ new Date(`${filter.to}T23:59:59.999Z`)).getTime() : null;
5019
+ const filterLocale = filter.locale && filter.locale !== "all" ? filter.locale : null;
5020
+ const responses = (rawResponses || []).filter((r) => {
5021
+ const tsRaw = r.submittedAt || r.createdAt;
5022
+ const ts = tsRaw ? new Date(tsRaw).getTime() : 0;
5023
+ if (fromTime && !Number.isNaN(fromTime) && ts < fromTime) return false;
5024
+ if (toTime && !Number.isNaN(toTime) && ts > toTime) return false;
5025
+ if (filterLocale && r.locale !== filterLocale) return false;
5026
+ return true;
5027
+ });
5028
+ const totalResponses = responses.length;
5029
+ const durations = responses.map((r) => Number(r.durationSeconds || 0)).filter((d) => d > 0).sort((a, b) => a - b);
5030
+ const avgDurationSeconds = durations.length > 0 ? Math.round(durations.reduce((acc, d) => acc + d, 0) / durations.length) : 0;
5031
+ const medianDurationSeconds = durations.length > 0 ? durations[Math.floor(durations.length / 2)] : 0;
5032
+ const localeCounts = {};
5033
+ const dailyCounts = {};
5034
+ let lastSubmittedAt = null;
5035
+ for (const r of responses) {
5036
+ const loc = String(r.locale || "en");
5037
+ localeCounts[loc] = (localeCounts[loc] || 0) + 1;
5038
+ const tsRaw = r.submittedAt || r.createdAt;
5039
+ if (tsRaw) {
5040
+ const iso = new Date(tsRaw).toISOString();
5041
+ const dayKey = iso.slice(0, 10);
5042
+ dailyCounts[dayKey] = (dailyCounts[dayKey] || 0) + 1;
5043
+ if (!lastSubmittedAt || iso > lastSubmittedAt) {
5044
+ lastSubmittedAt = iso;
5023
5045
  }
5024
- } catch {
5025
5046
  }
5026
- return [
5027
- { code: "en", name: "English (en)", isDefault: true },
5028
- { code: "tr", name: "Türkçe (tr)", isDefault: false }
5029
- ];
5030
- },
5031
- async ensureSampleSubmissions(force = false) {
5032
- try {
5033
- if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5034
- return;
5035
- }
5036
- const subCount = await strapi.db.query(SUBMISSION_UID).count();
5037
- if (subCount > 0 && !force) return;
5038
- let showcaseForm = await strapi.db.query(FORM_UID).findOne({
5039
- where: { slug: "showcase_contact_form" }
5047
+ }
5048
+ const localeBreakdown = Object.entries(localeCounts).map(([locale, count]) => ({
5049
+ locale,
5050
+ count,
5051
+ percentage: totalResponses > 0 ? Math.round(count / totalResponses * 1e3) / 10 : 0
5052
+ })).sort((a, b) => b.count - a.count);
5053
+ const dailyTrend = Object.entries(dailyCounts).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
5054
+ let promoters = 0;
5055
+ let passives = 0;
5056
+ let detractors = 0;
5057
+ for (const r of responses) {
5058
+ if (typeof r.npsValue === "number") {
5059
+ if (r.npsValue >= 9) promoters += 1;
5060
+ else if (r.npsValue >= 7) passives += 1;
5061
+ else detractors += 1;
5062
+ }
5063
+ }
5064
+ const totalNpsResponses = promoters + passives + detractors;
5065
+ const promotersPct = totalNpsResponses > 0 ? Math.round(promoters / totalNpsResponses * 1e3) / 10 : 0;
5066
+ const passivesPct = totalNpsResponses > 0 ? Math.round(passives / totalNpsResponses * 1e3) / 10 : 0;
5067
+ const detractorsPct = totalNpsResponses > 0 ? Math.round(detractors / totalNpsResponses * 1e3) / 10 : 0;
5068
+ const npsScore = totalNpsResponses > 0 ? Math.round((promoters - detractors) / totalNpsResponses * 100) : 0;
5069
+ const questionStats = (survey.questions || []).filter((q) => q && q.type !== "statement").map((q) => {
5070
+ let answeredCount = 0;
5071
+ const baseInfo = {
5072
+ key: q.key,
5073
+ type: q.type,
5074
+ title: q.title,
5075
+ required: Boolean(q.required),
5076
+ hasConditions: Boolean(q.conditions?.rules?.length)
5077
+ };
5078
+ if (q.type === "single_choice" || q.type === "multiple_choice" || q.type === "dropdown" || q.type === "image_choice") {
5079
+ const opts = Array.isArray(q.options) ? q.options : [];
5080
+ const countsMap = {};
5081
+ opts.forEach((o) => {
5082
+ countsMap[o.id] = 0;
5040
5083
  });
5041
- if (!showcaseForm && force) {
5042
- const seedDef = DEFAULT_SEED_FORMS.find((s) => s.slug === "showcase_contact_form");
5043
- if (seedDef) {
5044
- showcaseForm = await strapi.db.query(FORM_UID).create({ data: seedDef });
5084
+ let otherCount = 0;
5085
+ let noOpinionCount = 0;
5086
+ const otherSamples = [];
5087
+ for (const r of responses) {
5088
+ const v = r.answers?.[q.key];
5089
+ if (isEmptyFieldValue(v)) continue;
5090
+ answeredCount += 1;
5091
+ const selectedArr = Array.isArray(v) ? v.map(String) : [String(v)];
5092
+ for (const item of selectedArr) {
5093
+ if (item === "__other__") {
5094
+ otherCount += 1;
5095
+ const txt = String(r.otherTexts?.[q.key] || "").trim();
5096
+ if (txt && otherSamples.length < 30) {
5097
+ otherSamples.push({
5098
+ text: txt,
5099
+ locale: r.locale || "en",
5100
+ submittedAt: r.submittedAt || r.createdAt || ""
5101
+ });
5102
+ }
5103
+ } else if (item === NO_OPINION_VALUE) {
5104
+ noOpinionCount += 1;
5105
+ } else {
5106
+ countsMap[item] = (countsMap[item] || 0) + 1;
5107
+ }
5045
5108
  }
5046
5109
  }
5047
- if (!showcaseForm) return;
5048
- if (force) {
5049
- await strapi.db.query(SUBMISSION_UID).deleteMany({
5050
- where: { formSlug: "showcase_contact_form" }
5110
+ const optionsBreakdown = opts.map((o) => {
5111
+ const count = countsMap[o.id] || 0;
5112
+ return {
5113
+ id: o.id,
5114
+ labels: o.labels,
5115
+ image: o.image || null,
5116
+ count,
5117
+ percentage: answeredCount > 0 ? Math.round(count / answeredCount * 1e3) / 10 : 0
5118
+ };
5119
+ });
5120
+ if (q.allowOther || otherCount > 0) {
5121
+ optionsBreakdown.push({
5122
+ id: "__other__",
5123
+ labels: typeof q.otherLabel === "object" && q.otherLabel ? q.otherLabel : { tr: "Diğer", en: "Other" },
5124
+ image: null,
5125
+ count: otherCount,
5126
+ percentage: answeredCount > 0 ? Math.round(otherCount / answeredCount * 1e3) / 10 : 0
5051
5127
  });
5052
5128
  }
5053
- const samples = generateSampleFormSubmissions(showcaseForm);
5054
- for (const item of samples) {
5055
- await strapi.db.query(SUBMISSION_UID).create({ data: item });
5129
+ if (q.allowNoOpinion || noOpinionCount > 0) {
5130
+ optionsBreakdown.push({
5131
+ id: NO_OPINION_VALUE,
5132
+ labels: resolveNoOpinionLabels(q.noOpinionLabel),
5133
+ image: null,
5134
+ count: noOpinionCount,
5135
+ percentage: answeredCount > 0 ? Math.round(noOpinionCount / answeredCount * 1e3) / 10 : 0
5136
+ });
5056
5137
  }
5057
- } catch {
5058
- }
5059
- },
5060
- async ensureSeeded(force = false) {
5061
- if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5062
- return;
5063
- }
5064
- let count = 0;
5065
- try {
5066
- count = await strapi.db.query(FORM_UID).count();
5067
- } catch {
5068
- return;
5138
+ return {
5139
+ ...baseInfo,
5140
+ answeredCount,
5141
+ noOpinionCount,
5142
+ optionsBreakdown,
5143
+ otherSamples
5144
+ };
5069
5145
  }
5070
- if (count === 0 || force) {
5071
- for (const seed of DEFAULT_SEED_FORMS) {
5072
- const existingSeed = await strapi.db.query(FORM_UID).findOne({
5073
- where: { slug: seed.slug }
5074
- });
5075
- if (!existingSeed) {
5076
- await strapi.db.query(FORM_UID).create({ data: seed });
5146
+ if (q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") {
5147
+ const minVal = q.type === "nps" ? 0 : q.type === "likert_scale" ? q.scaleMin ?? 1 : 1;
5148
+ const maxVal = q.type === "nps" ? 10 : q.type === "likert_scale" ? q.scaleMax ?? 5 : q.maxStars ?? 5;
5149
+ const distMap = {};
5150
+ for (let i = minVal; i <= maxVal; i += 1) distMap[i] = 0;
5151
+ let sum = 0;
5152
+ let scoredCount = 0;
5153
+ let noOpinionCount = 0;
5154
+ let qPromoters = 0;
5155
+ let qPassives = 0;
5156
+ let qDetractors = 0;
5157
+ for (const r of responses) {
5158
+ const rawV = r.answers?.[q.key];
5159
+ if (isEmptyFieldValue(rawV)) continue;
5160
+ if (rawV === NO_OPINION_VALUE) {
5161
+ answeredCount += 1;
5162
+ noOpinionCount += 1;
5163
+ continue;
5077
5164
  }
5078
- }
5079
- } else {
5080
- try {
5081
- const showcase = await strapi.db.query(FORM_UID).findOne({
5082
- where: { slug: "showcase_contact_form" }
5083
- });
5084
- if (showcase && (showcase.subject === "Kurumsal İletişim & Destek Başvurusu" || showcase.title === "Kurumsal İletişim & Destek Formu")) {
5085
- await strapi.db.query(FORM_UID).update({
5086
- where: { id: showcase.id },
5087
- data: {
5088
- title: "Enterprise Inquiry & Support Form",
5089
- subject: "Enterprise Inquiry & Support Submission"
5090
- }
5091
- });
5165
+ const n = Number(rawV);
5166
+ if (Number.isNaN(n)) continue;
5167
+ answeredCount += 1;
5168
+ scoredCount += 1;
5169
+ sum += n;
5170
+ distMap[n] = (distMap[n] || 0) + 1;
5171
+ if (q.type === "nps") {
5172
+ if (n >= 9) qPromoters += 1;
5173
+ else if (n >= 7) qPassives += 1;
5174
+ else qDetractors += 1;
5092
5175
  }
5093
- } catch {
5094
5176
  }
5177
+ const distribution = Object.keys(distMap).map(Number).sort((a, b) => a - b).map((value) => ({
5178
+ value,
5179
+ labels: q.scaleLabels ? q.scaleLabels[String(value)] : void 0,
5180
+ count: distMap[value] || 0,
5181
+ percentage: scoredCount > 0 ? Math.round((distMap[value] || 0) / scoredCount * 1e3) / 10 : 0
5182
+ }));
5183
+ return {
5184
+ ...baseInfo,
5185
+ answeredCount,
5186
+ scoredCount,
5187
+ allowNoOpinion: Boolean(q.allowNoOpinion),
5188
+ noOpinionCount,
5189
+ noOpinionPercentage: answeredCount > 0 ? Math.round(noOpinionCount / answeredCount * 1e3) / 10 : 0,
5190
+ noOpinionLabels: resolveNoOpinionLabels(q.noOpinionLabel),
5191
+ min: minVal,
5192
+ max: maxVal,
5193
+ lowLabel: q.lowLabel,
5194
+ highLabel: q.highLabel,
5195
+ scaleLabels: q.scaleLabels,
5196
+ average: scoredCount > 0 ? Math.round(sum / scoredCount * 100) / 100 : 0,
5197
+ distribution,
5198
+ npsBreakdown: q.type === "nps" ? {
5199
+ score: scoredCount > 0 ? Math.round((qPromoters - qDetractors) / scoredCount * 100) : 0,
5200
+ promoters: qPromoters,
5201
+ passives: qPassives,
5202
+ detractors: qDetractors,
5203
+ promotersPct: scoredCount > 0 ? Math.round(qPromoters / scoredCount * 1e3) / 10 : 0,
5204
+ passivesPct: scoredCount > 0 ? Math.round(qPassives / scoredCount * 1e3) / 10 : 0,
5205
+ detractorsPct: scoredCount > 0 ? Math.round(qDetractors / scoredCount * 1e3) / 10 : 0
5206
+ } : void 0
5207
+ };
5095
5208
  }
5096
- await this.ensureSampleSubmissions(force);
5097
- await updateDemoSeedState(strapi, { formsInitialized: true });
5098
- },
5099
- async purgeDemoForms() {
5100
- let deletedForms = 0;
5101
- let deletedFormSubmissions = 0;
5102
- const demoSlugs = DEFAULT_SEED_FORMS.map((f) => f.slug);
5103
- for (const slug of demoSlugs) {
5104
- try {
5105
- const existingForm = await strapi.db.query(FORM_UID).findOne({
5106
- where: { slug }
5107
- });
5108
- const matchingSubs = await strapi.db.query(SUBMISSION_UID).findMany({
5109
- where: existingForm ? {
5110
- $or: [
5111
- { formSlug: slug },
5112
- { formId: String(existingForm.documentId || existingForm.id) },
5113
- { formId: String(existingForm.id) }
5114
- ]
5115
- } : { formSlug: slug }
5116
- }) || [];
5117
- if (matchingSubs.length > 0) {
5118
- const subIds = matchingSubs.map((s) => s.id).filter((id) => id !== void 0 && id !== null);
5119
- if (subIds.length > 0) {
5120
- await strapi.db.query(SUBMISSION_UID).deleteMany({
5121
- where: { id: { $in: subIds } }
5122
- });
5123
- }
5124
- await strapi.db.query(SUBMISSION_UID).deleteMany({
5125
- where: { formSlug: slug }
5126
- });
5127
- deletedFormSubmissions += matchingSubs.length;
5209
+ if (q.type === "matrix_single") {
5210
+ const mRows = Array.isArray(q.matrixRows) ? q.matrixRows : [];
5211
+ const baseCols = Array.isArray(q.matrixColumns) ? q.matrixColumns : [];
5212
+ const matrixData = {};
5213
+ const rowTotals = {};
5214
+ let anyNoOpinionCell = false;
5215
+ for (const rItem of mRows) {
5216
+ matrixData[rItem.id] = {};
5217
+ rowTotals[rItem.id] = 0;
5218
+ for (const cItem of baseCols) {
5219
+ matrixData[rItem.id][cItem.id] = 0;
5128
5220
  }
5129
- if (existingForm) {
5130
- await strapi.db.query(FORM_UID).delete({
5131
- where: { id: existingForm.id }
5132
- });
5133
- deletedForms += 1;
5221
+ }
5222
+ for (const r of responses) {
5223
+ const valObj = r.answers?.[q.key];
5224
+ if (!valObj || typeof valObj !== "object" || Array.isArray(valObj)) continue;
5225
+ let anyRow = false;
5226
+ for (const rItem of mRows) {
5227
+ const chosenCol = valObj[rItem.id];
5228
+ if (!isEmptyFieldValue(chosenCol)) {
5229
+ anyRow = true;
5230
+ if (chosenCol === NO_OPINION_VALUE) anyNoOpinionCell = true;
5231
+ rowTotals[rItem.id] = (rowTotals[rItem.id] || 0) + 1;
5232
+ if (matrixData[rItem.id]) {
5233
+ matrixData[rItem.id][chosenCol] = (matrixData[rItem.id][chosenCol] || 0) + 1;
5234
+ }
5235
+ }
5134
5236
  }
5135
- } catch {
5237
+ if (anyRow) answeredCount += 1;
5136
5238
  }
5239
+ const effectiveCols = q.allowNoOpinion || anyNoOpinionCell ? [
5240
+ ...baseCols,
5241
+ {
5242
+ id: NO_OPINION_VALUE,
5243
+ labels: resolveNoOpinionLabels(q.noOpinionLabel)
5244
+ }
5245
+ ] : baseCols;
5246
+ const rowsBreakdown = mRows.map((rItem) => {
5247
+ const rTot = rowTotals[rItem.id] || 0;
5248
+ return {
5249
+ rowId: rItem.id,
5250
+ labels: rItem.labels,
5251
+ total: rTot,
5252
+ columns: effectiveCols.map((cItem) => {
5253
+ const cnt = matrixData[rItem.id]?.[cItem.id] || 0;
5254
+ return {
5255
+ colId: cItem.id,
5256
+ labels: cItem.labels,
5257
+ count: cnt,
5258
+ percentage: rTot > 0 ? Math.round(cnt / rTot * 1e3) / 10 : 0
5259
+ };
5260
+ })
5261
+ };
5262
+ });
5263
+ return {
5264
+ ...baseInfo,
5265
+ answeredCount,
5266
+ rowsBreakdown
5267
+ };
5137
5268
  }
5138
- return {
5139
- deletedForms,
5140
- deletedFormSubmissions
5141
- };
5142
- },
5143
- async findRawByIdOrSlug(idOrSlug) {
5144
- await this.ensureSeeded();
5145
- const raw = String(idOrSlug || "").trim();
5146
- if (!raw) return null;
5147
- let found = null;
5148
- const numericId = Number(raw);
5149
- if (!Number.isNaN(numericId) && String(numericId) === raw) {
5150
- found = await strapi.db.query(FORM_UID).findOne({ where: { id: numericId } });
5151
- }
5152
- if (!found) {
5153
- found = await strapi.db.query(FORM_UID).findOne({ where: { documentId: raw } });
5154
- }
5155
- if (!found) {
5156
- found = await strapi.db.query(FORM_UID).findOne({ where: { slug: raw } });
5157
- }
5158
- return found;
5159
- },
5160
- async findAllAdmin() {
5161
- await this.ensureSeeded();
5162
- const entries = await strapi.db.query(FORM_UID).findMany({
5163
- orderBy: { createdAt: "desc" }
5164
- });
5165
- return (entries || []).map(formatFormForAdmin);
5166
- },
5167
- async findAllPublic() {
5168
- await this.ensureSeeded();
5169
- const entries = await strapi.db.query(FORM_UID).findMany({
5170
- orderBy: { createdAt: "desc" }
5171
- });
5172
- return (entries || []).map(sanitizeFormForPublic);
5173
- },
5174
- async findOneAdmin(idOrSlug) {
5175
- const found = await this.findRawByIdOrSlug(idOrSlug);
5176
- return formatFormForAdmin(found);
5177
- },
5178
- async findOnePublic(idOrSlug) {
5179
- const found = await this.findRawByIdOrSlug(idOrSlug);
5180
- return sanitizeFormForPublic(found);
5181
- },
5182
- async save(payload) {
5183
- const cleanTitle = String(payload.title || "New Dynamic Form").trim();
5184
- const cleanSlug = String(
5185
- payload.slug || slugifyIdentifier$1(cleanTitle) || `form_${Date.now()}`
5186
- ).trim();
5187
- let existing = null;
5188
- if (payload.id) {
5189
- const rawId = String(payload.id).trim();
5190
- const numId = Number(rawId);
5191
- if (!Number.isNaN(numId) && String(numId) === rawId) {
5192
- existing = await strapi.db.query(FORM_UID).findOne({ where: { id: numId } });
5193
- } else {
5194
- existing = await strapi.db.query(FORM_UID).findOne({ where: { documentId: rawId } });
5269
+ if (q.type === "ranking") {
5270
+ const opts = Array.isArray(q.options) ? q.options : [];
5271
+ const nOpts = opts.length;
5272
+ const rankSumMap = {};
5273
+ const bordaSumMap = {};
5274
+ const firstPlaceMap = {};
5275
+ const itemCountMap = {};
5276
+ let rankedCount = 0;
5277
+ let noOpinionCount = 0;
5278
+ opts.forEach((o) => {
5279
+ rankSumMap[o.id] = 0;
5280
+ bordaSumMap[o.id] = 0;
5281
+ firstPlaceMap[o.id] = 0;
5282
+ itemCountMap[o.id] = 0;
5283
+ });
5284
+ for (const r of responses) {
5285
+ const arr = r.answers?.[q.key];
5286
+ if (arr === NO_OPINION_VALUE || Array.isArray(arr) && arr[0] === NO_OPINION_VALUE) {
5287
+ answeredCount += 1;
5288
+ noOpinionCount += 1;
5289
+ continue;
5290
+ }
5291
+ if (!Array.isArray(arr) || arr.length === 0) continue;
5292
+ answeredCount += 1;
5293
+ rankedCount += 1;
5294
+ arr.forEach((optId, idx) => {
5295
+ if (rankSumMap[optId] !== void 0) {
5296
+ rankSumMap[optId] += idx + 1;
5297
+ bordaSumMap[optId] += Math.max(1, nOpts - idx);
5298
+ itemCountMap[optId] += 1;
5299
+ if (idx === 0) firstPlaceMap[optId] += 1;
5300
+ }
5301
+ });
5195
5302
  }
5303
+ const maxPossibleBorda = rankedCount * nOpts;
5304
+ const rankingBreakdown = opts.map((o) => {
5305
+ const cnt = itemCountMap[o.id] || 0;
5306
+ const avgRank = cnt > 0 ? Math.round(rankSumMap[o.id] / cnt * 100) / 100 : nOpts;
5307
+ const bordaPoints = bordaSumMap[o.id] || 0;
5308
+ const firstPlaces = firstPlaceMap[o.id] || 0;
5309
+ return {
5310
+ id: o.id,
5311
+ labels: o.labels,
5312
+ averageRank: avgRank,
5313
+ bordaPoints,
5314
+ scorePercentage: maxPossibleBorda > 0 ? Math.round(bordaPoints / maxPossibleBorda * 1e3) / 10 : 0,
5315
+ firstPlaceCount: firstPlaces,
5316
+ firstPlacePercentage: rankedCount > 0 ? Math.round(firstPlaces / rankedCount * 1e3) / 10 : 0
5317
+ };
5318
+ }).sort((a, b) => a.averageRank - b.averageRank);
5319
+ return {
5320
+ ...baseInfo,
5321
+ answeredCount,
5322
+ rankedCount,
5323
+ allowNoOpinion: Boolean(q.allowNoOpinion),
5324
+ noOpinionCount,
5325
+ noOpinionPercentage: answeredCount > 0 ? Math.round(noOpinionCount / answeredCount * 1e3) / 10 : 0,
5326
+ noOpinionLabels: resolveNoOpinionLabels(q.noOpinionLabel),
5327
+ rankingBreakdown
5328
+ };
5196
5329
  }
5197
- if (!existing && cleanSlug) {
5198
- existing = await strapi.db.query(FORM_UID).findOne({ where: { slug: cleanSlug } });
5330
+ if (q.type === "consent") {
5331
+ let acceptedCount = 0;
5332
+ for (const r of responses) {
5333
+ const v = r.answers?.[q.key];
5334
+ if (v === true || v === "true" || v === 1) {
5335
+ answeredCount += 1;
5336
+ acceptedCount += 1;
5337
+ }
5338
+ }
5339
+ return {
5340
+ ...baseInfo,
5341
+ answeredCount,
5342
+ acceptedCount,
5343
+ acceptedPercentage: totalResponses > 0 ? Math.round(acceptedCount / totalResponses * 1e3) / 10 : 0
5344
+ };
5199
5345
  }
5200
- const mergedMailConfig = {
5201
- ...existing?.mailConfig || { driver: "env" },
5202
- ...payload.mailConfig || {}
5203
- };
5204
- if (mergedMailConfig.driver === "mailtrap" && mergedMailConfig.apiKey && !String(mergedMailConfig.inboxId || "").trim()) {
5205
- const autoInbox = await discoverMailtrapSandboxInbox(mergedMailConfig.apiKey);
5206
- if (autoInbox) {
5207
- mergedMailConfig.inboxId = autoInbox;
5346
+ const textResponses = [];
5347
+ for (const r of responses) {
5348
+ const v = r.answers?.[q.key];
5349
+ if (typeof v === "string" && v.trim()) {
5350
+ answeredCount += 1;
5351
+ if (textResponses.length < 100) {
5352
+ textResponses.push({
5353
+ id: r.id || r.documentId,
5354
+ text: v.trim(),
5355
+ locale: r.locale || "en",
5356
+ submittedAt: r.submittedAt || r.createdAt || "",
5357
+ npsValue: r.npsValue ?? null
5358
+ });
5359
+ }
5208
5360
  }
5209
5361
  }
5210
- const recordData = {
5211
- title: cleanTitle,
5212
- slug: cleanSlug,
5213
- to: payload.to ?? existing?.to ?? "",
5214
- subject: payload.subject ?? existing?.subject ?? cleanTitle,
5215
- buttonLabel: payload.buttonLabel ?? existing?.buttonLabel ?? {
5216
- tr: "Gönder",
5217
- en: "Submit"
5218
- },
5219
- successMessage: payload.successMessage ?? existing?.successMessage ?? {
5220
- tr: "Mesajınız başarıyla iletildi.",
5221
- en: "Your message has been sent successfully."
5222
- },
5223
- redirect: payload.redirect ?? existing?.redirect ?? "",
5224
- hideLabels: Boolean(payload.hideLabels ?? existing?.hideLabels ?? false),
5225
- useRecaptcha: payload.useRecaptcha !== void 0 ? Boolean(payload.useRecaptcha) : existing?.useRecaptcha !== void 0 ? Boolean(existing.useRecaptcha) : true,
5226
- recaptchaSiteKey: payload.recaptchaSiteKey !== void 0 ? String(payload.recaptchaSiteKey) : existing?.recaptchaSiteKey || "",
5227
- recaptchaSecretKey: payload.recaptchaSecretKey !== void 0 ? String(payload.recaptchaSecretKey) : existing?.recaptchaSecretKey || "",
5228
- mailConfig: mergedMailConfig,
5229
- fields: payload.fields && typeof payload.fields === "object" ? payload.fields : existing?.fields || {},
5230
- form: Array.isArray(payload.form) ? payload.form : existing?.form || []
5362
+ return {
5363
+ ...baseInfo,
5364
+ answeredCount,
5365
+ textResponses
5231
5366
  };
5232
- if (existing) {
5233
- const updated = await strapi.db.query(FORM_UID).update({
5234
- where: { id: existing.id },
5235
- data: recordData
5236
- });
5237
- return formatFormForAdmin(updated);
5238
- }
5239
- const created = await strapi.db.query(FORM_UID).create({
5240
- data: recordData
5241
- });
5242
- return formatFormForAdmin(created);
5243
- },
5244
- async remove(idOrDocId) {
5245
- const raw = String(idOrDocId || "").trim();
5246
- const numericId = Number(raw);
5247
- if (!Number.isNaN(numericId) && String(numericId) === raw) {
5248
- await strapi.db.query(FORM_UID).delete({ where: { id: numericId } });
5367
+ });
5368
+ return {
5369
+ summary: {
5370
+ totalResponses,
5371
+ unfilteredTotalResponses: (rawResponses || []).length,
5372
+ quotaLimit: survey.quotaLimit || null,
5373
+ quotaPercentage: survey.quotaLimit && survey.quotaLimit > 0 ? Math.min(100, Math.round((rawResponses || []).length / survey.quotaLimit * 1e3) / 10) : null,
5374
+ avgDurationSeconds,
5375
+ medianDurationSeconds,
5376
+ lastSubmittedAt,
5377
+ localeBreakdown,
5378
+ dailyTrend,
5379
+ nps: {
5380
+ hasNps: totalNpsResponses > 0,
5381
+ score: npsScore,
5382
+ promoters,
5383
+ passives,
5384
+ detractors,
5385
+ promotersPct,
5386
+ passivesPct,
5387
+ detractorsPct,
5388
+ totalNpsResponses
5389
+ }
5390
+ },
5391
+ questionStats
5392
+ };
5393
+ }
5394
+ function computePublicSurveyResults(survey, rawResponses) {
5395
+ const full = computeSurveyAnalytics(survey, rawResponses);
5396
+ return {
5397
+ totalResponses: full.summary.totalResponses,
5398
+ questions: full.questionStats.filter((qs) => qs.type !== "short_text" && qs.type !== "long_text" && qs.type !== "consent").map((qs) => ({
5399
+ key: qs.key,
5400
+ type: qs.type,
5401
+ title: qs.title,
5402
+ answeredCount: qs.answeredCount,
5403
+ scoredCount: qs.scoredCount,
5404
+ noOpinionCount: qs.noOpinionCount,
5405
+ noOpinionPercentage: qs.noOpinionPercentage,
5406
+ noOpinionLabels: qs.noOpinionLabels,
5407
+ optionsBreakdown: qs.optionsBreakdown,
5408
+ average: qs.average,
5409
+ distribution: qs.distribution,
5410
+ scaleLabels: qs.scaleLabels,
5411
+ npsBreakdown: qs.npsBreakdown,
5412
+ rankingBreakdown: qs.rankingBreakdown
5413
+ }))
5414
+ };
5415
+ }
5416
+ function escapeCsvCell(val) {
5417
+ const str = val === null || val === void 0 ? "" : String(val);
5418
+ if (/[",\r\n]/.test(str)) {
5419
+ return `"${str.replace(/"/g, '""')}"`;
5420
+ }
5421
+ return str;
5422
+ }
5423
+ function buildSurveyResponseExportAoA(survey, rawResponses, locale = "en") {
5424
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
5425
+ const activeQuestions = (survey.questions || []).filter((q) => q && q.type !== "statement");
5426
+ const headers = tr ? [
5427
+ "Yanıt ID",
5428
+ "Gönderim Tarihi",
5429
+ "Dil",
5430
+ "Süre (sn)",
5431
+ "NPS Puanı",
5432
+ "NPS Kategorisi"
5433
+ ] : [
5434
+ "Response ID",
5435
+ "Submitted At",
5436
+ "Locale",
5437
+ "Duration (s)",
5438
+ "NPS Value",
5439
+ "NPS Category"
5440
+ ];
5441
+ for (const q of activeQuestions) {
5442
+ const qTitle = resolveLocalizedText(q.title, locale, q.key);
5443
+ if (q.type === "matrix_single" && Array.isArray(q.matrixRows)) {
5444
+ for (const mRow of q.matrixRows) {
5445
+ const rTitle = resolveLocalizedText(mRow.labels, locale, mRow.id);
5446
+ headers.push(`${qTitle} [${rTitle}]`);
5447
+ }
5249
5448
  } else {
5250
- const byDoc = await strapi.db.query(FORM_UID).findOne({ where: { documentId: raw } });
5251
- if (byDoc) {
5252
- await strapi.db.query(FORM_UID).delete({ where: { id: byDoc.id } });
5253
- } else {
5254
- await strapi.db.query(FORM_UID).delete({ where: { slug: raw } });
5449
+ headers.push(`${qTitle} (${q.key})`);
5450
+ if (q.allowOther) {
5451
+ headers.push(`${qTitle} [${tr ? "Diğer Açıklama" : "Other Text"}]`);
5255
5452
  }
5256
5453
  }
5257
- return { success: true };
5258
- },
5259
- async listSubmissions(formIdOrSlug) {
5260
- const where = {};
5261
- if (formIdOrSlug) {
5262
- const form = await this.findRawByIdOrSlug(formIdOrSlug);
5263
- if (form) {
5264
- where.$or = [
5265
- { formId: String(form.documentId || form.id) },
5266
- { formId: String(form.id) },
5267
- { formSlug: form.slug }
5268
- ];
5454
+ }
5455
+ const rows = [];
5456
+ for (const r of rawResponses || []) {
5457
+ const rowCells = [
5458
+ String(r.id || r.documentId || ""),
5459
+ String(r.submittedAt || r.createdAt || ""),
5460
+ String(r.locale || ""),
5461
+ typeof r.durationSeconds === "number" ? r.durationSeconds : String(r.durationSeconds ?? ""),
5462
+ typeof r.npsValue === "number" ? r.npsValue : r.npsValue !== null && r.npsValue !== void 0 && r.npsValue !== "" ? Number(r.npsValue) : "",
5463
+ String(r.npsCategory || "")
5464
+ ];
5465
+ for (const q of activeQuestions) {
5466
+ const ans = r.answers?.[q.key];
5467
+ const noOpLabel = resolveLocalizedText(
5468
+ resolveNoOpinionLabels(q.noOpinionLabel),
5469
+ locale,
5470
+ tr ? "Fikrim yok" : "No idea"
5471
+ );
5472
+ if (q.type === "matrix_single" && Array.isArray(q.matrixRows)) {
5473
+ const mCols = Array.isArray(q.matrixColumns) ? q.matrixColumns : [];
5474
+ for (const mRow of q.matrixRows) {
5475
+ const chosenColId = ans && typeof ans === "object" ? ans[mRow.id] : "";
5476
+ if (chosenColId === NO_OPINION_VALUE) {
5477
+ rowCells.push(noOpLabel);
5478
+ } else {
5479
+ const foundCol = mCols.find((c) => c.id === chosenColId);
5480
+ rowCells.push(
5481
+ foundCol ? resolveLocalizedText(foundCol.labels, locale, chosenColId) : String(chosenColId || "")
5482
+ );
5483
+ }
5484
+ }
5485
+ } else if (Array.isArray(q.options) && q.options.length > 0) {
5486
+ if (Array.isArray(ans)) {
5487
+ const mapped = ans.map((optId) => {
5488
+ if (optId === "__other__") return tr ? "Diğer" : "Other";
5489
+ if (optId === NO_OPINION_VALUE) return noOpLabel;
5490
+ const found = q.options.find((o) => o.id === optId);
5491
+ return found ? resolveLocalizedText(found.labels, locale, optId) : optId;
5492
+ });
5493
+ rowCells.push(mapped.join(q.type === "ranking" ? " > " : "; "));
5494
+ } else if (ans !== void 0 && ans !== null && ans !== "") {
5495
+ const strAns = String(ans);
5496
+ if (strAns === "__other__") {
5497
+ rowCells.push(tr ? "Diğer" : "Other");
5498
+ } else if (strAns === NO_OPINION_VALUE) {
5499
+ rowCells.push(noOpLabel);
5500
+ } else {
5501
+ const found = q.options.find((o) => o.id === strAns);
5502
+ rowCells.push(found ? resolveLocalizedText(found.labels, locale, strAns) : strAns);
5503
+ }
5504
+ } else {
5505
+ rowCells.push("");
5506
+ }
5507
+ if (q.allowOther) {
5508
+ rowCells.push(String(r.otherTexts?.[q.key] || ""));
5509
+ }
5269
5510
  } else {
5270
- where.$or = [{ formId: formIdOrSlug }, { formSlug: formIdOrSlug }];
5511
+ if (ans === NO_OPINION_VALUE) {
5512
+ rowCells.push(noOpLabel);
5513
+ } else if (q.type === "likert_scale" && q.scaleLabels && ans !== void 0 && ans !== null && ans !== "") {
5514
+ const ptLbl = resolveLocalizedText(q.scaleLabels[String(ans)], locale, "");
5515
+ rowCells.push(ptLbl ? `${ans} - ${ptLbl}` : Number.isNaN(Number(ans)) ? String(ans) : Number(ans));
5516
+ } else if ((q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") && ans !== void 0 && ans !== null && ans !== "" && !Number.isNaN(Number(ans))) {
5517
+ rowCells.push(Number(ans));
5518
+ } else {
5519
+ rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
5520
+ }
5521
+ if (q.allowOther) {
5522
+ rowCells.push(String(r.otherTexts?.[q.key] || ""));
5523
+ }
5271
5524
  }
5272
5525
  }
5273
- const rows = await strapi.db.query(SUBMISSION_UID).findMany({
5274
- where: Object.keys(where).length > 0 ? where : void 0,
5275
- orderBy: { createdAt: "desc" },
5276
- limit: 200
5277
- });
5278
- return rows || [];
5279
- },
5280
- getPublicRecaptchaConfig() {
5281
- const publicKey = getEnvRecaptchaPublicKey$1();
5282
- return {
5283
- publicKey,
5284
- enabled: Boolean(publicKey)
5285
- };
5286
- },
5287
- async submitForm(idOrSlug, rawBody, meta = {}) {
5288
- const form = await this.findRawByIdOrSlug(idOrSlug);
5289
- if (!form) {
5290
- return {
5291
- ok: false,
5292
- status: 404,
5293
- message: "Form not found"
5294
- };
5295
- }
5296
- const body = rawBody && typeof rawBody === "object" ? rawBody : {};
5297
- const rawLocale = String(body._locale || meta.locale || "en").trim().toLowerCase();
5298
- const locale = rawLocale ? rawLocale.split(/[,;]/)[0].trim() : "en";
5299
- const fieldsMap = form.fields && typeof form.fields === "object" ? form.fields : {};
5300
- const { errors } = validateFormSubmission(fieldsMap, body, locale);
5301
- const activeSecretKey = String(
5302
- form.recaptchaSecretKey || getEnvRecaptchaPrivateKey$1() || ""
5303
- ).trim();
5304
- const activePublicKey = String(
5305
- form.recaptchaSiteKey || getEnvRecaptchaPublicKey$1() || ""
5306
- ).trim();
5307
- if (form.useRecaptcha !== false && activeSecretKey && activePublicKey) {
5308
- const recaptchaToken = body["g-recaptcha-response"];
5309
- const recaptchaValid = await verifyRecaptchaToken(
5310
- recaptchaToken,
5311
- activeSecretKey,
5312
- meta.ip
5313
- );
5314
- if (!recaptchaValid) {
5315
- errors["g-recaptcha-response"] = [
5316
- locale === "tr" ? "Lütfen robot olmadığınızı doğrulayınız (reCAPTCHA)." : "Please complete the reCAPTCHA verification."
5317
- ];
5526
+ rows.push(rowCells);
5527
+ }
5528
+ return { headers, rows };
5529
+ }
5530
+ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5531
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
5532
+ const lines = [headers.map(escapeCsvCell).join(",")];
5533
+ for (const r of rows) {
5534
+ lines.push(r.map(escapeCsvCell).join(","));
5535
+ }
5536
+ return `\uFEFF${lines.join("\r\n")}`;
5537
+ }
5538
+ function exportSurveyResponsesToXlsxBuffer(survey, rawResponses, locale = "en", customOptions = {}) {
5539
+ return buildSurveyExecutiveXlsxBuffer(survey, rawResponses, {
5540
+ ...customOptions,
5541
+ locale: customOptions.locale || locale
5542
+ });
5543
+ }
5544
+ const CRC_TABLE = (() => {
5545
+ const table = new Uint32Array(256);
5546
+ for (let i = 0; i < 256; i++) {
5547
+ let c = i;
5548
+ for (let k = 0; k < 8; k++) {
5549
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
5550
+ }
5551
+ table[i] = c >>> 0;
5552
+ }
5553
+ return table;
5554
+ })();
5555
+ function crc32(bytes) {
5556
+ let crc = 4294967295;
5557
+ for (let i = 0; i < bytes.length; i++) {
5558
+ crc = CRC_TABLE[(crc ^ bytes[i]) & 255] ^ crc >>> 8;
5559
+ }
5560
+ return (crc ^ 4294967295) >>> 0;
5561
+ }
5562
+ function buildZipStoreBuffer(entries) {
5563
+ const enc = new TextEncoder();
5564
+ const localChunks = [];
5565
+ const centralChunks = [];
5566
+ let offset = 0;
5567
+ for (const entry of entries) {
5568
+ const nameBytes = enc.encode(entry.path);
5569
+ const data = typeof entry.data === "string" ? enc.encode(entry.data) : entry.data;
5570
+ const checksum = crc32(data);
5571
+ const lh = new Uint8Array(30 + nameBytes.length);
5572
+ const lhv = new DataView(lh.buffer);
5573
+ lhv.setUint32(0, 67324752, true);
5574
+ lhv.setUint16(4, 20, true);
5575
+ lhv.setUint16(6, 2048, true);
5576
+ lhv.setUint16(8, 0, true);
5577
+ lhv.setUint16(10, 0, true);
5578
+ lhv.setUint16(12, 33, true);
5579
+ lhv.setUint32(14, checksum, true);
5580
+ lhv.setUint32(18, data.length, true);
5581
+ lhv.setUint32(22, data.length, true);
5582
+ lhv.setUint16(26, nameBytes.length, true);
5583
+ lhv.setUint16(28, 0, true);
5584
+ lh.set(nameBytes, 30);
5585
+ localChunks.push(lh, data);
5586
+ const ch = new Uint8Array(46 + nameBytes.length);
5587
+ const chv = new DataView(ch.buffer);
5588
+ chv.setUint32(0, 33639248, true);
5589
+ chv.setUint16(4, 20, true);
5590
+ chv.setUint16(6, 20, true);
5591
+ chv.setUint16(8, 2048, true);
5592
+ chv.setUint16(10, 0, true);
5593
+ chv.setUint16(12, 0, true);
5594
+ chv.setUint16(14, 33, true);
5595
+ chv.setUint32(16, checksum, true);
5596
+ chv.setUint32(20, data.length, true);
5597
+ chv.setUint32(24, data.length, true);
5598
+ chv.setUint16(28, nameBytes.length, true);
5599
+ chv.setUint16(30, 0, true);
5600
+ chv.setUint16(32, 0, true);
5601
+ chv.setUint16(34, 0, true);
5602
+ chv.setUint16(36, 0, true);
5603
+ chv.setUint32(38, 0, true);
5604
+ chv.setUint32(42, offset, true);
5605
+ ch.set(nameBytes, 46);
5606
+ centralChunks.push(ch);
5607
+ offset += lh.length + data.length;
5608
+ }
5609
+ const centralSize = centralChunks.reduce((acc, c) => acc + c.length, 0);
5610
+ const eocd = new Uint8Array(22);
5611
+ const ev = new DataView(eocd.buffer);
5612
+ ev.setUint32(0, 101010256, true);
5613
+ ev.setUint16(4, 0, true);
5614
+ ev.setUint16(6, 0, true);
5615
+ ev.setUint16(8, entries.length, true);
5616
+ ev.setUint16(10, entries.length, true);
5617
+ ev.setUint32(12, centralSize, true);
5618
+ ev.setUint32(16, offset, true);
5619
+ ev.setUint16(20, 0, true);
5620
+ const totalLen = offset + centralSize + eocd.length;
5621
+ const out = Buffer.allocUnsafe(totalLen);
5622
+ let pos = 0;
5623
+ for (const chunk of localChunks) {
5624
+ out.set(chunk, pos);
5625
+ pos += chunk.length;
5626
+ }
5627
+ for (const chunk of centralChunks) {
5628
+ out.set(chunk, pos);
5629
+ pos += chunk.length;
5630
+ }
5631
+ out.set(eocd, pos);
5632
+ return out;
5633
+ }
5634
+ function escapeXml(raw) {
5635
+ return String(raw ?? "").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
5636
+ }
5637
+ function colLetter(zeroBasedCol) {
5638
+ let n = zeroBasedCol + 1;
5639
+ let out = "";
5640
+ while (n > 0) {
5641
+ const rem = (n - 1) % 26;
5642
+ out = String.fromCharCode(65 + rem) + out;
5643
+ n = Math.floor((n - 1) / 26);
5644
+ }
5645
+ return out;
5646
+ }
5647
+ function cellRef(zeroBasedCol, oneBasedRow) {
5648
+ return `${colLetter(zeroBasedCol)}${oneBasedRow}`;
5649
+ }
5650
+ function sanitizeSheetName(raw) {
5651
+ const clean = String(raw || "Sheet").replace(/[\\/?*[\]:']/g, "_").trim().slice(0, 31);
5652
+ return clean || "Sheet";
5653
+ }
5654
+ function parseHex6(raw, fallback = "1E3A8A") {
5655
+ if (!raw) return fallback;
5656
+ const match = String(raw).match(/#([0-9a-fA-F]{6})\b/);
5657
+ if (match) return match[1].toUpperCase();
5658
+ const shortMatch = String(raw).match(/#([0-9a-fA-F]{3})\b/);
5659
+ if (shortMatch) {
5660
+ const [r, g, b] = shortMatch[1].split("");
5661
+ return `${r}${r}${g}${g}${b}${b}`.toUpperCase();
5662
+ }
5663
+ if (/^[0-9a-fA-F]{6}$/.test(String(raw).trim())) {
5664
+ return String(raw).trim().toUpperCase();
5665
+ }
5666
+ return fallback;
5667
+ }
5668
+ function mixWithWhite(hex6, ratioWhite) {
5669
+ const r = parseInt(hex6.slice(0, 2), 16);
5670
+ const g = parseInt(hex6.slice(2, 4), 16);
5671
+ const b = parseInt(hex6.slice(4, 6), 16);
5672
+ const mr = Math.min(255, Math.round(r * (1 - ratioWhite) + 255 * ratioWhite));
5673
+ const mg = Math.min(255, Math.round(g * (1 - ratioWhite) + 255 * ratioWhite));
5674
+ const mb = Math.min(255, Math.round(b * (1 - ratioWhite) + 255 * ratioWhite));
5675
+ return [mr, mg, mb].map((v) => v.toString(16).padStart(2, "0")).join("").toUpperCase();
5676
+ }
5677
+ const CHART_SERIES_PALETTE = [
5678
+ "2563EB",
5679
+ "059669",
5680
+ "D97706",
5681
+ "7C3AED",
5682
+ "DB2777",
5683
+ "0891B2",
5684
+ "4F46E5",
5685
+ "DC2626",
5686
+ "65A30D",
5687
+ "64748B"
5688
+ ];
5689
+ const S = {
5690
+ BANNER_TITLE: 1,
5691
+ BANNER_SUB: 2,
5692
+ TBL_HEADER: 3,
5693
+ TBL_HEADER_CENTER: 4,
5694
+ SECTION_HDR: 5,
5695
+ KPI_LABEL: 6,
5696
+ KPI_VAL: 7,
5697
+ KPI_NPS_POS: 8,
5698
+ KPI_NPS_PAS: 9,
5699
+ KPI_NPS_NEG: 10,
5700
+ CELL_WHITE: 11,
5701
+ CELL_ZEBRA: 12,
5702
+ INT_WHITE: 13,
5703
+ INT_ZEBRA: 14,
5704
+ PCT_WHITE: 15,
5705
+ PCT_ZEBRA: 16,
5706
+ AVG_HIGHLIGHT: 17,
5707
+ BADGE_PROM: 18,
5708
+ BADGE_PASS: 19,
5709
+ BADGE_DETR: 20,
5710
+ NA_TEXT: 21,
5711
+ NA_INT: 22,
5712
+ NA_PCT: 23,
5713
+ WRAP_WHITE: 24,
5714
+ WRAP_ZEBRA: 25
5715
+ };
5716
+ function buildStylesXml(primaryHex6) {
5717
+ const softHex6 = mixWithWhite(primaryHex6, 0.88);
5718
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
5719
+ <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
5720
+ <numFmts count="3">
5721
+ <numFmt numFmtId="164" formatCode="#,##0"/>
5722
+ <numFmt numFmtId="165" formatCode="0.0%"/>
5723
+ <numFmt numFmtId="166" formatCode="0.00"/>
5724
+ </numFmts>
5725
+ <fonts count="11">
5726
+ <font><sz val="10"/><color rgb="FF0F172A"/><name val="Calibri"/></font>
5727
+ <font><b/><sz val="16"/><color rgb="FFFFFFFF"/><name val="Calibri"/></font>
5728
+ <font><i/><sz val="10"/><color rgb="FFE2E8F0"/><name val="Calibri"/></font>
5729
+ <font><b/><sz val="10.5"/><color rgb="FFFFFFFF"/><name val="Calibri"/></font>
5730
+ <font><b/><sz val="11"/><color rgb="FF${primaryHex6}"/><name val="Calibri"/></font>
5731
+ <font><b/><sz val="9.5"/><color rgb="FF475569"/><name val="Calibri"/></font>
5732
+ <font><b/><sz val="15"/><color rgb="FF0F172A"/><name val="Calibri"/></font>
5733
+ <font><b/><sz val="10.5"/><color rgb="FF166534"/><name val="Calibri"/></font>
5734
+ <font><b/><sz val="10.5"/><color rgb="FF92400E"/><name val="Calibri"/></font>
5735
+ <font><b/><sz val="10.5"/><color rgb="FF991B1B"/><name val="Calibri"/></font>
5736
+ <font><i/><sz val="10"/><color rgb="FF475569"/><name val="Calibri"/></font>
5737
+ </fonts>
5738
+ <fills count="10">
5739
+ <fill><patternFill patternType="none"/></fill>
5740
+ <fill><patternFill patternType="gray125"/></fill>
5741
+ <fill><patternFill patternType="solid"><fgColor rgb="FF${primaryHex6}"/></patternFill></fill>
5742
+ <fill><patternFill patternType="solid"><fgColor rgb="FF${softHex6}"/></patternFill></fill>
5743
+ <fill><patternFill patternType="solid"><fgColor rgb="FFFFFFFF"/></patternFill></fill>
5744
+ <fill><patternFill patternType="solid"><fgColor rgb="FFF8FAFC"/></patternFill></fill>
5745
+ <fill><patternFill patternType="solid"><fgColor rgb="FFDCFCE7"/></patternFill></fill>
5746
+ <fill><patternFill patternType="solid"><fgColor rgb="FFFEF3C7"/></patternFill></fill>
5747
+ <fill><patternFill patternType="solid"><fgColor rgb="FFFEE2E2"/></patternFill></fill>
5748
+ <fill><patternFill patternType="solid"><fgColor rgb="FFF1F5F9"/></patternFill></fill>
5749
+ </fills>
5750
+ <borders count="3">
5751
+ <border><left/><right/><top/><bottom/><diagonal/></border>
5752
+ <border>
5753
+ <left style="thin"><color rgb="FFE2E8F0"/></left>
5754
+ <right style="thin"><color rgb="FFE2E8F0"/></right>
5755
+ <top style="thin"><color rgb="FFE2E8F0"/></top>
5756
+ <bottom style="thin"><color rgb="FFE2E8F0"/></bottom>
5757
+ <diagonal/>
5758
+ </border>
5759
+ <border>
5760
+ <left style="thin"><color rgb="FFCBD5E1"/></left>
5761
+ <right style="thin"><color rgb="FFCBD5E1"/></right>
5762
+ <top style="thin"><color rgb="FFCBD5E1"/></top>
5763
+ <bottom style="medium"><color rgb="FF${primaryHex6}"/></bottom>
5764
+ <diagonal/>
5765
+ </border>
5766
+ </borders>
5767
+ <cellStyleXfs count="1">
5768
+ <xf numFmtId="0" fontId="0" fillId="0" borderId="0"/>
5769
+ </cellStyleXfs>
5770
+ <cellXfs count="26">
5771
+ <xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>
5772
+ <xf numFmtId="0" fontId="1" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1" applyAlignment="1"><alignment vertical="center" indent="1"/></xf>
5773
+ <xf numFmtId="0" fontId="2" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1" applyAlignment="1"><alignment vertical="center" wrapText="1" indent="1"/></xf>
5774
+ <xf numFmtId="0" fontId="3" fillId="2" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="center"/></xf>
5775
+ <xf numFmtId="0" fontId="3" fillId="2" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
5776
+ <xf numFmtId="0" fontId="4" fillId="3" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="center"/></xf>
5777
+ <xf numFmtId="0" fontId="5" fillId="3" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="center"/></xf>
5778
+ <xf numFmtId="0" fontId="6" fillId="4" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
5779
+ <xf numFmtId="0" fontId="7" fillId="6" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
5780
+ <xf numFmtId="0" fontId="8" fillId="7" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
5781
+ <xf numFmtId="0" fontId="9" fillId="8" borderId="2" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="left" vertical="center"/></xf>
5782
+ <xf numFmtId="0" fontId="0" fillId="4" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="center"/></xf>
5783
+ <xf numFmtId="0" fontId="0" fillId="5" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="center"/></xf>
5784
+ <xf numFmtId="164" fontId="0" fillId="4" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
5785
+ <xf numFmtId="164" fontId="0" fillId="5" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
5786
+ <xf numFmtId="165" fontId="0" fillId="4" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
5787
+ <xf numFmtId="165" fontId="0" fillId="5" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
5788
+ <xf numFmtId="166" fontId="4" fillId="3" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
5789
+ <xf numFmtId="0" fontId="7" fillId="6" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
5790
+ <xf numFmtId="0" fontId="8" fillId="7" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
5791
+ <xf numFmtId="0" fontId="9" fillId="8" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="center" vertical="center"/></xf>
5792
+ <xf numFmtId="0" fontId="10" fillId="9" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="center"/></xf>
5793
+ <xf numFmtId="164" fontId="10" fillId="9" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
5794
+ <xf numFmtId="165" fontId="10" fillId="9" borderId="1" xfId="0" applyNumberFormat="1" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment horizontal="right" vertical="center"/></xf>
5795
+ <xf numFmtId="0" fontId="0" fillId="4" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="top" wrapText="1"/></xf>
5796
+ <xf numFmtId="0" fontId="0" fillId="5" borderId="1" xfId="0" applyFont="1" applyFill="1" applyBorder="1" applyAlignment="1"><alignment vertical="top" wrapText="1"/></xf>
5797
+ </cellXfs>
5798
+ </styleSheet>`;
5799
+ }
5800
+ class WorksheetModel {
5801
+ constructor(name, opts) {
5802
+ this.rows = /* @__PURE__ */ new Map();
5803
+ this.rowHeights = /* @__PURE__ */ new Map();
5804
+ this.colWidths = /* @__PURE__ */ new Map();
5805
+ this.merges = [];
5806
+ this.condFormats = [];
5807
+ this.autoFilterRef = "";
5808
+ this.freezeTopRows = 0;
5809
+ this.showGridLines = true;
5810
+ this.drawingRelId = "";
5811
+ this.maxCol = 0;
5812
+ this.maxRow = 1;
5813
+ this.name = sanitizeSheetName(name);
5814
+ this.tabColorHex6 = opts?.tabColorHex6;
5815
+ if (opts?.showGridLines !== void 0) this.showGridLines = opts.showGridLines;
5816
+ }
5817
+ setColWidth(zeroCol, width) {
5818
+ this.colWidths.set(zeroCol, width);
5819
+ if (zeroCol > this.maxCol) this.maxCol = zeroCol;
5820
+ }
5821
+ setRowHeight(oneRow, heightPt) {
5822
+ this.rowHeights.set(oneRow, heightPt);
5823
+ if (oneRow > this.maxRow) this.maxRow = oneRow;
5824
+ }
5825
+ setCell(zeroCol, oneRow, spec) {
5826
+ if (!this.rows.has(oneRow)) this.rows.set(oneRow, /* @__PURE__ */ new Map());
5827
+ this.rows.get(oneRow).set(zeroCol, spec);
5828
+ if (zeroCol > this.maxCol) this.maxCol = zeroCol;
5829
+ if (oneRow > this.maxRow) this.maxRow = oneRow;
5830
+ }
5831
+ setMergedBox(startCol, startRow, endCol, endRow, spec) {
5832
+ for (let r = startRow; r <= endRow; r++) {
5833
+ for (let c = startCol; c <= endCol; c++) {
5834
+ if (r === startRow && c === startCol) {
5835
+ this.setCell(c, r, spec);
5836
+ } else {
5837
+ this.setCell(c, r, { value: null, style: spec.style });
5838
+ }
5318
5839
  }
5319
5840
  }
5320
- if (Object.keys(errors).length > 0) {
5321
- return {
5322
- ok: false,
5323
- status: 422,
5324
- errors
5325
- };
5841
+ if (startCol !== endCol || startRow !== endRow) {
5842
+ this.merges.push(`${cellRef(startCol, startRow)}:${cellRef(endCol, endRow)}`);
5326
5843
  }
5327
- const cleanData = {};
5328
- const definedKeys = Object.keys(fieldsMap);
5329
- if (definedKeys.length > 0) {
5330
- for (const k of definedKeys) {
5331
- cleanData[k] = body[k] !== void 0 ? body[k] : null;
5332
- }
5333
- } else {
5334
- for (const [k, v] of Object.entries(body)) {
5335
- if (k === "g-recaptcha-response" || k === "_locale") continue;
5336
- cleanData[k] = v;
5844
+ }
5845
+ setAutoFilter(ref) {
5846
+ this.autoFilterRef = ref;
5847
+ }
5848
+ setFreezeTopRows(count) {
5849
+ this.freezeTopRows = count;
5850
+ }
5851
+ addDataBar(sqref, hex6) {
5852
+ this.condFormats.push(
5853
+ `<conditionalFormatting sqref="${sqref}"><cfRule type="dataBar" priority="${this.condFormats.length + 1}"><dataBar><cfvo type="num" val="0"/><cfvo type="num" val="1"/><color rgb="FF${hex6}"/></dataBar></cfRule></conditionalFormatting>`
5854
+ );
5855
+ }
5856
+ addColorScale(sqref, hex6) {
5857
+ const midHex = mixWithWhite(hex6, 0.55);
5858
+ this.condFormats.push(
5859
+ `<conditionalFormatting sqref="${sqref}"><cfRule type="colorScale" priority="${this.condFormats.length + 1}"><colorScale><cfvo type="num" val="0"/><cfvo type="num" val="0.5"/><cfvo type="num" val="1"/><color rgb="FFF8FAFC"/><color rgb="FF${midHex}"/><color rgb="FF${hex6}"/></colorScale></cfRule></conditionalFormatting>`
5860
+ );
5861
+ }
5862
+ setDrawingRelId(rId) {
5863
+ this.drawingRelId = rId;
5864
+ }
5865
+ toXml() {
5866
+ const dimRef = `A1:${cellRef(this.maxCol, this.maxRow)}`;
5867
+ const sheetPrXml = this.tabColorHex6 ? `<sheetPr><tabColor rgb="FF${this.tabColorHex6}"/></sheetPr>` : "";
5868
+ const paneXml = this.freezeTopRows > 0 ? `<pane ySplit="${this.freezeTopRows}" topLeftCell="A${this.freezeTopRows + 1}" activePane="bottomLeft" state="frozen"/>` : "";
5869
+ const sheetViewsXml = `<sheetViews><sheetView showGridLines="${this.showGridLines ? 1 : 0}" workbookViewId="0">${paneXml}</sheetView></sheetViews>`;
5870
+ const colsList = [];
5871
+ for (let c = 0; c <= this.maxCol; c++) {
5872
+ const w = this.colWidths.get(c) ?? 15;
5873
+ colsList.push(`<col min="${c + 1}" max="${c + 1}" width="${w}" customWidth="1"/>`);
5874
+ }
5875
+ const colsXml = `<cols>${colsList.join("")}</cols>`;
5876
+ const sortedRowNums = Array.from(this.rows.keys()).sort((a, b) => a - b);
5877
+ const rowXmlParts = [];
5878
+ for (const rNum of sortedRowNums) {
5879
+ const rowCells = this.rows.get(rNum);
5880
+ const sortedCols = Array.from(rowCells.keys()).sort((a, b) => a - b);
5881
+ const ht = this.rowHeights.get(rNum);
5882
+ const htAttr = ht ? ` ht="${ht}" customHeight="1"` : "";
5883
+ const cellParts = [];
5884
+ for (const cIdx of sortedCols) {
5885
+ const cell = rowCells.get(cIdx);
5886
+ const ref = cellRef(cIdx, rNum);
5887
+ const sAttr = cell.style !== void 0 ? ` s="${cell.style}"` : "";
5888
+ if (cell.formula) {
5889
+ const cached = typeof cell.value === "number" && Number.isFinite(cell.value) ? `<v>${cell.value}</v>` : "";
5890
+ cellParts.push(`<c r="${ref}"${sAttr}><f>${escapeXml(cell.formula)}</f>${cached}</c>`);
5891
+ } else if (typeof cell.value === "number" && Number.isFinite(cell.value)) {
5892
+ cellParts.push(`<c r="${ref}"${sAttr}><v>${cell.value}</v></c>`);
5893
+ } else if (cell.value !== null && cell.value !== void 0 && cell.value !== "") {
5894
+ const str = String(cell.value);
5895
+ const preserve = /^\s|\s$|[\r\n]/.test(str) ? ' xml:space="preserve"' : "";
5896
+ cellParts.push(
5897
+ `<c r="${ref}"${sAttr} t="inlineStr"><is><t${preserve}>${escapeXml(str)}</t></is></c>`
5898
+ );
5899
+ } else if (cell.style !== void 0) {
5900
+ cellParts.push(`<c r="${ref}"${sAttr}/>`);
5901
+ }
5902
+ }
5903
+ rowXmlParts.push(`<row r="${rNum}"${htAttr}>${cellParts.join("")}</row>`);
5904
+ }
5905
+ const autoFilterXml = this.autoFilterRef ? `<autoFilter ref="${this.autoFilterRef}"/>` : "";
5906
+ const mergeCellsXml = this.merges.length > 0 ? `<mergeCells count="${this.merges.length}">${this.merges.map((m) => `<mergeCell ref="${m}"/>`).join("")}</mergeCells>` : "";
5907
+ const condXml = this.condFormats.join("");
5908
+ const drawingXml = this.drawingRelId ? `<drawing r:id="${this.drawingRelId}"/>` : "";
5909
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
5910
+ <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
5911
+ ${sheetPrXml}
5912
+ <dimension ref="${dimRef}"/>
5913
+ ${sheetViewsXml}
5914
+ <sheetFormatPr defaultRowHeight="20"/>
5915
+ ${colsXml}
5916
+ <sheetData>${rowXmlParts.join("")}</sheetData>
5917
+ ${autoFilterXml}
5918
+ ${mergeCellsXml}
5919
+ ${condXml}
5920
+ ${drawingXml}
5921
+ </worksheet>`;
5922
+ }
5923
+ }
5924
+ function buildStrCacheXml(items) {
5925
+ const pts = items.map((v, i) => `<c:pt idx="${i}"><c:v>${escapeXml(v)}</c:v></c:pt>`).join("");
5926
+ return `<c:strCache><c:ptCount val="${items.length}"/>${pts}</c:strCache>`;
5927
+ }
5928
+ function buildNumCacheXml(items, fmt = "#,##0") {
5929
+ const pts = items.map((v, i) => `<c:pt idx="${i}"><c:v>${Number.isFinite(v) ? v : 0}</c:v></c:pt>`).join("");
5930
+ return `<c:numCache><c:formatCode>${escapeXml(fmt)}</c:formatCode><c:ptCount val="${items.length}"/>${pts}</c:numCache>`;
5931
+ }
5932
+ function buildChartTitleXml(title) {
5933
+ return `<c:title>
5934
+ <c:tx>
5935
+ <c:rich>
5936
+ <a:bodyPr/>
5937
+ <a:lstStyle/>
5938
+ <a:p>
5939
+ <a:pPr><a:defRPr sz="1100" b="1"><a:solidFill><a:srgbClr val="0F172A"/></a:solidFill></a:defRPr></a:pPr>
5940
+ <a:r><a:rPr lang="en-US" sz="1100" b="1"><a:solidFill><a:srgbClr val="0F172A"/></a:solidFill></a:rPr><a:t>${escapeXml(
5941
+ title
5942
+ )}</a:t></a:r>
5943
+ </a:p>
5944
+ </c:rich>
5945
+ </c:tx>
5946
+ <c:overlay val="0"/>
5947
+ </c:title>
5948
+ <c:autoTitleDeleted val="0"/>`;
5949
+ }
5950
+ function buildChartXml(spec, chartIndex) {
5951
+ const catAxId = 1e5 + chartIndex * 10 + 1;
5952
+ const valAxId = 1e5 + chartIndex * 10 + 2;
5953
+ let plotElementXml = "";
5954
+ let axesXml = "";
5955
+ const showLegend = spec.kind === "doughnut" || spec.series.length > 1;
5956
+ if (spec.kind === "doughnut") {
5957
+ const ser = spec.series[0];
5958
+ const sliceColorsXml = ser.categories.map((_c, idx) => {
5959
+ const clr = CHART_SERIES_PALETTE[idx % CHART_SERIES_PALETTE.length];
5960
+ return `<c:dPt><c:idx val="${idx}"/><c:bubble3D val="0"/><c:spPr><a:solidFill><a:srgbClr val="${clr}"/></a:solidFill><a:ln w="12700"><a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill></a:ln></c:spPr></c:dPt>`;
5961
+ }).join("");
5962
+ plotElementXml = `<c:doughnutChart>
5963
+ <c:varyColors val="1"/>
5964
+ <c:ser>
5965
+ <c:idx val="0"/>
5966
+ <c:order val="0"/>
5967
+ <c:tx><c:v>${escapeXml(ser.name)}</c:v></c:tx>
5968
+ ${sliceColorsXml}
5969
+ <c:cat><c:strRef><c:f>${escapeXml(ser.catFormula)}</c:f>${buildStrCacheXml(
5970
+ ser.categories
5971
+ )}</c:strRef></c:cat>
5972
+ <c:val><c:numRef><c:f>${escapeXml(ser.valFormula)}</c:f>${buildNumCacheXml(
5973
+ ser.values,
5974
+ ser.numberFormat
5975
+ )}</c:numRef></c:val>
5976
+ </c:ser>
5977
+ <c:dLbls>
5978
+ <c:showLegendKey val="0"/>
5979
+ <c:showVal val="0"/>
5980
+ <c:showCatName val="0"/>
5981
+ <c:showSerName val="0"/>
5982
+ <c:showPercent val="1"/>
5983
+ <c:showBubbleSize val="0"/>
5984
+ </c:dLbls>
5985
+ <c:firstSliceAng val="0"/>
5986
+ <c:holeSize val="55"/>
5987
+ </c:doughnutChart>`;
5988
+ } else if (spec.kind === "line") {
5989
+ const serXml = spec.series.map(
5990
+ (s, idx) => `<c:ser>
5991
+ <c:idx val="${idx}"/>
5992
+ <c:order val="${idx}"/>
5993
+ <c:tx><c:v>${escapeXml(s.name)}</c:v></c:tx>
5994
+ <c:spPr>
5995
+ <a:ln w="25400" cap="rnd"><a:solidFill><a:srgbClr val="${s.colorHex6}"/></a:solidFill></a:ln>
5996
+ </c:spPr>
5997
+ <c:marker><c:symbol val="circle"/><c:size val="5"/><c:spPr><a:solidFill><a:srgbClr val="${s.colorHex6}"/></a:solidFill></c:spPr></c:marker>
5998
+ <c:cat><c:strRef><c:f>${escapeXml(s.catFormula)}</c:f>${buildStrCacheXml(
5999
+ s.categories
6000
+ )}</c:strRef></c:cat>
6001
+ <c:val><c:numRef><c:f>${escapeXml(s.valFormula)}</c:f>${buildNumCacheXml(
6002
+ s.values,
6003
+ s.numberFormat
6004
+ )}</c:numRef></c:val>
6005
+ <c:smooth val="0"/>
6006
+ </c:ser>`
6007
+ ).join("");
6008
+ plotElementXml = `<c:lineChart>
6009
+ <c:grouping val="standard"/>
6010
+ <c:varyColors val="0"/>
6011
+ ${serXml}
6012
+ <c:dLbls>
6013
+ <c:showLegendKey val="0"/>
6014
+ <c:showVal val="0"/>
6015
+ <c:showCatName val="0"/>
6016
+ <c:showSerName val="0"/>
6017
+ <c:showPercent val="0"/>
6018
+ <c:showBubbleSize val="0"/>
6019
+ </c:dLbls>
6020
+ <c:axId val="${catAxId}"/>
6021
+ <c:axId val="${valAxId}"/>
6022
+ </c:lineChart>`;
6023
+ axesXml = `<c:catAx>
6024
+ <c:axId val="${catAxId}"/>
6025
+ <c:scaling><c:orientation val="minMax"/></c:scaling>
6026
+ <c:delete val="0"/>
6027
+ <c:axPos val="b"/>
6028
+ <c:majorTickMark val="out"/>
6029
+ <c:minorTickMark val="none"/>
6030
+ <c:tickLblPos val="nextTo"/>
6031
+ <c:crossAx val="${valAxId}"/>
6032
+ <c:crosses val="autoZero"/>
6033
+ <c:auto val="1"/>
6034
+ <c:lblAlgn val="ctr"/>
6035
+ <c:lblOffset val="100"/>
6036
+ </c:catAx>
6037
+ <c:valAx>
6038
+ <c:axId val="${valAxId}"/>
6039
+ <c:scaling><c:orientation val="minMax"/></c:scaling>
6040
+ <c:delete val="0"/>
6041
+ <c:axPos val="l"/>
6042
+ <c:majorGridlines><c:spPr><a:ln w="9525"><a:solidFill><a:srgbClr val="E2E8F0"/></a:solidFill></a:ln></c:spPr></c:majorGridlines>
6043
+ <c:numFmt formatCode="#,##0" sourceLinked="0"/>
6044
+ <c:majorTickMark val="none"/>
6045
+ <c:minorTickMark val="none"/>
6046
+ <c:tickLblPos val="nextTo"/>
6047
+ <c:crossAx val="${catAxId}"/>
6048
+ <c:crosses val="autoZero"/>
6049
+ <c:crossBetween val="between"/>
6050
+ </c:valAx>`;
6051
+ } else {
6052
+ const barDir = spec.kind === "bar" ? "bar" : "col";
6053
+ const catPos = barDir === "bar" ? "l" : "b";
6054
+ const valPos = barDir === "bar" ? "b" : "l";
6055
+ const catOrientation = barDir === "bar" ? "maxMin" : "minMax";
6056
+ const crossesMode = barDir === "bar" ? "max" : "autoZero";
6057
+ const serXml = spec.series.map(
6058
+ (s, idx) => `<c:ser>
6059
+ <c:idx val="${idx}"/>
6060
+ <c:order val="${idx}"/>
6061
+ <c:tx><c:v>${escapeXml(s.name)}</c:v></c:tx>
6062
+ <c:spPr><a:solidFill><a:srgbClr val="${s.colorHex6}"/></a:solidFill></c:spPr>
6063
+ <c:invertIfNegative val="0"/>
6064
+ <c:cat><c:strRef><c:f>${escapeXml(s.catFormula)}</c:f>${buildStrCacheXml(
6065
+ s.categories
6066
+ )}</c:strRef></c:cat>
6067
+ <c:val><c:numRef><c:f>${escapeXml(s.valFormula)}</c:f>${buildNumCacheXml(
6068
+ s.values,
6069
+ s.numberFormat
6070
+ )}</c:numRef></c:val>
6071
+ </c:ser>`
6072
+ ).join("");
6073
+ plotElementXml = `<c:barChart>
6074
+ <c:barDir val="${barDir}"/>
6075
+ <c:grouping val="clustered"/>
6076
+ <c:varyColors val="0"/>
6077
+ ${serXml}
6078
+ <c:dLbls>
6079
+ <c:showLegendKey val="0"/>
6080
+ <c:showVal val="1"/>
6081
+ <c:showCatName val="0"/>
6082
+ <c:showSerName val="0"/>
6083
+ <c:showPercent val="0"/>
6084
+ <c:showBubbleSize val="0"/>
6085
+ </c:dLbls>
6086
+ <c:gapWidth val="140"/>
6087
+ <c:axId val="${catAxId}"/>
6088
+ <c:axId val="${valAxId}"/>
6089
+ </c:barChart>`;
6090
+ axesXml = `<c:catAx>
6091
+ <c:axId val="${catAxId}"/>
6092
+ <c:scaling><c:orientation val="${catOrientation}"/></c:scaling>
6093
+ <c:delete val="0"/>
6094
+ <c:axPos val="${catPos}"/>
6095
+ <c:majorTickMark val="none"/>
6096
+ <c:minorTickMark val="none"/>
6097
+ <c:tickLblPos val="nextTo"/>
6098
+ <c:crossAx val="${valAxId}"/>
6099
+ <c:crosses val="autoZero"/>
6100
+ <c:auto val="1"/>
6101
+ <c:lblAlgn val="ctr"/>
6102
+ <c:lblOffset val="100"/>
6103
+ </c:catAx>
6104
+ <c:valAx>
6105
+ <c:axId val="${valAxId}"/>
6106
+ <c:scaling><c:orientation val="minMax"/></c:scaling>
6107
+ <c:delete val="0"/>
6108
+ <c:axPos val="${valPos}"/>
6109
+ <c:majorGridlines><c:spPr><a:ln w="9525"><a:solidFill><a:srgbClr val="E2E8F0"/></a:solidFill></a:ln></c:spPr></c:majorGridlines>
6110
+ <c:numFmt formatCode="#,##0" sourceLinked="0"/>
6111
+ <c:majorTickMark val="none"/>
6112
+ <c:minorTickMark val="none"/>
6113
+ <c:tickLblPos val="nextTo"/>
6114
+ <c:crossAx val="${catAxId}"/>
6115
+ <c:crosses val="${crossesMode}"/>
6116
+ <c:crossBetween val="between"/>
6117
+ </c:valAx>`;
6118
+ }
6119
+ const legendXml = showLegend ? `<c:legend><c:legendPos val="b"/><c:overlay val="0"/></c:legend>` : "";
6120
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6121
+ <c:chartSpace xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
6122
+ <c:roundedCorners val="0"/>
6123
+ <c:chart>
6124
+ ${buildChartTitleXml(spec.title)}
6125
+ <c:plotArea>
6126
+ <c:layout/>
6127
+ ${plotElementXml}
6128
+ ${axesXml}
6129
+ </c:plotArea>
6130
+ ${legendXml}
6131
+ <c:plotVisOnly val="1"/>
6132
+ <c:dispBlanksAs val="gap"/>
6133
+ </c:chart>
6134
+ <c:spPr>
6135
+ <a:solidFill><a:srgbClr val="FFFFFF"/></a:solidFill>
6136
+ <a:ln w="12700"><a:solidFill><a:srgbClr val="CBD5E1"/></a:solidFill></a:ln>
6137
+ </c:spPr>
6138
+ </c:chartSpace>`;
6139
+ }
6140
+ function buildDrawingXml(charts) {
6141
+ const anchors = charts.map(
6142
+ (ch, idx) => `<xdr:twoCellAnchor>
6143
+ <xdr:from>
6144
+ <xdr:col>${ch.fromCol}</xdr:col>
6145
+ <xdr:colOff>76200</xdr:colOff>
6146
+ <xdr:row>${ch.fromRowZero}</xdr:row>
6147
+ <xdr:rowOff>76200</xdr:rowOff>
6148
+ </xdr:from>
6149
+ <xdr:to>
6150
+ <xdr:col>${ch.toCol}</xdr:col>
6151
+ <xdr:colOff>0</xdr:colOff>
6152
+ <xdr:row>${ch.toRowZero}</xdr:row>
6153
+ <xdr:rowOff>0</xdr:rowOff>
6154
+ </xdr:to>
6155
+ <xdr:graphicFrame macro="">
6156
+ <xdr:nvGraphicFramePr>
6157
+ <xdr:cNvPr id="${idx + 2}" name="Chart ${idx + 1}"/>
6158
+ <xdr:cNvGraphicFramePr/>
6159
+ </xdr:nvGraphicFramePr>
6160
+ <xdr:xfrm>
6161
+ <a:off x="0" y="0"/>
6162
+ <a:ext cx="0" cy="0"/>
6163
+ </xdr:xfrm>
6164
+ <a:graphic>
6165
+ <a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/chart">
6166
+ <c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:id="rId${idx + 1}"/>
6167
+ </a:graphicData>
6168
+ </a:graphic>
6169
+ </xdr:graphicFrame>
6170
+ <xdr:clientData/>
6171
+ </xdr:twoCellAnchor>`
6172
+ ).join("");
6173
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6174
+ <xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
6175
+ ${anchors}
6176
+ </xdr:wsDr>`;
6177
+ }
6178
+ function getDefaultChartKindForQuestion(qType, displayMode) {
6179
+ if (qType === "nps" || qType === "star_rating" || qType === "likert_scale" || qType === "matrix_single") {
6180
+ return "col";
6181
+ }
6182
+ if (qType === "single_choice" && displayMode === "quick_poll") {
6183
+ return "doughnut";
6184
+ }
6185
+ if (qType === "single_choice" || qType === "multiple_choice" || qType === "dropdown" || qType === "image_choice" || qType === "ranking") {
6186
+ return "bar";
6187
+ }
6188
+ return "none";
6189
+ }
6190
+ function buildSurveyExecutiveXlsxBuffer(survey, rawResponses, options2 = {}) {
6191
+ const locale = options2.locale || "en";
6192
+ const tr = String(locale).toLowerCase().startsWith("tr");
6193
+ const primaryHex6 = parseHex6(options2.themeColor, "1E3A8A");
6194
+ const includeTrendChart = options2.includeTrendChart !== false;
6195
+ const includeDataBars = options2.includeDataBars !== false;
6196
+ const includeRawSheet = options2.includeRawSheet !== false;
6197
+ const qOverrides = options2.questionOverrides || {};
6198
+ const analytics = computeSurveyAnalytics(survey, rawResponses, {
6199
+ from: options2.from,
6200
+ to: options2.to
6201
+ });
6202
+ const summary = analytics.summary;
6203
+ const dashSheetName = "1_Dashboard";
6204
+ const statsSheetName = tr ? "2_Ozet_Istatistik" : "2_Summary_Stats";
6205
+ const rawSheetName = tr ? "3_Ham_Yanitlar" : "3_Raw_Responses";
6206
+ const shStats = new WorksheetModel(statsSheetName, {
6207
+ tabColorHex6: "059669",
6208
+ showGridLines: true
6209
+ });
6210
+ shStats.setColWidth(0, 18);
6211
+ shStats.setColWidth(1, 38);
6212
+ shStats.setColWidth(2, 16);
6213
+ shStats.setColWidth(3, 16);
6214
+ shStats.setColWidth(4, 16);
6215
+ shStats.setFreezeTopRows(3);
6216
+ const resolvedReportTitle = options2.reportTitle && options2.reportTitle.trim() || resolveLocalizedText(survey.titleI18n, locale, survey.title);
6217
+ shStats.setRowHeight(1, 28);
6218
+ shStats.setMergedBox(0, 1, 5, 1, {
6219
+ value: `${resolvedReportTitle} — ${tr ? "Soru Bazlı İstatistik Özeti" : "Question Statistical Summary"}`,
6220
+ style: S.BANNER_TITLE
6221
+ });
6222
+ shStats.setRowHeight(2, 20);
6223
+ shStats.setMergedBox(0, 2, 5, 2, {
6224
+ value: tr ? `Toplam Yanıt: ${summary.totalResponses} • Ort. Süre: ${summary.avgDurationSeconds} sn • Bu sekmedeki değerler Dashboard grafiklerine canlı bağlıdır.` : `Total Responses: ${summary.totalResponses} • Avg Duration: ${summary.avgDurationSeconds}s • Values in this sheet feed the Dashboard charts live.`,
6225
+ style: S.BANNER_SUB
6226
+ });
6227
+ let statRow = 4;
6228
+ const pendingQuestionCharts = [];
6229
+ for (let qIdx = 0; qIdx < analytics.questionStats.length; qIdx++) {
6230
+ const qs = analytics.questionStats[qIdx];
6231
+ const ov = qOverrides[qs.key] || {};
6232
+ if (ov.included === false) continue;
6233
+ const baseQTitle = ov.customTitle && ov.customTitle.trim() || resolveLocalizedText(qs.title, locale, qs.key);
6234
+ const numberedTitle = `Q${qIdx + 1}. ${baseQTitle}`;
6235
+ const chosenChartKind = ov.chartType || getDefaultChartKindForQuestion(qs.type, survey.displayMode);
6236
+ shStats.setRowHeight(statRow, 24);
6237
+ shStats.setMergedBox(0, statRow, 5, statRow, {
6238
+ value: `${numberedTitle} [${qs.key}] — ${qs.answeredCount || 0} ${tr ? "Yanıt" : "Answers"}`,
6239
+ style: S.SECTION_HDR
6240
+ });
6241
+ statRow += 1;
6242
+ if (Array.isArray(qs.optionsBreakdown)) {
6243
+ shStats.setRowHeight(statRow, 21);
6244
+ shStats.setCell(0, statRow, { value: tr ? "Seçenek ID" : "Option ID", style: S.TBL_HEADER });
6245
+ shStats.setCell(1, statRow, { value: tr ? "Seçenek" : "Option Label", style: S.TBL_HEADER });
6246
+ shStats.setCell(2, statRow, { value: tr ? "Oy Sayısı" : "Votes", style: S.TBL_HEADER_CENTER });
6247
+ shStats.setCell(3, statRow, { value: tr ? "Oran (%)" : "Share (%)", style: S.TBL_HEADER_CENTER });
6248
+ statRow += 1;
6249
+ const dataStartRow = statRow;
6250
+ const cats = [];
6251
+ const vals = [];
6252
+ qs.optionsBreakdown.forEach((opt, idx) => {
6253
+ const isNa = opt.id === NO_OPINION_VALUE;
6254
+ const optLbl = opt.id === "__other__" ? tr ? "Diğer" : "Other" : resolveLocalizedText(opt.labels, locale, opt.id);
6255
+ const ratio = Math.max(0, Math.min(1, Number(opt.percentage || 0) / 100));
6256
+ const zebra = idx % 2 === 1;
6257
+ shStats.setCell(0, statRow, {
6258
+ value: opt.id,
6259
+ style: isNa ? S.NA_TEXT : zebra ? S.CELL_ZEBRA : S.CELL_WHITE
6260
+ });
6261
+ shStats.setCell(1, statRow, {
6262
+ value: optLbl,
6263
+ style: isNa ? S.NA_TEXT : zebra ? S.CELL_ZEBRA : S.CELL_WHITE
6264
+ });
6265
+ shStats.setCell(2, statRow, {
6266
+ value: Number(opt.count || 0),
6267
+ style: isNa ? S.NA_INT : zebra ? S.INT_ZEBRA : S.INT_WHITE
6268
+ });
6269
+ shStats.setCell(3, statRow, {
6270
+ value: ratio,
6271
+ style: isNa ? S.NA_PCT : zebra ? S.PCT_ZEBRA : S.PCT_WHITE
6272
+ });
6273
+ cats.push(optLbl);
6274
+ vals.push(Number(opt.count || 0));
6275
+ statRow += 1;
6276
+ });
6277
+ const dataEndRow = statRow - 1;
6278
+ if (includeDataBars && dataEndRow >= dataStartRow) {
6279
+ shStats.addDataBar(`D${dataStartRow}:D${dataEndRow}`, primaryHex6);
6280
+ }
6281
+ if (chosenChartKind !== "none" && cats.length > 0) {
6282
+ pendingQuestionCharts.push({
6283
+ kind: chosenChartKind,
6284
+ title: numberedTitle,
6285
+ series: [
6286
+ {
6287
+ name: tr ? "Oy Sayısı" : "Votes",
6288
+ colorHex6: primaryHex6,
6289
+ catFormula: `'${statsSheetName}'!$B$${dataStartRow}:$B$${dataEndRow}`,
6290
+ categories: cats,
6291
+ valFormula: `'${statsSheetName}'!$C$${dataStartRow}:$C$${dataEndRow}`,
6292
+ values: vals
6293
+ }
6294
+ ]
6295
+ });
5337
6296
  }
6297
+ statRow += 1;
6298
+ continue;
5338
6299
  }
5339
- const mailResult = await sendDynamicFormMail({
5340
- strapi,
5341
- form: {
5342
- title: form.title,
5343
- to: form.to,
5344
- subject: form.subject,
5345
- fields: fieldsMap,
5346
- mailConfig: form.mailConfig
5347
- },
5348
- data: cleanData,
5349
- meta: {
5350
- ip: meta.ip,
5351
- userAgent: meta.userAgent,
5352
- locale
6300
+ if (Array.isArray(qs.distribution)) {
6301
+ shStats.setRowHeight(statRow, 21);
6302
+ shStats.setCell(0, statRow, { value: tr ? "Metrik" : "Metric", style: S.KPI_LABEL });
6303
+ shStats.setCell(1, statRow, {
6304
+ value: qs.type === "nps" && qs.npsBreakdown ? `NPS: ${qs.npsBreakdown.score > 0 ? `+${qs.npsBreakdown.score}` : qs.npsBreakdown.score} (Promoters: ${qs.npsBreakdown.promoters}, Passives: ${qs.npsBreakdown.passives}, Detractors: ${qs.npsBreakdown.detractors})` : tr ? "Ağırlıklı Ortalama Puan" : "Weighted Average Score",
6305
+ style: S.KPI_LABEL
6306
+ });
6307
+ shStats.setCell(2, statRow, { value: Number(qs.average || 0), style: S.AVG_HIGHLIGHT });
6308
+ shStats.setCell(3, statRow, { value: `/ ${qs.max ?? 5}`, style: S.KPI_LABEL });
6309
+ statRow += 1;
6310
+ shStats.setRowHeight(statRow, 21);
6311
+ shStats.setCell(0, statRow, { value: tr ? "Puan" : "Score", style: S.TBL_HEADER });
6312
+ shStats.setCell(1, statRow, { value: tr ? "Puan Etiketi" : "Scale Label", style: S.TBL_HEADER });
6313
+ shStats.setCell(2, statRow, { value: tr ? "Yanıt Adedi" : "Count", style: S.TBL_HEADER_CENTER });
6314
+ shStats.setCell(3, statRow, { value: tr ? "Oran (%)" : "Share (%)", style: S.TBL_HEADER_CENTER });
6315
+ statRow += 1;
6316
+ const dataStartRow = statRow;
6317
+ const cats = [];
6318
+ const vals = [];
6319
+ qs.distribution.forEach((d, idx) => {
6320
+ const ptLbl = d.labels ? resolveLocalizedText(d.labels, locale, "") : "";
6321
+ const dispLbl = ptLbl ? `${d.value} — ${ptLbl}` : String(d.value);
6322
+ const ratio = Math.max(0, Math.min(1, Number(d.percentage || 0) / 100));
6323
+ const zebra = idx % 2 === 1;
6324
+ shStats.setCell(0, statRow, {
6325
+ value: Number(d.value),
6326
+ style: zebra ? S.INT_ZEBRA : S.INT_WHITE
6327
+ });
6328
+ shStats.setCell(1, statRow, {
6329
+ value: dispLbl,
6330
+ style: zebra ? S.CELL_ZEBRA : S.CELL_WHITE
6331
+ });
6332
+ shStats.setCell(2, statRow, {
6333
+ value: Number(d.count || 0),
6334
+ style: zebra ? S.INT_ZEBRA : S.INT_WHITE
6335
+ });
6336
+ shStats.setCell(3, statRow, {
6337
+ value: ratio,
6338
+ style: zebra ? S.PCT_ZEBRA : S.PCT_WHITE
6339
+ });
6340
+ cats.push(dispLbl);
6341
+ vals.push(Number(d.count || 0));
6342
+ statRow += 1;
6343
+ });
6344
+ const chartEndRow = statRow - 1;
6345
+ if (qs.allowNoOpinion || qs.noOpinionCount && qs.noOpinionCount > 0) {
6346
+ const noOpLbl = resolveLocalizedText(
6347
+ qs.noOpinionLabels,
6348
+ locale,
6349
+ tr ? "Fikrim yok" : "No idea"
6350
+ );
6351
+ shStats.setCell(0, statRow, { value: "N/A", style: S.NA_TEXT });
6352
+ shStats.setCell(1, statRow, {
6353
+ value: `${noOpLbl} (${tr ? "Ortalamaya katılmaz" : "Excluded from avg"})`,
6354
+ style: S.NA_TEXT
6355
+ });
6356
+ shStats.setCell(2, statRow, { value: Number(qs.noOpinionCount || 0), style: S.NA_INT });
6357
+ shStats.setCell(3, statRow, {
6358
+ value: Math.max(0, Math.min(1, Number(qs.noOpinionPercentage || 0) / 100)),
6359
+ style: S.NA_PCT
6360
+ });
6361
+ statRow += 1;
5353
6362
  }
5354
- });
5355
- const createdSubmission = await strapi.db.query(SUBMISSION_UID).create({
5356
- data: {
5357
- formId: String(form.documentId || form.id),
5358
- formSlug: form.slug,
5359
- formTitle: form.title,
5360
- data: cleanData,
5361
- ip: meta.ip || "",
5362
- userAgent: meta.userAgent || "",
5363
- mailSent: Boolean(mailResult.sent),
5364
- mailInfo: mailResult
6363
+ if (includeDataBars && chartEndRow >= dataStartRow) {
6364
+ shStats.addDataBar(`D${dataStartRow}:D${chartEndRow}`, primaryHex6);
5365
6365
  }
5366
- });
5367
- const successMsg = resolveLocalizedText(
5368
- form.successMessage,
5369
- locale,
5370
- locale === "tr" ? "Mesajınız başarıyla gönderildi." : "Your message has been submitted successfully."
5371
- );
5372
- return {
5373
- ok: true,
5374
- status: 200,
5375
- submissionId: createdSubmission?.documentId || String(createdSubmission?.id || ""),
5376
- message: successMsg,
5377
- redirect: form.redirect || "",
5378
- mailSent: Boolean(mailResult.sent),
5379
- mailDriver: mailResult.driver
5380
- };
5381
- },
5382
- async resolveEntityCard(params) {
5383
- const uid = String(params.uid || "").trim();
5384
- if (!uid || !uid.startsWith("api::")) {
5385
- return null;
5386
- }
5387
- const ct = (strapi.contentTypes || {})[uid];
5388
- if (!ct) {
5389
- return null;
6366
+ if (chosenChartKind !== "none" && cats.length > 0) {
6367
+ pendingQuestionCharts.push({
6368
+ kind: chosenChartKind,
6369
+ title: `${numberedTitle} (${tr ? "Ort:" : "Avg:"} ${qs.average})`,
6370
+ series: [
6371
+ {
6372
+ name: tr ? "Yanıt Adedi" : "Responses",
6373
+ colorHex6: qs.type === "nps" ? "059669" : primaryHex6,
6374
+ catFormula: `'${statsSheetName}'!$B$${dataStartRow}:$B$${chartEndRow}`,
6375
+ categories: cats,
6376
+ valFormula: `'${statsSheetName}'!$C$${dataStartRow}:$C$${chartEndRow}`,
6377
+ values: vals
6378
+ }
6379
+ ]
6380
+ });
6381
+ }
6382
+ statRow += 1;
6383
+ continue;
5390
6384
  }
5391
- const attrs = ct.attributes || {};
5392
- const populate = {};
5393
- const mediaFields = [];
5394
- const ciFields = [];
5395
- for (const [attrName, attrDef] of Object.entries(attrs)) {
5396
- if (attrDef?.type === "media") {
5397
- populate[attrName] = true;
5398
- mediaFields.push(attrName);
6385
+ if (qs.type === "matrix_single" && Array.isArray(qs.rowsBreakdown) && qs.rowsBreakdown.length > 0) {
6386
+ const colsMeta = qs.rowsBreakdown[0]?.columns || [];
6387
+ shStats.setRowHeight(statRow, 21);
6388
+ shStats.setCell(0, statRow, { value: tr ? "Satır ID" : "Row ID", style: S.TBL_HEADER });
6389
+ shStats.setCell(1, statRow, { value: tr ? "Değerlendirme Kriteri" : "Criterion", style: S.TBL_HEADER });
6390
+ colsMeta.forEach((cItem, cIdx) => {
6391
+ const colIdx = 2 + cIdx;
6392
+ shStats.setColWidth(colIdx, Math.max(15, resolveLocalizedText(cItem.labels, locale, cItem.colId).length + 5));
6393
+ shStats.setCell(colIdx, statRow, {
6394
+ value: resolveLocalizedText(cItem.labels, locale, cItem.colId),
6395
+ style: S.TBL_HEADER_CENTER
6396
+ });
6397
+ });
6398
+ statRow += 1;
6399
+ const dataStartRow = statRow;
6400
+ const rowLabels = [];
6401
+ const colValueVectors = colsMeta.map(() => []);
6402
+ qs.rowsBreakdown.forEach((rStat, rIdx) => {
6403
+ const rLbl = resolveLocalizedText(rStat.labels, locale, rStat.rowId);
6404
+ const zebra = rIdx % 2 === 1;
6405
+ rowLabels.push(rLbl);
6406
+ shStats.setCell(0, statRow, {
6407
+ value: rStat.rowId,
6408
+ style: zebra ? S.CELL_ZEBRA : S.CELL_WHITE
6409
+ });
6410
+ shStats.setCell(1, statRow, {
6411
+ value: rLbl,
6412
+ style: zebra ? S.CELL_ZEBRA : S.CELL_WHITE
6413
+ });
6414
+ (rStat.columns || []).forEach((cell, cIdx) => {
6415
+ const cnt = Number(cell.count || 0);
6416
+ colValueVectors[cIdx]?.push(cnt);
6417
+ shStats.setCell(2 + cIdx, statRow, {
6418
+ value: cnt,
6419
+ style: zebra ? S.INT_ZEBRA : S.INT_WHITE
6420
+ });
6421
+ });
6422
+ statRow += 1;
6423
+ });
6424
+ const dataEndRow = statRow - 1;
6425
+ if (includeDataBars && colsMeta.length > 0 && dataEndRow >= dataStartRow) {
6426
+ shStats.addColorScale(
6427
+ `C${dataStartRow}:${cellRef(1 + colsMeta.length, dataEndRow)}`,
6428
+ primaryHex6
6429
+ );
5399
6430
  }
5400
- if (attrDef?.customField === "plugin::content-input.content-input" || attrDef?.type === "json") {
5401
- ciFields.push(attrName);
6431
+ if (chosenChartKind !== "none" && rowLabels.length > 0 && colsMeta.length > 0) {
6432
+ const effectiveKind = chosenChartKind === "doughnut" ? "col" : chosenChartKind;
6433
+ const matrixSeries = colsMeta.map((cItem, cIdx) => {
6434
+ const cLetter = colLetter(2 + cIdx);
6435
+ return {
6436
+ name: resolveLocalizedText(cItem.labels, locale, cItem.colId),
6437
+ colorHex6: CHART_SERIES_PALETTE[cIdx % CHART_SERIES_PALETTE.length],
6438
+ catFormula: `'${statsSheetName}'!$B$${dataStartRow}:$B$${dataEndRow}`,
6439
+ categories: rowLabels,
6440
+ valFormula: `'${statsSheetName}'!$${cLetter}$${dataStartRow}:$${cLetter}$${dataEndRow}`,
6441
+ values: colValueVectors[cIdx] || []
6442
+ };
6443
+ });
6444
+ pendingQuestionCharts.push({
6445
+ kind: effectiveKind,
6446
+ title: numberedTitle,
6447
+ series: matrixSeries
6448
+ });
5402
6449
  }
6450
+ statRow += 1;
6451
+ continue;
5403
6452
  }
5404
- let rows = [];
5405
- try {
5406
- const where = {};
5407
- if (params.documentId) {
5408
- where.documentId = String(params.documentId);
5409
- } else if (params.id !== void 0 && params.id !== "") {
5410
- const numId = Number(params.id);
5411
- if (!Number.isNaN(numId)) where.id = numId;
5412
- } else if (params.slug) {
5413
- where.slug = String(params.slug);
5414
- }
5415
- rows = await strapi.db.query(uid).findMany({
5416
- where: Object.keys(where).length > 0 ? where : void 0,
5417
- populate: Object.keys(populate).length > 0 ? populate : void 0,
5418
- limit: 10,
5419
- orderBy: { id: "desc" }
6453
+ if (Array.isArray(qs.rankingBreakdown)) {
6454
+ shStats.setRowHeight(statRow, 21);
6455
+ shStats.setCell(0, statRow, { value: tr ? "Sıra" : "Rank", style: S.TBL_HEADER_CENTER });
6456
+ shStats.setCell(1, statRow, { value: tr ? "Seçenek" : "Item", style: S.TBL_HEADER });
6457
+ shStats.setCell(2, statRow, { value: tr ? "Borda Puanı" : "Borda Score", style: S.TBL_HEADER_CENTER });
6458
+ shStats.setCell(3, statRow, { value: tr ? "Skor Oranı (%)" : "Score (%)", style: S.TBL_HEADER_CENTER });
6459
+ shStats.setCell(4, statRow, { value: tr ? "Ort. Sıra" : "Avg Rank", style: S.TBL_HEADER_CENTER });
6460
+ statRow += 1;
6461
+ const dataStartRow = statRow;
6462
+ const cats = [];
6463
+ const vals = [];
6464
+ qs.rankingBreakdown.forEach((rk, idx) => {
6465
+ const lbl = resolveLocalizedText(rk.labels, locale, rk.id);
6466
+ const ratio = Math.max(0, Math.min(1, Number(rk.scorePercentage || 0) / 100));
6467
+ const zebra = idx % 2 === 1;
6468
+ shStats.setCell(0, statRow, { value: `#${idx + 1}`, style: zebra ? S.CELL_ZEBRA : S.CELL_WHITE });
6469
+ shStats.setCell(1, statRow, { value: lbl, style: zebra ? S.CELL_ZEBRA : S.CELL_WHITE });
6470
+ shStats.setCell(2, statRow, { value: Number(rk.bordaPoints || 0), style: zebra ? S.INT_ZEBRA : S.INT_WHITE });
6471
+ shStats.setCell(3, statRow, { value: ratio, style: zebra ? S.PCT_ZEBRA : S.PCT_WHITE });
6472
+ shStats.setCell(4, statRow, { value: Number(rk.averageRank || 0), style: S.AVG_HIGHLIGHT });
6473
+ cats.push(lbl);
6474
+ vals.push(Number(rk.bordaPoints || 0));
6475
+ statRow += 1;
5420
6476
  });
5421
- } catch {
5422
- rows = [];
5423
- }
5424
- if (!rows || rows.length === 0) {
5425
- return null;
6477
+ const dataEndRow = statRow - 1;
6478
+ if (includeDataBars && dataEndRow >= dataStartRow) {
6479
+ shStats.addDataBar(`D${dataStartRow}:D${dataEndRow}`, primaryHex6);
6480
+ }
6481
+ if (chosenChartKind !== "none" && cats.length > 0) {
6482
+ pendingQuestionCharts.push({
6483
+ kind: chosenChartKind,
6484
+ title: `${numberedTitle} (Borda)`,
6485
+ series: [
6486
+ {
6487
+ name: tr ? "Borda Puanı" : "Borda Points",
6488
+ colorHex6: primaryHex6,
6489
+ catFormula: `'${statsSheetName}'!$B$${dataStartRow}:$B$${dataEndRow}`,
6490
+ categories: cats,
6491
+ valFormula: `'${statsSheetName}'!$C$${dataStartRow}:$C$${dataEndRow}`,
6492
+ values: vals
6493
+ }
6494
+ ]
6495
+ });
6496
+ }
6497
+ statRow += 1;
6498
+ continue;
5426
6499
  }
5427
- const entry = rows.find((r) => Boolean(r.publishedAt)) || rows[0];
5428
- const titleCandidates = ["title", "name", "heading", "label", "subject", "baslik", "ad"];
5429
- const subtitleCandidates = ["subtitle", "kicker", "categoryName", "role", "department", "tag"];
5430
- const descCandidates = [
5431
- "description",
5432
- "excerpt",
5433
- "summary",
5434
- "seoDescription",
5435
- "shortDescription",
5436
- "lead",
5437
- "bio",
5438
- "ozet",
5439
- "aciklama"
5440
- ];
5441
- const imagePriority = [
5442
- "image",
5443
- "cover",
5444
- "thumbnail",
5445
- "featuredImage",
5446
- "photo",
5447
- "banner",
5448
- "media",
5449
- "avatar",
5450
- ...mediaFields
5451
- ];
5452
- const pickFirstString = (candidates) => {
5453
- for (const key of candidates) {
5454
- const val = entry[key];
5455
- if (typeof val === "string" && val.trim()) {
5456
- return stripHtmlTags(val);
6500
+ shStats.setCell(0, statRow, { value: qs.type, style: S.CELL_WHITE });
6501
+ shStats.setCell(1, statRow, {
6502
+ value: qs.type === "consent" ? tr ? "Onaylayan Katılımcı Sayısı" : "Accepted Count" : tr ? "Açık Uçlu Metin Yanıt Sayısı (3. Sekmede Detaylı)" : "Open-Ended Text Responses (See Sheet 3)",
6503
+ style: S.CELL_WHITE
6504
+ });
6505
+ shStats.setCell(2, statRow, {
6506
+ value: Number(qs.acceptedCount ?? qs.answeredCount ?? 0),
6507
+ style: S.INT_WHITE
6508
+ });
6509
+ statRow += 2;
6510
+ }
6511
+ let trendChartMeta = null;
6512
+ if (includeTrendChart && Array.isArray(summary.dailyTrend) && summary.dailyTrend.length > 0) {
6513
+ shStats.setRowHeight(statRow, 24);
6514
+ shStats.setMergedBox(0, statRow, 3, statRow, {
6515
+ value: tr ? "Günlük Katılım Trendi" : "Daily Participation Trend",
6516
+ style: S.SECTION_HDR
6517
+ });
6518
+ statRow += 1;
6519
+ shStats.setCell(0, statRow, { value: tr ? "Tarih" : "Date", style: S.TBL_HEADER });
6520
+ shStats.setCell(1, statRow, { value: tr ? "Yanıt Sayısı" : "Responses", style: S.TBL_HEADER_CENTER });
6521
+ statRow += 1;
6522
+ const tStart = statRow;
6523
+ const tDates = [];
6524
+ const tCounts = [];
6525
+ summary.dailyTrend.forEach((d, idx) => {
6526
+ const zebra = idx % 2 === 1;
6527
+ shStats.setCell(0, statRow, { value: d.date, style: zebra ? S.CELL_ZEBRA : S.CELL_WHITE });
6528
+ shStats.setCell(1, statRow, { value: Number(d.count || 0), style: zebra ? S.INT_ZEBRA : S.INT_WHITE });
6529
+ tDates.push(d.date);
6530
+ tCounts.push(Number(d.count || 0));
6531
+ statRow += 1;
6532
+ });
6533
+ const tEnd = statRow - 1;
6534
+ trendChartMeta = {
6535
+ kind: "line",
6536
+ title: tr ? "Günlük Katılım Trendi (Zaman Serisi)" : "Daily Participation Trend",
6537
+ series: [
6538
+ {
6539
+ name: tr ? "Günlük Yanıt" : "Daily Responses",
6540
+ colorHex6: primaryHex6,
6541
+ catFormula: `'${statsSheetName}'!$A$${tStart}:$A$${tEnd}`,
6542
+ categories: tDates,
6543
+ valFormula: `'${statsSheetName}'!$B$${tStart}:$B$${tEnd}`,
6544
+ values: tCounts
5457
6545
  }
5458
- }
5459
- return "";
6546
+ ]
5460
6547
  };
5461
- let title = pickFirstString(titleCandidates);
5462
- if (!title) {
5463
- const fallbackStrKey = Object.keys(attrs).find(
5464
- (k) => ["string", "text"].includes(attrs[k]?.type)
5465
- );
5466
- if (fallbackStrKey && typeof entry[fallbackStrKey] === "string") {
5467
- title = entry[fallbackStrKey];
6548
+ }
6549
+ const shDash = new WorksheetModel(dashSheetName, {
6550
+ tabColorHex6: primaryHex6,
6551
+ showGridLines: false
6552
+ });
6553
+ for (let c = 0; c < 8; c++) {
6554
+ shDash.setColWidth(c, 18);
6555
+ }
6556
+ const filterDesc = options2.from || options2.to ? ` • ${tr ? "Filtre:" : "Filter:"} ${options2.from || "..."} → ${options2.to || "..."}` : "";
6557
+ const defaultExecNote = tr ? `Rapor Tarihi: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)} • Slug: ${survey.slug}${filterDesc} • Tüm grafikler gerçek Excel nesnesidir ve '${statsSheetName}' sekmesine canlı bağlıdır.` : `Exported: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)} • Slug: ${survey.slug}${filterDesc} • All charts are native editable Excel objects linked to '${statsSheetName}'.`;
6558
+ shDash.setRowHeight(1, 34);
6559
+ shDash.setMergedBox(0, 1, 7, 1, {
6560
+ value: resolvedReportTitle,
6561
+ style: S.BANNER_TITLE
6562
+ });
6563
+ shDash.setRowHeight(2, 26);
6564
+ shDash.setMergedBox(0, 2, 7, 2, {
6565
+ value: options2.executiveNote && options2.executiveNote.trim() ? `${options2.executiveNote.trim()} (${defaultExecNote})` : defaultExecNote,
6566
+ style: S.BANNER_SUB
6567
+ });
6568
+ shDash.setRowHeight(4, 19);
6569
+ shDash.setRowHeight(5, 28);
6570
+ shDash.setMergedBox(0, 4, 1, 4, {
6571
+ value: tr ? "TOPLAM KATILIM" : "TOTAL RESPONSES",
6572
+ style: S.KPI_LABEL
6573
+ });
6574
+ shDash.setMergedBox(0, 5, 1, 5, {
6575
+ value: summary.quotaLimit ? `${summary.totalResponses} / ${summary.quotaLimit} (${summary.quotaPercentage || 0}%)` : String(summary.totalResponses),
6576
+ style: S.KPI_VAL
6577
+ });
6578
+ shDash.setMergedBox(2, 4, 3, 4, {
6579
+ value: tr ? "ORT. / MEDYAN SÜRE" : "AVG / MEDIAN DURATION",
6580
+ style: S.KPI_LABEL
6581
+ });
6582
+ shDash.setMergedBox(2, 5, 3, 5, {
6583
+ value: `${summary.avgDurationSeconds || 0}s (${tr ? "Medyan" : "Median"}: ${summary.medianDurationSeconds || 0}s)`,
6584
+ style: S.KPI_VAL
6585
+ });
6586
+ const hasNps = Boolean(summary.nps?.hasNps);
6587
+ const npsScoreVal = summary.nps?.score ?? 0;
6588
+ const npsStyle = !hasNps ? S.KPI_VAL : npsScoreVal >= 30 ? S.KPI_NPS_POS : npsScoreVal >= 0 ? S.KPI_NPS_PAS : S.KPI_NPS_NEG;
6589
+ shDash.setMergedBox(4, 4, 5, 4, {
6590
+ value: "NET PROMOTER SCORE (NPS)",
6591
+ style: S.KPI_LABEL
6592
+ });
6593
+ shDash.setMergedBox(4, 5, 5, 5, {
6594
+ value: hasNps ? `${npsScoreVal > 0 ? `+${npsScoreVal}` : npsScoreVal} (P:${summary.nps.promotersPct}% / D:${summary.nps.detractorsPct}%)` : "—",
6595
+ style: npsStyle
6596
+ });
6597
+ const topLocalesText = Array.isArray(summary.localeBreakdown) && summary.localeBreakdown.length > 0 ? summary.localeBreakdown.slice(0, 3).map((l) => `${String(l.locale).toUpperCase()}: ${l.percentage}%`).join(" • ") : "—";
6598
+ shDash.setMergedBox(6, 4, 7, 4, {
6599
+ value: tr ? "KATILIM DİL DAĞILIMI" : "LOCALE BREAKDOWN",
6600
+ style: S.KPI_LABEL
6601
+ });
6602
+ shDash.setMergedBox(6, 5, 7, 5, {
6603
+ value: topLocalesText,
6604
+ style: S.KPI_VAL
6605
+ });
6606
+ const dashboardCharts = [];
6607
+ let cursorRowZero = 6;
6608
+ if (trendChartMeta) {
6609
+ dashboardCharts.push({
6610
+ ...trendChartMeta,
6611
+ fromCol: 0,
6612
+ fromRowZero: cursorRowZero,
6613
+ toCol: 8,
6614
+ toRowZero: cursorRowZero + 12
6615
+ });
6616
+ cursorRowZero += 13;
6617
+ }
6618
+ for (let i = 0; i < pendingQuestionCharts.length; i++) {
6619
+ const meta = pendingQuestionCharts[i];
6620
+ const isLeft = i % 2 === 0;
6621
+ const rowBandStart = cursorRowZero + Math.floor(i / 2) * 15;
6622
+ dashboardCharts.push({
6623
+ ...meta,
6624
+ fromCol: isLeft ? 0 : 4,
6625
+ fromRowZero: rowBandStart,
6626
+ toCol: isLeft ? 4 : 8,
6627
+ toRowZero: rowBandStart + 14
6628
+ });
6629
+ }
6630
+ const totalChartRows = cursorRowZero + Math.ceil(pendingQuestionCharts.length / 2) * 15 + 2;
6631
+ shDash.setCell(0, totalChartRows, { value: null });
6632
+ if (dashboardCharts.length > 0) {
6633
+ shDash.setDrawingRelId("rId1");
6634
+ }
6635
+ const shRaw = new WorksheetModel(rawSheetName, {
6636
+ tabColorHex6: "475569",
6637
+ showGridLines: true
6638
+ });
6639
+ if (includeRawSheet) {
6640
+ shRaw.setFreezeTopRows(1);
6641
+ const activeQuestions = (survey.questions || []).filter(
6642
+ (q) => q && q.type !== "statement" && qOverrides[q.key]?.included !== false
6643
+ );
6644
+ const headers = tr ? ["Yanıt ID", "Gönderim Tarihi", "Dil", "Süre (sn)", "NPS Puanı", "NPS Kategorisi"] : ["Response ID", "Submitted At", "Locale", "Duration (s)", "NPS Score", "NPS Category"];
6645
+ for (const q of activeQuestions) {
6646
+ const qTitle = resolveLocalizedText(q.title, locale, q.key);
6647
+ if (q.type === "matrix_single" && Array.isArray(q.matrixRows)) {
6648
+ for (const mRow of q.matrixRows) {
6649
+ const rTitle = resolveLocalizedText(mRow.labels, locale, mRow.id);
6650
+ headers.push(`${qTitle} [${rTitle}]`);
6651
+ }
5468
6652
  } else {
5469
- title = `#${entry.documentId || entry.id}`;
5470
- }
5471
- }
5472
- const collectionLabel = ct.info?.displayName || ct.info?.singularName || uid;
5473
- const subtitle = pickFirstString(subtitleCandidates);
5474
- let description = pickFirstString(descCandidates);
5475
- let imageObj = null;
5476
- for (const imgKey of imagePriority) {
5477
- const rawMedia = entry[imgKey];
5478
- if (!rawMedia) continue;
5479
- const firstMedia = Array.isArray(rawMedia) ? rawMedia[0] : rawMedia;
5480
- if (firstMedia && typeof firstMedia === "object" && firstMedia.url) {
5481
- imageObj = {
5482
- id: firstMedia.id,
5483
- documentId: firstMedia.documentId,
5484
- url: firstMedia.url,
5485
- name: firstMedia.name || title,
5486
- alternativeText: firstMedia.alternativeText || title,
5487
- width: firstMedia.width,
5488
- height: firstMedia.height,
5489
- formats: firstMedia.formats
5490
- };
5491
- break;
6653
+ headers.push(`${qTitle} (${q.key})`);
6654
+ if (q.allowOther) {
6655
+ headers.push(`${qTitle} [${tr ? "Diğer Açıklama" : "Other Text"}]`);
6656
+ }
5492
6657
  }
5493
6658
  }
5494
- if (!description || !imageObj) {
5495
- for (const ciField of ciFields) {
5496
- if (Array.isArray(entry[ciField])) {
5497
- const extracted = extractSnippetAndImageFromContentInput(entry[ciField]);
5498
- if (!description && extracted.snippet) {
5499
- description = extracted.snippet;
6659
+ shRaw.setRowHeight(1, 24);
6660
+ const maxLenPerCol = headers.map((h) => Math.max(13, h.length + 3));
6661
+ headers.forEach((h, cIdx) => {
6662
+ shRaw.setCell(cIdx, 1, { value: h, style: S.TBL_HEADER });
6663
+ });
6664
+ const filteredResponses = (rawResponses || []).filter((r) => {
6665
+ const tsRaw = r.submittedAt || r.createdAt;
6666
+ const ts = tsRaw ? new Date(tsRaw).getTime() : 0;
6667
+ if (options2.from) {
6668
+ const fTs = new Date(options2.from).getTime();
6669
+ if (!Number.isNaN(fTs) && ts < fTs) return false;
6670
+ }
6671
+ if (options2.to) {
6672
+ const tTs = (/* @__PURE__ */ new Date(`${options2.to}T23:59:59.999Z`)).getTime();
6673
+ if (!Number.isNaN(tTs) && ts > tTs) return false;
6674
+ }
6675
+ return true;
6676
+ });
6677
+ filteredResponses.forEach((r, rIdx) => {
6678
+ const rowNum = rIdx + 2;
6679
+ const zebra = rIdx % 2 === 1;
6680
+ const baseTextStyle = zebra ? S.CELL_ZEBRA : S.CELL_WHITE;
6681
+ const baseIntStyle = zebra ? S.INT_ZEBRA : S.INT_WHITE;
6682
+ const npsVal = typeof r.npsValue === "number" ? r.npsValue : r.npsValue !== null && r.npsValue !== void 0 && r.npsValue !== "" ? Number(r.npsValue) : null;
6683
+ const npsCat = String(r.npsCategory || "");
6684
+ const npsBadgeStyle = npsCat === "promoter" || npsVal !== null && npsVal >= 9 ? S.BADGE_PROM : npsCat === "passive" || npsVal !== null && npsVal >= 7 ? S.BADGE_PASS : npsCat === "detractor" || npsVal !== null && npsVal <= 6 ? S.BADGE_DETR : baseTextStyle;
6685
+ const fixedCells = [
6686
+ { v: String(r.id || r.documentId || ""), s: baseTextStyle },
6687
+ { v: String(r.submittedAt || r.createdAt || ""), s: baseTextStyle },
6688
+ { v: String(r.locale || "").toUpperCase(), s: baseTextStyle },
6689
+ {
6690
+ v: typeof r.durationSeconds === "number" ? r.durationSeconds : Number(r.durationSeconds || 0),
6691
+ s: baseIntStyle
6692
+ },
6693
+ { v: npsVal !== null && !Number.isNaN(npsVal) ? npsVal : "", s: npsBadgeStyle },
6694
+ { v: npsCat ? npsCat.toUpperCase() : "", s: npsBadgeStyle }
6695
+ ];
6696
+ let colCursor = 0;
6697
+ for (const fc of fixedCells) {
6698
+ shRaw.setCell(colCursor, rowNum, { value: fc.v, style: fc.s });
6699
+ const len = String(fc.v ?? "").length + 3;
6700
+ if (rIdx < 250 && len > maxLenPerCol[colCursor]) maxLenPerCol[colCursor] = len;
6701
+ colCursor += 1;
6702
+ }
6703
+ for (const q of activeQuestions) {
6704
+ const ans = r.answers?.[q.key];
6705
+ const noOpText = resolveLocalizedText(
6706
+ resolveNoOpinionLabels(q.noOpinionLabel),
6707
+ locale,
6708
+ tr ? "Fikrim yok" : "No idea"
6709
+ );
6710
+ const pushCell = (val, styleOverride) => {
6711
+ const strLen = String(val ?? "").length;
6712
+ const chosenStyle = styleOverride ?? (strLen > 60 ? zebra ? S.WRAP_ZEBRA : S.WRAP_WHITE : baseTextStyle);
6713
+ shRaw.setCell(colCursor, rowNum, { value: val, style: chosenStyle });
6714
+ if (rIdx < 250 && strLen + 3 > (maxLenPerCol[colCursor] || 12)) {
6715
+ maxLenPerCol[colCursor] = strLen + 3;
5500
6716
  }
5501
- if (!imageObj && extracted.image) {
5502
- imageObj = extracted.image;
6717
+ colCursor += 1;
6718
+ };
6719
+ if (q.type === "matrix_single" && Array.isArray(q.matrixRows)) {
6720
+ const mCols = Array.isArray(q.matrixColumns) ? q.matrixColumns : [];
6721
+ for (const mRow of q.matrixRows) {
6722
+ const chosenColId = ans && typeof ans === "object" ? ans[mRow.id] : "";
6723
+ if (chosenColId === NO_OPINION_VALUE) {
6724
+ pushCell(noOpText, S.NA_TEXT);
6725
+ } else {
6726
+ const foundCol = mCols.find((c) => c.id === chosenColId);
6727
+ pushCell(
6728
+ foundCol ? resolveLocalizedText(foundCol.labels, locale, chosenColId) : String(chosenColId || "")
6729
+ );
6730
+ }
6731
+ }
6732
+ } else if (Array.isArray(q.options) && q.options.length > 0) {
6733
+ if (Array.isArray(ans)) {
6734
+ const isOnlyNa = ans.length === 1 && ans[0] === NO_OPINION_VALUE;
6735
+ const mapped = ans.map((optId) => {
6736
+ if (optId === "__other__") return tr ? "Diğer" : "Other";
6737
+ if (optId === NO_OPINION_VALUE) return noOpText;
6738
+ const found = q.options.find((o) => o.id === optId);
6739
+ return found ? resolveLocalizedText(found.labels, locale, optId) : optId;
6740
+ });
6741
+ pushCell(
6742
+ mapped.join(q.type === "ranking" ? " > " : "; "),
6743
+ isOnlyNa ? S.NA_TEXT : void 0
6744
+ );
6745
+ } else if (ans !== void 0 && ans !== null && ans !== "") {
6746
+ const strAns = String(ans);
6747
+ if (strAns === "__other__") {
6748
+ pushCell(tr ? "Diğer" : "Other");
6749
+ } else if (strAns === NO_OPINION_VALUE) {
6750
+ pushCell(noOpText, S.NA_TEXT);
6751
+ } else {
6752
+ const found = q.options.find((o) => o.id === strAns);
6753
+ pushCell(found ? resolveLocalizedText(found.labels, locale, strAns) : strAns);
6754
+ }
6755
+ } else {
6756
+ pushCell("");
6757
+ }
6758
+ if (q.allowOther) {
6759
+ pushCell(String(r.otherTexts?.[q.key] || ""));
6760
+ }
6761
+ } else {
6762
+ if (ans === NO_OPINION_VALUE) {
6763
+ pushCell(noOpText, S.NA_TEXT);
6764
+ } else if (q.type === "likert_scale" && q.scaleLabels && ans !== void 0 && ans !== null && ans !== "") {
6765
+ const ptLbl = resolveLocalizedText(q.scaleLabels[String(ans)], locale, "");
6766
+ pushCell(ptLbl ? `${ans} - ${ptLbl}` : Number.isNaN(Number(ans)) ? String(ans) : Number(ans));
6767
+ } else if ((q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") && ans !== void 0 && ans !== null && ans !== "" && !Number.isNaN(Number(ans))) {
6768
+ pushCell(Number(ans), baseIntStyle);
6769
+ } else {
6770
+ pushCell(ans === void 0 || ans === null ? "" : String(ans));
6771
+ }
6772
+ if (q.allowOther) {
6773
+ pushCell(String(r.otherTexts?.[q.key] || ""));
5503
6774
  }
5504
6775
  }
5505
6776
  }
6777
+ });
6778
+ maxLenPerCol.forEach((w, cIdx) => {
6779
+ shRaw.setColWidth(cIdx, Math.min(52, Math.max(12, w)));
6780
+ });
6781
+ const lastRow = Math.max(1, filteredResponses.length + 1);
6782
+ if (headers.length > 0) {
6783
+ shRaw.setAutoFilter(`A1:${cellRef(headers.length - 1, lastRow)}`);
5506
6784
  }
5507
- if (imageObj) {
5508
- try {
5509
- imageObj = await enrichMediaAssetNode(strapi, imageObj, {
5510
- defaultAutoMaxW: 960
6785
+ }
6786
+ const sheets = includeRawSheet ? [shDash, shStats, shRaw] : [shDash, shStats];
6787
+ const entries = [];
6788
+ const contentTypeOverrides = [
6789
+ `<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>`,
6790
+ `<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>`
6791
+ ];
6792
+ sheets.forEach((_sh, idx) => {
6793
+ contentTypeOverrides.push(
6794
+ `<Override PartName="/xl/worksheets/sheet${idx + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>`
6795
+ );
6796
+ });
6797
+ if (dashboardCharts.length > 0) {
6798
+ contentTypeOverrides.push(
6799
+ `<Override PartName="/xl/drawings/drawing1.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>`
6800
+ );
6801
+ dashboardCharts.forEach((_ch, cIdx) => {
6802
+ contentTypeOverrides.push(
6803
+ `<Override PartName="/xl/charts/chart${cIdx + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.drawingml.chart+xml"/>`
6804
+ );
6805
+ });
6806
+ }
6807
+ entries.push({
6808
+ path: "[Content_Types].xml",
6809
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6810
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
6811
+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
6812
+ <Default Extension="xml" ContentType="application/xml"/>
6813
+ ${contentTypeOverrides.join("\n ")}
6814
+ </Types>`
6815
+ });
6816
+ entries.push({
6817
+ path: "_rels/.rels",
6818
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6819
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
6820
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
6821
+ </Relationships>`
6822
+ });
6823
+ entries.push({
6824
+ path: "xl/workbook.xml",
6825
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6826
+ <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
6827
+ <sheets>
6828
+ ${sheets.map(
6829
+ (sh, idx) => `<sheet name="${escapeXml(sh.name)}" sheetId="${idx + 1}" r:id="rId${idx + 1}"/>`
6830
+ ).join("\n ")}
6831
+ </sheets>
6832
+ </workbook>`
6833
+ });
6834
+ const wbRels = sheets.map(
6835
+ (_sh, idx) => `<Relationship Id="rId${idx + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet${idx + 1}.xml"/>`
6836
+ );
6837
+ wbRels.push(
6838
+ `<Relationship Id="rId${sheets.length + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>`
6839
+ );
6840
+ entries.push({
6841
+ path: "xl/_rels/workbook.xml.rels",
6842
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6843
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
6844
+ ${wbRels.join("\n ")}
6845
+ </Relationships>`
6846
+ });
6847
+ entries.push({
6848
+ path: "xl/styles.xml",
6849
+ data: buildStylesXml(primaryHex6)
6850
+ });
6851
+ sheets.forEach((sh, idx) => {
6852
+ entries.push({
6853
+ path: `xl/worksheets/sheet${idx + 1}.xml`,
6854
+ data: sh.toXml()
6855
+ });
6856
+ });
6857
+ if (dashboardCharts.length > 0) {
6858
+ entries.push({
6859
+ path: "xl/worksheets/_rels/sheet1.xml.rels",
6860
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6861
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
6862
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" Target="../drawings/drawing1.xml"/>
6863
+ </Relationships>`
6864
+ });
6865
+ entries.push({
6866
+ path: "xl/drawings/drawing1.xml",
6867
+ data: buildDrawingXml(dashboardCharts)
6868
+ });
6869
+ entries.push({
6870
+ path: "xl/drawings/_rels/drawing1.xml.rels",
6871
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6872
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
6873
+ ${dashboardCharts.map(
6874
+ (_ch, cIdx) => `<Relationship Id="rId${cIdx + 1}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="../charts/chart${cIdx + 1}.xml"/>`
6875
+ ).join("\n ")}
6876
+ </Relationships>`
6877
+ });
6878
+ dashboardCharts.forEach((ch, cIdx) => {
6879
+ entries.push({
6880
+ path: `xl/charts/chart${cIdx + 1}.xml`,
6881
+ data: buildChartXml(ch, cIdx + 1)
6882
+ });
6883
+ });
6884
+ }
6885
+ return buildZipStoreBuffer(entries);
6886
+ }
6887
+ function buildStyledTableXlsxBuffer(params) {
6888
+ const primaryHex6 = parseHex6(params.themeColor, "1E3A8A");
6889
+ const sh = new WorksheetModel(params.sheetName, {
6890
+ tabColorHex6: primaryHex6,
6891
+ showGridLines: true
6892
+ });
6893
+ const colCount = Math.max(1, params.headers.length);
6894
+ const maxWidths = params.headers.map((h) => Math.max(14, h.length + 4));
6895
+ sh.setRowHeight(1, 28);
6896
+ sh.setMergedBox(0, 1, Math.max(3, colCount - 1), 1, {
6897
+ value: params.bannerTitle,
6898
+ style: S.BANNER_TITLE
6899
+ });
6900
+ sh.setRowHeight(2, 20);
6901
+ sh.setMergedBox(0, 2, Math.max(3, colCount - 1), 2, {
6902
+ value: params.bannerSubtitle || `Exported: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`,
6903
+ style: S.BANNER_SUB
6904
+ });
6905
+ sh.setRowHeight(3, 23);
6906
+ sh.setFreezeTopRows(3);
6907
+ params.headers.forEach((h, cIdx) => {
6908
+ sh.setCell(cIdx, 3, { value: h, style: S.TBL_HEADER });
6909
+ });
6910
+ params.rows.forEach((row, rIdx) => {
6911
+ const rowNum = 4 + rIdx;
6912
+ const zebra = rIdx % 2 === 1;
6913
+ row.forEach((val, cIdx) => {
6914
+ if (typeof val === "number" && Number.isFinite(val)) {
6915
+ sh.setCell(cIdx, rowNum, {
6916
+ value: val,
6917
+ style: zebra ? S.INT_ZEBRA : S.INT_WHITE
5511
6918
  });
5512
- } catch {
6919
+ } else {
6920
+ const sVal = val === null || val === void 0 ? "" : String(val);
6921
+ const isWrap = sVal.length > 60;
6922
+ sh.setCell(cIdx, rowNum, {
6923
+ value: sVal,
6924
+ style: isWrap ? zebra ? S.WRAP_ZEBRA : S.WRAP_WHITE : zebra ? S.CELL_ZEBRA : S.CELL_WHITE
6925
+ });
6926
+ if (rIdx < 250 && sVal.length + 3 > (maxWidths[cIdx] || 12)) {
6927
+ maxWidths[cIdx] = sVal.length + 3;
6928
+ }
6929
+ }
6930
+ });
6931
+ });
6932
+ maxWidths.forEach((w, cIdx) => {
6933
+ sh.setColWidth(cIdx, Math.min(54, Math.max(12, w)));
6934
+ });
6935
+ const lastRow = Math.max(3, 3 + params.rows.length);
6936
+ sh.setAutoFilter(`A3:${cellRef(colCount - 1, lastRow)}`);
6937
+ return buildZipStoreBuffer([
6938
+ {
6939
+ path: "[Content_Types].xml",
6940
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6941
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
6942
+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
6943
+ <Default Extension="xml" ContentType="application/xml"/>
6944
+ <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
6945
+ <Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
6946
+ <Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
6947
+ </Types>`
6948
+ },
6949
+ {
6950
+ path: "_rels/.rels",
6951
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6952
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
6953
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
6954
+ </Relationships>`
6955
+ },
6956
+ {
6957
+ path: "xl/workbook.xml",
6958
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6959
+ <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
6960
+ <sheets>
6961
+ <sheet name="${escapeXml(sh.name)}" sheetId="1" r:id="rId1"/>
6962
+ </sheets>
6963
+ </workbook>`
6964
+ },
6965
+ {
6966
+ path: "xl/_rels/workbook.xml.rels",
6967
+ data: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
6968
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
6969
+ <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
6970
+ <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
6971
+ </Relationships>`
6972
+ },
6973
+ {
6974
+ path: "xl/styles.xml",
6975
+ data: buildStylesXml(primaryHex6)
6976
+ },
6977
+ {
6978
+ path: "xl/worksheets/sheet1.xml",
6979
+ data: sh.toXml()
6980
+ }
6981
+ ]);
6982
+ }
6983
+ const FORM_UID = "plugin::content-input.ci-form";
6984
+ const SUBMISSION_UID = "plugin::content-input.ci-form-submission";
6985
+ function slugifyIdentifier$1(text) {
6986
+ const map = {
6987
+ ç: "c",
6988
+ Ç: "c",
6989
+ ğ: "g",
6990
+ Ğ: "g",
6991
+ ı: "i",
6992
+ İ: "i",
6993
+ ö: "o",
6994
+ Ö: "o",
6995
+ ş: "s",
6996
+ Ş: "s",
6997
+ ü: "u",
6998
+ Ü: "u"
6999
+ };
7000
+ return String(text || "").replace(/[çÇğĞıİöÖşŞüÜ]/g, (ch) => map[ch] || ch).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-{2,}/g, "-").replace(/_{2,}/g, "_").replace(/^[-_]+|[-_]+$/g, "");
7001
+ }
7002
+ function stripHtmlTags(html) {
7003
+ 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();
7004
+ }
7005
+ const DEFAULT_SEED_FORMS = [
7006
+ {
7007
+ title: "Enterprise Inquiry & Support Form",
7008
+ slug: "showcase_contact_form",
7009
+ to: "info@example.com",
7010
+ subject: "Enterprise Inquiry & Support Submission",
7011
+ buttonLabel: {
7012
+ tr: "Başvuruyu Gönder",
7013
+ en: "Submit Inquiry"
7014
+ },
7015
+ successMessage: {
7016
+ tr: "Başvurunuz başarıyla kaydedildi. Ekibimiz en kısa sürede sizinle iletişime geçecektir.",
7017
+ en: "Your inquiry has been submitted successfully. Our team will get back to you shortly."
7018
+ },
7019
+ redirect: "",
7020
+ hideLabels: false,
7021
+ useRecaptcha: true,
7022
+ recaptchaSiteKey: "",
7023
+ recaptchaSecretKey: "",
7024
+ mailConfig: {
7025
+ driver: "env"
7026
+ },
7027
+ fields: {
7028
+ full_name: {
7029
+ name: "full_name",
7030
+ field_type: "input",
7031
+ alias: { tr: "Adınız Soyadınız", en: "Full Name" },
7032
+ placeholder: { tr: "Örn: Özgür Altan", en: "e.g. Jane Doe" },
7033
+ validation: "required|min:3|max:100",
7034
+ options: {}
7035
+ },
7036
+ email: {
7037
+ name: "email",
7038
+ field_type: "emailInput",
7039
+ alias: { tr: "Kurumsal E-Posta", en: "Work Email" },
7040
+ placeholder: { tr: "ad.soyad@sirket.com", en: "name@company.com" },
7041
+ validation: "required|email",
7042
+ options: {}
7043
+ },
7044
+ phone: {
7045
+ name: "phone",
7046
+ field_type: "telInput",
7047
+ alias: { tr: "Telefon Numarası", en: "Phone Number" },
7048
+ placeholder: { tr: "+90 555 123 45 67", en: "+1 555 123 4567" },
7049
+ hint: {
7050
+ tr: "İsteğe bağlı; girildiğinde telefon formatı doğrulanır.",
7051
+ en: "Optional; validated when entered."
7052
+ },
7053
+ validation: "phone",
7054
+ options: {}
7055
+ },
7056
+ department: {
7057
+ name: "department",
7058
+ field_type: "selectGroup",
7059
+ alias: { tr: "İlgili Departman", en: "Department" },
7060
+ placeholder: { tr: "Departman seçiniz...", en: "Select department..." },
7061
+ validation: "required",
7062
+ options: {
7063
+ optionList: {
7064
+ tr: [
7065
+ "Satış & Kurumsal Çözümler",
7066
+ "Teknik Destek & SLA",
7067
+ "Strapi & Nuxt Mimari Danışmanlık",
7068
+ "İnsan Kaynakları"
7069
+ ],
7070
+ en: [
7071
+ "Sales & Enterprise Solutions",
7072
+ "Technical Support & SLA",
7073
+ "Strapi & Nuxt Architecture Consulting",
7074
+ "Human Resources"
7075
+ ]
7076
+ }
7077
+ }
7078
+ },
7079
+ priority: {
7080
+ name: "priority",
7081
+ field_type: "radioGroup",
7082
+ alias: { tr: "Öncelik Seviyesi", en: "Priority Level" },
7083
+ validation: "required",
7084
+ options: {
7085
+ inline: true,
7086
+ optionList: {
7087
+ tr: ["Standart", "Yüksek Öncelik", "Kritik / Acil"],
7088
+ en: ["Standard", "High Priority", "Critical / Urgent"]
7089
+ }
7090
+ }
7091
+ },
7092
+ services: {
7093
+ name: "services",
7094
+ field_type: "checkboxGroup",
7095
+ alias: { tr: "İlgilendiğiniz Modüller", en: "Modules of Interest" },
7096
+ validation: "min:1",
7097
+ options: {
7098
+ optionList: {
7099
+ tr: [
7100
+ "Strapi ContentInput Builder",
7101
+ "Nuxt Vuetify Renderer",
7102
+ "Nuxt Element Plus Renderer",
7103
+ "Özel Entegrasyon"
7104
+ ],
7105
+ en: [
7106
+ "Strapi ContentInput Builder",
7107
+ "Nuxt Vuetify Renderer",
7108
+ "Nuxt Element Plus Renderer",
7109
+ "Custom Integration"
7110
+ ]
7111
+ }
7112
+ }
7113
+ },
7114
+ message: {
7115
+ name: "message",
7116
+ field_type: "textArea",
7117
+ alias: { tr: "Proje Detayları & Mesajınız", en: "Project Details & Message" },
7118
+ placeholder: {
7119
+ tr: "Projeniz ve beklentileriniz hakkında bilgi paylaşınız (en az 10 karakter)...",
7120
+ en: "Tell us about your project and requirements (at least 10 characters)..."
7121
+ },
7122
+ validation: "required|min:10|max:1000",
7123
+ options: { rows: 4 }
7124
+ },
7125
+ kvkk_consent: {
7126
+ name: "kvkk_consent",
7127
+ field_type: "switchBox",
7128
+ alias: {
7129
+ tr: "KVKK Aydınlatma Metnini okudum ve kişisel verilerimin işlenmesini kabul ediyorum.",
7130
+ en: "I have read and accept the Privacy Policy & GDPR data processing notice."
7131
+ },
7132
+ validation: "accepted",
7133
+ options: {}
7134
+ }
7135
+ },
7136
+ form: [
7137
+ {
7138
+ _uId: "frow_1",
7139
+ blocks: [
7140
+ { _uId: "fblk_1a", cols: [12, 6, 6, 6, 6], fields: ["full_name"] },
7141
+ { _uId: "fblk_1b", cols: [12, 6, 6, 6, 6], fields: ["email"] }
7142
+ ]
7143
+ },
7144
+ {
7145
+ _uId: "frow_2",
7146
+ blocks: [
7147
+ { _uId: "fblk_2a", cols: [12, 6, 6, 6, 6], fields: ["phone"] },
7148
+ { _uId: "fblk_2b", cols: [12, 6, 6, 6, 6], fields: ["department"] }
7149
+ ]
7150
+ },
7151
+ {
7152
+ _uId: "frow_3",
7153
+ blocks: [
7154
+ { _uId: "fblk_3a", cols: [12, 6, 6, 6, 6], fields: ["priority"] },
7155
+ { _uId: "fblk_3b", cols: [12, 6, 6, 6, 6], fields: ["services"] }
7156
+ ]
7157
+ },
7158
+ {
7159
+ _uId: "frow_4",
7160
+ blocks: [
7161
+ {
7162
+ _uId: "fblk_4a",
7163
+ cols: [12, 12, 12, 12, 12],
7164
+ fields: ["message", "kvkk_consent"]
7165
+ }
7166
+ ]
5513
7167
  }
5514
- }
5515
- const pluralName = ct.info?.pluralName || "items";
5516
- const slugField = ["slug", "path", "url", "permalink"].find(
5517
- (k) => typeof entry[k] === "string" && entry[k].trim()
5518
- );
5519
- const rawSlug = slugField ? String(entry[slugField]).trim() : String(entry.documentId || entry.id);
5520
- let url = "/";
5521
- if (rawSlug === "home" || rawSlug === "anasayfa" || rawSlug === "/") {
5522
- url = "/";
5523
- } else if (rawSlug.startsWith("/")) {
5524
- url = rawSlug;
5525
- } else {
5526
- const prefix = pluralName === "pages" ? "" : `/${pluralName}`;
5527
- url = `${prefix}/${rawSlug}`.replace(/\/+/g, "/");
5528
- }
5529
- return {
5530
- id: entry.id,
5531
- documentId: String(entry.documentId || entry.id),
5532
- uid,
5533
- collectionName: pluralName,
5534
- collectionLabel,
5535
- title,
5536
- subtitle,
5537
- description,
5538
- image: imageObj,
5539
- url,
5540
- slug: rawSlug,
5541
- publishedAt: entry.publishedAt || entry.updatedAt || entry.createdAt || null
5542
- };
5543
- }
5544
- });
5545
- const XLSX = XLSXNs?.utils ? XLSXNs : XLSXNs?.default || XLSXNs;
5546
- function evalSingleRule(rule, answers) {
5547
- const targetVal = answers ? answers[rule.questionKey] : void 0;
5548
- const op = rule.operator;
5549
- if (op === "is_answered") {
5550
- return !isEmptyFieldValue(targetVal);
5551
- }
5552
- if (op === "is_empty") {
5553
- return isEmptyFieldValue(targetVal);
5554
- }
5555
- const cmp = rule.value;
5556
- if (op === "equals") {
5557
- if (Array.isArray(targetVal)) return targetVal.map(String).includes(String(cmp));
5558
- return String(targetVal ?? "") === String(cmp ?? "");
5559
- }
5560
- if (op === "not_equals") {
5561
- if (Array.isArray(targetVal)) return !targetVal.map(String).includes(String(cmp));
5562
- return String(targetVal ?? "") !== String(cmp ?? "");
5563
- }
5564
- if (op === "includes") {
5565
- if (Array.isArray(targetVal)) return targetVal.map(String).includes(String(cmp));
5566
- return String(targetVal ?? "").includes(String(cmp ?? ""));
5567
- }
5568
- if (op === "not_includes") {
5569
- if (Array.isArray(targetVal)) return !targetVal.map(String).includes(String(cmp));
5570
- return !String(targetVal ?? "").includes(String(cmp ?? ""));
5571
- }
5572
- const numTarget = Number(targetVal);
5573
- const numCmp = Number(cmp);
5574
- if (isEmptyFieldValue(targetVal) || Number.isNaN(numTarget) || Number.isNaN(numCmp)) {
5575
- return false;
7168
+ ]
5576
7169
  }
5577
- if (op === "gt") return numTarget > numCmp;
5578
- if (op === "gte") return numTarget >= numCmp;
5579
- if (op === "lt") return numTarget < numCmp;
5580
- if (op === "lte") return numTarget <= numCmp;
5581
- return true;
7170
+ ];
7171
+ function getEnvRecaptchaPublicKey$1() {
7172
+ return (process.env.MIX_RECAPTCHA_PUBLIC_KEY || process.env.RECAPTCHA_PUBLIC_KEY || process.env.NUXT_PUBLIC_RECAPTCHA_SITE_KEY || "").trim();
5582
7173
  }
5583
- function evaluateSurveyConditions(conditions, answers) {
5584
- if (!conditions || !Array.isArray(conditions.rules) || conditions.rules.length === 0) {
5585
- return true;
5586
- }
5587
- if (conditions.match === "any") {
5588
- return conditions.rules.some((r) => evalSingleRule(r, answers));
5589
- }
5590
- return conditions.rules.every((r) => evalSingleRule(r, answers));
7174
+ function getEnvRecaptchaPrivateKey$1() {
7175
+ return (process.env.RECAPTCHA_PRIVATE_KEY || process.env.RECAPTCHA_SECRET_KEY || "").trim();
5591
7176
  }
5592
- function isQuestionVisible(question, survey, answers) {
5593
- if (survey.displayMode === "multi_step" && question.stepId && Array.isArray(survey.steps)) {
5594
- const parentStep = survey.steps.find((s) => s.id === question.stepId);
5595
- if (parentStep && !evaluateSurveyConditions(parentStep.conditions, answers)) {
5596
- return false;
5597
- }
5598
- }
5599
- return evaluateSurveyConditions(question.conditions, answers);
7177
+ function getEnvStatusSummary$1() {
7178
+ return {
7179
+ hasEnvRecaptchaPublicKey: Boolean(getEnvRecaptchaPublicKey$1()),
7180
+ hasEnvRecaptchaPrivateKey: Boolean(getEnvRecaptchaPrivateKey$1()),
7181
+ envMailDriver: process.env.MAIL_DRIVER || "auto",
7182
+ hasMailtrapToken: Boolean(process.env.MAILTRAP_API_TOKEN || process.env.MAILTRAP_TOKEN),
7183
+ hasMailgunSecret: Boolean(process.env.MAILGUN_SECRET || process.env.MAILGUN_API_KEY),
7184
+ hasSmtpHost: Boolean(process.env.MAIL_HOST)
7185
+ };
5600
7186
  }
5601
- function lMsg(locale, tr, en) {
5602
- return String(locale || "").toLowerCase().startsWith("tr") ? tr : en;
7187
+ function sanitizeFormForPublic(entry) {
7188
+ if (!entry) return null;
7189
+ const { recaptchaSecretKey, mailConfig, ...safeRest } = entry;
7190
+ const publicKey = entry.useRecaptcha !== false ? String(entry.recaptchaSiteKey || getEnvRecaptchaPublicKey$1() || "").trim() : "";
7191
+ return {
7192
+ ...safeRest,
7193
+ _id: entry.documentId || String(entry.id),
7194
+ recaptchaPublicKey: publicKey,
7195
+ recaptchaEnabled: Boolean(entry.useRecaptcha !== false && publicKey)
7196
+ };
5603
7197
  }
5604
- function validateSurveySubmission(survey, answers, otherTexts = {}, locale = "en") {
5605
- const errors = {};
5606
- const questions = Array.isArray(survey.questions) ? survey.questions : [];
5607
- for (const q of questions) {
5608
- if (!q || !q.key || q.type === "statement") continue;
5609
- if (!isQuestionVisible(q, survey, answers)) continue;
5610
- const val = answers ? answers[q.key] : void 0;
5611
- const qLabel = resolveLocalizedText(q.title, locale, q.key);
5612
- const qErrors = [];
5613
- const empty = isEmptyFieldValue(val);
5614
- if (q.type === "consent") {
5615
- if (q.required !== false && val !== true && val !== "true" && val !== 1) {
5616
- qErrors.push(lMsg(locale, `${qLabel} onaylanmalıdır.`, `${qLabel} must be accepted.`));
7198
+ function formatFormForAdmin(entry) {
7199
+ if (!entry) return null;
7200
+ return {
7201
+ ...entry,
7202
+ _id: entry.documentId || String(entry.id),
7203
+ envStatus: getEnvStatusSummary$1()
7204
+ };
7205
+ }
7206
+ function extractSnippetAndImageFromContentInput(content) {
7207
+ let snippet = "";
7208
+ let image = null;
7209
+ const visitRows = (rows) => {
7210
+ if (!Array.isArray(rows)) return;
7211
+ for (const row of rows) {
7212
+ const blocks = Array.isArray(row?.blocks) ? row.blocks : [];
7213
+ for (const block of blocks) {
7214
+ const widgets = Array.isArray(block?.widgets) ? block.widgets : [];
7215
+ for (const widget of widgets) {
7216
+ const wId = widget?.id;
7217
+ const wData = widget?.data || {};
7218
+ if (!image) {
7219
+ if (wId === "singleImage") {
7220
+ if (wData?.image?.url) image = wData.image;
7221
+ else if (wData?.file?.url) image = wData.file;
7222
+ } else if (wId === "gallery") {
7223
+ if (Array.isArray(wData) && wData[0]?.url) {
7224
+ image = wData[0];
7225
+ } else if (Array.isArray(wData?.images) && wData.images[0]?.url) {
7226
+ image = wData.images[0];
7227
+ }
7228
+ } else if (wId === "banner" && wData?.image?.url) {
7229
+ image = wData.image;
7230
+ }
7231
+ }
7232
+ if (!snippet) {
7233
+ const rawHtml = wId === "HtmlEditor" ? typeof wData === "string" ? wData : wData?.content : "";
7234
+ if (typeof rawHtml === "string" && rawHtml.trim()) {
7235
+ const plain = stripHtmlTags(rawHtml);
7236
+ if (plain.length > 15) {
7237
+ snippet = plain.length > 180 ? `${plain.slice(0, 177)}...` : plain;
7238
+ }
7239
+ }
7240
+ }
7241
+ if (wId === "tab" && Array.isArray(wData?.tabs)) {
7242
+ for (const tab of wData.tabs) {
7243
+ if (Array.isArray(tab?.content)) visitRows(tab.content);
7244
+ }
7245
+ }
7246
+ }
5617
7247
  }
5618
- } else if (q.type === "matrix_single") {
5619
- const mRows = Array.isArray(q.matrixRows) ? q.matrixRows : [];
5620
- if (q.required) {
5621
- const objVal = val && typeof val === "object" && !Array.isArray(val) ? val : {};
5622
- const missingRow = mRows.some((r) => isEmptyFieldValue(objVal[r.id]));
5623
- if (missingRow) {
5624
- qErrors.push(
5625
- lMsg(
5626
- locale,
5627
- `Lütfen "${qLabel}" tablosundaki tüm satırları yanıtlayınız.`,
5628
- `Please answer all rows in "${qLabel}".`
5629
- )
5630
- );
7248
+ }
7249
+ };
7250
+ if (Array.isArray(content)) {
7251
+ visitRows(content);
7252
+ }
7253
+ return { snippet, image };
7254
+ }
7255
+ const ciFormService = ({ strapi }) => ({
7256
+ async listStrapiLocales() {
7257
+ try {
7258
+ let rawLocales = [];
7259
+ let defaultCode = "";
7260
+ const i18nPlugin = strapi.plugin?.("i18n");
7261
+ if (i18nPlugin) {
7262
+ try {
7263
+ const localesService = i18nPlugin.service?.("locales");
7264
+ if (localesService?.find) {
7265
+ rawLocales = await localesService.find() || [];
7266
+ }
7267
+ if (localesService?.getDefaultLocale) {
7268
+ defaultCode = String(await localesService.getDefaultLocale() || "");
7269
+ }
7270
+ } catch {
5631
7271
  }
5632
7272
  }
5633
- } else if (q.type === "multiple_choice" || q.type === "image_choice" && (q.maxSelections ?? 1) > 1) {
5634
- const arr = Array.isArray(val) ? val : [];
5635
- if (q.required && arr.length === 0) {
5636
- qErrors.push(lMsg(locale, `Lütfen en az bir seçenek işaretleyiniz.`, `Please select at least one option.`));
5637
- } else if (arr.length > 0) {
5638
- if (q.minSelections && arr.length < q.minSelections) {
5639
- qErrors.push(
5640
- lMsg(
5641
- locale,
5642
- `En az ${q.minSelections} seçenek işaretlemelisiniz.`,
5643
- `Please select at least ${q.minSelections} options.`
5644
- )
5645
- );
7273
+ if (!Array.isArray(rawLocales) || rawLocales.length === 0) {
7274
+ try {
7275
+ rawLocales = await strapi.db.query("plugin::i18n.locale").findMany({
7276
+ orderBy: { id: "asc" }
7277
+ }) || [];
7278
+ } catch {
7279
+ rawLocales = [];
5646
7280
  }
5647
- if (q.maxSelections && arr.length > q.maxSelections) {
5648
- qErrors.push(
5649
- lMsg(
5650
- locale,
5651
- `En fazla ${q.maxSelections} seçenek işaretleyebilirsiniz.`,
5652
- `You may select at most ${q.maxSelections} options.`
5653
- )
7281
+ }
7282
+ if (Array.isArray(rawLocales) && rawLocales.length > 0) {
7283
+ const mapped = rawLocales.filter((loc) => loc && typeof loc.code === "string" && loc.code.trim()).map((loc) => {
7284
+ const code = String(loc.code).trim();
7285
+ const isDefault = Boolean(
7286
+ loc.isDefault || defaultCode && code === defaultCode
5654
7287
  );
7288
+ return {
7289
+ code,
7290
+ name: String(loc.name || code.toUpperCase()),
7291
+ isDefault
7292
+ };
7293
+ });
7294
+ if (mapped.length > 0) {
7295
+ if (!mapped.some((m) => m.isDefault)) {
7296
+ mapped[0].isDefault = true;
7297
+ }
7298
+ mapped.sort((a, b) => Number(b.isDefault) - Number(a.isDefault));
7299
+ return mapped;
5655
7300
  }
5656
7301
  }
5657
- if (q.allowOther && arr.includes("__other__") && !String(otherTexts?.[q.key] || "").trim()) {
5658
- qErrors.push(
5659
- lMsg(locale, `Lütfen "Diğer" seçeneği için açıklama giriniz.`, `Please specify your "Other" choice.`)
5660
- );
7302
+ } catch {
7303
+ }
7304
+ return [
7305
+ { code: "en", name: "English (en)", isDefault: true },
7306
+ { code: "tr", name: "Türkçe (tr)", isDefault: false }
7307
+ ];
7308
+ },
7309
+ async ensureSampleSubmissions(force = false) {
7310
+ try {
7311
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
7312
+ return;
5661
7313
  }
5662
- } else if (q.type === "single_choice" || q.type === "dropdown" || q.type === "image_choice") {
5663
- if (q.required && empty) {
5664
- qErrors.push(lMsg(locale, `Lütfen bir seçim yapınız.`, `Please choose an option.`));
7314
+ const subCount = await strapi.db.query(SUBMISSION_UID).count();
7315
+ if (subCount > 0 && !force) return;
7316
+ let showcaseForm = await strapi.db.query(FORM_UID).findOne({
7317
+ where: { slug: "showcase_contact_form" }
7318
+ });
7319
+ if (!showcaseForm && force) {
7320
+ const seedDef = DEFAULT_SEED_FORMS.find((s) => s.slug === "showcase_contact_form");
7321
+ if (seedDef) {
7322
+ showcaseForm = await strapi.db.query(FORM_UID).create({ data: seedDef });
7323
+ }
5665
7324
  }
5666
- if (q.allowOther && val === "__other__" && !String(otherTexts?.[q.key] || "").trim()) {
5667
- qErrors.push(
5668
- lMsg(locale, `Lütfen "Diğer" seçeneği için açıklama giriniz.`, `Please specify your "Other" choice.`)
5669
- );
7325
+ if (!showcaseForm) return;
7326
+ if (force) {
7327
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
7328
+ where: { formSlug: "showcase_contact_form" }
7329
+ });
5670
7330
  }
5671
- } else if (q.type === "nps") {
5672
- if (q.required && empty) {
5673
- qErrors.push(lMsg(locale, `Lütfen 0 ile 10 arasında bir puan seçiniz.`, `Please choose a score from 0 to 10.`));
5674
- } else if (!empty) {
5675
- const n = Number(val);
5676
- if (Number.isNaN(n) || n < 0 || n > 10) {
5677
- qErrors.push(lMsg(locale, `Puan 0 ile 10 arasında olmalıdır.`, `Score must be between 0 and 10.`));
7331
+ const samples = generateSampleFormSubmissions(showcaseForm);
7332
+ for (const item of samples) {
7333
+ await strapi.db.query(SUBMISSION_UID).create({ data: item });
7334
+ }
7335
+ } catch {
7336
+ }
7337
+ },
7338
+ async ensureSeeded(force = false) {
7339
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
7340
+ return;
7341
+ }
7342
+ let count = 0;
7343
+ try {
7344
+ count = await strapi.db.query(FORM_UID).count();
7345
+ } catch {
7346
+ return;
7347
+ }
7348
+ if (count === 0 || force) {
7349
+ for (const seed of DEFAULT_SEED_FORMS) {
7350
+ const existingSeed = await strapi.db.query(FORM_UID).findOne({
7351
+ where: { slug: seed.slug }
7352
+ });
7353
+ if (!existingSeed) {
7354
+ await strapi.db.query(FORM_UID).create({ data: seed });
5678
7355
  }
5679
7356
  }
5680
- } else if (q.type === "star_rating") {
5681
- const maxS = q.maxStars || 5;
5682
- if (q.required && empty) {
5683
- qErrors.push(lMsg(locale, `Lütfen derecelendirme yapınız.`, `Please provide a rating.`));
5684
- } else if (!empty) {
5685
- const n = Number(val);
5686
- if (Number.isNaN(n) || n < 1 || n > maxS) {
5687
- qErrors.push(lMsg(locale, `Derece 1 ile ${maxS} arasında olmalıdır.`, `Rating must be between 1 and ${maxS}.`));
7357
+ } else {
7358
+ try {
7359
+ const showcase = await strapi.db.query(FORM_UID).findOne({
7360
+ where: { slug: "showcase_contact_form" }
7361
+ });
7362
+ if (showcase && (showcase.subject === "Kurumsal İletişim & Destek Başvurusu" || showcase.title === "Kurumsal İletişim & Destek Formu")) {
7363
+ await strapi.db.query(FORM_UID).update({
7364
+ where: { id: showcase.id },
7365
+ data: {
7366
+ title: "Enterprise Inquiry & Support Form",
7367
+ subject: "Enterprise Inquiry & Support Submission"
7368
+ }
7369
+ });
5688
7370
  }
7371
+ } catch {
5689
7372
  }
5690
- } else if (q.type === "likert_scale") {
5691
- const sMin = q.scaleMin ?? 1;
5692
- const sMax = q.scaleMax ?? 5;
5693
- if (q.required && empty) {
5694
- qErrors.push(lMsg(locale, `Lütfen ölçekten bir değer seçiniz.`, `Please select a value on the scale.`));
5695
- } else if (!empty) {
5696
- const n = Number(val);
5697
- if (Number.isNaN(n) || n < sMin || n > sMax) {
5698
- qErrors.push(
5699
- lMsg(locale, `Değer ${sMin} ile ${sMax} arasında olmalıdır.`, `Value must be between ${sMin} and ${sMax}.`)
5700
- );
7373
+ }
7374
+ await this.ensureSampleSubmissions(force);
7375
+ await updateDemoSeedState(strapi, { formsInitialized: true });
7376
+ },
7377
+ async purgeDemoForms() {
7378
+ let deletedForms = 0;
7379
+ let deletedFormSubmissions = 0;
7380
+ const demoSlugs = DEFAULT_SEED_FORMS.map((f) => f.slug);
7381
+ for (const slug of demoSlugs) {
7382
+ try {
7383
+ const existingForm = await strapi.db.query(FORM_UID).findOne({
7384
+ where: { slug }
7385
+ });
7386
+ const matchingSubs = await strapi.db.query(SUBMISSION_UID).findMany({
7387
+ where: existingForm ? {
7388
+ $or: [
7389
+ { formSlug: slug },
7390
+ { formId: String(existingForm.documentId || existingForm.id) },
7391
+ { formId: String(existingForm.id) }
7392
+ ]
7393
+ } : { formSlug: slug }
7394
+ }) || [];
7395
+ if (matchingSubs.length > 0) {
7396
+ const subIds = matchingSubs.map((s) => s.id).filter((id) => id !== void 0 && id !== null);
7397
+ if (subIds.length > 0) {
7398
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
7399
+ where: { id: { $in: subIds } }
7400
+ });
7401
+ }
7402
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
7403
+ where: { formSlug: slug }
7404
+ });
7405
+ deletedFormSubmissions += matchingSubs.length;
7406
+ }
7407
+ if (existingForm) {
7408
+ await strapi.db.query(FORM_UID).delete({
7409
+ where: { id: existingForm.id }
7410
+ });
7411
+ deletedForms += 1;
5701
7412
  }
7413
+ } catch {
5702
7414
  }
5703
- } else if (q.type === "ranking") {
5704
- if (q.required && (!Array.isArray(val) || val.length === 0)) {
5705
- qErrors.push(lMsg(locale, `Lütfen sıralamayı onaylayınız.`, `Please confirm the ranking.`));
7415
+ }
7416
+ return {
7417
+ deletedForms,
7418
+ deletedFormSubmissions
7419
+ };
7420
+ },
7421
+ async findRawByIdOrSlug(idOrSlug) {
7422
+ await this.ensureSeeded();
7423
+ const raw = String(idOrSlug || "").trim();
7424
+ if (!raw) return null;
7425
+ let found = null;
7426
+ const numericId = Number(raw);
7427
+ if (!Number.isNaN(numericId) && String(numericId) === raw) {
7428
+ found = await strapi.db.query(FORM_UID).findOne({ where: { id: numericId } });
7429
+ }
7430
+ if (!found) {
7431
+ found = await strapi.db.query(FORM_UID).findOne({ where: { documentId: raw } });
7432
+ }
7433
+ if (!found) {
7434
+ found = await strapi.db.query(FORM_UID).findOne({ where: { slug: raw } });
7435
+ }
7436
+ return found;
7437
+ },
7438
+ async findAllAdmin() {
7439
+ await this.ensureSeeded();
7440
+ const entries = await strapi.db.query(FORM_UID).findMany({
7441
+ orderBy: { createdAt: "desc" }
7442
+ });
7443
+ return (entries || []).map(formatFormForAdmin);
7444
+ },
7445
+ async findAllPublic() {
7446
+ await this.ensureSeeded();
7447
+ const entries = await strapi.db.query(FORM_UID).findMany({
7448
+ orderBy: { createdAt: "desc" }
7449
+ });
7450
+ return (entries || []).map(sanitizeFormForPublic);
7451
+ },
7452
+ async findOneAdmin(idOrSlug) {
7453
+ const found = await this.findRawByIdOrSlug(idOrSlug);
7454
+ return formatFormForAdmin(found);
7455
+ },
7456
+ async findOnePublic(idOrSlug) {
7457
+ const found = await this.findRawByIdOrSlug(idOrSlug);
7458
+ return sanitizeFormForPublic(found);
7459
+ },
7460
+ async save(payload) {
7461
+ const cleanTitle = String(payload.title || "New Dynamic Form").trim();
7462
+ const cleanSlug = String(
7463
+ payload.slug || slugifyIdentifier$1(cleanTitle) || `form_${Date.now()}`
7464
+ ).trim();
7465
+ let existing = null;
7466
+ if (payload.id) {
7467
+ const rawId = String(payload.id).trim();
7468
+ const numId = Number(rawId);
7469
+ if (!Number.isNaN(numId) && String(numId) === rawId) {
7470
+ existing = await strapi.db.query(FORM_UID).findOne({ where: { id: numId } });
7471
+ } else {
7472
+ existing = await strapi.db.query(FORM_UID).findOne({ where: { documentId: rawId } });
5706
7473
  }
5707
- } else if (q.type === "short_text" || q.type === "long_text") {
5708
- const ruleParts = [];
5709
- if (q.required) ruleParts.push("required");
5710
- if (q.validation) ruleParts.push(q.validation);
5711
- const combinedRules = Array.from(new Set(ruleParts.join("|").split("|").filter(Boolean))).join("|");
5712
- if (combinedRules) {
5713
- const vErrs = validateSingleField(
5714
- val,
5715
- {
5716
- name: q.key,
5717
- field_type: q.type === "long_text" ? "textArea" : "input",
5718
- alias: q.title,
5719
- validation: combinedRules
5720
- },
5721
- answers,
5722
- locale
5723
- );
5724
- qErrors.push(...vErrs);
7474
+ }
7475
+ if (!existing && cleanSlug) {
7476
+ existing = await strapi.db.query(FORM_UID).findOne({ where: { slug: cleanSlug } });
7477
+ }
7478
+ const mergedMailConfig = {
7479
+ ...existing?.mailConfig || { driver: "env" },
7480
+ ...payload.mailConfig || {}
7481
+ };
7482
+ if (mergedMailConfig.driver === "mailtrap" && mergedMailConfig.apiKey && !String(mergedMailConfig.inboxId || "").trim()) {
7483
+ const autoInbox = await discoverMailtrapSandboxInbox(mergedMailConfig.apiKey);
7484
+ if (autoInbox) {
7485
+ mergedMailConfig.inboxId = autoInbox;
5725
7486
  }
5726
7487
  }
5727
- if (qErrors.length > 0) {
5728
- errors[q.key] = qErrors;
7488
+ const recordData = {
7489
+ title: cleanTitle,
7490
+ slug: cleanSlug,
7491
+ to: payload.to ?? existing?.to ?? "",
7492
+ subject: payload.subject ?? existing?.subject ?? cleanTitle,
7493
+ buttonLabel: payload.buttonLabel ?? existing?.buttonLabel ?? {
7494
+ tr: "Gönder",
7495
+ en: "Submit"
7496
+ },
7497
+ successMessage: payload.successMessage ?? existing?.successMessage ?? {
7498
+ tr: "Mesajınız başarıyla iletildi.",
7499
+ en: "Your message has been sent successfully."
7500
+ },
7501
+ redirect: payload.redirect ?? existing?.redirect ?? "",
7502
+ hideLabels: Boolean(payload.hideLabels ?? existing?.hideLabels ?? false),
7503
+ useRecaptcha: payload.useRecaptcha !== void 0 ? Boolean(payload.useRecaptcha) : existing?.useRecaptcha !== void 0 ? Boolean(existing.useRecaptcha) : true,
7504
+ recaptchaSiteKey: payload.recaptchaSiteKey !== void 0 ? String(payload.recaptchaSiteKey) : existing?.recaptchaSiteKey || "",
7505
+ recaptchaSecretKey: payload.recaptchaSecretKey !== void 0 ? String(payload.recaptchaSecretKey) : existing?.recaptchaSecretKey || "",
7506
+ mailConfig: mergedMailConfig,
7507
+ fields: payload.fields && typeof payload.fields === "object" ? payload.fields : existing?.fields || {},
7508
+ form: Array.isArray(payload.form) ? payload.form : existing?.form || []
7509
+ };
7510
+ if (existing) {
7511
+ const updated = await strapi.db.query(FORM_UID).update({
7512
+ where: { id: existing.id },
7513
+ data: recordData
7514
+ });
7515
+ return formatFormForAdmin(updated);
5729
7516
  }
5730
- }
5731
- return {
5732
- valid: Object.keys(errors).length === 0,
5733
- errors
5734
- };
5735
- }
5736
- function computeVoterHash(surveySlug, ip, userAgent, voterToken) {
5737
- const salt = process.env.APP_KEYS || process.env.API_TOKEN_SALT || "ci-survey-default-salt";
5738
- const rawIdentity = voterToken ? `${surveySlug}::token::${voterToken}` : `${surveySlug}::ipua::${ip || "unknown"}::${(userAgent || "").slice(0, 120)}`;
5739
- return crypto.createHmac("sha256", salt).update(rawIdentity).digest("hex");
5740
- }
5741
- function computeResponseMetrics(survey, answers) {
5742
- let totalScore = 0;
5743
- let hasScoredItem = false;
5744
- let npsValue = null;
5745
- let npsCategory = null;
5746
- for (const q of survey.questions || []) {
5747
- const val = answers?.[q.key];
5748
- if (isEmptyFieldValue(val)) continue;
5749
- if (q.type === "nps" && npsValue === null) {
5750
- const n = Number(val);
5751
- if (!Number.isNaN(n)) {
5752
- npsValue = n;
5753
- npsCategory = n >= 9 ? "promoter" : n >= 7 ? "passive" : "detractor";
7517
+ const created = await strapi.db.query(FORM_UID).create({
7518
+ data: recordData
7519
+ });
7520
+ return formatFormForAdmin(created);
7521
+ },
7522
+ async remove(idOrDocId) {
7523
+ const raw = String(idOrDocId || "").trim();
7524
+ const numericId = Number(raw);
7525
+ if (!Number.isNaN(numericId) && String(numericId) === raw) {
7526
+ await strapi.db.query(FORM_UID).delete({ where: { id: numericId } });
7527
+ } else {
7528
+ const byDoc = await strapi.db.query(FORM_UID).findOne({ where: { documentId: raw } });
7529
+ if (byDoc) {
7530
+ await strapi.db.query(FORM_UID).delete({ where: { id: byDoc.id } });
7531
+ } else {
7532
+ await strapi.db.query(FORM_UID).delete({ where: { slug: raw } });
5754
7533
  }
5755
7534
  }
5756
- if (Array.isArray(q.options) && q.options.length > 0) {
5757
- if (Array.isArray(val)) {
5758
- for (const chosen of val) {
5759
- const opt = q.options.find((o) => o.id === chosen);
5760
- if (opt && typeof opt.score === "number") {
5761
- totalScore += opt.score;
5762
- hasScoredItem = true;
5763
- }
5764
- }
7535
+ return { success: true };
7536
+ },
7537
+ async listSubmissions(formIdOrSlug, limit = 200) {
7538
+ const where = {};
7539
+ if (formIdOrSlug && formIdOrSlug !== "all") {
7540
+ const form = await this.findRawByIdOrSlug(formIdOrSlug);
7541
+ if (form) {
7542
+ where.$or = [
7543
+ { formId: String(form.documentId || form.id) },
7544
+ { formId: String(form.id) },
7545
+ { formSlug: form.slug }
7546
+ ];
5765
7547
  } else {
5766
- const opt = q.options.find((o) => o.id === val);
5767
- if (opt && typeof opt.score === "number") {
5768
- totalScore += opt.score;
5769
- hasScoredItem = true;
5770
- }
7548
+ where.$or = [{ formId: formIdOrSlug }, { formSlug: formIdOrSlug }];
5771
7549
  }
5772
7550
  }
5773
- }
5774
- return {
5775
- score: hasScoredItem ? totalScore : null,
5776
- npsValue,
5777
- npsCategory
5778
- };
5779
- }
5780
- function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
5781
- const fromTime = filter.from ? new Date(filter.from).getTime() : null;
5782
- const toTime = filter.to ? (/* @__PURE__ */ new Date(`${filter.to}T23:59:59.999Z`)).getTime() : null;
5783
- const filterLocale = filter.locale && filter.locale !== "all" ? filter.locale : null;
5784
- const responses = (rawResponses || []).filter((r) => {
5785
- const tsRaw = r.submittedAt || r.createdAt;
5786
- const ts = tsRaw ? new Date(tsRaw).getTime() : 0;
5787
- if (fromTime && !Number.isNaN(fromTime) && ts < fromTime) return false;
5788
- if (toTime && !Number.isNaN(toTime) && ts > toTime) return false;
5789
- if (filterLocale && r.locale !== filterLocale) return false;
5790
- return true;
5791
- });
5792
- const totalResponses = responses.length;
5793
- const durations = responses.map((r) => Number(r.durationSeconds || 0)).filter((d) => d > 0).sort((a, b) => a - b);
5794
- const avgDurationSeconds = durations.length > 0 ? Math.round(durations.reduce((acc, d) => acc + d, 0) / durations.length) : 0;
5795
- const medianDurationSeconds = durations.length > 0 ? durations[Math.floor(durations.length / 2)] : 0;
5796
- const localeCounts = {};
5797
- const dailyCounts = {};
5798
- let lastSubmittedAt = null;
5799
- for (const r of responses) {
5800
- const loc = String(r.locale || "en");
5801
- localeCounts[loc] = (localeCounts[loc] || 0) + 1;
5802
- const tsRaw = r.submittedAt || r.createdAt;
5803
- if (tsRaw) {
5804
- const iso = new Date(tsRaw).toISOString();
5805
- const dayKey = iso.slice(0, 10);
5806
- dailyCounts[dayKey] = (dailyCounts[dayKey] || 0) + 1;
5807
- if (!lastSubmittedAt || iso > lastSubmittedAt) {
5808
- lastSubmittedAt = iso;
7551
+ const rows = await strapi.db.query(SUBMISSION_UID).findMany({
7552
+ where: Object.keys(where).length > 0 ? where : void 0,
7553
+ orderBy: { createdAt: "desc" },
7554
+ limit
7555
+ });
7556
+ return rows || [];
7557
+ },
7558
+ async exportSubmissionsXlsx(formIdOrSlug, locale = "en") {
7559
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
7560
+ const cleanTarget = formIdOrSlug && formIdOrSlug !== "all" ? String(formIdOrSlug).trim() : void 0;
7561
+ const singleForm = cleanTarget ? await this.findRawByIdOrSlug(cleanTarget) : null;
7562
+ const submissions = await this.listSubmissions(cleanTarget, 2e3);
7563
+ let themeColor = "#1E3A8A";
7564
+ try {
7565
+ const colorSvc = strapi.plugin("content-input").service("ci-color");
7566
+ if (colorSvc?.findAll) {
7567
+ const colorData = await colorSvc.findAll();
7568
+ const primaryHex = colorData?.active?.semanticTokens?.primary?.hex;
7569
+ if (primaryHex && typeof primaryHex === "string") {
7570
+ themeColor = primaryHex;
7571
+ }
5809
7572
  }
7573
+ } catch {
5810
7574
  }
5811
- }
5812
- const localeBreakdown = Object.entries(localeCounts).map(([locale, count]) => ({
5813
- locale,
5814
- count,
5815
- percentage: totalResponses > 0 ? Math.round(count / totalResponses * 1e3) / 10 : 0
5816
- })).sort((a, b) => b.count - a.count);
5817
- const dailyTrend = Object.entries(dailyCounts).map(([date, count]) => ({ date, count })).sort((a, b) => a.date.localeCompare(b.date));
5818
- let promoters = 0;
5819
- let passives = 0;
5820
- let detractors = 0;
5821
- for (const r of responses) {
5822
- if (typeof r.npsValue === "number") {
5823
- if (r.npsValue >= 9) promoters += 1;
5824
- else if (r.npsValue >= 7) passives += 1;
5825
- else detractors += 1;
5826
- }
5827
- }
5828
- const totalNpsResponses = promoters + passives + detractors;
5829
- const promotersPct = totalNpsResponses > 0 ? Math.round(promoters / totalNpsResponses * 1e3) / 10 : 0;
5830
- const passivesPct = totalNpsResponses > 0 ? Math.round(passives / totalNpsResponses * 1e3) / 10 : 0;
5831
- const detractorsPct = totalNpsResponses > 0 ? Math.round(detractors / totalNpsResponses * 1e3) / 10 : 0;
5832
- const npsScore = totalNpsResponses > 0 ? Math.round((promoters - detractors) / totalNpsResponses * 100) : 0;
5833
- const questionStats = (survey.questions || []).filter((q) => q && q.type !== "statement").map((q) => {
5834
- let answeredCount = 0;
5835
- const baseInfo = {
5836
- key: q.key,
5837
- type: q.type,
5838
- title: q.title,
5839
- required: Boolean(q.required),
5840
- hasConditions: Boolean(q.conditions?.rules?.length)
7575
+ const dataKeys = Array.from(
7576
+ new Set(
7577
+ submissions.flatMap(
7578
+ (s) => s.data && typeof s.data === "object" ? Object.keys(s.data) : []
7579
+ )
7580
+ )
7581
+ );
7582
+ const singleFields = singleForm?.fields && typeof singleForm.fields === "object" ? singleForm.fields : {};
7583
+ const headers = [
7584
+ "ID",
7585
+ tr ? "Form Adı" : "Form",
7586
+ tr ? "Gönderim Tarihi" : "Submitted At",
7587
+ tr ? "E-Posta İletildi" : "Mail Sent",
7588
+ ...dataKeys.map((k) => {
7589
+ const fDef = singleFields[k];
7590
+ const alias = fDef?.alias ? resolveLocalizedText(fDef.alias, locale, "") : "";
7591
+ return alias ? `${alias} (${k})` : k;
7592
+ })
7593
+ ];
7594
+ const formatCell = (v) => {
7595
+ if (v === null || v === void 0) return "";
7596
+ if (typeof v === "number" && Number.isFinite(v)) return v;
7597
+ if (typeof v === "boolean") return v ? tr ? "Evet" : "Yes" : tr ? "Hayır" : "No";
7598
+ if (Array.isArray(v)) return v.join("; ");
7599
+ if (typeof v === "object") return JSON.stringify(v);
7600
+ return String(v);
5841
7601
  };
5842
- if (q.type === "single_choice" || q.type === "multiple_choice" || q.type === "dropdown" || q.type === "image_choice") {
5843
- const opts = Array.isArray(q.options) ? q.options : [];
5844
- const countsMap = {};
5845
- opts.forEach((o) => {
5846
- countsMap[o.id] = 0;
5847
- });
5848
- let otherCount = 0;
5849
- const otherSamples = [];
5850
- for (const r of responses) {
5851
- const v = r.answers?.[q.key];
5852
- if (isEmptyFieldValue(v)) continue;
5853
- answeredCount += 1;
5854
- const selectedArr = Array.isArray(v) ? v.map(String) : [String(v)];
5855
- for (const item of selectedArr) {
5856
- if (item === "__other__") {
5857
- otherCount += 1;
5858
- const txt = String(r.otherTexts?.[q.key] || "").trim();
5859
- if (txt && otherSamples.length < 30) {
5860
- otherSamples.push({
5861
- text: txt,
5862
- locale: r.locale || "en",
5863
- submittedAt: r.submittedAt || r.createdAt || ""
5864
- });
5865
- }
5866
- } else {
5867
- countsMap[item] = (countsMap[item] || 0) + 1;
5868
- }
5869
- }
5870
- }
5871
- const optionsBreakdown = opts.map((o) => {
5872
- const count = countsMap[o.id] || 0;
5873
- return {
5874
- id: o.id,
5875
- labels: o.labels,
5876
- image: o.image || null,
5877
- count,
5878
- percentage: answeredCount > 0 ? Math.round(count / answeredCount * 1e3) / 10 : 0
5879
- };
5880
- });
5881
- if (q.allowOther || otherCount > 0) {
5882
- optionsBreakdown.push({
5883
- id: "__other__",
5884
- labels: typeof q.otherLabel === "object" && q.otherLabel ? q.otherLabel : { tr: "Diğer", en: "Other" },
5885
- image: null,
5886
- count: otherCount,
5887
- percentage: answeredCount > 0 ? Math.round(otherCount / answeredCount * 1e3) / 10 : 0
5888
- });
5889
- }
7602
+ const rows = submissions.map((s) => [
7603
+ String(s.id || s.documentId || ""),
7604
+ String(s.formTitle || s.formSlug || ""),
7605
+ String(s.createdAt || ""),
7606
+ s.mailSent ? tr ? "Evet" : "Yes" : tr ? "Hayır" : "No",
7607
+ ...dataKeys.map((k) => formatCell(s.data?.[k]))
7608
+ ]);
7609
+ const bannerTitle = singleForm ? `${singleForm.title} — ${tr ? "Form Başvuruları" : "Form Submissions"}` : tr ? "Tüm Dinamik Form Başvuruları" : "All Dynamic Form Submissions";
7610
+ const bannerSubtitle = tr ? `Toplam Kayıt: ${rows.length} • Dışa Aktarım: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace("T", " ")} UTC` : `Total Submissions: ${rows.length} • Exported: ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16).replace("T", " ")} UTC`;
7611
+ const xlsxBuf = buildStyledTableXlsxBuffer({
7612
+ sheetName: tr ? "Form_Basvurulari" : "Form_Submissions",
7613
+ bannerTitle,
7614
+ bannerSubtitle,
7615
+ headers,
7616
+ rows,
7617
+ themeColor
7618
+ });
7619
+ const slugPart = singleForm?.slug || cleanTarget || "all";
7620
+ return {
7621
+ filename: `form-submissions-${slugPart}.xlsx`,
7622
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
7623
+ body: xlsxBuf
7624
+ };
7625
+ },
7626
+ getPublicRecaptchaConfig() {
7627
+ const publicKey = getEnvRecaptchaPublicKey$1();
7628
+ return {
7629
+ publicKey,
7630
+ enabled: Boolean(publicKey)
7631
+ };
7632
+ },
7633
+ async submitForm(idOrSlug, rawBody, meta = {}) {
7634
+ const form = await this.findRawByIdOrSlug(idOrSlug);
7635
+ if (!form) {
5890
7636
  return {
5891
- ...baseInfo,
5892
- answeredCount,
5893
- optionsBreakdown,
5894
- otherSamples
7637
+ ok: false,
7638
+ status: 404,
7639
+ message: "Form not found"
5895
7640
  };
5896
7641
  }
5897
- if (q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") {
5898
- const minVal = q.type === "nps" ? 0 : q.type === "likert_scale" ? q.scaleMin ?? 1 : 1;
5899
- const maxVal = q.type === "nps" ? 10 : q.type === "likert_scale" ? q.scaleMax ?? 5 : q.maxStars ?? 5;
5900
- const distMap = {};
5901
- for (let i = minVal; i <= maxVal; i += 1) distMap[i] = 0;
5902
- let sum = 0;
5903
- let qPromoters = 0;
5904
- let qPassives = 0;
5905
- let qDetractors = 0;
5906
- for (const r of responses) {
5907
- const rawV = r.answers?.[q.key];
5908
- if (isEmptyFieldValue(rawV)) continue;
5909
- const n = Number(rawV);
5910
- if (Number.isNaN(n)) continue;
5911
- answeredCount += 1;
5912
- sum += n;
5913
- distMap[n] = (distMap[n] || 0) + 1;
5914
- if (q.type === "nps") {
5915
- if (n >= 9) qPromoters += 1;
5916
- else if (n >= 7) qPassives += 1;
5917
- else qDetractors += 1;
5918
- }
7642
+ const body = rawBody && typeof rawBody === "object" ? rawBody : {};
7643
+ const rawLocale = String(body._locale || meta.locale || "en").trim().toLowerCase();
7644
+ const locale = rawLocale ? rawLocale.split(/[,;]/)[0].trim() : "en";
7645
+ const fieldsMap = form.fields && typeof form.fields === "object" ? form.fields : {};
7646
+ const { errors } = validateFormSubmission(fieldsMap, body, locale);
7647
+ const activeSecretKey = String(
7648
+ form.recaptchaSecretKey || getEnvRecaptchaPrivateKey$1() || ""
7649
+ ).trim();
7650
+ const activePublicKey = String(
7651
+ form.recaptchaSiteKey || getEnvRecaptchaPublicKey$1() || ""
7652
+ ).trim();
7653
+ if (form.useRecaptcha !== false && activeSecretKey && activePublicKey) {
7654
+ const recaptchaToken = body["g-recaptcha-response"];
7655
+ const recaptchaValid = await verifyRecaptchaToken(
7656
+ recaptchaToken,
7657
+ activeSecretKey,
7658
+ meta.ip
7659
+ );
7660
+ if (!recaptchaValid) {
7661
+ errors["g-recaptcha-response"] = [
7662
+ locale === "tr" ? "Lütfen robot olmadığınızı doğrulayınız (reCAPTCHA)." : "Please complete the reCAPTCHA verification."
7663
+ ];
5919
7664
  }
5920
- const distribution = Object.keys(distMap).map(Number).sort((a, b) => a - b).map((value) => ({
5921
- value,
5922
- labels: q.scaleLabels ? q.scaleLabels[String(value)] : void 0,
5923
- count: distMap[value] || 0,
5924
- percentage: answeredCount > 0 ? Math.round((distMap[value] || 0) / answeredCount * 1e3) / 10 : 0
5925
- }));
7665
+ }
7666
+ if (Object.keys(errors).length > 0) {
5926
7667
  return {
5927
- ...baseInfo,
5928
- answeredCount,
5929
- min: minVal,
5930
- max: maxVal,
5931
- lowLabel: q.lowLabel,
5932
- highLabel: q.highLabel,
5933
- scaleLabels: q.scaleLabels,
5934
- average: answeredCount > 0 ? Math.round(sum / answeredCount * 100) / 100 : 0,
5935
- distribution,
5936
- npsBreakdown: q.type === "nps" ? {
5937
- score: answeredCount > 0 ? Math.round((qPromoters - qDetractors) / answeredCount * 100) : 0,
5938
- promoters: qPromoters,
5939
- passives: qPassives,
5940
- detractors: qDetractors,
5941
- promotersPct: answeredCount > 0 ? Math.round(qPromoters / answeredCount * 1e3) / 10 : 0,
5942
- passivesPct: answeredCount > 0 ? Math.round(qPassives / answeredCount * 1e3) / 10 : 0,
5943
- detractorsPct: answeredCount > 0 ? Math.round(qDetractors / answeredCount * 1e3) / 10 : 0
5944
- } : void 0
7668
+ ok: false,
7669
+ status: 422,
7670
+ errors
5945
7671
  };
5946
7672
  }
5947
- if (q.type === "matrix_single") {
5948
- const mRows = Array.isArray(q.matrixRows) ? q.matrixRows : [];
5949
- const mCols = Array.isArray(q.matrixColumns) ? q.matrixColumns : [];
5950
- const matrixData = {};
5951
- const rowTotals = {};
5952
- for (const rItem of mRows) {
5953
- matrixData[rItem.id] = {};
5954
- rowTotals[rItem.id] = 0;
5955
- for (const cItem of mCols) {
5956
- matrixData[rItem.id][cItem.id] = 0;
5957
- }
7673
+ const cleanData = {};
7674
+ const definedKeys = Object.keys(fieldsMap);
7675
+ if (definedKeys.length > 0) {
7676
+ for (const k of definedKeys) {
7677
+ cleanData[k] = body[k] !== void 0 ? body[k] : null;
5958
7678
  }
5959
- for (const r of responses) {
5960
- const valObj = r.answers?.[q.key];
5961
- if (!valObj || typeof valObj !== "object" || Array.isArray(valObj)) continue;
5962
- let anyRow = false;
5963
- for (const rItem of mRows) {
5964
- const chosenCol = valObj[rItem.id];
5965
- if (!isEmptyFieldValue(chosenCol)) {
5966
- anyRow = true;
5967
- rowTotals[rItem.id] = (rowTotals[rItem.id] || 0) + 1;
5968
- if (matrixData[rItem.id]) {
5969
- matrixData[rItem.id][chosenCol] = (matrixData[rItem.id][chosenCol] || 0) + 1;
5970
- }
5971
- }
5972
- }
5973
- if (anyRow) answeredCount += 1;
7679
+ } else {
7680
+ for (const [k, v] of Object.entries(body)) {
7681
+ if (k === "g-recaptcha-response" || k === "_locale") continue;
7682
+ cleanData[k] = v;
5974
7683
  }
5975
- const rowsBreakdown = mRows.map((rItem) => {
5976
- const rTot = rowTotals[rItem.id] || 0;
5977
- return {
5978
- rowId: rItem.id,
5979
- labels: rItem.labels,
5980
- total: rTot,
5981
- columns: mCols.map((cItem) => {
5982
- const cnt = matrixData[rItem.id]?.[cItem.id] || 0;
5983
- return {
5984
- colId: cItem.id,
5985
- labels: cItem.labels,
5986
- count: cnt,
5987
- percentage: rTot > 0 ? Math.round(cnt / rTot * 1e3) / 10 : 0
5988
- };
5989
- })
5990
- };
5991
- });
5992
- return {
5993
- ...baseInfo,
5994
- answeredCount,
5995
- rowsBreakdown
5996
- };
5997
7684
  }
5998
- if (q.type === "ranking") {
5999
- const opts = Array.isArray(q.options) ? q.options : [];
6000
- const nOpts = opts.length;
6001
- const rankSumMap = {};
6002
- const bordaSumMap = {};
6003
- const firstPlaceMap = {};
6004
- const itemCountMap = {};
6005
- opts.forEach((o) => {
6006
- rankSumMap[o.id] = 0;
6007
- bordaSumMap[o.id] = 0;
6008
- firstPlaceMap[o.id] = 0;
6009
- itemCountMap[o.id] = 0;
6010
- });
6011
- for (const r of responses) {
6012
- const arr = r.answers?.[q.key];
6013
- if (!Array.isArray(arr) || arr.length === 0) continue;
6014
- answeredCount += 1;
6015
- arr.forEach((optId, idx) => {
6016
- if (rankSumMap[optId] !== void 0) {
6017
- rankSumMap[optId] += idx + 1;
6018
- bordaSumMap[optId] += Math.max(1, nOpts - idx);
6019
- itemCountMap[optId] += 1;
6020
- if (idx === 0) firstPlaceMap[optId] += 1;
6021
- }
6022
- });
7685
+ const mailResult = await sendDynamicFormMail({
7686
+ strapi,
7687
+ form: {
7688
+ title: form.title,
7689
+ to: form.to,
7690
+ subject: form.subject,
7691
+ fields: fieldsMap,
7692
+ mailConfig: form.mailConfig
7693
+ },
7694
+ data: cleanData,
7695
+ meta: {
7696
+ ip: meta.ip,
7697
+ userAgent: meta.userAgent,
7698
+ locale
6023
7699
  }
6024
- const maxPossibleBorda = answeredCount * nOpts;
6025
- const rankingBreakdown = opts.map((o) => {
6026
- const cnt = itemCountMap[o.id] || 0;
6027
- const avgRank = cnt > 0 ? Math.round(rankSumMap[o.id] / cnt * 100) / 100 : nOpts;
6028
- const bordaPoints = bordaSumMap[o.id] || 0;
6029
- const firstPlaces = firstPlaceMap[o.id] || 0;
6030
- return {
6031
- id: o.id,
6032
- labels: o.labels,
6033
- averageRank: avgRank,
6034
- bordaPoints,
6035
- scorePercentage: maxPossibleBorda > 0 ? Math.round(bordaPoints / maxPossibleBorda * 1e3) / 10 : 0,
6036
- firstPlaceCount: firstPlaces,
6037
- firstPlacePercentage: answeredCount > 0 ? Math.round(firstPlaces / answeredCount * 1e3) / 10 : 0
6038
- };
6039
- }).sort((a, b) => a.averageRank - b.averageRank);
6040
- return {
6041
- ...baseInfo,
6042
- answeredCount,
6043
- rankingBreakdown
6044
- };
7700
+ });
7701
+ const createdSubmission = await strapi.db.query(SUBMISSION_UID).create({
7702
+ data: {
7703
+ formId: String(form.documentId || form.id),
7704
+ formSlug: form.slug,
7705
+ formTitle: form.title,
7706
+ data: cleanData,
7707
+ ip: meta.ip || "",
7708
+ userAgent: meta.userAgent || "",
7709
+ mailSent: Boolean(mailResult.sent),
7710
+ mailInfo: mailResult
7711
+ }
7712
+ });
7713
+ const successMsg = resolveLocalizedText(
7714
+ form.successMessage,
7715
+ locale,
7716
+ locale === "tr" ? "Mesajınız başarıyla gönderildi." : "Your message has been submitted successfully."
7717
+ );
7718
+ return {
7719
+ ok: true,
7720
+ status: 200,
7721
+ submissionId: createdSubmission?.documentId || String(createdSubmission?.id || ""),
7722
+ message: successMsg,
7723
+ redirect: form.redirect || "",
7724
+ mailSent: Boolean(mailResult.sent),
7725
+ mailDriver: mailResult.driver
7726
+ };
7727
+ },
7728
+ async resolveEntityCard(params) {
7729
+ const uid = String(params.uid || "").trim();
7730
+ if (!uid || !uid.startsWith("api::")) {
7731
+ return null;
6045
7732
  }
6046
- if (q.type === "consent") {
6047
- let acceptedCount = 0;
6048
- for (const r of responses) {
6049
- const v = r.answers?.[q.key];
6050
- if (v === true || v === "true" || v === 1) {
6051
- answeredCount += 1;
6052
- acceptedCount += 1;
6053
- }
7733
+ const ct = (strapi.contentTypes || {})[uid];
7734
+ if (!ct) {
7735
+ return null;
7736
+ }
7737
+ const attrs = ct.attributes || {};
7738
+ const populate = {};
7739
+ const mediaFields = [];
7740
+ const ciFields = [];
7741
+ for (const [attrName, attrDef] of Object.entries(attrs)) {
7742
+ if (attrDef?.type === "media") {
7743
+ populate[attrName] = true;
7744
+ mediaFields.push(attrName);
7745
+ }
7746
+ if (attrDef?.customField === "plugin::content-input.content-input" || attrDef?.type === "json") {
7747
+ ciFields.push(attrName);
6054
7748
  }
6055
- return {
6056
- ...baseInfo,
6057
- answeredCount,
6058
- acceptedCount,
6059
- acceptedPercentage: totalResponses > 0 ? Math.round(acceptedCount / totalResponses * 1e3) / 10 : 0
6060
- };
6061
7749
  }
6062
- const textResponses = [];
6063
- for (const r of responses) {
6064
- const v = r.answers?.[q.key];
6065
- if (typeof v === "string" && v.trim()) {
6066
- answeredCount += 1;
6067
- if (textResponses.length < 100) {
6068
- textResponses.push({
6069
- id: r.id || r.documentId,
6070
- text: v.trim(),
6071
- locale: r.locale || "en",
6072
- submittedAt: r.submittedAt || r.createdAt || "",
6073
- npsValue: r.npsValue ?? null
6074
- });
7750
+ let rows = [];
7751
+ try {
7752
+ const where = {};
7753
+ if (params.documentId) {
7754
+ where.documentId = String(params.documentId);
7755
+ } else if (params.id !== void 0 && params.id !== "") {
7756
+ const numId = Number(params.id);
7757
+ if (!Number.isNaN(numId)) where.id = numId;
7758
+ } else if (params.slug) {
7759
+ where.slug = String(params.slug);
7760
+ }
7761
+ rows = await strapi.db.query(uid).findMany({
7762
+ where: Object.keys(where).length > 0 ? where : void 0,
7763
+ populate: Object.keys(populate).length > 0 ? populate : void 0,
7764
+ limit: 10,
7765
+ orderBy: { id: "desc" }
7766
+ });
7767
+ } catch {
7768
+ rows = [];
7769
+ }
7770
+ if (!rows || rows.length === 0) {
7771
+ return null;
7772
+ }
7773
+ const entry = rows.find((r) => Boolean(r.publishedAt)) || rows[0];
7774
+ const titleCandidates = ["title", "name", "heading", "label", "subject", "baslik", "ad"];
7775
+ const subtitleCandidates = ["subtitle", "kicker", "categoryName", "role", "department", "tag"];
7776
+ const descCandidates = [
7777
+ "description",
7778
+ "excerpt",
7779
+ "summary",
7780
+ "seoDescription",
7781
+ "shortDescription",
7782
+ "lead",
7783
+ "bio",
7784
+ "ozet",
7785
+ "aciklama"
7786
+ ];
7787
+ const imagePriority = [
7788
+ "image",
7789
+ "cover",
7790
+ "thumbnail",
7791
+ "featuredImage",
7792
+ "photo",
7793
+ "banner",
7794
+ "media",
7795
+ "avatar",
7796
+ ...mediaFields
7797
+ ];
7798
+ const pickFirstString = (candidates) => {
7799
+ for (const key of candidates) {
7800
+ const val = entry[key];
7801
+ if (typeof val === "string" && val.trim()) {
7802
+ return stripHtmlTags(val);
6075
7803
  }
6076
7804
  }
6077
- }
6078
- return {
6079
- ...baseInfo,
6080
- answeredCount,
6081
- textResponses
7805
+ return "";
6082
7806
  };
6083
- });
6084
- return {
6085
- summary: {
6086
- totalResponses,
6087
- unfilteredTotalResponses: (rawResponses || []).length,
6088
- quotaLimit: survey.quotaLimit || null,
6089
- quotaPercentage: survey.quotaLimit && survey.quotaLimit > 0 ? Math.min(100, Math.round((rawResponses || []).length / survey.quotaLimit * 1e3) / 10) : null,
6090
- avgDurationSeconds,
6091
- medianDurationSeconds,
6092
- lastSubmittedAt,
6093
- localeBreakdown,
6094
- dailyTrend,
6095
- nps: {
6096
- hasNps: totalNpsResponses > 0,
6097
- score: npsScore,
6098
- promoters,
6099
- passives,
6100
- detractors,
6101
- promotersPct,
6102
- passivesPct,
6103
- detractorsPct,
6104
- totalNpsResponses
6105
- }
6106
- },
6107
- questionStats
6108
- };
6109
- }
6110
- function computePublicSurveyResults(survey, rawResponses) {
6111
- const full = computeSurveyAnalytics(survey, rawResponses);
6112
- return {
6113
- totalResponses: full.summary.totalResponses,
6114
- questions: full.questionStats.filter((qs) => qs.type !== "short_text" && qs.type !== "long_text" && qs.type !== "consent").map((qs) => ({
6115
- key: qs.key,
6116
- type: qs.type,
6117
- title: qs.title,
6118
- answeredCount: qs.answeredCount,
6119
- optionsBreakdown: qs.optionsBreakdown,
6120
- average: qs.average,
6121
- distribution: qs.distribution,
6122
- scaleLabels: qs.scaleLabels,
6123
- npsBreakdown: qs.npsBreakdown,
6124
- rankingBreakdown: qs.rankingBreakdown
6125
- }))
6126
- };
6127
- }
6128
- function escapeCsvCell(val) {
6129
- const str = val === null || val === void 0 ? "" : String(val);
6130
- if (/[",\r\n]/.test(str)) {
6131
- return `"${str.replace(/"/g, '""')}"`;
6132
- }
6133
- return str;
6134
- }
6135
- function buildSurveyResponseExportAoA(survey, rawResponses, locale = "en") {
6136
- const tr = String(locale || "").toLowerCase().startsWith("tr");
6137
- const activeQuestions = (survey.questions || []).filter((q) => q && q.type !== "statement");
6138
- const headers = tr ? [
6139
- "Yanıt ID",
6140
- "Gönderim Tarihi",
6141
- "Dil",
6142
- "Süre (sn)",
6143
- "NPS Puanı",
6144
- "NPS Kategorisi"
6145
- ] : [
6146
- "Response ID",
6147
- "Submitted At",
6148
- "Locale",
6149
- "Duration (s)",
6150
- "NPS Value",
6151
- "NPS Category"
6152
- ];
6153
- for (const q of activeQuestions) {
6154
- const qTitle = resolveLocalizedText(q.title, locale, q.key);
6155
- if (q.type === "matrix_single" && Array.isArray(q.matrixRows)) {
6156
- for (const mRow of q.matrixRows) {
6157
- const rTitle = resolveLocalizedText(mRow.labels, locale, mRow.id);
6158
- headers.push(`${qTitle} [${rTitle}]`);
7807
+ let title = pickFirstString(titleCandidates);
7808
+ if (!title) {
7809
+ const fallbackStrKey = Object.keys(attrs).find(
7810
+ (k) => ["string", "text"].includes(attrs[k]?.type)
7811
+ );
7812
+ if (fallbackStrKey && typeof entry[fallbackStrKey] === "string") {
7813
+ title = entry[fallbackStrKey];
7814
+ } else {
7815
+ title = `#${entry.documentId || entry.id}`;
6159
7816
  }
6160
- } else {
6161
- headers.push(`${qTitle} (${q.key})`);
6162
- if (q.allowOther) {
6163
- headers.push(`${qTitle} [${tr ? "Diğer Açıklama" : "Other Text"}]`);
7817
+ }
7818
+ const collectionLabel = ct.info?.displayName || ct.info?.singularName || uid;
7819
+ const subtitle = pickFirstString(subtitleCandidates);
7820
+ let description = pickFirstString(descCandidates);
7821
+ let imageObj = null;
7822
+ for (const imgKey of imagePriority) {
7823
+ const rawMedia = entry[imgKey];
7824
+ if (!rawMedia) continue;
7825
+ const firstMedia = Array.isArray(rawMedia) ? rawMedia[0] : rawMedia;
7826
+ if (firstMedia && typeof firstMedia === "object" && firstMedia.url) {
7827
+ imageObj = {
7828
+ id: firstMedia.id,
7829
+ documentId: firstMedia.documentId,
7830
+ url: firstMedia.url,
7831
+ name: firstMedia.name || title,
7832
+ alternativeText: firstMedia.alternativeText || title,
7833
+ width: firstMedia.width,
7834
+ height: firstMedia.height,
7835
+ formats: firstMedia.formats
7836
+ };
7837
+ break;
6164
7838
  }
6165
7839
  }
6166
- }
6167
- const rows = [];
6168
- for (const r of rawResponses || []) {
6169
- const rowCells = [
6170
- String(r.id || r.documentId || ""),
6171
- String(r.submittedAt || r.createdAt || ""),
6172
- String(r.locale || ""),
6173
- typeof r.durationSeconds === "number" ? r.durationSeconds : String(r.durationSeconds ?? ""),
6174
- typeof r.npsValue === "number" ? r.npsValue : r.npsValue !== null && r.npsValue !== void 0 && r.npsValue !== "" ? Number(r.npsValue) : "",
6175
- String(r.npsCategory || "")
6176
- ];
6177
- for (const q of activeQuestions) {
6178
- const ans = r.answers?.[q.key];
6179
- if (q.type === "matrix_single" && Array.isArray(q.matrixRows)) {
6180
- const mCols = Array.isArray(q.matrixColumns) ? q.matrixColumns : [];
6181
- for (const mRow of q.matrixRows) {
6182
- const chosenColId = ans && typeof ans === "object" ? ans[mRow.id] : "";
6183
- const foundCol = mCols.find((c) => c.id === chosenColId);
6184
- rowCells.push(
6185
- foundCol ? resolveLocalizedText(foundCol.labels, locale, chosenColId) : String(chosenColId || "")
6186
- );
6187
- }
6188
- } else if (Array.isArray(q.options) && q.options.length > 0) {
6189
- if (Array.isArray(ans)) {
6190
- const mapped = ans.map((optId) => {
6191
- if (optId === "__other__") return tr ? "Diğer" : "Other";
6192
- const found = q.options.find((o) => o.id === optId);
6193
- return found ? resolveLocalizedText(found.labels, locale, optId) : optId;
6194
- });
6195
- rowCells.push(mapped.join(q.type === "ranking" ? " > " : "; "));
6196
- } else if (ans !== void 0 && ans !== null && ans !== "") {
6197
- const strAns = String(ans);
6198
- if (strAns === "__other__") {
6199
- rowCells.push(tr ? "Diğer" : "Other");
6200
- } else {
6201
- const found = q.options.find((o) => o.id === strAns);
6202
- rowCells.push(found ? resolveLocalizedText(found.labels, locale, strAns) : strAns);
7840
+ if (!description || !imageObj) {
7841
+ for (const ciField of ciFields) {
7842
+ if (Array.isArray(entry[ciField])) {
7843
+ const extracted = extractSnippetAndImageFromContentInput(entry[ciField]);
7844
+ if (!description && extracted.snippet) {
7845
+ description = extracted.snippet;
7846
+ }
7847
+ if (!imageObj && extracted.image) {
7848
+ imageObj = extracted.image;
6203
7849
  }
6204
- } else {
6205
- rowCells.push("");
6206
- }
6207
- if (q.allowOther) {
6208
- rowCells.push(String(r.otherTexts?.[q.key] || ""));
6209
- }
6210
- } else {
6211
- if (q.type === "likert_scale" && q.scaleLabels && ans !== void 0 && ans !== null && ans !== "") {
6212
- const ptLbl = resolveLocalizedText(q.scaleLabels[String(ans)], locale, "");
6213
- rowCells.push(ptLbl ? `${ans} - ${ptLbl}` : Number.isNaN(Number(ans)) ? String(ans) : Number(ans));
6214
- } else if ((q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") && ans !== void 0 && ans !== null && ans !== "" && !Number.isNaN(Number(ans))) {
6215
- rowCells.push(Number(ans));
6216
- } else {
6217
- rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
6218
- }
6219
- if (q.allowOther) {
6220
- rowCells.push(String(r.otherTexts?.[q.key] || ""));
6221
7850
  }
6222
7851
  }
6223
7852
  }
6224
- rows.push(rowCells);
6225
- }
6226
- return { headers, rows };
6227
- }
6228
- function computeAutoColWidths(aoa) {
6229
- const colCount = aoa.reduce((m, r) => Math.max(m, r.length), 0);
6230
- const widths = [];
6231
- for (let c = 0; c < colCount; c++) {
6232
- let maxLen = 12;
6233
- for (let r = 0; r < Math.min(aoa.length, 300); r++) {
6234
- const cell = aoa[r]?.[c];
6235
- const str = cell === null || cell === void 0 ? "" : String(cell);
6236
- if (str.length > maxLen) maxLen = str.length;
6237
- }
6238
- widths.push({ wch: Math.min(54, maxLen + 3) });
6239
- }
6240
- return widths;
6241
- }
6242
- function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
6243
- const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
6244
- const lines = [headers.map(escapeCsvCell).join(",")];
6245
- for (const r of rows) {
6246
- lines.push(r.map(escapeCsvCell).join(","));
6247
- }
6248
- return `\uFEFF${lines.join("\r\n")}`;
6249
- }
6250
- function exportSurveyResponsesToXlsxBuffer(survey, rawResponses, locale = "en") {
6251
- const tr = String(locale || "").toLowerCase().startsWith("tr");
6252
- const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
6253
- const responsesAoA = [headers, ...rows];
6254
- const wb = XLSX.utils.book_new();
6255
- const wsResponses = XLSX.utils.aoa_to_sheet(responsesAoA);
6256
- wsResponses["!cols"] = computeAutoColWidths(responsesAoA);
6257
- XLSX.utils.book_append_sheet(wb, wsResponses, tr ? "Yanitlar" : "Responses");
6258
- const analytics = computeSurveyAnalytics(survey, rawResponses);
6259
- const s = analytics.summary;
6260
- const summaryAoA = [
6261
- [tr ? "Anket Başlığı" : "Survey Title", resolveLocalizedText(survey.titleI18n, locale, survey.title)],
6262
- ["Survey Slug", survey.slug],
6263
- [tr ? "Dışa Aktarım Tarihi" : "Exported At", (/* @__PURE__ */ new Date()).toISOString()],
6264
- [tr ? "Toplam Yanıt" : "Total Responses", s.totalResponses],
6265
- [tr ? "Ortalama Süre (sn)" : "Average Duration (s)", s.avgDurationSeconds],
6266
- [tr ? "Medyan Süre (sn)" : "Median Duration (s)", s.medianDurationSeconds]
6267
- ];
6268
- if (s.nps?.hasNps) {
6269
- summaryAoA.push(
6270
- ["Net Promoter Score (NPS)", s.nps.score ?? 0],
6271
- [
6272
- tr ? "NPS Dağılımı" : "NPS Breakdown",
6273
- `Promoters: ${s.nps.promoters} (${s.nps.promotersPct}%) | Passives: ${s.nps.passives} (${s.nps.passivesPct}%) | Detractors: ${s.nps.detractors} (${s.nps.detractorsPct}%)`
6274
- ]
6275
- );
6276
- }
6277
- summaryAoA.push(
6278
- [],
6279
- tr ? ["Soru Anahtarı", "Soru Başlığı", "Tip", "Seçenek / Kriter", "Adet / Ort.", "Yüzde (%)"] : ["Question Key", "Question Title", "Type", "Option / Metric", "Count / Avg", "Share (%)"]
6280
- );
6281
- for (const qs of analytics.questionStats) {
6282
- const qTitle = resolveLocalizedText(qs.title, locale, qs.key);
6283
- if (Array.isArray(qs.optionsBreakdown)) {
6284
- for (const opt of qs.optionsBreakdown) {
6285
- const optLbl = opt.id === "__other__" ? tr ? "Diğer" : "Other" : resolveLocalizedText(opt.labels, locale, opt.id);
6286
- summaryAoA.push([qs.key, qTitle, qs.type, optLbl, opt.count, opt.percentage]);
6287
- }
6288
- } else if (Array.isArray(qs.distribution)) {
6289
- summaryAoA.push([
6290
- qs.key,
6291
- qTitle,
6292
- qs.type,
6293
- tr ? "Ortalama Puan" : "Average Score",
6294
- qs.average,
6295
- ""
6296
- ]);
6297
- for (const d of qs.distribution) {
6298
- const ptLbl = d.labels ? resolveLocalizedText(d.labels, locale, "") : "";
6299
- summaryAoA.push([
6300
- qs.key,
6301
- qTitle,
6302
- qs.type,
6303
- ptLbl ? `${d.value} - ${ptLbl}` : String(d.value),
6304
- d.count,
6305
- d.percentage
6306
- ]);
6307
- }
6308
- } else if (Array.isArray(qs.rankingBreakdown)) {
6309
- for (const rk of qs.rankingBreakdown) {
6310
- summaryAoA.push([
6311
- qs.key,
6312
- qTitle,
6313
- qs.type,
6314
- resolveLocalizedText(rk.labels, locale, rk.id),
6315
- rk.averageRank,
6316
- rk.scorePercentage
6317
- ]);
7853
+ if (imageObj) {
7854
+ try {
7855
+ imageObj = await enrichMediaAssetNode(strapi, imageObj, {
7856
+ defaultAutoMaxW: 960
7857
+ });
7858
+ } catch {
6318
7859
  }
7860
+ }
7861
+ const pluralName = ct.info?.pluralName || "items";
7862
+ const slugField = ["slug", "path", "url", "permalink"].find(
7863
+ (k) => typeof entry[k] === "string" && entry[k].trim()
7864
+ );
7865
+ const rawSlug = slugField ? String(entry[slugField]).trim() : String(entry.documentId || entry.id);
7866
+ let url = "/";
7867
+ if (rawSlug === "home" || rawSlug === "anasayfa" || rawSlug === "/") {
7868
+ url = "/";
7869
+ } else if (rawSlug.startsWith("/")) {
7870
+ url = rawSlug;
6319
7871
  } else {
6320
- summaryAoA.push([
6321
- qs.key,
6322
- qTitle,
6323
- qs.type,
6324
- tr ? "Toplam Yanıt" : "Answered Count",
6325
- qs.answeredCount || 0,
6326
- ""
6327
- ]);
7872
+ const prefix = pluralName === "pages" ? "" : `/${pluralName}`;
7873
+ url = `${prefix}/${rawSlug}`.replace(/\/+/g, "/");
6328
7874
  }
7875
+ return {
7876
+ id: entry.id,
7877
+ documentId: String(entry.documentId || entry.id),
7878
+ uid,
7879
+ collectionName: pluralName,
7880
+ collectionLabel,
7881
+ title,
7882
+ subtitle,
7883
+ description,
7884
+ image: imageObj,
7885
+ url,
7886
+ slug: rawSlug,
7887
+ publishedAt: entry.publishedAt || entry.updatedAt || entry.createdAt || null
7888
+ };
6329
7889
  }
6330
- const wsSummary = XLSX.utils.aoa_to_sheet(summaryAoA);
6331
- wsSummary["!cols"] = computeAutoColWidths(summaryAoA);
6332
- XLSX.utils.book_append_sheet(wb, wsSummary, tr ? "Ozet_Istatistik" : "Summary");
6333
- const out = XLSX.write(wb, { type: "buffer", bookType: "xlsx" });
6334
- return Buffer.isBuffer(out) ? out : Buffer.from(out);
6335
- }
7890
+ });
6336
7891
  const SURVEY_UID = "plugin::content-input.ci-survey";
6337
7892
  const SURVEY_RESPONSE_UID = "plugin::content-input.ci-survey-response";
6338
7893
  let activeSeedPromise = null;
@@ -7053,13 +8608,33 @@ const ciSurveyService = ({ strapi }) => ({
7053
8608
  });
7054
8609
  }
7055
8610
  if (options2.format === "xlsx") {
8611
+ let resolvedThemeColor = options2.xlsxOptions?.themeColor;
8612
+ if (!resolvedThemeColor) {
8613
+ try {
8614
+ const colorSvc = strapi.plugin("content-input").service("ci-color");
8615
+ if (colorSvc?.findAll) {
8616
+ const colorData = await colorSvc.findAll();
8617
+ const primaryHex = colorData?.active?.semanticTokens?.primary?.hex;
8618
+ if (primaryHex && typeof primaryHex === "string") {
8619
+ resolvedThemeColor = primaryHex;
8620
+ }
8621
+ }
8622
+ } catch {
8623
+ }
8624
+ }
7056
8625
  const xlsxBuf = exportSurveyResponsesToXlsxBuffer(
7057
8626
  survey,
7058
8627
  responses,
7059
- options2.locale || "en"
8628
+ options2.locale || "en",
8629
+ {
8630
+ from: options2.from,
8631
+ to: options2.to,
8632
+ ...options2.xlsxOptions,
8633
+ ...resolvedThemeColor ? { themeColor: resolvedThemeColor } : {}
8634
+ }
7060
8635
  );
7061
8636
  return {
7062
- filename: `${survey.slug}-responses.xlsx`,
8637
+ filename: `${survey.slug}-executive-report.xlsx`,
7063
8638
  contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
7064
8639
  body: xlsxBuf
7065
8640
  };