@ozguraltan/strapi-content-input 1.0.22 → 1.0.24

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 (26) hide show
  1. package/README.md +14 -9
  2. package/dist/admin/{AnalyticsHubPage-B1_chQkG.js → AnalyticsHubPage-ByOrVZCl.js} +555 -59
  3. package/dist/admin/{AnalyticsHubPage-DUj3D2kA.mjs → AnalyticsHubPage-O-7pF2E5.mjs} +537 -59
  4. package/dist/admin/{ContentInputField-BrtpTCDd.mjs → ContentInputField-BoZHf0Ka.mjs} +6 -236
  5. package/dist/admin/{ContentInputField-CQFQxxgm.js → ContentInputField-DK97AIG0.js} +22 -252
  6. package/dist/admin/{SurveyWidgetEditor-C5Uvyf_h.js → SurveyWidgetEditor-D3KiAotu.js} +6133 -514
  7. package/dist/admin/{SurveyWidgetEditor-DGSwgTzR.mjs → SurveyWidgetEditor-Y5BR-NWE.mjs} +6157 -539
  8. package/dist/admin/{index-Dc7AFLOj.mjs → index-C5Uj5YV9.mjs} +2 -2
  9. package/dist/admin/{index-i0NfSYto.js → index-CHtB_Fa5.js} +2 -2
  10. package/dist/admin/index.js +1 -1
  11. package/dist/admin/index.mjs +1 -1
  12. package/dist/admin/src/components/widgets/SurveyLivePreviewPane.d.ts +9 -0
  13. package/dist/admin/src/components/widgets/SurveyTransferCleanupModal.d.ts +35 -0
  14. package/dist/admin/src/components/widgets/SurveyWidgetEditor.d.ts +3 -1
  15. package/dist/admin/src/components/widgets/surveyStepTreeOps.d.ts +54 -0
  16. package/dist/server/index.js +796 -32
  17. package/dist/server/index.mjs +778 -32
  18. package/dist/server/src/controllers/ci-survey.d.ts +4 -0
  19. package/dist/server/src/controllers/index.d.ts +4 -0
  20. package/dist/server/src/index.d.ts +56 -2
  21. package/dist/server/src/services/ci-form.d.ts +5 -1
  22. package/dist/server/src/services/ci-survey.d.ts +47 -1
  23. package/dist/server/src/services/index.d.ts +52 -2
  24. package/dist/server/src/utils/demoSeedState.d.ts +14 -0
  25. package/dist/server/src/utils/surveyEngine.d.ts +5 -0
  26. package/package.json +1 -1
@@ -3,6 +3,7 @@ import fs from "fs";
3
3
  import { createRequire } from "module";
4
4
  import os from "os";
5
5
  import path from "path";
6
+ import * as XLSXNs from "xlsx";
6
7
  const register = ({ strapi }) => {
7
8
  strapi.customFields.register({
8
9
  name: "content-input",
@@ -1908,18 +1909,31 @@ const ciSurveyController = ({ strapi }) => ({
1908
1909
  async exportResponses(ctx) {
1909
1910
  try {
1910
1911
  const { id } = ctx.params;
1911
- const format = String(ctx.query?.format || "csv").toLowerCase() === "json" ? "json" : "csv";
1912
+ const rawFmt = String(ctx.query?.format || "xlsx").toLowerCase();
1913
+ const format = rawFmt === "json" ? "json" : rawFmt === "csv" ? "csv" : "xlsx";
1912
1914
  const locale = String(ctx.query?.locale || "en").trim();
1913
1915
  const from = ctx.query?.from ? String(ctx.query.from) : void 0;
1914
1916
  const to = ctx.query?.to ? String(ctx.query.to) : void 0;
1917
+ const encoding = String(ctx.query?.encoding || "").toLowerCase();
1915
1918
  const exported = await strapi.plugin("content-input").service("ci-survey").exportResponses(id, { format, locale, from, to });
1916
1919
  if (!exported) {
1917
1920
  return ctx.notFound("Survey not found");
1918
1921
  }
1922
+ if (encoding === "base64") {
1923
+ const buf = Buffer.isBuffer(exported.body) ? exported.body : Buffer.from(String(exported.body), "utf8");
1924
+ ctx.status = 200;
1925
+ ctx.body = {
1926
+ filename: exported.filename,
1927
+ contentType: exported.contentType,
1928
+ base64: buf.toString("base64")
1929
+ };
1930
+ return;
1931
+ }
1932
+ ctx.body = exported.body;
1933
+ ctx.type = exported.contentType;
1919
1934
  ctx.set("Content-Type", exported.contentType);
1920
1935
  ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
1921
1936
  ctx.status = 200;
1922
- ctx.body = exported.body;
1923
1937
  } catch (err) {
1924
1938
  ctx.throw(500, err);
1925
1939
  }
@@ -1931,6 +1945,79 @@ const ciSurveyController = ({ strapi }) => ({
1931
1945
  } catch (err) {
1932
1946
  ctx.throw(500, err);
1933
1947
  }
1948
+ },
1949
+ async purgeDemo(ctx) {
1950
+ try {
1951
+ const res = await strapi.plugin("content-input").service("ci-survey").purgeDemoData();
1952
+ ctx.status = 200;
1953
+ ctx.body = res;
1954
+ } catch (err) {
1955
+ ctx.throw(500, err);
1956
+ }
1957
+ },
1958
+ async clearResponses(ctx) {
1959
+ try {
1960
+ const { id } = ctx.params;
1961
+ const res = await strapi.plugin("content-input").service("ci-survey").clearResponses(id);
1962
+ if (!res) {
1963
+ return ctx.notFound("Survey not found");
1964
+ }
1965
+ ctx.status = 200;
1966
+ ctx.body = res;
1967
+ } catch (err) {
1968
+ ctx.throw(500, err);
1969
+ }
1970
+ },
1971
+ async exportBundle(ctx) {
1972
+ try {
1973
+ const target = String(ctx.query?.target || "all").trim();
1974
+ const rawMode = String(ctx.query?.mode || "structure").trim().toLowerCase();
1975
+ const mode = rawMode === "full" ? "full" : "structure";
1976
+ const directDownload = String(ctx.query?.download || "") === "1";
1977
+ const exported = await strapi.plugin("content-input").service("ci-survey").exportBundle(target, mode);
1978
+ if (!exported) {
1979
+ return ctx.notFound("Survey not found");
1980
+ }
1981
+ if (directDownload) {
1982
+ ctx.body = JSON.stringify(exported.bundle, null, 2);
1983
+ ctx.type = exported.contentType;
1984
+ ctx.set("Content-Type", exported.contentType);
1985
+ ctx.set("Content-Disposition", `attachment; filename="${exported.filename}"`);
1986
+ ctx.status = 200;
1987
+ return;
1988
+ }
1989
+ ctx.status = 200;
1990
+ ctx.body = {
1991
+ filename: exported.filename,
1992
+ bundle: exported.bundle
1993
+ };
1994
+ } catch (err) {
1995
+ ctx.throw(500, err);
1996
+ }
1997
+ },
1998
+ async importBundle(ctx) {
1999
+ try {
2000
+ const rawBody = ctx.request.body || {};
2001
+ const hasEnvelope = rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) && rawBody.bundle !== void 0;
2002
+ const bundlePayload = hasEnvelope ? rawBody.bundle : rawBody;
2003
+ const rawStrategy = String(
2004
+ (hasEnvelope ? rawBody.conflictStrategy : ctx.query?.conflictStrategy) || "duplicate"
2005
+ ).trim().toLowerCase();
2006
+ const conflictStrategy = rawStrategy === "overwrite" ? "overwrite" : "duplicate";
2007
+ const rawInclude = hasEnvelope ? rawBody.includeResponses : ctx.query?.includeResponses;
2008
+ const includeResponses = rawInclude === void 0 ? true : rawInclude !== false && String(rawInclude).toLowerCase() !== "false";
2009
+ const res = await strapi.plugin("content-input").service("ci-survey").importBundle(bundlePayload, {
2010
+ conflictStrategy,
2011
+ includeResponses
2012
+ });
2013
+ ctx.status = 200;
2014
+ ctx.body = res;
2015
+ } catch (err) {
2016
+ if (err?.status === 400) {
2017
+ return ctx.badRequest(err.message || "Invalid survey bundle");
2018
+ }
2019
+ ctx.throw(500, err);
2020
+ }
1934
2021
  }
1935
2022
  });
1936
2023
  const ciColorController = ({ strapi }) => ({
@@ -2244,6 +2331,46 @@ const routes = {
2244
2331
  policies: []
2245
2332
  }
2246
2333
  },
2334
+ {
2335
+ method: "POST",
2336
+ path: "/surveys/purge-demo",
2337
+ handler: "ci-survey.purgeDemo",
2338
+ config: {
2339
+ policies: []
2340
+ }
2341
+ },
2342
+ {
2343
+ method: "GET",
2344
+ path: "/survey-bundle/export",
2345
+ handler: "ci-survey.exportBundle",
2346
+ config: {
2347
+ policies: []
2348
+ }
2349
+ },
2350
+ {
2351
+ method: "POST",
2352
+ path: "/survey-bundle/import",
2353
+ handler: "ci-survey.importBundle",
2354
+ config: {
2355
+ policies: []
2356
+ }
2357
+ },
2358
+ {
2359
+ method: "GET",
2360
+ path: "/surveys/bundle/export",
2361
+ handler: "ci-survey.exportBundle",
2362
+ config: {
2363
+ policies: []
2364
+ }
2365
+ },
2366
+ {
2367
+ method: "POST",
2368
+ path: "/surveys/bundle/import",
2369
+ handler: "ci-survey.importBundle",
2370
+ config: {
2371
+ policies: []
2372
+ }
2373
+ },
2247
2374
  {
2248
2375
  method: "POST",
2249
2376
  path: "/surveys",
@@ -2268,6 +2395,14 @@ const routes = {
2268
2395
  policies: []
2269
2396
  }
2270
2397
  },
2398
+ {
2399
+ method: "DELETE",
2400
+ path: "/surveys/:id/responses",
2401
+ handler: "ci-survey.clearResponses",
2402
+ config: {
2403
+ policies: []
2404
+ }
2405
+ },
2271
2406
  {
2272
2407
  method: "GET",
2273
2408
  path: "/surveys/:id/analytics",
@@ -4489,6 +4624,84 @@ function generateSampleFormSubmissions(formEntry) {
4489
4624
  }
4490
4625
  return list;
4491
4626
  }
4627
+ const DEMO_SEED_STORE_KEY = "demo_seed_state";
4628
+ const fallbackStore = /* @__PURE__ */ new WeakMap();
4629
+ function isDemoSeedDisabledByEnv() {
4630
+ const raw = String(process.env.CI_DISABLE_DEMO_SEED || "").trim().toLowerCase();
4631
+ return raw === "true" || raw === "1" || raw === "yes";
4632
+ }
4633
+ function getPluginStore(strapi) {
4634
+ if (strapi && typeof strapi.store === "function") {
4635
+ return strapi.store({
4636
+ type: "plugin",
4637
+ name: "content-input"
4638
+ });
4639
+ }
4640
+ return null;
4641
+ }
4642
+ async function getDemoSeedState(strapi) {
4643
+ const disabledByEnv = isDemoSeedDisabledByEnv();
4644
+ let stored = null;
4645
+ try {
4646
+ const store = getPluginStore(strapi);
4647
+ if (store && typeof store.get === "function") {
4648
+ const val = await store.get({ key: DEMO_SEED_STORE_KEY });
4649
+ if (val && typeof val === "object") {
4650
+ stored = val;
4651
+ }
4652
+ } else if (strapi && typeof strapi === "object") {
4653
+ stored = fallbackStore.get(strapi) || null;
4654
+ }
4655
+ } catch {
4656
+ if (strapi && typeof strapi === "object") {
4657
+ stored = fallbackStore.get(strapi) || null;
4658
+ }
4659
+ }
4660
+ return {
4661
+ cleared: Boolean(stored?.cleared),
4662
+ surveysInitialized: Boolean(stored?.surveysInitialized),
4663
+ formsInitialized: Boolean(stored?.formsInitialized),
4664
+ updatedAt: stored?.updatedAt || "",
4665
+ disabledByEnv
4666
+ };
4667
+ }
4668
+ async function updateDemoSeedState(strapi, patch) {
4669
+ const current = await getDemoSeedState(strapi);
4670
+ const next = {
4671
+ cleared: patch.cleared !== void 0 ? Boolean(patch.cleared) : current.cleared,
4672
+ surveysInitialized: patch.surveysInitialized !== void 0 ? Boolean(patch.surveysInitialized) : Boolean(current.surveysInitialized),
4673
+ formsInitialized: patch.formsInitialized !== void 0 ? Boolean(patch.formsInitialized) : Boolean(current.formsInitialized),
4674
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4675
+ };
4676
+ if (strapi && typeof strapi === "object") {
4677
+ fallbackStore.set(strapi, next);
4678
+ }
4679
+ try {
4680
+ const store = getPluginStore(strapi);
4681
+ if (store && typeof store.set === "function") {
4682
+ await store.set({
4683
+ key: DEMO_SEED_STORE_KEY,
4684
+ value: next
4685
+ });
4686
+ }
4687
+ } catch {
4688
+ }
4689
+ return next;
4690
+ }
4691
+ async function isDemoSeedBlocked(strapi, domain) {
4692
+ const state = await getDemoSeedState(strapi);
4693
+ if (state.disabledByEnv || state.cleared) return true;
4694
+ if (domain === "surveys" && state.surveysInitialized) return true;
4695
+ if (domain === "forms" && state.formsInitialized) return true;
4696
+ return false;
4697
+ }
4698
+ async function setDemoSeedCleared(strapi, cleared) {
4699
+ return updateDemoSeedState(strapi, {
4700
+ cleared,
4701
+ surveysInitialized: true,
4702
+ formsInitialized: true
4703
+ });
4704
+ }
4492
4705
  const FORM_UID = "plugin::content-input.ci-form";
4493
4706
  const SUBMISSION_UID = "plugin::content-input.ci-form-submission";
4494
4707
  function slugifyIdentifier$1(text) {
@@ -4817,11 +5030,20 @@ const ciFormService = ({ strapi }) => ({
4817
5030
  },
4818
5031
  async ensureSampleSubmissions(force = false) {
4819
5032
  try {
5033
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5034
+ return;
5035
+ }
4820
5036
  const subCount = await strapi.db.query(SUBMISSION_UID).count();
4821
5037
  if (subCount > 0 && !force) return;
4822
- const showcaseForm = await strapi.db.query(FORM_UID).findOne({
5038
+ let showcaseForm = await strapi.db.query(FORM_UID).findOne({
4823
5039
  where: { slug: "showcase_contact_form" }
4824
5040
  });
5041
+ if (!showcaseForm && force) {
5042
+ const seedDef = DEFAULT_SEED_FORMS.find((s) => s.slug === "showcase_contact_form");
5043
+ if (seedDef) {
5044
+ showcaseForm = await strapi.db.query(FORM_UID).create({ data: seedDef });
5045
+ }
5046
+ }
4825
5047
  if (!showcaseForm) return;
4826
5048
  if (force) {
4827
5049
  await strapi.db.query(SUBMISSION_UID).deleteMany({
@@ -4835,16 +5057,24 @@ const ciFormService = ({ strapi }) => ({
4835
5057
  } catch {
4836
5058
  }
4837
5059
  },
4838
- async ensureSeeded() {
5060
+ async ensureSeeded(force = false) {
5061
+ if (!force && await isDemoSeedBlocked(strapi, "forms")) {
5062
+ return;
5063
+ }
4839
5064
  let count = 0;
4840
5065
  try {
4841
5066
  count = await strapi.db.query(FORM_UID).count();
4842
5067
  } catch {
4843
5068
  return;
4844
5069
  }
4845
- if (count === 0) {
5070
+ if (count === 0 || force) {
4846
5071
  for (const seed of DEFAULT_SEED_FORMS) {
4847
- await strapi.db.query(FORM_UID).create({ data: seed });
5072
+ const existingSeed = await strapi.db.query(FORM_UID).findOne({
5073
+ where: { slug: seed.slug }
5074
+ });
5075
+ if (!existingSeed) {
5076
+ await strapi.db.query(FORM_UID).create({ data: seed });
5077
+ }
4848
5078
  }
4849
5079
  } else {
4850
5080
  try {
@@ -4863,7 +5093,52 @@ const ciFormService = ({ strapi }) => ({
4863
5093
  } catch {
4864
5094
  }
4865
5095
  }
4866
- await this.ensureSampleSubmissions(false);
5096
+ await this.ensureSampleSubmissions(force);
5097
+ await updateDemoSeedState(strapi, { formsInitialized: true });
5098
+ },
5099
+ async purgeDemoForms() {
5100
+ let deletedForms = 0;
5101
+ let deletedFormSubmissions = 0;
5102
+ const demoSlugs = DEFAULT_SEED_FORMS.map((f) => f.slug);
5103
+ for (const slug of demoSlugs) {
5104
+ try {
5105
+ const existingForm = await strapi.db.query(FORM_UID).findOne({
5106
+ where: { slug }
5107
+ });
5108
+ const matchingSubs = await strapi.db.query(SUBMISSION_UID).findMany({
5109
+ where: existingForm ? {
5110
+ $or: [
5111
+ { formSlug: slug },
5112
+ { formId: String(existingForm.documentId || existingForm.id) },
5113
+ { formId: String(existingForm.id) }
5114
+ ]
5115
+ } : { formSlug: slug }
5116
+ }) || [];
5117
+ if (matchingSubs.length > 0) {
5118
+ const subIds = matchingSubs.map((s) => s.id).filter((id) => id !== void 0 && id !== null);
5119
+ if (subIds.length > 0) {
5120
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
5121
+ where: { id: { $in: subIds } }
5122
+ });
5123
+ }
5124
+ await strapi.db.query(SUBMISSION_UID).deleteMany({
5125
+ where: { formSlug: slug }
5126
+ });
5127
+ deletedFormSubmissions += matchingSubs.length;
5128
+ }
5129
+ if (existingForm) {
5130
+ await strapi.db.query(FORM_UID).delete({
5131
+ where: { id: existingForm.id }
5132
+ });
5133
+ deletedForms += 1;
5134
+ }
5135
+ } catch {
5136
+ }
5137
+ }
5138
+ return {
5139
+ deletedForms,
5140
+ deletedFormSubmissions
5141
+ };
4867
5142
  },
4868
5143
  async findRawByIdOrSlug(idOrSlug) {
4869
5144
  await this.ensureSeeded();
@@ -5267,6 +5542,7 @@ const ciFormService = ({ strapi }) => ({
5267
5542
  };
5268
5543
  }
5269
5544
  });
5545
+ const XLSX = XLSXNs?.utils ? XLSXNs : XLSXNs?.default || XLSXNs;
5270
5546
  function evalSingleRule(rule, answers) {
5271
5547
  const targetVal = answers ? answers[rule.questionKey] : void 0;
5272
5548
  const op = rule.operator;
@@ -5643,6 +5919,7 @@ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
5643
5919
  }
5644
5920
  const distribution = Object.keys(distMap).map(Number).sort((a, b) => a - b).map((value) => ({
5645
5921
  value,
5922
+ labels: q.scaleLabels ? q.scaleLabels[String(value)] : void 0,
5646
5923
  count: distMap[value] || 0,
5647
5924
  percentage: answeredCount > 0 ? Math.round((distMap[value] || 0) / answeredCount * 1e3) / 10 : 0
5648
5925
  }));
@@ -5653,6 +5930,7 @@ function computeSurveyAnalytics(survey, rawResponses, filter = {}) {
5653
5930
  max: maxVal,
5654
5931
  lowLabel: q.lowLabel,
5655
5932
  highLabel: q.highLabel,
5933
+ scaleLabels: q.scaleLabels,
5656
5934
  average: answeredCount > 0 ? Math.round(sum / answeredCount * 100) / 100 : 0,
5657
5935
  distribution,
5658
5936
  npsBreakdown: q.type === "nps" ? {
@@ -5841,6 +6119,7 @@ function computePublicSurveyResults(survey, rawResponses) {
5841
6119
  optionsBreakdown: qs.optionsBreakdown,
5842
6120
  average: qs.average,
5843
6121
  distribution: qs.distribution,
6122
+ scaleLabels: qs.scaleLabels,
5844
6123
  npsBreakdown: qs.npsBreakdown,
5845
6124
  rankingBreakdown: qs.rankingBreakdown
5846
6125
  }))
@@ -5853,9 +6132,17 @@ function escapeCsvCell(val) {
5853
6132
  }
5854
6133
  return str;
5855
6134
  }
5856
- function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
6135
+ function buildSurveyResponseExportAoA(survey, rawResponses, locale = "en") {
6136
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
5857
6137
  const activeQuestions = (survey.questions || []).filter((q) => q && q.type !== "statement");
5858
- const headers = [
6138
+ const headers = tr ? [
6139
+ "Yanıt ID",
6140
+ "Gönderim Tarihi",
6141
+ "Dil",
6142
+ "Süre (sn)",
6143
+ "NPS Puanı",
6144
+ "NPS Kategorisi"
6145
+ ] : [
5859
6146
  "Response ID",
5860
6147
  "Submitted At",
5861
6148
  "Locale",
@@ -5873,18 +6160,18 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5873
6160
  } else {
5874
6161
  headers.push(`${qTitle} (${q.key})`);
5875
6162
  if (q.allowOther) {
5876
- headers.push(`${qTitle} [Other Text]`);
6163
+ headers.push(`${qTitle} [${tr ? "Diğer Açıklama" : "Other Text"}]`);
5877
6164
  }
5878
6165
  }
5879
6166
  }
5880
- const lines = [headers.map(escapeCsvCell).join(",")];
6167
+ const rows = [];
5881
6168
  for (const r of rawResponses || []) {
5882
6169
  const rowCells = [
5883
6170
  String(r.id || r.documentId || ""),
5884
6171
  String(r.submittedAt || r.createdAt || ""),
5885
6172
  String(r.locale || ""),
5886
- String(r.durationSeconds ?? ""),
5887
- r.npsValue !== null && r.npsValue !== void 0 ? String(r.npsValue) : "",
6173
+ typeof r.durationSeconds === "number" ? r.durationSeconds : String(r.durationSeconds ?? ""),
6174
+ typeof r.npsValue === "number" ? r.npsValue : r.npsValue !== null && r.npsValue !== void 0 && r.npsValue !== "" ? Number(r.npsValue) : "",
5888
6175
  String(r.npsCategory || "")
5889
6176
  ];
5890
6177
  for (const q of activeQuestions) {
@@ -5901,7 +6188,7 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5901
6188
  } else if (Array.isArray(q.options) && q.options.length > 0) {
5902
6189
  if (Array.isArray(ans)) {
5903
6190
  const mapped = ans.map((optId) => {
5904
- if (optId === "__other__") return locale === "tr" ? "Diğer" : "Other";
6191
+ if (optId === "__other__") return tr ? "Diğer" : "Other";
5905
6192
  const found = q.options.find((o) => o.id === optId);
5906
6193
  return found ? resolveLocalizedText(found.labels, locale, optId) : optId;
5907
6194
  });
@@ -5909,7 +6196,7 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5909
6196
  } else if (ans !== void 0 && ans !== null && ans !== "") {
5910
6197
  const strAns = String(ans);
5911
6198
  if (strAns === "__other__") {
5912
- rowCells.push(locale === "tr" ? "Diğer" : "Other");
6199
+ rowCells.push(tr ? "Diğer" : "Other");
5913
6200
  } else {
5914
6201
  const found = q.options.find((o) => o.id === strAns);
5915
6202
  rowCells.push(found ? resolveLocalizedText(found.labels, locale, strAns) : strAns);
@@ -5921,16 +6208,131 @@ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
5921
6208
  rowCells.push(String(r.otherTexts?.[q.key] || ""));
5922
6209
  }
5923
6210
  } else {
5924
- rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
6211
+ if (q.type === "likert_scale" && q.scaleLabels && ans !== void 0 && ans !== null && ans !== "") {
6212
+ const ptLbl = resolveLocalizedText(q.scaleLabels[String(ans)], locale, "");
6213
+ rowCells.push(ptLbl ? `${ans} - ${ptLbl}` : Number.isNaN(Number(ans)) ? String(ans) : Number(ans));
6214
+ } else if ((q.type === "nps" || q.type === "star_rating" || q.type === "likert_scale") && ans !== void 0 && ans !== null && ans !== "" && !Number.isNaN(Number(ans))) {
6215
+ rowCells.push(Number(ans));
6216
+ } else {
6217
+ rowCells.push(ans === void 0 || ans === null ? "" : String(ans));
6218
+ }
5925
6219
  if (q.allowOther) {
5926
6220
  rowCells.push(String(r.otherTexts?.[q.key] || ""));
5927
6221
  }
5928
6222
  }
5929
6223
  }
5930
- lines.push(rowCells.map(escapeCsvCell).join(","));
6224
+ rows.push(rowCells);
6225
+ }
6226
+ return { headers, rows };
6227
+ }
6228
+ function computeAutoColWidths(aoa) {
6229
+ const colCount = aoa.reduce((m, r) => Math.max(m, r.length), 0);
6230
+ const widths = [];
6231
+ for (let c = 0; c < colCount; c++) {
6232
+ let maxLen = 12;
6233
+ for (let r = 0; r < Math.min(aoa.length, 300); r++) {
6234
+ const cell = aoa[r]?.[c];
6235
+ const str = cell === null || cell === void 0 ? "" : String(cell);
6236
+ if (str.length > maxLen) maxLen = str.length;
6237
+ }
6238
+ widths.push({ wch: Math.min(54, maxLen + 3) });
6239
+ }
6240
+ return widths;
6241
+ }
6242
+ function exportSurveyResponsesToCsv(survey, rawResponses, locale = "en") {
6243
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
6244
+ const lines = [headers.map(escapeCsvCell).join(",")];
6245
+ for (const r of rows) {
6246
+ lines.push(r.map(escapeCsvCell).join(","));
5931
6247
  }
5932
6248
  return `\uFEFF${lines.join("\r\n")}`;
5933
6249
  }
6250
+ function exportSurveyResponsesToXlsxBuffer(survey, rawResponses, locale = "en") {
6251
+ const tr = String(locale || "").toLowerCase().startsWith("tr");
6252
+ const { headers, rows } = buildSurveyResponseExportAoA(survey, rawResponses, locale);
6253
+ const responsesAoA = [headers, ...rows];
6254
+ const wb = XLSX.utils.book_new();
6255
+ const wsResponses = XLSX.utils.aoa_to_sheet(responsesAoA);
6256
+ wsResponses["!cols"] = computeAutoColWidths(responsesAoA);
6257
+ XLSX.utils.book_append_sheet(wb, wsResponses, tr ? "Yanitlar" : "Responses");
6258
+ const analytics = computeSurveyAnalytics(survey, rawResponses);
6259
+ const s = analytics.summary;
6260
+ const summaryAoA = [
6261
+ [tr ? "Anket Başlığı" : "Survey Title", resolveLocalizedText(survey.titleI18n, locale, survey.title)],
6262
+ ["Survey Slug", survey.slug],
6263
+ [tr ? "Dışa Aktarım Tarihi" : "Exported At", (/* @__PURE__ */ new Date()).toISOString()],
6264
+ [tr ? "Toplam Yanıt" : "Total Responses", s.totalResponses],
6265
+ [tr ? "Ortalama Süre (sn)" : "Average Duration (s)", s.avgDurationSeconds],
6266
+ [tr ? "Medyan Süre (sn)" : "Median Duration (s)", s.medianDurationSeconds]
6267
+ ];
6268
+ if (s.nps?.hasNps) {
6269
+ summaryAoA.push(
6270
+ ["Net Promoter Score (NPS)", s.nps.score ?? 0],
6271
+ [
6272
+ tr ? "NPS Dağılımı" : "NPS Breakdown",
6273
+ `Promoters: ${s.nps.promoters} (${s.nps.promotersPct}%) | Passives: ${s.nps.passives} (${s.nps.passivesPct}%) | Detractors: ${s.nps.detractors} (${s.nps.detractorsPct}%)`
6274
+ ]
6275
+ );
6276
+ }
6277
+ summaryAoA.push(
6278
+ [],
6279
+ tr ? ["Soru Anahtarı", "Soru Başlığı", "Tip", "Seçenek / Kriter", "Adet / Ort.", "Yüzde (%)"] : ["Question Key", "Question Title", "Type", "Option / Metric", "Count / Avg", "Share (%)"]
6280
+ );
6281
+ for (const qs of analytics.questionStats) {
6282
+ const qTitle = resolveLocalizedText(qs.title, locale, qs.key);
6283
+ if (Array.isArray(qs.optionsBreakdown)) {
6284
+ for (const opt of qs.optionsBreakdown) {
6285
+ const optLbl = opt.id === "__other__" ? tr ? "Diğer" : "Other" : resolveLocalizedText(opt.labels, locale, opt.id);
6286
+ summaryAoA.push([qs.key, qTitle, qs.type, optLbl, opt.count, opt.percentage]);
6287
+ }
6288
+ } else if (Array.isArray(qs.distribution)) {
6289
+ summaryAoA.push([
6290
+ qs.key,
6291
+ qTitle,
6292
+ qs.type,
6293
+ tr ? "Ortalama Puan" : "Average Score",
6294
+ qs.average,
6295
+ ""
6296
+ ]);
6297
+ for (const d of qs.distribution) {
6298
+ const ptLbl = d.labels ? resolveLocalizedText(d.labels, locale, "") : "";
6299
+ summaryAoA.push([
6300
+ qs.key,
6301
+ qTitle,
6302
+ qs.type,
6303
+ ptLbl ? `${d.value} - ${ptLbl}` : String(d.value),
6304
+ d.count,
6305
+ d.percentage
6306
+ ]);
6307
+ }
6308
+ } else if (Array.isArray(qs.rankingBreakdown)) {
6309
+ for (const rk of qs.rankingBreakdown) {
6310
+ summaryAoA.push([
6311
+ qs.key,
6312
+ qTitle,
6313
+ qs.type,
6314
+ resolveLocalizedText(rk.labels, locale, rk.id),
6315
+ rk.averageRank,
6316
+ rk.scorePercentage
6317
+ ]);
6318
+ }
6319
+ } else {
6320
+ summaryAoA.push([
6321
+ qs.key,
6322
+ qTitle,
6323
+ qs.type,
6324
+ tr ? "Toplam Yanıt" : "Answered Count",
6325
+ qs.answeredCount || 0,
6326
+ ""
6327
+ ]);
6328
+ }
6329
+ }
6330
+ const wsSummary = XLSX.utils.aoa_to_sheet(summaryAoA);
6331
+ wsSummary["!cols"] = computeAutoColWidths(summaryAoA);
6332
+ XLSX.utils.book_append_sheet(wb, wsSummary, tr ? "Ozet_Istatistik" : "Summary");
6333
+ const out = XLSX.write(wb, { type: "buffer", bookType: "xlsx" });
6334
+ return Buffer.isBuffer(out) ? out : Buffer.from(out);
6335
+ }
5934
6336
  const SURVEY_UID = "plugin::content-input.ci-survey";
5935
6337
  const SURVEY_RESPONSE_UID = "plugin::content-input.ci-survey-response";
5936
6338
  let activeSeedPromise = null;
@@ -6016,38 +6418,126 @@ function sanitizeSurveyForPublic(entry, extra = {}) {
6016
6418
  publicResults: extra.publicResults || null
6017
6419
  };
6018
6420
  }
6421
+ function sanitizeSurveyForBundle(entry, rawResponses) {
6422
+ const cleanTitle = String(entry?.title || "Untitled Survey").trim();
6423
+ const cleanSlug = String(entry?.slug || slugifyIdentifier(cleanTitle) || "survey").trim();
6424
+ const sortedResponses = Array.isArray(rawResponses) ? [...rawResponses].sort((a, b) => {
6425
+ const ta = new Date(a?.submittedAt || a?.createdAt || 0).getTime();
6426
+ const tb = new Date(b?.submittedAt || b?.createdAt || 0).getTime();
6427
+ return ta - tb;
6428
+ }) : [];
6429
+ return {
6430
+ title: cleanTitle,
6431
+ titleI18n: entry?.titleI18n || { tr: cleanTitle, en: cleanTitle },
6432
+ slug: cleanSlug,
6433
+ description: entry?.description ?? { tr: "", en: "" },
6434
+ status: entry?.status || "published",
6435
+ displayMode: entry?.displayMode || "single_page",
6436
+ startsAt: entry?.startsAt || null,
6437
+ endsAt: entry?.endsAt || null,
6438
+ quotaLimit: entry?.quotaLimit ? Number(entry.quotaLimit) : null,
6439
+ submissionPolicy: entry?.submissionPolicy || "one_per_voter",
6440
+ anonymizeIp: entry?.anonymizeIp !== void 0 ? Boolean(entry.anonymizeIp) : true,
6441
+ showPublicResults: entry?.showPublicResults || "after_vote",
6442
+ allowBackNavigation: entry?.allowBackNavigation !== void 0 ? Boolean(entry.allowBackNavigation) : true,
6443
+ showProgressBar: entry?.showProgressBar !== void 0 ? Boolean(entry.showProgressBar) : true,
6444
+ useRecaptcha: entry?.useRecaptcha !== void 0 ? Boolean(entry.useRecaptcha) : false,
6445
+ recaptchaSiteKey: entry?.recaptchaSiteKey ? String(entry.recaptchaSiteKey) : "",
6446
+ steps: Array.isArray(entry?.steps) ? entry.steps : [],
6447
+ questions: Array.isArray(entry?.questions) ? entry.questions : [],
6448
+ settings: entry?.settings && typeof entry.settings === "object" ? entry.settings : {},
6449
+ version: Number(entry?.version || 1),
6450
+ responses: sortedResponses.map((r) => ({
6451
+ answers: r?.answers && typeof r.answers === "object" && !Array.isArray(r.answers) ? r.answers : {},
6452
+ otherTexts: r?.otherTexts && typeof r.otherTexts === "object" && !Array.isArray(r.otherTexts) ? r.otherTexts : {},
6453
+ score: typeof r?.score === "number" ? r.score : null,
6454
+ npsValue: typeof r?.npsValue === "number" ? r.npsValue : null,
6455
+ npsCategory: r?.npsCategory || null,
6456
+ locale: String(r?.locale || "en"),
6457
+ durationSeconds: Math.max(0, Number(r?.durationSeconds || 0) || 0),
6458
+ voterHash: r?.voterHash || null,
6459
+ respondentToken: r?.respondentToken || null,
6460
+ submittedAt: r?.submittedAt || r?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
6461
+ }))
6462
+ };
6463
+ }
6464
+ function makeUniqueSlug(baseSlug, usedSlugs) {
6465
+ const cleanBase = slugifyIdentifier(baseSlug) || "survey";
6466
+ if (!usedSlugs.has(cleanBase)) {
6467
+ usedSlugs.add(cleanBase);
6468
+ return cleanBase;
6469
+ }
6470
+ let candidate = `${cleanBase}_copy`;
6471
+ let counter = 2;
6472
+ while (usedSlugs.has(candidate)) {
6473
+ candidate = `${cleanBase}_copy_${counter}`;
6474
+ counter += 1;
6475
+ }
6476
+ usedSlugs.add(candidate);
6477
+ return candidate;
6478
+ }
6019
6479
  const ciSurveyService = ({ strapi }) => ({
6480
+ async deleteResponsesForSurveyRecord(survey) {
6481
+ if (!survey) return 0;
6482
+ const existing = await this.getResponsesForSurvey(survey);
6483
+ const count = existing.length;
6484
+ if (count > 0) {
6485
+ const ids = existing.map((r) => r.id).filter((id) => id !== void 0 && id !== null);
6486
+ if (ids.length > 0) {
6487
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6488
+ where: { id: { $in: ids } }
6489
+ });
6490
+ }
6491
+ }
6492
+ if (survey.slug) {
6493
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6494
+ where: { surveySlug: survey.slug }
6495
+ });
6496
+ }
6497
+ return count;
6498
+ },
6020
6499
  async ensureSeeded(forceReseedResponses = false) {
6021
6500
  if (activeSeedPromise && !forceReseedResponses) {
6022
6501
  return activeSeedPromise;
6023
6502
  }
6024
6503
  const runSeed = async () => {
6504
+ if (!forceReseedResponses && await isDemoSeedBlocked(strapi, "surveys")) {
6505
+ return;
6506
+ }
6025
6507
  let existingSurveys = [];
6026
6508
  try {
6027
6509
  existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
6028
6510
  } catch {
6029
6511
  return;
6030
6512
  }
6513
+ const isFreshEmptyDb = existingSurveys.length === 0;
6031
6514
  const bySlug = {};
6032
6515
  for (const s of existingSurveys) {
6033
6516
  if (s?.slug) bySlug[s.slug] = s;
6034
6517
  }
6035
- for (const seed of DEFAULT_SEED_SURVEYS) {
6036
- if (!bySlug[seed.slug]) {
6037
- const created = await strapi.db.query(SURVEY_UID).create({
6038
- data: seed
6039
- });
6040
- bySlug[seed.slug] = created;
6518
+ if (isFreshEmptyDb || forceReseedResponses) {
6519
+ for (const seed of DEFAULT_SEED_SURVEYS) {
6520
+ if (!bySlug[seed.slug]) {
6521
+ const created = await strapi.db.query(SURVEY_UID).create({
6522
+ data: seed
6523
+ });
6524
+ bySlug[seed.slug] = created;
6525
+ }
6041
6526
  }
6042
6527
  }
6043
6528
  const totalResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
6044
- if (totalResponses === 0 || forceReseedResponses) {
6529
+ if (isFreshEmptyDb && totalResponses === 0 || forceReseedResponses) {
6045
6530
  if (forceReseedResponses) {
6046
6531
  const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
6047
6532
  for (const slug of demoSlugs) {
6048
- await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6049
- where: { surveySlug: slug }
6050
- });
6533
+ const demoSrv = bySlug[slug];
6534
+ if (demoSrv) {
6535
+ await this.deleteResponsesForSurveyRecord(demoSrv);
6536
+ } else {
6537
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6538
+ where: { surveySlug: slug }
6539
+ });
6540
+ }
6051
6541
  }
6052
6542
  }
6053
6543
  const rows = generateSeedSurveyResponses(bySlug);
@@ -6063,6 +6553,7 @@ const ciSurveyService = ({ strapi }) => ({
6063
6553
  );
6064
6554
  }
6065
6555
  }
6556
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6066
6557
  };
6067
6558
  activeSeedPromise = runSeed().finally(() => {
6068
6559
  activeSeedPromise = null;
@@ -6070,9 +6561,10 @@ const ciSurveyService = ({ strapi }) => ({
6070
6561
  return activeSeedPromise;
6071
6562
  },
6072
6563
  async reseedSampleData() {
6564
+ await setDemoSeedCleared(strapi, false);
6073
6565
  await this.ensureSeeded(true);
6074
6566
  try {
6075
- await strapi.plugin("content-input").service("ci-form").ensureSampleSubmissions(true);
6567
+ await strapi.plugin("content-input").service("ci-form").ensureSeeded(true);
6076
6568
  } catch {
6077
6569
  }
6078
6570
  const totalSurveyResponses = await strapi.db.query(SURVEY_RESPONSE_UID).count();
@@ -6081,6 +6573,47 @@ const ciSurveyService = ({ strapi }) => ({
6081
6573
  totalSurveyResponses
6082
6574
  };
6083
6575
  },
6576
+ async purgeDemoData() {
6577
+ await setDemoSeedCleared(strapi, true);
6578
+ const demoSlugs = DEFAULT_SEED_SURVEYS.map((s) => s.slug);
6579
+ let deletedSurveys = 0;
6580
+ let deletedSurveyResponses = 0;
6581
+ for (const slug of demoSlugs) {
6582
+ const found = await strapi.db.query(SURVEY_UID).findOne({
6583
+ where: { slug }
6584
+ });
6585
+ if (found) {
6586
+ deletedSurveyResponses += await this.deleteResponsesForSurveyRecord(found);
6587
+ await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
6588
+ deletedSurveys += 1;
6589
+ } else {
6590
+ const orphanRows = await strapi.db.query(SURVEY_RESPONSE_UID).findMany({
6591
+ where: { surveySlug: slug }
6592
+ }) || [];
6593
+ if (orphanRows.length > 0) {
6594
+ await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6595
+ where: { surveySlug: slug }
6596
+ });
6597
+ deletedSurveyResponses += orphanRows.length;
6598
+ }
6599
+ }
6600
+ }
6601
+ let deletedForms = 0;
6602
+ let deletedFormSubmissions = 0;
6603
+ try {
6604
+ const formRes = await strapi.plugin("content-input").service("ci-form").purgeDemoForms();
6605
+ deletedForms = Number(formRes?.deletedForms || 0);
6606
+ deletedFormSubmissions = Number(formRes?.deletedFormSubmissions || 0);
6607
+ } catch {
6608
+ }
6609
+ return {
6610
+ ok: true,
6611
+ deletedSurveys,
6612
+ deletedSurveyResponses,
6613
+ deletedForms,
6614
+ deletedFormSubmissions
6615
+ };
6616
+ },
6084
6617
  async findRawByIdOrSlug(idOrSlug) {
6085
6618
  await this.ensureSeeded(false);
6086
6619
  const raw = String(idOrSlug || "").trim();
@@ -6253,17 +6786,36 @@ const ciSurveyService = ({ strapi }) => ({
6253
6786
  const created = await strapi.db.query(SURVEY_UID).create({
6254
6787
  data: recordData
6255
6788
  });
6789
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6256
6790
  return formatSurveyForAdmin(created, { responseCount: 0 });
6257
6791
  },
6258
6792
  async remove(idOrSlug) {
6259
6793
  const found = await this.findRawByIdOrSlug(idOrSlug);
6794
+ let deletedResponses = 0;
6260
6795
  if (found) {
6261
- await strapi.db.query(SURVEY_RESPONSE_UID).deleteMany({
6262
- where: { surveySlug: found.slug }
6263
- });
6796
+ deletedResponses = await this.deleteResponsesForSurveyRecord(found);
6264
6797
  await strapi.db.query(SURVEY_UID).delete({ where: { id: found.id } });
6798
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6265
6799
  }
6266
- return { success: true };
6800
+ return { success: true, deletedResponses };
6801
+ },
6802
+ async clearResponses(idOrSlug) {
6803
+ const found = await this.findRawByIdOrSlug(idOrSlug);
6804
+ if (!found) {
6805
+ return null;
6806
+ }
6807
+ const deletedCount = await this.deleteResponsesForSurveyRecord(found);
6808
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
6809
+ return {
6810
+ ok: true,
6811
+ slug: found.slug,
6812
+ deletedCount,
6813
+ survey: formatSurveyForAdmin(found, {
6814
+ responseCount: 0,
6815
+ npsScore: null,
6816
+ lastSubmittedAt: null
6817
+ })
6818
+ };
6267
6819
  },
6268
6820
  async submitSurvey(idOrSlug, rawBody, meta = {}) {
6269
6821
  const survey = await this.findRawByIdOrSlug(idOrSlug);
@@ -6502,6 +7054,18 @@ const ciSurveyService = ({ strapi }) => ({
6502
7054
  return true;
6503
7055
  });
6504
7056
  }
7057
+ if (options2.format === "xlsx") {
7058
+ const xlsxBuf = exportSurveyResponsesToXlsxBuffer(
7059
+ survey,
7060
+ responses,
7061
+ options2.locale || "en"
7062
+ );
7063
+ return {
7064
+ filename: `${survey.slug}-responses.xlsx`,
7065
+ contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
7066
+ body: xlsxBuf
7067
+ };
7068
+ }
6505
7069
  if (options2.format === "json") {
6506
7070
  return {
6507
7071
  filename: `${survey.slug}-responses.json`,
@@ -6531,6 +7095,188 @@ const ciSurveyService = ({ strapi }) => ({
6531
7095
  contentType: "text/csv; charset=utf-8",
6532
7096
  body: csv
6533
7097
  };
7098
+ },
7099
+ async exportBundle(targetIdOrAll = "all", mode = "structure") {
7100
+ await this.ensureSeeded(false);
7101
+ const cleanTarget = String(targetIdOrAll || "all").trim();
7102
+ const exportMode = mode === "full" ? "full" : "structure";
7103
+ let targetSurveys = [];
7104
+ if (!cleanTarget || cleanTarget === "all") {
7105
+ targetSurveys = await strapi.db.query(SURVEY_UID).findMany({
7106
+ orderBy: { id: "asc" }
7107
+ }) || [];
7108
+ } else {
7109
+ const single = await this.findRawByIdOrSlug(cleanTarget);
7110
+ if (!single) {
7111
+ return null;
7112
+ }
7113
+ targetSurveys = [single];
7114
+ }
7115
+ const portableSurveys = [];
7116
+ let totalResponses = 0;
7117
+ for (const srv of targetSurveys) {
7118
+ const rawResps = exportMode === "full" ? await this.getResponsesForSurvey(srv) : [];
7119
+ const item = sanitizeSurveyForBundle(srv, rawResps);
7120
+ totalResponses += item.responses.length;
7121
+ portableSurveys.push(item);
7122
+ }
7123
+ const dateStamp = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
7124
+ const modeSuffix = exportMode === "full" ? "full-backup" : "structure";
7125
+ const filename = cleanTarget && cleanTarget !== "all" && portableSurveys[0]?.slug ? `${portableSurveys[0].slug}-${modeSuffix}.ci-survey.json` : `ci-surveys-all-${modeSuffix}-${dateStamp}.ci-survey.json`;
7126
+ const bundle = {
7127
+ packageType: "strapi-content-input-survey-bundle",
7128
+ schemaVersion: 1,
7129
+ mode: exportMode,
7130
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
7131
+ surveyCount: portableSurveys.length,
7132
+ totalResponses,
7133
+ surveys: portableSurveys
7134
+ };
7135
+ return {
7136
+ filename,
7137
+ contentType: "application/json; charset=utf-8",
7138
+ bundle
7139
+ };
7140
+ },
7141
+ async importBundle(rawPayload, options2 = {}) {
7142
+ await updateDemoSeedState(strapi, { surveysInitialized: true });
7143
+ let parsed = rawPayload;
7144
+ if (typeof parsed === "string") {
7145
+ try {
7146
+ parsed = JSON.parse(parsed);
7147
+ } catch {
7148
+ const err = new Error("Invalid JSON bundle payload");
7149
+ err.status = 400;
7150
+ throw err;
7151
+ }
7152
+ }
7153
+ let rawItems = [];
7154
+ if (Array.isArray(parsed)) {
7155
+ rawItems = parsed;
7156
+ } else if (parsed && typeof parsed === "object") {
7157
+ if (Array.isArray(parsed.surveys)) {
7158
+ rawItems = parsed.surveys;
7159
+ } else if (Array.isArray(parsed.questions) || parsed.title || parsed.slug) {
7160
+ rawItems = [parsed];
7161
+ }
7162
+ }
7163
+ const validItems = rawItems.filter(
7164
+ (it) => it && typeof it === "object" && (Array.isArray(it.questions) || it.title)
7165
+ );
7166
+ if (validItems.length === 0) {
7167
+ const err = new Error(
7168
+ "No valid survey definitions found in the provided JSON package."
7169
+ );
7170
+ err.status = 400;
7171
+ throw err;
7172
+ }
7173
+ const conflictStrategy = options2.conflictStrategy === "overwrite" ? "overwrite" : "duplicate";
7174
+ const includeResponses = options2.includeResponses !== false;
7175
+ const existingSurveys = await strapi.db.query(SURVEY_UID).findMany() || [];
7176
+ const usedSlugs = new Set(
7177
+ existingSurveys.map((s) => String(s?.slug || "").trim()).filter(Boolean)
7178
+ );
7179
+ const importedSurveys = [];
7180
+ let importedResponsesCount = 0;
7181
+ for (const item of validItems) {
7182
+ const cleanTitle = String(item.title || "Imported Survey").trim();
7183
+ const baseSlug = slugifyIdentifier(String(item.slug || cleanTitle)) || "imported_survey";
7184
+ const existing = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: baseSlug } });
7185
+ const isOverwriting = Boolean(existing && conflictStrategy === "overwrite");
7186
+ const isDuplicatingCollision = Boolean(
7187
+ existing && conflictStrategy === "duplicate"
7188
+ );
7189
+ const finalSlug = isOverwriting ? baseSlug : makeUniqueSlug(baseSlug, usedSlugs);
7190
+ const finalTitle = isDuplicatingCollision ? `${cleanTitle} (Copy)` : cleanTitle;
7191
+ const rawTitleI18n = item.titleI18n && typeof item.titleI18n === "object" ? { ...item.titleI18n } : { tr: cleanTitle, en: cleanTitle };
7192
+ if (isDuplicatingCollision) {
7193
+ for (const k of Object.keys(rawTitleI18n)) {
7194
+ if (rawTitleI18n[k]) {
7195
+ rawTitleI18n[k] = `${rawTitleI18n[k]} (${k === "tr" ? "Kopya" : "Copy"})`;
7196
+ }
7197
+ }
7198
+ }
7199
+ const savePayload = {
7200
+ ...isOverwriting ? { id: existing.documentId || existing.id } : {},
7201
+ title: finalTitle,
7202
+ titleI18n: rawTitleI18n,
7203
+ slug: finalSlug,
7204
+ description: item.description ?? { tr: "", en: "" },
7205
+ status: item.status || "published",
7206
+ displayMode: item.displayMode || "single_page",
7207
+ startsAt: item.startsAt || null,
7208
+ endsAt: item.endsAt || null,
7209
+ quotaLimit: item.quotaLimit ? Number(item.quotaLimit) : null,
7210
+ submissionPolicy: item.submissionPolicy || "one_per_voter",
7211
+ anonymizeIp: item.anonymizeIp !== void 0 ? Boolean(item.anonymizeIp) : true,
7212
+ showPublicResults: item.showPublicResults || "after_vote",
7213
+ allowBackNavigation: item.allowBackNavigation !== void 0 ? Boolean(item.allowBackNavigation) : true,
7214
+ showProgressBar: item.showProgressBar !== void 0 ? Boolean(item.showProgressBar) : true,
7215
+ useRecaptcha: item.useRecaptcha !== void 0 ? Boolean(item.useRecaptcha) : false,
7216
+ recaptchaSiteKey: item.recaptchaSiteKey ? String(item.recaptchaSiteKey) : "",
7217
+ steps: Array.isArray(item.steps) ? item.steps : [],
7218
+ questions: Array.isArray(item.questions) ? item.questions : [],
7219
+ settings: item.settings && typeof item.settings === "object" ? item.settings : {}
7220
+ };
7221
+ await this.save(savePayload);
7222
+ const savedRaw = await strapi.db.query(SURVEY_UID).findOne({ where: { slug: finalSlug } });
7223
+ if (!savedRaw) continue;
7224
+ const rawResponses = Array.isArray(item.responses) ? item.responses : [];
7225
+ if (includeResponses) {
7226
+ if (isOverwriting) {
7227
+ await this.deleteResponsesForSurveyRecord(savedRaw);
7228
+ }
7229
+ if (rawResponses.length > 0) {
7230
+ const surveyDocOrId = String(savedRaw.documentId || savedRaw.id);
7231
+ const batchSize = 50;
7232
+ for (let i = 0; i < rawResponses.length; i += batchSize) {
7233
+ const chunk = rawResponses.slice(i, i + batchSize);
7234
+ await Promise.all(
7235
+ chunk.map((r) => {
7236
+ const answers = r?.answers && typeof r.answers === "object" && !Array.isArray(r.answers) ? r.answers : {};
7237
+ const otherTexts = r?.otherTexts && typeof r.otherTexts === "object" && !Array.isArray(r.otherTexts) ? r.otherTexts : {};
7238
+ const metrics = computeResponseMetrics(
7239
+ savedRaw,
7240
+ answers
7241
+ );
7242
+ const durationSeconds = typeof r?.durationSeconds === "number" ? Math.max(0, Math.round(r.durationSeconds)) : typeof r?.durationMs === "number" ? Math.max(0, Math.round(r.durationMs / 1e3)) : 0;
7243
+ return strapi.db.query(SURVEY_RESPONSE_UID).create({
7244
+ data: {
7245
+ surveyId: surveyDocOrId,
7246
+ surveySlug: savedRaw.slug,
7247
+ surveyTitle: savedRaw.title,
7248
+ surveyVersion: Number(savedRaw.version || 1),
7249
+ answers,
7250
+ otherTexts,
7251
+ score: typeof r?.score === "number" ? r.score : metrics.score,
7252
+ npsValue: typeof r?.npsValue === "number" ? r.npsValue : metrics.npsValue,
7253
+ npsCategory: r?.npsCategory || metrics.npsCategory,
7254
+ locale: String(r?.locale || "en"),
7255
+ durationSeconds,
7256
+ voterHash: r?.voterHash || null,
7257
+ respondentToken: r?.respondentToken || null,
7258
+ ip: null,
7259
+ userAgent: String(r?.userAgent || "imported"),
7260
+ submittedAt: r?.submittedAt || r?.createdAt || (/* @__PURE__ */ new Date()).toISOString()
7261
+ }
7262
+ });
7263
+ })
7264
+ );
7265
+ }
7266
+ importedResponsesCount += rawResponses.length;
7267
+ }
7268
+ }
7269
+ const finalAdminObj = await this.findOneAdmin(finalSlug);
7270
+ if (finalAdminObj) {
7271
+ importedSurveys.push(finalAdminObj);
7272
+ }
7273
+ }
7274
+ return {
7275
+ ok: true,
7276
+ importedCount: importedSurveys.length,
7277
+ importedResponsesCount,
7278
+ importedSurveys
7279
+ };
6534
7280
  }
6535
7281
  });
6536
7282
  const PALETTE_UID = "plugin::content-input.ci-color-palette";