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